You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/manual/src/docs/asciidoc/_includes/servlet/authentication/anonymous.adoc
+32Lines changed: 32 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -100,3 +100,35 @@ This is an example of the use of the `AuthenticatedVoter` which we will see in t
100
100
It uses an `AuthenticationTrustResolver` to process this particular configuration attribute and grant access to anonymous users.
101
101
The `AuthenticatedVoter` approach is more powerful, since it allows you to differentiate between anonymous, remember-me and fully-authenticated users.
102
102
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 MVC 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
+
[source,java]
129
+
----
130
+
@GetMapping("/")
131
+
public String method(@CurrentSecurityContext SecurityContext context) {
0 commit comments