小编典典

如何在不配置XML的情况下定义自定义AuthenticationEntryPoint

spring-boot

我已经挣扎了几天。我在Spring Boot中是新手,并且喜欢不使用XML配置的想法。

我创建了一个RESTfull应用程序(带有JSON)。

我认为我设法使用Java配置重现了几乎所有配置,除了一件事- AuthenticationEntryPoint

本教程使用这样的http标记中的属性,并通过以下方式定义 formLogin

<http entry-point-ref="restAuthenticationEntryPoint">

  <intercept-url pattern="/api/admin/**" access="ROLE_ADMIN"/>

  <form-login
     authentication-success-handler-ref="mySuccessHandler"
     authentication-failure-handler-ref="myFailureHandler"
  />

  <logout />

</http>

Spring Security手册中
AuthenticationEntryPoint 解释说:

可以使用元素上的entry-point-ref属性来设置AuthenticationEntryPoint。

没有提及有关如何使用Java Configuration进行操作的任何内容。

那么,如何restAuthenticationEntryPoint在不使用XML 的情况下“注册”自己的XML以防止在使用 formLogin
时重定向到登录表单?

下面我将提到我尝试过的。

谢谢你们。


在我的尝试中,发现您可以使用 basicAuth 定义它,如下所示:

@Configuration
@Order(1)                                                        
public static class RestWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

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


        if (restAuthenticationEntryPoint == null) {
            restAuthenticationEntryPoint = new RestAuthenticationEntryPoint();
        }

        http
            .authorizeRequests()
                .antMatchers("/**").hasAnyRole(Sec.ADMIN,Sec.SUPER_USER)
...
        .and()
            .httpBasic()
                .authenticationEntryPoint(restAuthenticationEntryPoint)

但是我正在使用这样的表单登录名(没有 httpBasic 部分):

        .and()
            .formLogin()
                .successHandler(mySavedRequestAwareAuthenticationSuccessHandler)
                .failureHandler(simpleUrlAuthenticationFailureHandler)

问题在于,当它没有收到凭据时,它将重定向到登录表单。由于这是REST服务,因此不应该。

文件FormLoginConfigurer(类.formLogin()用途)说:

创建共享对象

填充以下共享库

AuthenticationEntryPoint

但是找不到替代它的方法。
有任何想法吗?

PS
不要以为将登录表单替换为仅返回错误的自定义表单是一个好主意。


阅读 636

收藏
2020-05-30

共1个答案

小编典典

您提供的参考文档中的报价将您指向http.exceptionHandling()。您可以在那里设置共享入口点。

http.exceptionHandling().authenticationEntryPoint(myEntryPoint);
2020-05-30