栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Spring Boot 2的401而不是403

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Spring Boot 2的401而不是403

默认情况下, Spring Boot 2将

401
spring-boot-starter-security
添加为依赖项并执行未授权的请求时返回。

如果你放置一些自定义配置来修改安全机制行为,则可能会更改。如果是这种情况,并且你确实需要强制执行该

401
状态,请阅读以下原始帖子。

Original Post

The class

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));        //...    }}

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));        //...    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/386365.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号