[英]JWT role Based Authorization with Spring Security
我想向具有“ADMIN”角色的用户授予对 /hello URL 的访问权限,我有这样的安全配置。 从“/authenticate” URL 我得到 jwt 令牌。
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/authenticate").permitAll()
//.antMatchers("/hello").hasRole("ADMIN")
.anyRequest().authenticated().
and().
exceptionHandling().and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
我试图在我的控制器中添加 @PreAuthorize 注释,但它不起作用所有用户都可以访问该 url。
@GetMapping("/hello")
@PreAuthorize("hasRole('ADMIN')")
public String test(){
return "Hello";
}
从控制器中删除 @PreAuthorize 注释并像这样更改安全配置后,它解决了我的问题。
@Darren 非常感谢您的评论,它解决了我的问题。
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/authenticate").permitAll()
.antMatchers("/hello").hasAuthority("ADMIN")
.anyRequest().authenticated().
and().
exceptionHandling().and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtRequestFilter,
UsernamePasswordAuthenticationFilter.class);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.