03-HttpSecurity配置

重写 HttpSecurity configure

@Override
protected void configure(HttpSecurity http) throws Exception {
    // 开启配置
    http.authorizeRequests()
            // 访问路径以: /admin/开头的 需要具备哪些角色
            .antMatchers("/admin/**").hasRole("admin")
            // 访问路径以: /user/开头的 需要具备 hasAnyRole中的任意一个角色即可
            .antMatchers("/user/**").hasAnyRole("admin", "user")
            //.antMatchers("/user/**").access("hasAnyRole('admin','admin')")
            //.antMatchers("/user/**").access("hasRole('admin') and hasRole('user')")
            // 剩下的其它请求,都是登录之后就能访问
            .anyRequest().authenticated()
            .and()
            // 表单登陆
            .formLogin()
            // 处理登陆请求的Url
            .loginProcessingUrl("/doLogin")
            // 登陆相关的接口可以直接访问,直接过
            .permitAll()
            .and()
            // postman测试,关闭csrf攻击
            .csrf().disable();
}

编写测试Controller

@GetMapping("/admin/hello")
public String admin(){
    return "Hello admin!";
}

@GetMapping("/user/hello")
public String user(){
    return "Hello user!";
}

启动项目测试

如果以 javaboy 用户登陆那么所有的接口都可以访问 因为 javaboy 用户具有 admin角色

如果以 xhh 用户登陆 那么就只能访问 /user/hello xhh 用户只具备user 角色

postman自行测试

源码下载地址:https://github.com/XiaoHuiHuiT/SpringSecurity-case/releases/tag/3.0

posted @ 2020-05-14 00:47  Leader_TBlog  阅读(693)  评论(0编辑  收藏  举报