首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AuthenticationEntryPoint Spring Boot 2

AuthenticationEntryPoint Spring Boot 2
EN

Stack Overflow用户
提问于 2018-04-20 16:37:07
回答 3查看 11.2K关注 0票数 3

我正在尝试在我的WebSecurityConfig配置方法中实现Spring Boot2中的自定义AuthenticationEntryPoint。

我见过很多这样的例子:

代码语言:javascript
复制
@Component
public class Http401UnauthorizedEntryPoint implements AuthenticationEntryPoint {

private final Logger log = LoggerFactory.getLogger(Http401UnauthorizedEntryPoint.class);

/**
 * Always returns a 401 error code to the client.
 */
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2) throws IOException,
        ServletException {

    log.debug("Pre-authenticated entry point called. Rejecting access");
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access Denied");
}
}

但我总是得到403分而不是401分。

我如何在Spring boot2中做到这一点?

EN

回答 3

Stack Overflow用户

发布于 2018-10-25 18:24:48

看看我的答案:https://stackoverflow.com/a/52986942/3437868https://stackoverflow.com/a/52986779/3437868

简而言之:从Spring Boot2开始,Http401AuthenticationEntryPoint类已经被移除(参见Spring Boot Issue 10725)。

使用带有HttpStatus.UNAUTHORIZED的HttpStatusEntryPoint而不是Http401AuthenticationEntryPoint:

代码语言:javascript
复制
http.exceptionHandling()
    .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
票数 5
EN

Stack Overflow用户

发布于 2018-10-17 17:26:40

我使用的是Spring boot 1.5,也许它不适合这种情况,但我仍然希望这能对你有所帮助。

在创建Http401UnauthorizedEntryPoint bean之后,您应该将其配置到Spring Security中。

代码语言:javascript
复制
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/api/login").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().disable()
                .httpBasic().disable()
                .logout().disable()
                .csrf().disable()

                // look here,bro
                .exceptionHandling()
                .authenticationEntryPoint(new Http401AuthenticationEntryPoint(""))
        ;
    }

那么入口点应该可以工作了。

实际上,Spring已经为您提供了许多入口点beans.Just,如"Http401AuthenticationEntryPoint“,它们也可以解决您自己创建bean的即时问题。

票数 1
EN

Stack Overflow用户

发布于 2018-10-29 17:44:39

您可以创建一个扩展WebSecurityConfigurerAdapter的类。然后从AuthenticationEntryPoint实现自动连接的Http401UnauthorizedEntryPoint类。您可以参考以下内容:

代码语言:javascript
复制
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private Http401UnauthorizedEntryPoint authenticationEntryPoint;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint)


    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49937472

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档