spring-security使用-权限控制(八)

基于注解

需要配置启用@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)

prePostEnabled: 确定 前置注解[@PreAuthorize,@PostAuthorize,..] 是否启用
securedEnabled: 确定安全注解 [@Secured] 是否启用
jsr250Enabled: 确定 JSR-250注解 [@RolesAllowed..]是否启用

 各个注解特点可以参考:https://www.jianshu.com/p/77b4835b6e8e 或者https://juejin.cn/post/6844904000026837005

@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()
            ...
}
原文地址:https://www.cnblogs.com/LQBlog/p/15505361.html