具有Spring Security和Java Config的自定义身份验证提供程序

vde*_*ris 20 spring spring-security spring-java-config

如何使用Spring Security with Java Configurations定义自定义身份验证提供程序?我想在我自己的数据库上执行登录检查凭据.

geo*_*and 43

以下是您需要的(CustomAuthenticationProvider您的实现需要由Spring管理)

@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationProvider customAuthenticationProvider;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /**
         * Do your stuff here
         */
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(customAuthenticationProvider);
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 7

如在baeldung.com所示,定义身份验证提供者,如下所示:

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) 
      throws AuthenticationException {

        String name = authentication.getName();
        String password = authentication.getCredentials().toString();

        if (shouldAuthenticateAgainstThirdPartySystem(username, password)) {

            // use the credentials
            // and authenticate against the third-party system
            return new UsernamePasswordAuthenticationToken(
              name, password, new ArrayList<>());
        } else {
            return null;
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(
          UsernamePasswordAuthenticationToken.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

以下代码是对应的java配置:

@Configuration
@EnableWebSecurity
@ComponentScan("org.project.security")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationProvider authProvider;

    @Override
    protected void configure(
      AuthenticationManagerBuilder auth) throws Exception {

        auth.authenticationProvider(authProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated()
            .and()
            .httpBasic();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 您只是从http://www.baeldung.com/spring-security-authentication-provider复制了该文件。虽然答案肯定会有所帮助,但归因来源也是必要的。 (4认同)