How redirect based on role after authentication with spring security

廉价感情. 提交于 2020-01-23 11:51:29

问题


I use spring security, spring, hibernate and jsf authentication work correctly but it always redirects me to the page home.jsf

I want to manage the access of users after authentication

I want to manage the access of users after authentication

if authority = ROLE_ADMIN redirect ves homeadmin.jsf

if authority = ROLE_RH redirect ves homerh.jsf

if authority = ROLE_EXCUTIVE redirect ves homeex.jsf

if authority = ROLE_MANAGER redirect ves homem.jsf

if authority = ROLE_GP redirect ves homegp.jsf

The autority field in the Collaborateur table

the Colaborateur Class is

private Integer idColaborateur;
    private Rolecol rolecol;
    private String matriculeColaborateur;
    private String nomColaborateur;
    private String prenomColaborateur;
    private String mailColaborateur;
    private String pwdColaboratuer;
    private String loginColaborateur;

    private String adresseColaborateur;
    private Boolean flgSuspendu;
    private Set<HistoriqueNoteObjctif> historiqueNoteObjctifs = new HashSet<HistoriqueNoteObjctif>(
            0);
    private Set<Note> notes = new HashSet<Note>(0);
    private Set<NoteObjectifs> noteObjectifses = new HashSet<NoteObjectifs>(0);
    private Set<CompagneDevaluation> compagneDevaluations = new HashSet<CompagneDevaluation>(
            0);
    private Set<ColaborateurHierarchique> colaborateurHierarchiques = new HashSet<ColaborateurHierarchique>(
            0);
    private String authority;
  //getter and seter

Datasource configuration is in the file applicationContext.xml

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="root" />
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/modulevsql" />
        <property name="password" value="root" />
        <property name="maxStatementsPerConnection" value="0" />
        <property name="maxAdministrativeTaskTime" value="0" />
        <property name="maxConnectionAge" value="0" />
        <property name="maxIdleTime" value="0" />
        <property name="maxIdleTimeExcessConnections" value="0" />
        <property name="maxPoolSize" value="0" />
        <property name="maxStatements" value="0" />
    </bean>

the User Class is

public class User implements UserDetails {


    private static final long serialVersionUID = 1L;
    private String name;
    private String password;
    private Colaborateur user;

    public void setUser(Colaborateur user) {
        this.user = user;
    }

    public User(String name) {
        FacesContext fc=FacesContext.getCurrentInstance();      
        UserBean userBean=(UserBean) fc.getApplication().createValueBinding("#{UserBean}").getValue(fc);

        userBean.chargerUtilisateur(name);
        user = userBean.getUtilisateur();


        System.err.println("USERS    >>> "+user);


        PasswordSupport pswdSupport = new PasswordSupport();

        if (user!=null){

            System.out.println("User.getLogin() :"+user.getLoginColaborateur());
            System.out.println("user.getPwd() :"+user.getPwdColaboratuer());
            this.name=user.getMatriculeColaborateur();
            this.password=user.getPwdColaboratuer();
            System.err.println(pswdSupport.getMD5Hash("1"));
        }
    }


    public Collection<GrantedAuthority> getAuthorities() {

        List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();



        System.out.println("GrantedAuthorityImpl  1");
        System.out.println("GrantedAuthorityImpl  2");
        System.out.println("GrantedAuthorityImpl  3");
        System.out.println("GrantedAuthorityImpl  4");

        grantedAuthorities.add(new GrantedAuthorityImpl("ROLE_VISITEUR"));


        return grantedAuthorities;
    }
           //getter and setter

and this is applicationContext-security.xml file

<?xml version="1.0" encoding="UTF-8"?>

<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"
             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">

      <global-method-security secured-annotations="enabled">
      </global-method-security>


      <http pattern="/modules/members/**" access-denied-page="/modules/members/accessDenied.jsf" authentication-manager-ref="MembersAuthenticationManager">

              <intercept-url pattern="/modules/members/secure/**" access="ROLE_VISITEUR" /> 
            <intercept-url pattern="/modules/members/secure/homeadmin.jsf" access="ROLE_ADMIN" />

            <intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />

            <form-login login-page="/modules/members/login.jsf"
                   default-target-url="/modules/members/secure/home.jsf" 
                  login-processing-url="/modules/members/j_spring_security_check"
                  authentication-failure-url="/modules/members/login.jsf" /> 
            <logout logout-url="/modules/members/secure/logout"
                  logout-success-url="/modules/members/login.jsf" delete-cookies="true" />

      </http>


      <authentication-manager alias="MembersAuthenticationManager">
            <authentication-provider user-service-ref="securityManager">
                  <password-encoder hash="md5" />
            </authentication-provider>
      </authentication-manager>
      <beans:bean id="securityManager" class="tn.com.security.SecurityManager" />

</beans:beans>

回答1:


Implement an AuthenticationSuccessHandler and redirect based on the collection of GrantedAuthority objects that's contained within the Authentication that you get passed in.

public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException, ServletException {
            /* Redirect on the successful authentication of the user */
            logger.info("Hit the AuthSuccessHandler");
            String redirectAddress = null;
            Collection<? extends GrantedAuthority> auths = authResult.getAuthorities();
            if(auths.contains("ROLE_ADMIN"){
                response.sendRedirect(response.encodeURL("homeadmin.jsf");
            }

etc etc etc.

You could even add your roles to an Enum and write a switch statement to determine the redirect location.

Make sure you declare your AuthenticationSuccessHandler in your Security Config

<beans:bean id="customAuthenticationSuccessHandler" class="foo.bar.CustomAuthenticationSuccessHandler" /> 

<form-login login-page="/LoginView"
        authentication-success-handler-ref="customAuthenticationSuccessHandler" 
        authentication-failure-url="/FailedLogin" />



回答2:


The answer given by JamesENL is correct but with one mention:
You need to iterate over the collection of GrantedAuthority and only afterwards check for the ROLE:

 Collection<? extends GrantedAuthority> authorities = authResult.getAuthorities();
      for (GrantedAuthority grantedAuthority : authorities) {
            if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
                response.sendRedirect("/userHome);
                return;
            } else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
               response.sendRedirect("/adminHome);
               return;
            }
        }


来源:https://stackoverflow.com/questions/23642325/how-redirect-based-on-role-after-authentication-with-spring-security

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!