We are Borg
We are Borg

Reputation: 5313

Spring Security retrieve current user object out two methods implementing UserDetails

I am working on a Spring-MVC project where I am using Spring-Security for authentication and other security features. Now the Project is divided into 2 parts, one is for personal login and another is group login. For both of them, I use different database tables. But Java classes for both the tables have one instance of UserDetails and userDetailsService implemented. Now when the user logs-in either from the personal account or from group account, I would like to extract the currently logged in users object from either of the class. This way, I would know if its a group user logged in or a personal account user logged in. Kindly let me know what should I do?

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 (Personal accounts model 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 (Group Account members model)

@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
}

Edit : This is how I retrieve the current user, but I cannot find how to check to which object it is, I can get an Object of UserDetails, but as both methods are implementing UserDetails, I cannot tell which one it is.

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

Upvotes: 0

Views: 261

Answers (1)

Ekansh Rastogi
Ekansh Rastogi

Reputation: 2546

I hope this should be simple.

You have two UserDetails objects User1 and User2, suppose User1 is of the Person class and User2 is of GroupPerson.

You can get theUserDetails Object as you stated, then all you need to do is to check if the object is instance of Person or GroupMembers.

You can do it using instanceof like the following

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

Here your userObject can be an object of either Person or GroupMember

Upvotes: 1

Related Questions