基于JWT角色的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);
}

最新更新