使用Spring Boot 2的401而不是403

随着spring引导 1.5.6.RELEASE我能够发送HTTP状态代码401,而不是403在描述如何让春天的安全响应未经授权(HTTP 401码)如果请求URI不进行认证,这样做:

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" title="Spring Boot">Spring Boot 2.0.0.RELEASE,发现不再有此类(至少在该软件包中)。

问题:

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

  • 如果不是,那么在现有项目中保持相同行为,以便与依赖于此状态代码(401)而不是其他状态的其他实现保持一致的最佳选择是403什么?

回答:

默认情况下, Spring Boot 2将401spring-boot-starter-security添加为依赖项并执行未授权的请求时返回。

如果你放置一些自定义配置来修改安全机制行为,则可能会更改。如果是这种情况,并且你确实需要强制执行该401状态,请阅读以下原始帖子。

Original Post

The classorg.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));

//...

}

}

Bonus

如果你需要在响应正文中返回一些信息或以某种方式自定义响应,则可以执行以下操作:

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));

//...

}

}

以上是 使用Spring Boot 2的401而不是403 的全部内容, 来源链接: utcz.com/qa/418507.html

回到顶部