in my spring web application I want to get an authenticated user in my controller:
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
But the principal's value is "anonymousUser" although I have loged in. How can I get an authenticated user? My configurations in spring-security.xml:
<http auto-config="true" request-matcher="regex">
<intercept-url pattern="/welcome*" access="ROLE_USER" />
<form-login login-page="/login" default-target-url="/welcome"
authentication-failure-url="/loginfailed" />
<logout logout-success-url="/logout" />
</http>
The HttpServletRequest.getUserPrincipal() will return the result of SecurityContextHolder.getContext().getAuthentication() . This means it is an Authentication which is typically an instance of UsernamePasswordAuthenticationToken when using username and password based authentication.
Spring Security's anonymous authentication just gives you a more convenient way to configure your access-control attributes. Calls to servlet API such as getCallerPrincipal , for example, will still return null even though there is actually an anonymous authentication object in the SecurityContextHolder .
The principal is the currently logged in user. However, you retrieve it through the security context which is bound to the current thread and as such it's also bound to the current request and its session.
Once you have Spring Security configured and working, here is how you can get the currently authenticated principal user object in the Controller class. Just add a Principal object to your method as an argument and you will be able to access the Principal user details. return "Working for managers. Principal name = " + principal.getName();
This is what we mean by anonymous authentication. Note that there is no real conceptual difference between a user who is "anonymously authenticated" and an unauthenticated user. Spring Security’s anonymous authentication just gives you a more convenient way to configure your access-control attributes.
To fully leverage the Spring dependency injection and be able to retrieve the authentication everywhere, not just in @Controller beans, we need to hide the static access behind a simple facade: The facade exposes the Authentication object while hiding the static state and keeping the code decoupled and fully testable:
The facade exposes the Authentication object while hiding the static state and keeping the code decoupled and fully testable: 5. Get the User in JSP The currently authenticated principal can also be accessed in JSP pages, by leveraging the Spring Security Taglib support.
Not sure I understand but try this
<http auto-config="true" request-matcher="regex">
<intercept-url pattern="/welcome*" access="ROLE_USER" />
<intercept-url pattern="/*" access="IS_AUTHENTICATED,IS_AUTHENTICATED_ANONYMOUSLY"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With