Spring 安全性 - 使用 @PreAuthorize( "hasRole('ADMIN')" ) 时出错会导致 404



我在使用@PreAuthorize("hasRole('ADMIN'("(时遇到问题注释。我的控制器代码如下,它有welcome((方法,只有角色为ADMIN:的用户才能访问该方法

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/user/auth")
public class TestController {

@GetMapping("/welcome")
@PreAuthorize("hasRole('ADMIN')")
public String welcome() {
return "Welcome!!!";
}
}

以下是我的安全配置:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsServiceImpl userDetailsService;
@Autowired
private AuthEntryPointJwt unauthorizedHandler;
@Bean
public AuthTokenFilter authenticationJwtTokenFilter() {
return new AuthTokenFilter();
}
@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests().antMatchers("/user/auth/**").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
}

AuthEntryPointJwt类如下:

@Component
public class AuthEntryPointJwt implements AuthenticationEntryPoint {
private static final Logger logger = LoggerFactory.getLogger(AuthEntryPointJwt.class);
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
logger.error("Unauthorized error: {}", authException.getMessage());
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Error: Unauthorized");
}
}

这是我正在使用的网址:http://localhost:8080/user/auth/welcome这是响应

{
"message": null,
"httpStatusCode": 404,
"errorLevelCode": "0x2",
"errorMessage": "Access is denied",
"apiPath": null,
"httpMethod": null
}

所以,我使用poster在Authorization头中发送jwt Bearer+令牌,它正在抛出404。它应该在发送授权标头后返回带有令牌的资源。我不知道问题出在哪里。如果能给我一些建议或知道我在这里做错了什么,那就太好了。提前谢谢。

错误404表明端点映射有问题(在路径中找不到资源(。如果是安全问题,您将得到错误401(未经授权(或错误403(禁止(。

如果我是对的,那么当您删除@PreAuthorize并添加";欢迎";具有访问权限的安全配置的路径";permitAll";。

相关内容

最新更新