我的 securityConfig.java 看起来像这样,在我的项目中,有很多访问权限,我只写下面的securityConfig
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final TokenAuthenticationService tokenAuthenticationService;
@Autowired
protected SecurityConfig(final TokenAuthenticationService tokenAuthenticationService) {
super();
this.tokenAuthenticationService = tokenAuthenticationService;
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.headers().frameOptions().sameOrigin().and().authorizeRequests().antMatchers("/api/pub/**").permitAll()
.antMatchers("/api/**").authenticated().anyRequest().permitAll().and()
.addFilterBefore(new AuthenticationTokenFilter(this.tokenAuthenticationService),
UsernamePasswordAuthenticationFilter.class)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().httpBasic().and()
.csrf().disable().exceptionHandling()
.accessDeniedHandler((request, response, accessDeniedException) -> {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
}).authenticationEntryPoint((request, response, authException) -> {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
});
}
}
它显示访问被拒绝错误,我的意图是用来显示具有GET_USER访问权限的用户详细信息。
而 controller 文件看起来像这个,我尝试了ROLE_GET_USR和GET_USR。
@PreAuthorize("hasRole('GET_USR')")
@RequestMapping(value = "/min", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<?> getUserMinimalData() {
final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
System.out.println("User name " + auth.getName()); // prints - User name pratap
System.out.println("User Authorities " + auth.getAuthorities()); // prints - User Authorities [ADMIN]
return new ResponseEntity<>(this.facade.getUserMinimalData(), HttpStatus.OK);
}
答案 0 :(得分:3)
在您的控制器中,请使用hasAuthority代替hasRole
@PreAuthorize("hasAuthority('GET_USR')")
@RequestMapping(value = "/min", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<?> getUserMinimalData() {
final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
System.out.println("User name " + auth.getName()); // prints - User name pratap
System.out.println("User Authorities " + auth.getAuthorities()); // prints - User Authorities [ADMIN]
return new ResponseEntity<>(this.facade.getUserMinimalData(), HttpStatus.OK);
}