jacekn
jacekn

Reputation: 1541

How to retrieve UserDetails with Spring Security 3?

www.someurl.com - public access not intercepted by Spring Security 3.
www.someurl.com/admin  - intercepted by Spring Security 3. Works fine. 

I log into a page under www.someurl.com/admin. Then I change the url to www.someurl.com in the same window tab. I am working within the same http session so I expect to be able to retrieve user login details.

The public url request is handled by a dedicated controller. Within this controller, I have a wired user service. The implementer of this service is attempting to retrieve credentials but can't - Authentication object is null.

Authentication a=SecurityContextHolder.getContext().getAuthentication();
userDetails=(UserDetails) a.getPrincipal();

=== UPDATE =========================

When I inspect the HttpSession in the public url request controller, I see this attribute:

{SPRING_SECURITY_CONTEXT=org.springframework.security.core.context.SecurityContextImpl@ed20eaf7: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@ed20eaf7: Principal: org.springframework.security.core.userdetails.User@586034f: Username: admin; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ADMINISTRATOR,AUTHOR,EDITOR,READER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@380f4: RemoteIpAddress: 127.0.0.1; SessionId: 43A582157C5813018632ACDD7499CF7D; Granted Authorities: ADMINISTRATOR, AUTHOR, EDITOR, READER}

Upvotes: 0

Views: 1038

Answers (1)

John Farrelly
John Farrelly

Reputation: 7459

If you want to get security details like you are, Spring Security must intercept the url, otherwise there won't be any security information. You can add the following to your spring security config:

<security:http pattern="/" security='none' />

This means that spring security will let everyone see the root url (whether logged in or not), but spring security will process the url, meaning your controller against the root url will be able to get the current user login details from SecurityContextHolder

Upvotes: 1

Related Questions