我有一个带有 jwt 身份验证的 spring boot rest api。问题是我无法摆脱默认的 403 Access Denied rest 响应,它看起来像这样:
{
"timestamp": 1516206966541,
"status": 403,
"error": "Forbidden",
"message": "Access Denied",
"path": "/api/items/2"
}
我创建了自定义 AccessDeniedHandler:
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest req,
HttpServletResponse res,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
ObjectMapper mapper = new ObjectMapper();
res.setContentType("application/json;charset=UTF-8");
res.setStatus(403);
res.getWriter().write(mapper.writeValueAsString(new JsonResponse()
.add("timestamp", System.currentTimeMillis())
.add("status", 403)
.add("message", "Access denied")));
}
}
并将其添加到 WebConfig 类中
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {
private UserDetailsService userDetailsService;
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
public WebSecurity(UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
this.userDetailsService = userDetailsService;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.POST, REGISTER_URL).permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling().accessDeniedHandler(accessDeniedHandler())
.and()
.addFilter(new JWTAuthenticationFilter(authenticationManager(), tokenProvider()))
.addFilter(new JWTAuthorizationFilter(authenticationManager(), tokenProvider()));
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}
@Bean
public TokenProvider tokenProvider(){
return new TokenProvider();
}
@Bean
public AccessDeniedHandler accessDeniedHandler(){
return new CustomAccessDeniedHandler();
}
}
尽管如此,我仍然收到默认的拒绝访问响应。调试时我意识到甚至没有调用自定义处理程序的 handle
方法。这是什么情况?
最佳答案
我想我已经解决了这个问题。 我没有创建 AccessDeniedHandler 的实现,而是必须创建一个自定义的 AuthenticationEntryPoint 并将其设置在异常处理中。
WebConfig 现在看起来像这样:
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {
private UserDetailsService userDetailsService;
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
public WebSecurity(UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
this.userDetailsService = userDetailsService;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.POST, REGISTER_URL).permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint())
.and()
.addFilter(new JWTAuthenticationFilter(authenticationManager(), tokenProvider()))
.addFilter(new JWTAuthorizationFilter(authenticationManager(), tokenProvider()));
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}
@Bean
public TokenProvider tokenProvider(){
return new TokenProvider();
}
@Bean
public AuthenticationEntryPoint authenticationEntryPoint(){
return new CustomAuthenticationEntryPoint();
}
}
和 CustomAuthenticationEntryPoint:
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest req, HttpServletResponse res, AuthenticationException authException) throws IOException, ServletException {
res.setContentType("application/json;charset=UTF-8");
res.setStatus(403);
res.getWriter().write(JsonBuilder //my util class for creating json strings
.put("timestamp", DateGenerator.getDate())
.put("status", 403)
.put("message", "Access denied")
.build());
}
}
现在一切如我所愿。
关于java - Spring security - 创建 403 访问被拒绝的自定义响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48306302/