使用Spring Security进行身份验证后如何根据角色进行重定向 [英] How can redirect based on role after authentication with spring security

查看:78
本文介绍了使用Spring Security进行身份验证后如何根据角色进行重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用spring安全性,spring,hibernate和jsf身份验证可以正常工作,但是它始终将我重定向到home.jsf页面

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

如果权限= ROLE_ADMIN重定向ves homeadmin.jsf

if authority = ROLE_ADMIN redirect ves homeadmin.jsf

如果权限= ROLE_RH,则重定向ves homerh.jsf

if authority = ROLE_RH redirect ves homerh.jsf

如果权限= ROLE_EXCUTIVE重定向ves homeex.jsf

if authority = ROLE_EXCUTIVE redirect ves homeex.jsf

如果权限= ROLE_MANAGER重定向ves homem.jsf

if authority = ROLE_MANAGER redirect ves homem.jsf

如果权限= ROLE_GP重定向ves homegp.jsf

if authority = ROLE_GP redirect ves homegp.jsf

Collaborateur表中的autority字段

The autority field in the Collaborateur table

Collaborateur班是

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

数据源配置位于文件applicationContext.xml

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>

用户类别为

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

这是applicationContext-security.xml文件

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>

这是MyAuthSuccessHandler类

and this is MyAuthSuccessHandler class

@Component
public class MyAuthSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    //    @Autowired
    //    private UserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {

        //        // changeLastLoginTime(username)
        // userService.changeLastLoginTime(authentication.getName());

        setDefaultTargetUrl("/modules/members/secure/home.jsf");

        super.onAuthenticationSuccess(request, response, authentication);
    }


    protected boolean hasRole(String role) {
        // get security context from thread local
        SecurityContext context = SecurityContextHolder.getContext();
        if (context == null)
            return false;

        Authentication authentication = context.getAuthentication();
        if (authentication == null)
            return false;

        for (GrantedAuthority auth : authentication.getAuthorities()) {
            if (role.equals(auth.getAuthority()))
                return true;
        }

        return false;
    }
}

如何更新类MyAuthSuccessHandler,USer和applicationContext.xml文件 认证后管理用户的访问权限

how I can update the class MyAuthSuccessHandler ,USer and applicationContext.xml file to manage the access of users after authentication

如果权限= ROLE_ADMIN重定向ves homeadmin.jsf

if authority = ROLE_ADMIN redirect ves homeadmin.jsf

如果权限= ROLE_RH,则重定向ves homerh.jsf

if authority = ROLE_RH redirect ves homerh.jsf

如果权限= ROLE_EXCUTIVE重定向ves homeex.jsf

if authority = ROLE_EXCUTIVE redirect ves homeex.jsf

如果权限= ROLE_MANAGER重定向ves homem.jsf

if authority = ROLE_MANAGER redirect ves homem.jsf

如果权限= ROLE_GP重定向ves homegp.jsf

if authority = ROLE_GP redirect ves homegp.jsf  

这是UserBean类

this is UserBean class

@Component("UserBean")
@Scope("session")
public final class UserBean implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Autowired
    private Colaborateurservice colaborateurservice;

    private Colaborateur utilisateur;

    public UserBean() {
        super();
        // TODO Auto-generated constructor stub
    }

    @PostConstruct
    public void initiate() {

        try {

        } catch (Exception e) {
            e.printStackTrace();

        }

    }

    public void testBean() {
        System.out.println("testBean");

    }

    public void chargerParametreGlob() {

        try {

            System.out.println("chargerParametreGlob  ");

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void chargerUtilisateur(String login) {
        System.out.println(login);
        try {

            utilisateur = new Colaborateur();
            List<Colaborateur> list = colaborateurservice
                    .findByMatriculeColaborateurlo(login);

            System.out.println(list);

            if (list.size() > 0) {

                this.utilisateur = (Colaborateur) list.get(0);
                System.out.println("utilisateur.getLogin() :"
                        + utilisateur.getMatriculeColaborateur());

                System.out.println("utilisateur.getPwd() :"
                        + utilisateur.getLoginColaborateur().length());
            }

        } catch (Exception e) {
            e.printStackTrace();

        }

    }

    public String logout() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) context.getExternalContext()
                .getSession(true);
        if (session == null) {
            return "logout";
        } else {
            session.invalidate();
            return "logout";
        }
    }

    public void setUtilisateur(Colaborateur utilisateur) {
        this.utilisateur = utilisateur;
    }

    public Colaborateur getUtilisateur() {
        return utilisateur;
    }

}

推荐答案

您正在扩展AuthenticationSuccessHandler,它实际上并不能通过调用super.onAuthenticationSuccess()来帮助您.

You are extending out an AuthenticationSuccessHandler, its not really going to help you by calling super.onAuthenticationSuccess().

请尝试以下操作:

public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authResult){
        Collection<? extends GrantedAuthority> auths = authResult.getAuthorities();
        for (GrantedAuthority authorities : auths)
        {
            if (authorities.getAuthority().equals("ROLE_ADMIN")){
                response.sendRedirect(response.encodeURL("homeadmin.jsf");
            }
            else if(authorities.getAuthority().equals("ROLE_RH")){
                response.sendRedirect(response.encodeURL("homerh.jsf");
        .  .  .
           //Repeat pattern until all roles checked
        }

,然后将您的配置更改为:

and then change your config to:

<http pattern="/modules/members/**" 
    <!-- Pass in a reference to your customAuthenticationSuccessHandler -->
    authentication-success-handler-ref="customAuthenticationSuccessHandler"
    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>

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

扩展SimpleUrlAuthenticationSuccessHandler几乎是没有意义的,因为您无法设置希望超类发送到的位置.您也可以实现AuthenticationSuccessHandler接口,并将您的自定义实现传递给Spring Security.

Extending out SimpleUrlAuthenticationSuccessHandler is almost pointless, because you can't set where you want the superclass to send you to. You may as well implement the AuthenticationSuccessHandler interface and pass your custom implementation into Spring Security.

此外,由于您正在实现接口,因此可以将任何服务类自动连接到其中.

Also because you are implementing an interface, you can autowire any of your service classes in.

我自己使用了此方法,并且假设每个用户只有一个角色,它可以正常工作.如果用户具有多个角色,他们将被重定向到找到的第一个角色.您可能希望对if语句进行排序,以便将用户发送到责任最少的区域.

I've used this method myself and it works fine, assuming that each user has only 1 role. If a user has more than one role, they will be redirected to the first role found. You may wish to order your if statements so that the user gets sent to the area with the least responsibility.

这篇关于使用Spring Security进行身份验证后如何根据角色进行重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆