2016-04-19 3 views
7

Ich versuche, eine REST-basierte Webanwendung einzurichten, in der das Frontend Reactjs verwendet und das Back-End Spring Boot verwendet. Ich versuche auch, einen benutzerdefinierten Authentifizierungsanbieter einzurichten, und hier beginnen meine Probleme. Beim Versuch, den Login-API-Aufruf zu testen, wird der CustomAuthenticationProvider nie aufgerufen, stattdessen wird der Standard-DaoAuthenticationProvider verwendet. Dies führt dazu, dass der Login "Bad credentials" meldet.Spring Boot Benutzerdefinierter Authentifizierungsanbieter mit Java-Konfiguration FIXED

Ich lade haben eine kleine Beispielanwendung auf GitHub: spring-boot-auth-demo

die Login-API Um zu testen, ich folgende curl verwenden:

curl -H "Content-Type: application/json" -X POST -d '{"username":"admin","password":"admin"}' http://localhost:8080/api/users/login 

Die CustomAuthenticationProvider hat einen einfachen Benutzernamen/Passwort-Check und gibt eine UsernamePasswordAuthenicationToken Objekt.

package no.bluebit.demo; 

import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.security.authentication.AuthenticationProvider; 
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 
import org.springframework.security.core.Authentication; 
import org.springframework.security.core.AuthenticationException; 
import org.springframework.security.core.GrantedAuthority; 
import org.springframework.security.core.authority.SimpleGrantedAuthority; 
import org.springframework.stereotype.Component; 

import java.util.ArrayList; 
import java.util.List; 

@Component 
public class CustomAuthenticationProvider implements AuthenticationProvider { 

private static final Logger logger =  LoggerFactory.getLogger(CustomAuthenticationProvider.class); 

public CustomAuthenticationProvider() { 
    logger.info("*** CustomAuthenticationProvider created"); 
} 

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

    if(authentication.getName().equals("admin") && authentication.getCredentials().equals("admin")) { 
     List<GrantedAuthority> grantedAuths = new ArrayList<>(); 
     grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER")); 
     grantedAuths.add(new SimpleGrantedAuthority("ROLE_ADMIN")); 
     return new UsernamePasswordAuthenticationToken(authentication.getName(), authentication.getCredentials(), grantedAuths); 
    } else { 
     return null; 
    } 

} 

@Override 
public boolean supports(Class<?> authentication) { 
    return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication); 
} 

} 

Der CustomAuthenticationProvider wird mit der SecurityConfiguration-Klasse verdrahtet. Beim Durchlaufen des Codes kann ich sehen, dass sich der CustomAuthenicationProvider nicht in der Liste der Provider befindet, die zur Authentifizierung der eingehenden Anfrage verwendet werden.

package no.bluebit.demo; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 
import org.springframework.security.config.annotation.web.builders.HttpSecurity; 
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 

@Configuration 
@EnableWebSecurity 
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) 
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 
    @Autowired 
    private CustomAuthenticationProvider customAuthenticationProvider; 

    @Autowired 
    @Override 
    protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
     auth 
      .authenticationProvider(this.customAuthenticationProvider); 
    } 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
      .authorizeRequests() 
       .antMatchers("/api/users/login").permitAll() // Permit access for all to login REST service 
       .antMatchers("/").permitAll()     // Neccessary to permit access to default document 
      .anyRequest().authenticated().and()     // All other requests require authentication 
      .httpBasic().and() 
      .logout().and() 
      .csrf().disable(); 
    } 
} 

Warum funktioniert das nicht?

+1

Werfen Sie einen Blick auf diese: http://stackoverflow.com/questions/22453550/custom-authentication-provider-not-being-called/22457561#22457561 – franDayz

+0

Vielen Dank! Die fehlende @Autowired-Anmerkung war das Problem. Problem gelöst! –

+0

@franDayz vielleicht fügen Sie Ihren Kommentar als Antwort, so dass Håvard Bakke kann als Antwort akzeptieren? – demaniak

Antwort

-1

Blick auf der AuthenticationProvider Klasse (bzw. ist es java doc)

Die Methode authenticate erwartet zu:

* Performs authentication with the same contract as 
* {@link org.springframework.security.authentication.AuthenticationManager#authenticate(Authentication)} 
* @return a fully authenticated object including credentials. May return 
* <code>null</code> if the <code>AuthenticationProvider</code> is unable to support 
* authentication of the passed <code>Authentication</code> object. In such a case, 
* the next <code>AuthenticationProvider</code> that supports the presented 
* <code>Authentication</code> class will be tried. 

Wenn Sie null zurück, dann die nächsten AuthenticationProvider, die die defaut sind aufgerufen werden .

Ich bin mir nicht sicher, dass das das Problem ist, aber das könnte etwas sein. Versuchen BadCredentialsException zu werfen, da die AuthenticationManager Klasse, die Sie zu tun, sagt:

* <li>A {@link BadCredentialsException} must be thrown if incorrect credentials are 
* presented. Whilst the above exceptions are optional, an 
* <code>AuthenticationManager</code> must <B>always</B> test credentials.</li> 
0

Sie haben die Anmeldeinformationen auf andere Weise eingestellt werden. Versuchen Sie, ein funktionierendes Beispiel für Benutzername Passwort Token zu sehen. Ihre "authenticate" -Funktion muss jedoch die Anmeldeinformationen festlegen.