Spring 安全检索当前用户对象的两种实现 UserDetails 的方法

Spring Security retrieve current user object out two methods implementing UserDetails

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

安全应用程序-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(个人账户模型class):

@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());
        }
    }

我希望这应该很简单。

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

你可以像你说的那样得到UserDetails对象,然后你需要做的就是检查这个对象是Person还是GroupMembers的实例。

您可以使用 instanceof 来完成,如下所示

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

这里你的userObject可以是Person或GroupMember的对象