dud*_*nii 9 java rest spring httpresponse spring-security
我有一个带有jwt身份验证的spring boot rest api.问题是我无法摆脱默认的403 Access Denied rest响应,如下所示:
{
"timestamp": 1516206966541,
"status": 403,
"error": "Forbidden",
"message": "Access Denied",
"path": "/api/items/2"
}
Run Code Online (Sandbox Code Playgroud)
我创建了自定义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")));
}
}
Run Code Online (Sandbox Code Playgroud)
并将其添加到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();
}
}
Run Code Online (Sandbox Code Playgroud)
尽管如此,我仍然得到默认的拒绝访问响应.调试时我意识到handle
自定义处理程序的方法甚至没有被调用.这是怎么回事?
dud*_*nii 15
我想我解决了这个问题。我没有创建 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();
}
}
Run Code Online (Sandbox Code Playgroud)
和 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());
}
}
Run Code Online (Sandbox Code Playgroud)
现在一切都如我所愿。
小智 7
我有同样的问题并试图按照正确的答案解决,但它没有解决问题。处理此问题的最佳方法是实现自定义访问被拒绝处理程序。AuthenticationEntryPoint 实现最好处理 401、UNAUTHORIZED 访问和 AccessDeniedHandler 实现用于 403、FORBIDDEN 访问。
将实现类中的 AccessDeniedHandler 方法重写为:
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.getWriter().write("Access Denied... Forbidden");
}
Run Code Online (Sandbox Code Playgroud)
并在您的安全配置中添加这个自定义访问被拒绝处理程序,如下所示:
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint())
.accessDeniedHandler(accessDeniedHandler())
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8880 次 |
最近记录: |