Fournisseur d’authentification de sécurité Spring

Fournisseur d'authentification de sécurité Spring

1. Vue d'ensemble

Ce tutoriel montrera comment configurer unAuthentication Provider in Spring Security pour permettre une flexibilité supplémentaire par rapport au scénario standard utilisant un simpleUserDetailsService.

2. Le fournisseur d'authentification

Spring Security propose diverses options pour effectuer l'authentification. Ceux-ci suivent un simple contrat -an Authentication request is processed by an AuthenticationProvider et un objet entièrement authentifié avec des informations d'identification complètes est renvoyé.

L'implémentation standard et la plus courante est leDaoAuthenticationProvider - qui récupère les détails de l'utilisateur à partir d'un simple utilisateur DAO en lecture seule - leUserDetailsService. Ce service de détails utilisateuronly has access to the username afin de récupérer l'entité utilisateur complète. Cela suffit pour la plupart des scénarios.

D'autres scénarios personnalisés devront toujours accéder à la requêteAuthentication complète pour pouvoir effectuer le processus d'authentification. Par exemple, lors de l'authentification auprès d'un service tiers externe (tel queCrowd) -both the username and the password from the authentication request will be necessary.

Pour ces scénarios plus avancés, nous devronsdefine a custom Authentication Provider:

@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()) {

            // 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);
    }
}

Notez que les droits accordés définis sur l'objetAuthentication renvoyé sont vides. C'est parce que les autorités sont bien sûr spécifiques à l'application.

3. Enregistrer le fournisseur d'authentification

Maintenant que nous avons défini le fournisseur d'authentification, nous devons le spécifier dans la configuration de sécurité XML, en utilisant la prise en charge des espaces de noms disponibles:


    
    



    

4. Configuration Java

Voyons ensuite la configuration Java correspondante:

@Configuration
@EnableWebSecurity
@ComponentScan("org.example.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();
    }
}

5. Exécution de l'authentification

La demande d'authentification du client est fondamentalement la même avec ou sans ce fournisseur d'authentification personnalisé sur le serveur principal.

Utilisons une simple commandecurl pour envoyer une requête authentifiée:

curl --header "Accept:application/json" -i --user user1:user1Pass
    http://localhost:8080/spring-security-custom/api/foo/1

Pour les besoins de cet exemple, nous avons sécurisé l'API REST avec l'authentification de base.

Et nous récupérons les 200 OK attendus du serveur:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=B8F0EFA81B78DE968088EBB9AFD85A60; Path=/spring-security-custom/; HttpOnly
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Sun, 02 Jun 2013 17:50:40 GMT

6. Conclusion

Dans cet article, nous avons présenté un exemple de fournisseur d'authentification personnalisé pour Spring Security.

L'implémentation complète de ce didacticiel se trouve dansthe GitHub project.