AUTHENTICATION-FAILURE-URL

mary87

Nuovo Utente
2
0
Buon pomeriggio,
sto implementando un progetto con Spring Security e Hibernate che semplicemente ha una pagina di registrazione e una di login.
la mia pagina di login non funziona come dovrebbe...
L'utente esiste nel database e userDetailsService me lo trova ma vengo sempre reindirizzata nella pagina di login con un errore...

il mio file application-springsecurity.xml è:

Codice:
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
        xmlns:security="http://www.springframework.org/schema/security"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    
    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.0.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/security 
            http://www.springframework.org/schema/security/spring-security-3.0.xsd
            http://www.springframework.org/schema/mvc 
            http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
            http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">




<!-- A custom service where Spring will retrieve users and their corresponding access levels  -->
    <beans:bean id="customUserDetailsService" class="main.esempio.service.CustomUserDetailsService"/>
    




    
<security:http auto-config="true" use-expressions="true" access-denied-page="/denied" >
    
        <security:intercept-url pattern="/login" access="permitAll"/>
        <security:intercept-url pattern="/common" access="hasRole('ROLE_USER')"/>
        
        <security:form-login
                login-page="/login" 
                authentication-failure-url="/login?error=true" 
                default-target-url="/common"
                login-processing-url="/j_spring_security_check"/>
            
        <security:logout 
                invalidate-session="true" 
                logout-success-url="/login" 
                logout-url="/logout"/>
    
    </security:http>
    
    <!-- Declare an authentication-manager to use a custom userDetailsService -->
    <security:authentication-manager>
            <security:authentication-provider user-service-ref="customUserDetailsService">
                    <security:password-encoder ref="passwordEncoder"/>
            </security:authentication-provider>
    </security:authentication-manager>
    
    <!-- Use a Md5 encoder since the user's passwords are stored as Md5 in the database -->
    <beans:bean class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" id="passwordEncoder"/>


 
      
    <!-- Activates various annotations to be detected in bean classes -->
    <context:annotation-config />
    
    <!-- Scans the classpath for annotated components that will be auto-registered as Spring beans.
     For example @Controller and [MENTION=41682]ser[/MENTION]vice. Make sure to set the correct base-package-->
    <context:component-scan base-package="main.esempio" />
    
        
</beans:beans>

la classe che implementa userDetailsService è:



Codice:
package main.esempio.service;




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


import main.esempio.dominio.Utenti;




import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import main.esempio.dao.UtentiDAO;


/**
 * A custom service for retrieving users from a custom datasource, such as a database.
 * <p>
 * This custom service must implement Spring's {@link UserDetailsService}
 */ [MENTION=41682]ser[/MENTION]vice
@Transactional
public class CustomUserDetailsService implements UserDetailsService {
    


    @Autowired
    private UtentiDAO userDAO ;
    
    /**
     * Retrieves a user record containing the user's credentials and access. 
     */


    
    /**
     * Retrieves the correct ROLE type depending on the access level, where access level is an Integer.
     * Basically, this interprets the access value whether it's for a regular user or admin.
     * 
     * [MENTION=128354]Para[/MENTION]m access an integer value representing the access of the user
     * @return collection of granted authorities
     */
     public Collection<GrantedAuthority> getAuthorities(Integer access) 
     {
         System.out.println("sono in getAutority");
            // Create a list of grants for this user
            List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);
            
            // All users are granted with ROLE_USER access
            // Therefore this user gets a ROLE_USER by default
            authList.add(new GrantedAuthorityImpl("ROLE_USER"));
            
            // Check if this user has admin access 
            // We interpret Integer(1) as an admin user
            if ( access.compareTo(1) == 0) {
                // User has admin access
                authList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
            }


            // Return list of granted authorities
            return authList;
      }


    [MENTION=75845]Override[/MENTION]
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException, DataAccessException
            {
        System.out.println("sono in loadUserByUsername ");
        // TODO Auto-generated method stub
        // Declare a null Spring User
                UserDetails user = null;
                
                try {
                    
                    // 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
                    Utenti utenti = userDAO.findUtente(username);
                    // Populate the Spring User object with details from the dbUser
                    // Here we just pass the username, password, and access level
                    // getAuthorities() will translate the access level to the correct role type
                    System.out.println("sono nel try");
                    user =  new User(
                            utenti.getUtentiName(), 
                            utenti.getPassword().toLowerCase(),
                            true,
                            true,
                            true,
                            true,
                            getAuthorities(utenti.getAccess()) );
                    


                } catch (Exception e) {
                    throw new UsernameNotFoundException("Error in retrieving user");
                }
                
                // Return user to Spring for processing.
                // Take note we're not the one evaluating whether this user is authenticated or valid
                // We just merely retrieve a user that matches the specified username
                System.out.println("ritorno l'utente trovato");
                System.out.println("l'utente trovato ha autority"+user.getAuthorities().toString());
                return user;
    }
}



e il mio login logout controller è:

Codice:
package main.esempio.controller;




import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;


/**
 * Handles and retrieves the login or denied page depending on the URI template
 */
@Controller
public class LoginLogoutController {
        


    /**
     * Handles and retrieves the login JSP page
     * 
     * @return the name of the JSP page
     */
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String getLoginPage(@RequestParam(value="error", required=false) boolean error, 
            ModelMap model) {


        // Add an error message to the model if login is unsuccessful
        // The 'error' parameter is set to true based on the when the authentication has failed. 
        // We declared this under the authentication-failure-url attribute inside the spring-security.xml
        /* See below:
         <form-login 
                login-page="/auth/login" 
                authentication-failure-url="/auth/login?error=true" 
                default-target-url="/main/common"/>
         */
        //System.out.println("l'errore è "+logger.getAdditivity());
        System.out.println("sono in loginlogoutController ");
        
        System.out.println("il modello è"+model.toString());
        if (error == true) {
            //logger.setAdditivity(false);    
            System.out.println("l'errore c'è");
            // Assign an error message
            model.put("error", "Utente non valido Riprovare");
        } else {
            System.out.println("non c'è errore");
            model.put("error", "");
            //return "common";
        }
        System.out.println("ritorno login");
        // This will resolve to /WEB-INF/jsp/loginpage.jsp
        return "login";
    }


    
    
    /**
     * Handles and retrieves the denied JSP page. This is shown whenever a regular user
     * tries to access an admin only page.
     * 
     * @return the name of the JSP page
     */
    @RequestMapping(value = "denied", method = RequestMethod.GET)
     public String getDeniedPage() {
        
        System.out.println("sono in denied e ritorno denied");
        // This will resolve to /WEB-INF/jsp/deniedpage.jsp
        return "deniedpage";
    }
}

qualcuno mi sa spiegare perchè non entro mai in /common e vado sempre in authentication-failure-url="/login?error=true" ????

 

Entra

oppure Accedi utilizzando

Discussioni Simili