Skip to content

Commit e601d96

Browse files
committed
Anonymous Authentication Argument Resolution Docs
Closes gh-3338
1 parent 18d04f2 commit e601d96

File tree

1 file changed

+44
-0
lines changed
  • docs/manual/src/docs/asciidoc/_includes/servlet/authentication

1 file changed

+44
-0
lines changed

docs/manual/src/docs/asciidoc/_includes/servlet/authentication/anonymous.adoc

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,3 +100,47 @@ This is an example of the use of the `AuthenticatedVoter` which we will see in t
100100
It uses an `AuthenticationTrustResolver` to process this particular configuration attribute and grant access to anonymous users.
101101
The `AuthenticatedVoter` approach is more powerful, since it allows you to differentiate between anonymous, remember-me and fully-authenticated users.
102102
If you don't need this functionality though, then you can stick with `ROLE_ANONYMOUS`, which will be processed by Spring Security's standard `RoleVoter`.
103+
104+
[[anonymous-auth-mvc-controller]]
105+
=== Getting Anonymous Authentications with Spring MVC
106+
107+
https://docs.spring.io/spring-framework/docs/5.2.x/spring-framework-reference/web.html#mvc-ann-arguments[Spring MViC resolves parameters of type `Principal`] using its own argument resolver.
108+
109+
This means that a construct like this one:
110+
111+
[source,java]
112+
----
113+
@GetMapping("/")
114+
public String method(Authentication authentication) {
115+
if (authentication instanceof AnonymousAuthenticationToken) {
116+
return "anonymous";
117+
} else {
118+
return "not anonymous";
119+
}
120+
}
121+
----
122+
123+
will always return "not anonymous", even for anonymous requests.
124+
The reason is that Spring MVC resolves the parameter using `HttpServletRequest#getPrincipal`, which is `null` when the request is anonymous.
125+
126+
If you'd like to obtain the `Authentication` in anonymous requests, use `@CurrentSecurityContext` instead:
127+
128+
.Use CurrentSecurityContext for Anonymous requests
129+
====
130+
.Java
131+
[source,java,role="primary"]
132+
----
133+
@GetMapping("/")
134+
public String method(@CurrentSecurityContext SecurityContext context) {
135+
return context.getAuthentication().getName();
136+
}
137+
----
138+
139+
.Kotlin
140+
[source,kotlin,role="secondary"]
141+
----
142+
@GetMapping("/")
143+
fun method(@CurrentSecurityContext context : SecurityContext) : String =
144+
context!!.authentication!!.name
145+
----
146+
====

0 commit comments

Comments
 (0)