Spring Security 4具有自定义身份验证和本地数据库

时间:2017-02-11 06:47:03

标签: spring-security

Spring Security 4使开发人员能够编写更少的代码,但有时这也会导致事情失控。例如,现在我正在编写一个登录功能,一旦用户按下一个按钮(登录/ unionauth URI),就会启动第三方提供的OAuth 2.0认证,最后结果返回,我们将用户与我们的本地数据库为了做到这一点,首先我有这样的适配器类:

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

        http
            .antMatcher("/**")
            .authorizeRequests()
                .antMatchers("/", "/login**", "/webjars/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .exceptionHandling()
                .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/"))
                .and()
            .logout()
                .logoutSuccessUrl("/").permitAll()
                .and()
            .csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                .and()
            .addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
    }


    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService);
    }

然后我有ssoFilter()这样:

public class UnionAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
        // authentication steps.
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("tom", "N/A", null);
        AuthenticationManager manager = this.getAuthenticationManager();
        return manager.authenticate(token);
    }

现在问题是,经理是null。为什么是null?我认为在密码用户名模式的情况下,适配器中的auth.userDetailsService(myUserDetailsService);将启用DAO管理器。在official website中,它有:

  

如何添加本地用户数据库

     

许多应用程序需要在本地保存有关其用户的数据,即使这样   身份验证委派给外部提供程序。我们没有显示   代码在这里,但很容易分两步完成。

     
      
  1. 为您的数据库选择后端,并设置一些存储库(例如   使用Spring Data)来获得适合您需求的自定义User对象   可以从外部完全或部分填充   认证

  2.   
  3. 为每个登录的唯一用户设置User个对象   检查/user端点中的存储库。如果已经存在了   具有当前Principal标识的用户,可以更新,   否则就创造了。

  4.         

    提示:在User对象中添加一个字段以链接到其中的唯一标识符   外部提供者(不是用户的名字,而是一些东西)   对于外部提供商的帐户而言是唯一的。)

知道如何将数据库添加到Spring Security OAuth2中,或者为什么第一段中的管理器是null

0 个答案:

没有答案