需要配置启用@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
@RestController public class HelloController { /** * 只有当前登录用户名为 javaboy 的用户才可以访问该方法。 * @return */ @PreAuthorize("principal.username.equals('javaboy')") @GetMapping("/hello") public String hello() { return "hello"; } /** * 表示访问该方法的用户必须具备 admin 角色。 * @return */ @PreAuthorize("hasRole('admin')") public String admin() { return "admin"; } /** * 表示方法该方法的用户必须具备 user 角色,但是注意 user 角色需要加上 ROLE_ 前缀。 * @return */ @Secured({"ROLE_user"}) public String user() { return "user"; } /** * 第四个 getAge 方法,表示访问该方法的 age 参数必须大于 98,否则请求不予通过 * @param age * @return */ @PreAuthorize("#age>98") public String getAge(Integer age) { return String.valueOf(age); } @GetMapping("/login") public ModelAndView login(){ ModelAndView modelAndView=new ModelAndView(); modelAndView.setViewName("login"); return modelAndView; } }
基于URL
protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("admin") .antMatchers("/user/**").hasAnyRole("admin", "user") .anyRequest().authenticated() .and() ... }
6e99086629a5 8 月前
69c6fad9a073 8 月前