What can be a use case for #Transient annotation from Spring Security Core? - spring

The official documentation for the #Transient states: (Link here)
A marker for Authentications that should never be stored across requests, for example a bearer token authentication
I understand that #Transient should be used when we do not want to persist any details.
One such example that the documentation mentions is for bearer token authentication which makes sense.
What can be a general rule of thumb for situtation(s) where #Transient should be used?
Thank you,

It is pretty much what is written in the Javadocs. The transient authentication tokens indicate to the filter chain, specifically the
HttpSessionSecurityContextRepository, whether or not the token ought
to be persisted across requests.
Implementations of SecurityContextRepository may choose to not persist
tokens that are marked with #Transient in the same way
that HttpSessionSecurityContextRepository does.
There are more details in the related issue.

Related

Spring Security some time AnonymousUser [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 days ago.
Improve this question
Spring Boot - Angular Application:
Why does my method return "AnonymousUser" when called from one controller, but the correct user id when called from another controller?
I have a method that returns the logged-in user:
#Override
public String getLoggedUserName() {
return SecurityContextHolder.getContext().getAuthentication().getName();
}
When I call it from a controller, it returns the name of the logged-in user, but when I call it from another controller, it returns "AnonymousUser". Why is this happening?
I don't know if it can be useful as additional information but authentication is via Keycloak
I'll answer first to what I guess your actual question is: "how to be sure to have a JwtAuthenticationToken in the security-context of a #ResController?"
Configure your app as resource-server with a JWT decoder
Protect entry-points with isAuthenticated() either form security filter-chain configuration or #PreAuthorize (or equivalent) on controller class or method (with #EnableMethodSecurity somewhere in the config)
Off course, do not explicitly replace the default Authentication implementation for successful authorizations... (when providing an authentication converter for instance)
Now a complete answer to what you formulated and is way wider as the type of Authentication implementation in the security context of controller method invocation varies depending on quite a few factors.
Runtime
Let's start with "real" invocations (spring app up and running, nothing mocked):
request is not authorized, then an AnonymousAuthenticationToken is put in the security context. Depending on the security config, this could be because of missing or invalid access token (expired, wrong issuer or audience, bad signature, ...), missing basic header, etc., or because the type of authorization is not the right one (for instance a Bearer token on a route intercepted by a security filter-chain expecting basic authentication)
request is successfully authorized => default authentication depends on the security conf
resource-server with JWT decoder, then JwtAuthenticationToken is used (can be accessed verridden by configuring http.oauth2ResourceServer().jwt().jwtAuthenticationConver(...)
resource-server with access token introspection, then BearerTokenAuthentication is used ( override with http.oauth2ResourceServer().opaqueToken().authenticationConver(...))
client with oauth2Login, then OAuth2AuthenticationToken is used
etc., the list continues for non OAuth2 authentications (just have a look at Authentication type hierarchy)
Tests
Test security context can be set for tests in plain JUnit using annotations like #WithMockUser or using MockMvc (respectively WebTestClient for reactive apps) and either annotations or request post processors (respectively WebTestClient mutators).
The type of Authentication injected depends on the annotation (or mutator / post-processor) used. For instance, #WithMockUser builds a UsernamePasswordAuthenticationToken which is rarely adapted to an OAuth2 context. Mutators from SecurityMockMvcRequestPostProcessors from spring-security-test or annotations like
#WithMockJwtAuth, #WithMockBearerTokenAuthentication or #WithOAuth2Login from spring-addons are generally better suited.
Tutorials for both runtime config and tests
I wrote some available from there: https://github.com/ch4mpy/spring-addons/tree/master/samples/tutorials

Spring security has authorities on Authentication and on the Principal - why and which one to use?

I'am aware of the question Duplicate authorities in spring security authentication but it's scope is much narrow.
My question is, if the idea of both should be "they should share the exact same information" - why is there no contract enforcing the very same? For example neitherAbstractUserDetailsAuthenticationProvider nor DaoAuthenticationProvider is providing that implementation to enforce that those are the same. Actually, they both do not care about all having the authorities set on the principal in the first stem.
So for example, if i add the Authority FOO to the token inside my Filter, they would never be set on the Principal/UserDetails, just stay on the Authentication container.
Reading the javaDoc of org.springframework.security.core.Authentication#getAuthorities it seems it is planned that this the source of truth for checking if the principal has any authorities.
But the very same goes for org.springframework.security.core.userdetails.UserDetails#getAuthorities.
AFAICS it is usually much more practical to use the Authorities withing the principal, since one can keep the principal of the same type for all the different providers that might have authenticated the user. This helps when one consumes the principal via #AuthenticationPrincipal in controllers and such.
The concrete question is thus:
If so, what ensures that those two authority lists are the same? (both as contract and in the spring security default implementation)
if that is not present, which of those is considered the "real source of truth"
Thanks!
If you use spring security expressions like hasAnyAuthority or others, spring will use the authorities on the authentication object, not the user principal. You can see an example of this in SecurityExpressionsRoot.java:getAuthoritySet().
To account for this the base implementation of AbstractUserDetailsAuthenticationProvider copies all authorities from the UserDetails after loading them to the Authentication object it returns. This is done in the method createSuccessAuthentication.
Therefore if one is to implement its own provider one has to make sure the authorities are set on the outer Authentication object.
So for spring security it seems the Authentication.authorities is the one that's relevant, not sure about the 'which is the one point of truth' part though. You could argue that the one on the UserDetails is the source of truth since AbstractUserDetailsAuthenticationProvider implementation copy those over to the Authorization. On the other hand you could argue Spring security uses Authentication.authorities to evaluate expressions, so this is it.

Spring: Why is it bad to return a whole OAuth2User in an endpoint?

I'm building an OAuth2 authenticated app using Spring Boot, following this tutorial: https://spring.io/guides/tutorials/spring-boot-oauth2/
At one point, the endpoint /user sends back the currently logged in user.
The guide warns by saying:
"It’s not a great idea to return a whole OAuth2User in an endpoint since it might contain information you would rather not reveal to a browser client."
But it doesn't give any more information - what type of information should I not be revealing to a browser client?
Thanks!
In Spring Security 5.x, the OAuth2User is a specific OAuth2AuthenticatedPrincipal (very similar to a UserDetails but without any notion of a password). Even without a password, exposing it can (and often will) leak sensitive information, implementation details of your authentication scheme, etc. You can expose it if you choose, but the warning in the guide is suggesting that care should be taken so as not to expose anything considered sensitive, and you should consider alternatives before exposing it directly.
For example, you might consider creating a CustomUser class that is populated from claims on the OAuth2User using a custom OAuth2UserService (various examples in the advanced configuration section of the docs). You can also take various steps to decouple the representation of an oauth2 user in Spring Security from the representation of a user in your application (e.g. by using #AuthenticationPrincipal to resolve your own custom user or access claims). If the application itself does not need a custom user, you can simply map claims of the OAuth2User to a response in your custom endpoint, as demonstrated in the guide.
Finally, you can combine all of these techniques to make your /user endpoint a "one liner" again, as in:
#Target({ElementType.PARAMETER, ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
#Documented
#AuthenticationPrincipal(expression = "customUser")
public #interface CurrentUser {}
#GetMapping("/user")
public CustomUser user(#CurrentUser CustomUser customUser) {
return customUser;
}

How does CRSF LazyCsrfTokenRepository work?

Java 8 - spring 4.3.x
While configuring spring security and enable csrf feature i came across two implementations of CsrfTokenRepository one is Lazy another is Cookie based
I know CookieCsrfTokenRepository works using writing a csrf token into cookie and accepts a cookie value in header to verify the valid request
Can some one help me to understand how does LazyCsrfTokenRepository works ?
From the javadoc:
A CsrfTokenRepository that delays saving new CsrfToken until the
attributes of the CsrfToken that were generated are accessed.
So why this? In earlier versions of Spring Security the HttpSessionCsrfTokenRepository was default. The drawback with this was that it always creates a token, triggering session creation, regardless of whether the token was used or not, which could be wasteful in some applications.
The LazyCsrfTokenRepository on the other hand only creates a wrapper, and creates the actual token only if getToken() is invoked (like when for example generating a form). This avoids unnecessary session creation.
A gotcha with LazyCsrfTokenRepository is that the actual token generation must still happen before HTTP response is committed, otherwise you get an exception. If you get problem with this, it is easiest to use (only) one of the other two implementations.

Where is the refreshToken endpoint implementation?

I am using springboot-security-jwt because have good recomendation, and it is running... But when I was testing refreshToken, where the implementation? How to use it?
Perhaps it is so obvious for a "Senior Developer Spring", but it is not for me, I not see it there. Where the /auth/token endpoint implementation?
There are some examples or documentation about it and how to (parameters) call it?
... Where the springboot-security-jwt /token endpoint implementation? to check it (or a kind of "health endpoint test")...
The primary configuration in the project springboot-security-jwt is in the WebSecurityConfig.java: (see https://github.com/svlada/springboot-security-jwt/blob/master/src/main/java/com/svlada/security/config/WebSecurityConfig.java).
In this class you will see a bean created of type AjaxLoginProcessingFilter configured with to intercept requests matching "/api/auth/login". This will process the login and generate the JWT tokens.
You can then follow to the next bean configured - JwtTokenAuthenticationProcessingFilter to see what it is intercepting and authenticating using the JWTToken provided on the api requests
refreshToken is a standard spring controller - see RefreshTokenEndpoint class (https://github.com/svlada/springboot-security-jwt/blob/master/src/main/java/com/svlada/security/endpoint/RefreshTokenEndpoint.java)
The author also provides a detailed explanation in the Blog.md under the etc folder - check it out! there are lots of useful links to get up to speed on using JWTs

Resources