• 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()
                ...
    }
  • 相关阅读:
    vue 实现左侧分类列表,右侧文档列表
    C# string数组与list< string >的相互转换
    c# List<string>的用法
    类数组 数组
    事件
    js封装方法和浏览器内核
    dom
    try...catch es5
    data对象 定时器
    call apply 原型 原型链
  • 原文地址:https://www.cnblogs.com/LQBlog/p/15505361.html
Copyright © 2020-2023  润新知