I'm new to Spring Security and have followed some basic recipes to get Spring Security working in my application, but now I'm trying to see if there is a way to get my own User object added to Spring's SecurityContext upon login/authentication.
My security is currently configured to use the JdbcDaoImpl:
<authentication-manager alias="authenticationManager"> <authentication-provider user-service-ref="com.ia.security.SpringSecurityDao" /> </authentication-manager> <beans:bean id="com.ia.security.SpringSecurityDao" class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl"> <beans:property name="usersByUsernameQuery"> <beans:value>select username,password,enabled from user where username = ? </beans:value> </beans:property> <beans:property name="dataSource" ref="dataSource" /> <beans:property name="enableGroups" value="true" /> <beans:property name="enableAuthorities" value="false" /> <beans:property name="groupAuthoritiesByUsernameQuery"> <beans:value>SELECT R.ID, R.NAME, P.NAME FROM ROLE R JOIN USER_ROLE UR on R.id = UR.role_id JOIN USER U on U.id = UR.user_id JOIN ROLE_PERMISSION RP ON RP.role_id = R.id JOIN PERMISSION P ON P.id = RP.permission_id WHERE U.username=? </beans:value> </beans:property> </beans:bean>
I realize that I can retrieve the
Principal object from the SecurityContext and get the username and requery the DB given the username, but was thinking it would be easier to simple store the my entire
User object in the SecurityContext to have it easily accessible whenever I need it throughout my application as opposed to just storing the username, password and enabled fields in the
I've looked into the UserDetailsService, and more specifically the
JdbcDaoImpl class, but not entirely sure of the best way to proceed. If I simply override/extend by calling
loadUserByUsername method to return my own UserDetails object is that sufficient? Then would I just be able to do
SecurityContextHolder.getContext().getAuthentication().getDetails() and cast it to my own object?
I've found other posts on StackOverflow that relate to this, but most seem to be ignoring anything to do with Authorities and Roles that are retrieved from the DB, so I'm not sure if this is the best way to proceed.</div