zoukankan      html  css  js  c++  java
  • 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()
                ...
    }
  • 相关阅读:
    markdown模式的一些语法
    markdown模式的一些语法
    微信小游戏跳一跳外挂教程(安卓版)
    微信小游戏跳一跳外挂教程(安卓版)
    仿百度地图上拉下滑抽屉盒
    仿百度地图上拉下滑抽屉盒
    验证码倒计时的注册页面
    验证码倒计时的注册页面
    1430 素数判定
    2834 斐波那契数
  • 原文地址:https://www.cnblogs.com/LQBlog/p/15505361.html
Copyright © 2011-2022 走看看