关于安全:Spring-Cloud-Spring-Security实践三-数据库方式的认证和授权

首先,创立针对三种role的controller(App/Admin/User):

@RestController
@RequestMapping("/app/api")
public class Controllers {
    @GetMapping("hello")
    public String hello(){
        return "hello, app";
    }
}
@RestController
@RequestMapping("/admin/api")
class AdminController {
    @GetMapping("hello")
    public String hello(){
        return "hello, admin";
    }
}
@RestController
@RequestMapping("/user/api")
class UserController {
    @GetMapping("hello")
    public String hello(){
        return "hello, user";
    }
}

此三个controller别离对应三种Role,此时咱们在配置中增加权限管制的配置:

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
     @Override
     protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .antMatchers("/admin/**").hasRole("ADMIN")
                    .antMatchers("/user/**").hasRole("USER")
                    .antMatchers("/app/**").permitAll()
                    .anyRequest().authenticated()
                    .and()
                .formLogin();
        }
}

留神其中的antMatchers办法,此办法为采纳ANT模式的URL匹配器

此时重启服务,发现登录后拜访user及admin资源均提醒403谬误,但app能够失常进入,阐明此配置没有问题。只短少用户信息的Role局部。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理