Spring Security检索实现UserDetails的两个方法的当前用户对象

时间:2015-01-23 08:42:00

标签: spring-mvc spring-security

我正在开发一个Spring-MVC项目,我正在使用Spring-Security进行身份验证和其他安全功能。现在项目分为两部分,一部分用于个人登录,另一部分用于登录。 对于他们两个,我使用不同的数据库表。但是这两个表的Java类都有一个UserDetails实例和userDetailsS​​ervice实现。 现在,当用户从个人帐户或组帐户登录时,我想从任一类中提取当前登录的用户对象。这样,我就会知道是否有一个组用户登录或者是个人帐户用户登录。请告诉我该怎么办?

security-application-context.xml:

    <security:http create-session="ifRequired" use-expressions="true"
                   entry-point-ref="loginUrlAuthenticationEntryPoint"
                   auto-config="false" disable-url-rewriting="true">
        <security:logout logout-success-url="/" delete-cookies="JSESSIONID"
                         invalidate-session="true" logout-url="/j_spring_security_logout"/>
        <security:custom-filter ref="CustomUsernamePasswordAuthenticationFilter" position="FORM_LOGIN_FILTER" />
        <security:port-mappings>
            <security:port-mapping http="8080" https="8443"/>
        </security:port-mappings>
    </security:http>

  <bean id="failureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
      <property name="defaultFailureUrl" value="/login.do?error"/>
  </bean>

    <bean id="loginUrlAuthenticationEntryPoint"
          class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
        <property name="loginFormUrl" value="/login.do"/>
    </bean>

    <bean id="authenticationManagerForPersonal" class="com.journaldev.spring.utility.CustomDAOAuthenticationProvider">
        <constructor-arg index="0" value="org.springframework.security.authentication.UsernamePasswordAuthenticationToken"/>
        <property name="userDetailsService" ref="LoginServiceImpl"/>
        <property name="passwordEncoder" ref="encoder"/>
    </bean>

    <bean id="authenticationManagerForGroup" class="com.journaldev.spring.utility.CustomDAOAuthenticationProvider">
        <constructor-arg index="0" value="com.journaldev.spring.utility.CustomUsernamePasswordAuthenticationToken"/>
        <property name="userDetailsService" ref="GroupLoginServiceImpl"/>
        <property name="passwordEncoder" ref="encoder"/>
    </bean>

    <bean id="CustomUsernamePasswordAuthenticationFilter" class="com.journaldev.spring.utility.CustomUsernamePasswordAuthenticationFilter">
        <property name="authenticationManager" ref="authenticationManager"/>
        <property name="authenticationFailureHandler" ref="failureHandler"/>
        <property name="authenticationSuccessHandler" ref="redirectRoleStrategy"/>
    </bean>

    <security:authentication-manager alias="authenticationManager">
        <security:authentication-provider ref="authenticationManagerForPersonal"/>
        <security:authentication-provider ref="authenticationManagerForGroup"/>
    </security:authentication-manager>

    <bean id="redirectRoleStrategy" class="com.journaldev.spring.utility.RoleBasedAuthenticationSuccessHandler">
        <property name="roleUrlMap">
            <map>
                <entry key="ROLE_USER" value="/person.do"/>
                <entry key="ROLE_GROUP" value="/group.do"/>
            </map>
        </property>
    </bean>

    <beans:bean id="encoder"
                class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
        <beans:constructor-arg name="strength" value="11" />
    </beans:bean>

Person.Java(个人账户模型类):

@Entity
@Table(name="person")
public class Person implements UserDetails{

@Id
    @Column(name="id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "person_seq_gen")
    @SequenceGenerator(name = "person_seq_gen",sequenceName = "person_seq")
    private int id;
// other values
}

GroupMember.java(群组帐户成员模型)

@Entity
@Table(name="groupmembers")
public class GroupMembers implements UserDetails {

    private static final GrantedAuthority USER_AUTH = new SimpleGrantedAuthority("ROLE_GROUP");

    @Id
    @Column(name="memberid")
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "groupmembers_seq_gen")
    @SequenceGenerator(name = "groupmembers_seq_gen",sequenceName = "groupmembers_seq")
    private Long memberid;
    // Other values
}

编辑: 这是我检索当前用户的方式,但是我找不到如何检查它是哪个对象,我可以得到一个UserDetails对象,但由于这两个方法都在实现UserDetails,我无法分辨它是哪一个。

  @Override
    public Person getCurrentlyAuthenticatedUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication == null){
            return null;
        } else {
            return personDAO.findPersonByUsername(authentication.getName());
        }
    }

1 个答案:

答案 0 :(得分:1)

我希望这应该很简单。

您有两个UserDetails对象User1和User2,假设User1属于Person类,User2属于GroupPerson。

您可以按照说明获取UserDetails对象,然后您需要做的就是检查对象是Person还是GroupMembers的实例。

您可以使用instanceof执行此操作,如下所示

if(userObject instanceof Person){
 // DO Stuff
}
else if(userObject instanceof GroupMembers){
 // Do Stuff
}

此处,您的userObject可以是Person或GroupMember

的对象