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

ely*_*sch 27 java spring spring-security 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>
Run Code Online (Sandbox Code Playgroud)

Spring Security手册中AuthenticationEntryPoint解释说:

可以使用<http>元素上的entry-point-ref属性设置AuthenticationEntryPoint.

没有提到有关如何使用Java配置执行此操作的任何内容.

那么如何restAuthenticationEntryPoint在没有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)
Run Code Online (Sandbox Code Playgroud)

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

        .and()
            .formLogin()
                .successHandler(mySavedRequestAwareAuthenticationSuccessHandler)
                .failureHandler(simpleUrlAuthenticationFailureHandler)
Run Code Online (Sandbox Code Playgroud)

问题是,当它没有收到凭据时,它会重定向到登录表单.由于这是一个REST服务,它不应该.

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

共享对象已创建

填充以下共享对象

AuthenticationEntryPoint
Run Code Online (Sandbox Code Playgroud)

但是找不到覆盖它的方法.
有任何想法吗?

PS
不要认为将登录表单覆盖到只返回错误的自定义表单是个好主意.

Dav*_*yer 52

您提供的参考文档的引用指向您http.exceptionHandling().您可以在那里设置共享入口点.

http.exceptionHandling().authenticationEntryPoint(myEntryPoint);
Run Code Online (Sandbox Code Playgroud)

  • 我没有按照教程.当你了解API时,它与XML相同,所以我猜,但我打赌你可以在Security ref docs中找到它. (2认同)
  • 似乎Spring Security Reference没有一次提到exceptionHandling()方法,而是将用户留给他自己的设备来解决这个问题. (2认同)
  • 它似乎没有直接出现在参考文献中,但您可以在 Spring 文档中找到几个示例: [示例 1](https://spring.io/guides/tutorials/spring-boot-oauth2) [示例 2]( http://docs.spring.io/spring-security-kerberos/docs/current/reference/htmlsingle/#ssk-spnego) (2认同)