1
0
mirror of synced 2026-08-05 01:36:56 +00:00

Add @AuthenticationPrincipal expression

It is now possible to provide a SpEL expression for
@AuthenticationPrincipal. This allows invoking custom logic including
methods on the principal object.

Fixes gh-3859
This commit is contained in:
Rob Winch
2016-05-03 15:42:04 -05:00
committed by Joe Grandja
parent 78bf6e2bd5
commit 9745de9510
6 changed files with 267 additions and 9 deletions
+31
View File
@@ -388,6 +388,7 @@ Here is the list of improvements:
* <<headers-hpkp,HTTP Public Key Pinning (HPKP)>>
* <<csrf-cookie,CookieCsrfTokenRepository>> provides simple AngularJS & CSRF integration
* Added `ForwardAuthenticationFailureHandler` & `ForwardAuthenticationSuccessHandler`
* <<mvc-authentication-principal,AuthenticationPrincipal>> supports expression attribute to support transforming the `Authentication.getPrincipal()` object (i.e. handling immutable custom `User` domain objects)
=== Authorization Improvements
* <<el-access-web-path-variables,Path Variables in Web Security Expressions>>
@@ -6630,6 +6631,36 @@ public ModelAndView findMessagesForUser(@AuthenticationPrincipal CustomUser cust
}
----
Sometimes it may be necessary to transform the principal in some way.
For example, if `CustomUser` needed to be final it could not be extended.
In this situation the `UserDetailsService` might returns an `Object` that implements `UserDetails` and provides a method named `getCustomUser` to access `CustomUser`.
For example, it might look like:
[source,java]
----
public class CustomUserUserDetails extends User {
// ...
public CustomUser getCustomUser() {
return customUser;
}
}
----
We could then access the `CustomUser` using a https://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html[SpEL expression] that uses `Authentication.getPrincipal()` as the root object:
[source,java]
----
import org.springframework.security.core.annotation.AuthenticationPrincipal;
// ...
@RequestMapping("/messages/inbox")
public ModelAndView findMessagesForUser(@AuthenticationPrincipal(expression = "customUser") CustomUser customUser) {
// .. find messags for this user and return them ...
}
----
We can further remove our dependency on Spring Security by making `@AuthenticationPrincipal` a meta annotation on our own annotation. Below we demonstrate how we could do this on an annotation named `@CurrentUser`.
NOTE: It is important to realize that in order to remove the dependency on Spring Security, it is the consuming application that would create `@CurrentUser`. This step is not strictly required, but assists in isolating your dependency to Spring Security to a more central location.