#WithMockKeycloakAuth get accesstoken as bearer String for mockMvc perform Header - spring-security

I have one service and Keycloak 11 as Authentication server. Now I want to write tests. To mock the accesstoken, I use #WithMockKeycloakAuth. This works well and I get an unauthorized when I pass a bad role for example. Now I want to document it with spring rest docs the therefor I have to add the acesstoken as header field ( Bearer tokenAsBearerString ). Because of the annotation, the mocked token is added to the SecurityContext and I can extract it before doing the mvc.perform.
#Test
#Order(5)
#WithMockKeycloakAuth(authorities = "ROLE_owner")
void createProduct_RealmRoleOwner_HttpStatusCreated() throws Exception {
SecurityContext context = SecurityContextHolder.getContext();
KeycloakAuthenticationToken authentication =(KeycloakAuthenticationToken) context.getAuthentication();
AccessToken token = authentication.getAccount().getKeycloakSecurityContext().getToken();
The problem is that I need the accesstoken as Bearer string representation. I'm not yet very familiar with the jwt topic but I expected that if I use the mocked acces token and convert it to a jwt format / Base 64 encoded String the header should be correct.
In addition: I'm running a Keycloak container via docker in a seperate network so it is not reachable while I run my automated test. So mocking would be the only solution.

This question was also asked (and answered) here with a little more context.
The code snippet provided above doesn't show that test class is decorated with #AutoConfigureMockMvc(addFilters = false), reason why the security context is not attached to the MockMvc HTTP request (this is normally done by a spring-security filter).
The complete stack trace isn't provided neither, but it's very likely that the exception occurring when filters are enabled is due to JwtDecoder wiring from Keycloak boot lib. #MockBean JwtDecoder jwtDecoder; should be enough to fix it.
Finally, it is one of main features of the lib #WithMockKeycloakAuth is taken from to skip fetching, decoding and parsing an actual JWT from Keycloak instance. Trying to build an authorization header with valid JWT from mocked spring authentication is ...

Related

Spring OAuth2 Resource Server - user-name-attribute not reflected in SecurityContextHolder

I have a claim named user_name within my JWT and also corresponding user-name-attribute set as user_name in spring security oauth2 client provider proper property:
spring.security.oauth2.client.provider.my-oauth-provider.user-name-attribute=user_name
I can also see this property is properly being read by ReactiveClientRegistrationRepository class (ClientRegistration.ProviderDetails.UserInfoEndpoint). But when I read SecurityContextHolder.getContext().getAuthentication().getName() on Resource Server I can see the value taken from (default) sub - IdTokenClaimNames.SUB claim.
Why is that? Do I still miss some additional configuration also on resource server side to have specified user-name-attribute taken and returned by SecurityContextHolder.getContext().getAuthentication().getName() on Resource Server? I understand that only Bearer token (and maybe some cookies) is being sent from client to resource server so maybe also some other filter is needed on Gateway/client side - just guessing?
The reason is that you are using a property prefixed with security.oauth2.client, which is intended for OAuth 2.0 Clients.
In Spring Security 5.2.x, there is no Spring Boot property to indicate a user name attribute to Resource Server, e.g. security.oauth2.resourceserver.xyz
You could publish your own Converter to the DSL, though:
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
http
.oauth2ResourceServer()
.jwtAuthenticationConverter(jwt -> {
JwtAuthenticationToken authentication = converter.convert(jwt);
return new JwtAuthenticationToken(authentication.getToken(),
authentication.getAuthorities(), jwt.getClaim("claim"));
});

Understanding Keycloak Adapter (Spring-Security & Spring Boot) session requirement

For a software in active development we are using Spring Boot (with Spring Security) and the Keycloak Adapter.
The goal is to:
require valid authentication for all endpoints except those annotated with #Public (see the code snippet) (this works)
the authentication must be via OAuth - the client gets a token directly from Keycloak and the Spring Security + Keycloak adapter make sure it is valid
optionally, Basic Auth is also supported (the Keycloak adapter can be configured to perform a login and make it appear like a regular token auth for the rest of the code) (this works as well)
Everything is working fine as it stands, but I have some problems understanding a few details:
The KeycloakWebSecurityConfigurerAdapter enables CSRF protection. I think this is only done so it can register its own Matcher to allow requests from Keycloak
It enables session management and requires some according beans
Even though requests are made with token authentication, a JSESSIONID cookie is returned
According to my understanding:
sessions should not be needed since stateless token authentication is used (so why is the KeycloakWebSecurityConfigurerAdapter enabling it). Is this only for the BASIC Auth part?
since sessions are enabled, CSRF protection is indeed needed - but I don't want the sessions in the first place and then the API would not need CSRF protection, right?
even if I set http.sessionManagement().disable() after the super.configure(http) call the JSESSIONID cookie is set (so where is this coming from?)
As stated in the code snippet, SessionAuthenticationStrategy is not set to the null once since we use the Authorization part of Keycloak and the application is a Service Account Manager (thus managing those resource records).
Would be great if someone can clear things up. Thanks in advance!
#KeycloakConfiguration
public class WebSecurityConfiguration extends KeycloakWebSecurityConfigurerAdapter {
#Inject private RequestMappingHandlerMapping requestMappingHandlerMapping;
#Override
protected void configure(final HttpSecurity http) throws Exception {
super.configure(http);
http
.authorizeRequests()
.requestMatchers(new PublicHandlerMethodMatcher(requestMappingHandlerMapping))
.permitAll()
.anyRequest()
.authenticated();
}
// ~~~~~~~~~~ Keycloak ~~~~~~~~~~
#Override
#ConditionalOnMissingBean(HttpSessionManager.class)
#Bean protected HttpSessionManager httpSessionManager() {
return new HttpSessionManager();
}
/**
* {#link NullAuthenticatedSessionStrategy} is not used since we initiate logins
* from our application and this would not be possible with {#code bearer-only}
* clients (for which the null strategy is recommended).
*/
#Override
#Bean protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
/**
* HTTP session {#link ApplicationEvent} publisher needed for the
* {#link SessionRegistryImpl} of {#link #sessionAuthenticationStrategy()}
* to work properly.
*/
#Bean public HttpSessionEventPublisher httpSessionEventPublisher() {
return new HttpSessionEventPublisher();
}
#Override
#Bean public KeycloakAuthenticationProvider keycloakAuthenticationProvider() {
return super.keycloakAuthenticationProvider();
}
}
You may fall into excessive JWT token usage. Look at this article for example https://blog.logrocket.com/jwt-authentication-best-practices/. Especially look at the references at the end of the article about JWT as a session token.
For your web-application UI you are using sessions in most of the cases. It doesn't matter what type of token is used for authentication. Keycloak does everything correctly - it gives back httpOnly secure cookie for session management and tracks user status at backend. For better understanding of how it works you may look at the example code here: examples
For better separation of stateless backend (micro-)services and user UI session keycloak documentation suggest to use 2 different authentication stratagies: RegisterSessionAuthenticationStrategy for sessions and NullAuthenticatedSessionStrategy for bearer-only services

How do I dynamically specify OAuth2 resource details in Spring Security?

I'm creating an application integrating with Shopify's API, which uses OAuth2 for authentication and authorization. Using the tutorial for Spring Security OAuth2, and the tutorial for Shopify, I've been able to get integration working with a single shop. The YAML configuration looks like this:
shopify:
shop: myshop
scopes: read_customers,read_orders
security:
oauth2:
client:
clientId: myclientid
clientSecret: mysecret
tokenName: access_token
authenticationScheme: query
clientAuthenticationScheme: form
accessTokenUri: https://${shopify.shop}.myshopify.com/admin/oauth/access_token
userAuthorizationUri: https://${shopify.shop}.myshopify.com/admin/oauth/authorize?scope=${shopify.scopes}&grant_options[]=
pre-established-redirect-uri: https://myapp/login
registered-redirect-uri: https://myapp/login
use-current-uri: false
resource:
userInfoUri: https://${shopify.shop}.myshopify.com/admin/shop.json
However, this static configuration won't work for an app published in Shopify's App Store because the redirect, access token, user info, and user authorization URIs depend on the shop name. There are examples of using more than one provider, but they still have to be static.
To allow these URI's to be dynamic, I've come up with a few possible options:
Use a parameter in the /login path to identify the shop, then create a filter that adds the shop name to a ThreadLocal that runs before everything else, then dynamically create the AuthorizationCodeResourceDetails that is needed by the OAuth2 filter via a Spring proxied factory bean.
Use a sort of "metafilter" that dynamically recreates the OAuth2ClientAuthenticationProcessingFilter per request along with all of the resources that it needs.
Override OAuth2ClientAuthenticationProcessingFilter so that it can handle recreating the RestTemplate it needs to obtain the access token.
All of these options seem pretty difficult. What's a good way to handle dynamically-generated URI's for access tokens and user information in Spring Security OAuth2?
Also, since I'm new to OAuth2 in general, do I need to enable a Resource Server in my Spring configuration to protect my app with the access token?
a bit late but I did return a dynamic url for an oauth resource by overriding the getter for the Oauth2ProtectedResource
#Bean(name = "googleOauthResource")
public BaseOAuth2ProtectedResourceDetails getGoogleOauthResource() {
final AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails() {
#Override
public String getPreEstablishedRedirectUri() {
final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes instanceof ServletRequestAttributes) {
final HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
return request.getRequestURL() + "?" + request.getQueryString() + "&addStuff";
}
return super.getPreEstablishedRedirectUri();
}
};
details.setId("google-oauth-client");
details.setClientId("xxxxxxxxxxx");
details.setClientSecret("xxxxxxxx");
details.setAccessTokenUri("https://www.googleapis.com/oauth2/v4/token");
details.setUserAuthorizationUri("https://accounts.google.com/o/oauth2/v2/auth");
details.setTokenName("authorization_code");
details.setScope(Arrays.asList("https://mail.google.com/,https://www.googleapis.com/auth/gmail.modify"));
details.setPreEstablishedRedirectUri("http://localhost:8080/xxx-api-web/v2/gmail"); //TODO
details.setUseCurrentUri(false);
details.setAuthenticationScheme(AuthenticationScheme.query);
details.setClientAuthenticationScheme(AuthenticationScheme.form);
details.setGrantType("authorization_code");
return details;
}
I'm having the same problem you are and I'm leaning toward your first theory of using ThreadLocal storage. Here is how I'll probably go about my solution:
Set values from ServletRequest in LocalThread storage by overriding methods in OAuth2ClientAuthenticationProcessingFilter:
attemptAuthentication
successfulAuthentication
unsuccessfulAuthentication
requiresAuthentication
Then translate the URI's within the OAuth2RestTemplate by overriding the followign methods:
createRequest
doExecute
appendQueryParameter
I'll probably have to make my own #Bean for the RestTemplate that has an injected #Service that will lookup the dynamic Shopify domain.
I'll post my solution if it works.

How to obtain HttpServletRequest #Context in DropWizard Auth

I am using Basic Auth in Dropwizard 0.8
and I need to get access to the request context in my SimpleAuthenticator class, beyond the basic credentials.
Perhaps I need my own AuthFactory implementation to do this?
I want to implement basic access control for Basic Auth based on the resource path requested.
Thanks
Jon
#PermitAll
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response getResponse(**#Context** SecurityContext context) {
SimplePrincipal principal = (SimplePrincipal)context.getUserPrincipal();
return Response.ok("{\"Hello\": \"" + principal.getUsername() + "\"}").build();
}
Using #Context suffice for the basic Authorization atleast for Dropwizard version 0.9.2
I haven't used 0.8, but in 0.9+, you can use #Auth and #PermitAll to control which resources have auth and which ones don't. Would that not satisfy your requirement? or you prefer a finer grained control?
Here's a changeset for auth in 0.9. You can refer to Dropwizard: BasicAuth for sample code.

Change Bearer-Token-Type in Spring Cloud OAuth

I'm using Spring Cloud OAuth, I'm using the official sample from https://github.com/spring-cloud-samples/sso/ with GitLab (https://about.gitlab.com/) as OAuth Provider.
The Problem is that GitLab sends a Token of the Type "bearer" and Spring Cloud SSO retrieves the token and sends a Header in the form of
Authorization bearer xxxxxxx
which is rejected by the GitLab Server cause according to the documentation it only accepts Tokens in the form of
Authorization Bearer xxxxxxx.
This is probably a bug in the GitLab Server but is there any way to work around this problem with Spring Cloud SSO.
Update 19.03.:
This is what I've tried in SsoApplication.java of the SpringCloud-sample.
#Autowired
private OAuth2RestTemplate oAuth2RestTemplate;
#PostConstruct
private void modifyOAuthRestTemplate() {
this.oAuth2RestTemplate.setAuthenticator(new OAuth2RequestAuthenticator() { // this line gets called
#Override
public void authenticate(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext clientContext, ClientHttpRequest request) {
// this line is never called
}
});
}
instead of the newly Injected OAuth2ProtectedResourceDetails the "original" one gets called. Everytime I try to authenticate in the sample app
UPDATE: there is a callback in Spring Cloud if you define a bean of type UserInfoRestTemplateCustomizer you will get an instance of OAuth2RestTemplate during startup where you can apply customizations (e.g. an OAuth2RequestAuthenticator to change "Bearer" to "bearer").
The workaround I have seen others use is to #Autowired the OAuth2RestTemplate and modify its OAuth2RequestAuthenticator in a #PostConstruct (before it is used anyway).

Resources