gpt4 book ai didi

java - 401 而不是 403 与 Spring Boot 2

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:30:53 25 4
gpt4 key购买 nike

Spring Boot 1.5.6.RELEASE 我能够发送 HTTP 状态代码 401 而不是 403,如 How let spring security response unauthorized(http 401 code) if requesting uri without authentication 中所述,通过这样做:

public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
//...
http.exceptionHandling()
.authenticationEntryPoint(new Http401AuthenticationEntryPoint("myHeader"));
//...
}
}

使用 org.springframework.boot.autoconfigure.security.Http401AuthenticationEntryPoint 类。

我刚刚升级到 Spring Boot 2.0.0.RELEASE并发现不再有这样的类(至少在那个包中)。

问题:

  • Spring Boot 中是否存在这个类 (Http401AuthenticationEntryPoint)?

  • 如果否,为了与依赖此状态代码 (401) 而不是403


请注意这不同于Spring Security anonymous 401 instead of 403因为它专门指的是 SpringBoot 2(该帖子中的解决方案在 SpringBoot 版本 2 中不再适用,或者根本不需要其他解决方案)

最佳答案

注意

默认情况下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 {
// customize your response body as needed
Map<String, String> responseBody = new HashMap<>();
responseBody.put("error", "unauthorized");

//...
http.exceptionHandling()
.authenticationEntryPoint(new MyEntryPoint(HttpStatus.UNAUTHORIZED, responseBody));
//...
}
}

关于java - 401 而不是 403 与 Spring Boot 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49241384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com