2012-02-29 15 views
10

Utilizzo la sicurezza di primavera con HTTP Basic Auth per proteggere una webapp java. Nella mia webapp ho bisogno di ottenere il nome utente e la password dell'utente corrente per poterli autenticare ulteriormente con un altro servizio. Posso ottenere il nome utente, ma non la password.Richiamare la password dell'utente corrente da spring security

Ho provato a utilizzare SecurityContextHolder.getContext().getAuthentication() per accedere a queste informazioni come suggerito qui How can I get plaintext password from spring-security? ma la password viene restituita come null.

Come posso ottenere la password?

Grazie.

Questo è il mio applicationContext-security.xml

<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:sec="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
     http://www.springframework.org/schema/security 
     http://www.springframework.org/schema/security/spring-security-3.1.xsd"> 

<sec:http authentication-manager-ref='authenticationManager'> 
    <sec:intercept-url pattern="/spring/**" access="ROLE_USER" /> 
    <sec:http-basic /> 
</sec:http> 

<bean id="basicAuthenticationFilter" 
    class="org.springframework.security.web.authentication.www.BasicAuthenticationFilter"> 
    <property name="authenticationManager" ref="authenticationManager" /> 
    <property name="authenticationEntryPoint" ref="authenticationEntryPoint" /> 
</bean> 

<bean id="authenticationEntryPoint" 
    class="org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint"> 
    <property name="realmName" value="Announcements Rest Realm" /> 
</bean> 

<bean id="authenticationManager" 
    class="org.springframework.security.authentication.ProviderManager"> 
    <property name="providers"> 
     <list> 
      <ref local="authProvider" /> 
     </list> 
    </property> 
</bean> 

<bean id="authProvider" 
    class="org.springframework.security.authentication.dao.DaoAuthenticationProvider"> 
    <property name="userDetailsService" ref="userDetailsService" /> 
</bean> 

<bean id="filterChainProxy" class="org.springframework.security.web.FilterChainProxy"> 
    <constructor-arg> 
     <list> 
      <sec:filter-chain pattern="/spring/**" filters="basicAuthenticationFilter" /> 
     </list> 
    </constructor-arg> 
</bean> 

<sec:user-service id="userDetailsService"> 
    <sec:user name="admin" password="**" authorities="ROLE_USER, ROLE_ADMIN" /> 
    <sec:user name="user" password="**" authorities="ROLE_USER" /> 
</sec:user-service> 

risposta

0

Usi ricordati di me/eseguito come/switch user? In tal caso, la password è nullo (come descritto in una discussione che hai menzionato). Inoltre, probabilmente è necessario utilizzare l'autenticazione di base modulo, (richiesta POST al j_spring_security_check)

+0

non sto usando ricordati di me, eseguito come utente o passare, per quanto a mia conoscenza (a meno che siano attivati ​​per impostazione predefinita ? Non sto usando auto-config). Inoltre non posso usare l'autenticazione del modulo in quanto la mia webapp è un servizio web. – ssloan

+0

ok, quindi come informa SI che l'utente è stato autenticato con successo? Se si utilizza SecurityContextHolder.getContext(). SetAuthentication (...), quale tipo di token si passa? –

+0

Non sto chiamando setAuthentication() direttamente - deve essere in corso in uno dei bean che ho configurato. Aggiornerò il mio post con il mio applicationContext-security.xml che aiuta. – ssloan

0

Se si imposta l'intero dettagli dell'utente attuale password nel oggetto della sessione, quindi è possibile ottenere la password da quella oggetto di sessione.

+0

L'unica cosa che è nella sessione è lo stesso oggetto che viene restituito da getAuthentication, e ancora il metodo getcredentials() restituisce null. – ssloan

+1

Questo non funzionerà per impostazione predefinita dalla primavera 3.1 in poi - le credenziali vengono cancellate in caso di autenticazione avvenuta con successo.Vedi http://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#core-services-erasing-credentials –

22

L'ho capito.

ho cambiato Authentication Manager config per usare l'elemento di autenticazione-manager e ha aggiunto l'attributo c'è:

<sec:authentication-manager alias="authenticationManager" erase-credentials="false"> 
    <sec:authentication-provider ref="authProvider" />  
</sec:authentication-manager> 

posso poi usare SecurityContextHolder.getContext().getAuthentication().getCredentials() nella mia classe controller per ottenere la password.

Grazie per il vostro aiuto se Piotrek De

+0

Bella scoperta. Non sapevo su 'erase-credentials =" false "' – cowls

+0

Questo è quello di cui avevo bisogno, anche se sono un po 'preoccupato per i problemi di sicurezza; ma non vedo nessun altro modo sensato per evitare questi problemi. –

+0

Funziona bene anche con il login LDAP. – romhail

0

un modo migliore è quello di implementare il 'userDetailsService'. in modo da poter controllare come gli UserDetails possano essere inseriti quando si esegue l'autenticazione. Ho implementato l'autenticazione basata su form e ho scritto il mio servizio utente self-definito,

@Service("userService") 
public class UserServiceImpl extends GenericService<User> implements UserDetailsService,UserService{ 



    @Override 
     @Transactional 
     public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { 
       // Declare a null Spring User 
      UserDetails userDetails = null; 



      // Search database for a user that matches the specified username 
      // You can provide a custom DAO to access your persistence layer 
      // Or use JDBC to access your database 
      // DbUser is our custom domain user. This is not the same as Spring's User 
      User dbUser=this.findUserByUserName(username); 

      if (dbUser == null) { 
       throw new UsernameNotFoundException("HiMVC Security:: Error in retrieving user(username=" + username + ")"); 
      } 



      userDetails = new org.springframework.security.core.userdetails.User(
        dbUser.getUserName(), 
        dbUser.getPassword(),//here you can put a clear text password 
        true, 
        true, 
        true, 
        true, 
        loadUserAuthorities(username)); 


      return userDetails; 
     } 
Problemi correlati