Rab*_*tha 8 java spring-security jwt spring-boot
我想知道是否可以自定义以下禁止的 JSON 错误:
实际反应
{
"timestamp": "2018-09-26T06:11:05.047+0000",
"status": 403,
"error": "Forbidden",
"message": "Access Denied",
"path": "/api/rest/hello/me"
}
Run Code Online (Sandbox Code Playgroud)
自定义响应 - 当用户请求没有权限时我会收到它。
{
"code": 403,
"message": "Access denied by the system",
"status": "Failure"
}
Run Code Online (Sandbox Code Playgroud)
我的网络安全课程
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtTokenProvider jwtTokenProvider;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.authorizeRequests()//
.antMatchers("/rest/hello/signin").permitAll()//
.anyRequest().authenticated();
http.apply(new JwtTokenFilterConfigurer(jwtTokenProvider));
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用Jackson ObjectMapper创建自定义处理程序,如下所示:
@Bean
public AccessDeniedHandler accessDeniedHandler() {
return (request, response, ex) -> {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
ServletOutputStream out = response.getOutputStream();
new ObjectMapper().writeValue(out, new MyCustomErrorDTO());
out.flush();
};
}
Run Code Online (Sandbox Code Playgroud)
并像这样配置你的HttpSecurity:
http.exceptionHandling().accessDeniedHandler(accessDeniedHandler());
Run Code Online (Sandbox Code Playgroud)
另外,你可以尝试抛出AuthenticationException:
@Bean
public AuthenticationFailureHandler failureHandler() {
return (request, response, ex) -> { throw ex; };
}
Run Code Online (Sandbox Code Playgroud)
并处理它们@RestControllerAdvice:
@RestControllerAdvice
public class AdviseController {
@ExceptionHandler(AuthenticationException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
public MyCustomErrorDTO handleAuthenticationException(AuthenticationException ex) {
return new MyCustomErrorDTO();
}
}
Run Code Online (Sandbox Code Playgroud)
但我不确定它是否有效,你可以检查一下。
为了显示自定义消息,我为 JWT Security 创建了入口点类 JwtAuthenticationEntryPoint。
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationEntryPoint.class);
@Override
public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
AuthenticationException e) throws IOException, ServletException {
logger.error("Responding with unauthorized error. Message - {}", e.getMessage());
httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED,
"Sorry, You're not authorized to access this resource.");
}
}
Run Code Online (Sandbox Code Playgroud)
并作为入口点传递给安全配置,例如,
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
.antMatchers("auth/singIn" , "auth/singUp/")
.permitAll().anyRequest().authenticated();
}
}
Run Code Online (Sandbox Code Playgroud)
或者您可以使用@ControllerAdvice和自定义异常处理来处理自定义或系统异常
| 归档时间: |
|
| 查看次数: |
6319 次 |
| 最近记录: |