注意
默认情况下,当添加spring-boot-starter-security
作为依赖项并执行未经授权的请求时,Spring Boot 2将返回401
。
如果您需要更改安全机制行为以进行自定义配置,则可能会更改这种情况。如果是这种情况,并且您确实需要强制使用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 {
Map<String, String> responseBody = new HashMap<>();
responseBody.put("error", "unauthorized");
http.exceptionHandling()
.authenticationEntryPoint(new MyEntryPoint(HttpStatus.UNAUTHORIZED, responseBody));
}
}