小心
默认情况下401
,当spring-boot-starter-security
被添加为依赖项并执行未经授权的请求时, Spring Boot 2 将返回。
如果您放置一些自定义配置来修改安全机制行为,这可能会改变。如果是这种情况并且您确实需要强制401
状态,请阅读以下原始帖子。
原帖
该类org.springframework.boot.autoconfigure.security.Http401AuthenticationEntryPoint
被删除以支持org.springframework.security.web.authentication.HttpStatusEntryPoint
.
在我的情况下,代码将如下所示:
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//...
http.exceptionHandling()
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
//...
}
}
奖金
如果您需要在响应正文中返回一些信息或以某种方式自定义响应,您可以执行以下操作:
1- 扩展AuthenticationEntryPoint
public class MyEntryPoint implements AuthenticationEntryPoint {
private final HttpStatus httpStatus;
private final Object responseBody;
public MyEntryPoint(HttpStatus httpStatus, Object responseBody) {
Assert.notNull(httpStatus, "httpStatus cannot be null");
Assert.notNull(responseBody, "responseBody cannot be null");
this.httpStatus = httpStatus;
this.responseBody = responseBody;
}
@Override
public final void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
response.setStatus(httpStatus.value());
try (PrintWriter writer = response.getWriter()) {
writer.print(new ObjectMapper().writeValueAsString(responseBody));
}
}
}
2-提供MyEntryPoint
安全配置的实例
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// customize your response body as needed
Map<String, String> responseBody = new HashMap<>();
responseBody.put("error", "unauthorized");
//...
http.exceptionHandling()
.authenticationEntryPoint(new MyEntryPoint(HttpStatus.UNAUTHORIZED, responseBody));
//...
}
}