Customize Spring OAuth2TokenEndpointFilter - spring

I need to customize the Authentication Success Handler method for the Spring Authorization Server OAuth2TokenEndpointFilter to simulate a OAuth2 provider with limited capabilities.
I've tried the following:
#Bean
public OAuth2TokenEndpointFilter oauth2TokenEndpointFilter(AuthenticationManager authenticationManager) {
OAuth2TokenEndpointFilter filter = new OAuth2TokenEndpointFilter(authenticationManager);
// this is ugly but seems to be the only way to customize the token format.
filter.setAuthenticationSuccessHandler((request, response, authentication) -> {
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication =
(OAuth2AccessTokenAuthenticationToken) authentication;
OAuth2AccessToken accessToken = accessTokenAuthentication.getAccessToken();
OAuth2RefreshToken refreshToken = accessTokenAuthentication.getRefreshToken();
Map<String, Object> additionalParameters = accessTokenAuthentication.getAdditionalParameters();
additionalParameters.put("expires_in", null);
additionalParameters.put("user_id", null);
final HttpMessageConverter<OAuth2AccessTokenResponse> accessTokenHttpResponseConverter =
new OAuth2AccessTokenResponseHttpMessageConverter();
OAuth2AccessTokenResponse.Builder builder = OAuth2AccessTokenResponse.withToken(accessToken.getTokenValue())
.refreshToken(refreshToken.getTokenValue())
.additionalParameters(additionalParameters);
OAuth2AccessTokenResponse accessTokenResponse = builder.build();
ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);
accessTokenHttpResponseConverter.write(accessTokenResponse, null, httpResponse);
});
return filter;
}
Unfortunately, the token still comes back with the default fields in the token.
Can anyone tell me what I'm doing wrong?

Related

Configuring AWS Signing in Reactive Elasticsearch Configuration

In one of our service I tried to configure AWS signing in Spring data Reactive Elasticsearch configuration.
Spring provides the configuring the webclient through webclientClientConfigurer
ClientConfiguration clientConfiguration = ClientConfiguration.builder()
.connectedTo("localhost:9200")
.usingSsl()
.withWebClientConfigurer(
webClient -> {
return webClient.mutate().filter(new AwsSigningInterceptor()).build();
})
. // ... other options to configure if required
.build();
through which we can configure to sign the requests but however AWS signing it requires url, queryparams, headers and request body(in case of POST,POST) to generate the signed headers.
Using this I created a simple exchange filter function to sign the request but in this function I was not able to access the request body and use it.
Below is the Filter function i was trying to use
#Component
public class AwsSigningInterceptor implements ExchangeFilterFunction
{
private final AwsHeaderSigner awsHeaderSigner;
public AwsSigningInterceptor(AwsHeaderSigner awsHeaderSigner)
{
this.awsHeaderSigner = awsHeaderSigner;
}
#Override
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next)
{
Map<String, List<String>> signingHeaders = awsHeaderSigner.createSigningHeaders(request, new byte[]{}, "es", "us-west-2"); // should pass request body bytes in place of new byte[]{}
ClientRequest.Builder requestBuilder = ClientRequest.from(request);
signingHeaders.forEach((key, value) -> requestBuilder.header(key, value.toArray(new String[0])));
return next.exchange(requestBuilder.build());
}
}
I also tried to access the request body inside ExchangeFilterFunction using below approach but once i get the request body using below approach.
ClientRequest.from(newRequest.build())
.body(
(outputMessage, context) -> {
ClientHttpRequestDecorator loggingOutputMessage =
new ClientHttpRequestDecorator(outputMessage) {
#Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
log.info("Inside write with method");
body =
DataBufferUtils.join(body)
.map(
content -> {
// Log request body using
// 'content.toString(StandardCharsets.UTF_8)'
String requestBody =
content.toString(StandardCharsets.UTF_8);
Map<String, Object> signedHeaders =
awsSigner.getSignedHeaders(
request.url().getPath(),
request.method().name(),
multimap,
requestHeadersMap,
Optional.of(
requestBody.getBytes(StandardCharsets.UTF_8)));
log.info("Signed Headers generated:{}", signedHeaders);
signedHeaders.forEach(
(key, value) -> {
newRequest.header(key, value.toString());
});
return content;
});
log.info("Before returning the body");
return super.writeWith(body);
}
#Override
public Mono<Void>
setComplete() { // This is for requests with no body (e.g. GET).
Map<String, Object> signedHeaders =
awsSigner.getSignedHeaders(
request.url().getPath(),
request.method().name(),
multimap,
requestHeadersMap,
Optional.of("".getBytes(StandardCharsets.UTF_8)));
log.info("Signed Headers generated:{}", signedHeaders);
signedHeaders.forEach(
(key, value) -> {
newRequest.header(key, value.toString());
});
return super.setComplete();
}
};
return originalBodyInserter.insert(loggingOutputMessage, context);
})
.build();
But with above approach I was not able to change the request headers as adding headers throws UnsupportedOperationException inside writewith method.
Has anyone used the spring data reactive elastic search and configured to sign with AWS signed headers?
Any help would be highly appreciated.

Service that checks if token hasnt expired

so I have a authentication bean which provides access tokens from client credentials.
public class AuthServiceBean {
#Value("${some.url}")
private String someUrl;
#Value("${some.clientId}")
private String someClientId;
#Value("${some.secret}")
private String someSecret;
#Value("${some.username}")
private String someUsername;
#Value("${some.password}")
private String somePassword;
public AuthInfo getPrevAuth() {
return prevAuth;
}
public void setPrevAuth(AuthInfo prevAuth) {
this.prevAuth = prevAuth;
}
private AuthInfo prevAuth;
public AuthInfo getAuthInfo() throws IOException {
if (this.prevAuth != null && this.prevAuth.isNotExpired()) {
return this.prevAuth;
}
return this.Authenticate();
}
private AuthInfo Authenticate() throws IOException {
final String url = this.someUrl + "/api/oauth/v1/token";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
String clientIdSecret = this.someClientId +":"+ this.someSecret;
String authString = Base64.getEncoder().encodeToString(clientIdSecret.getBytes());
headers.add("Authorization", "Basic " + authString);
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("username", this.someUsername);
map.add("password", this.somePassword);
map.add("grant_type", "password");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
ResponseEntity<?> response = restTemplate.postForEntity(url, request, String.class);
String bodyString = response.getBody().toString();
ObjectMapper mapper = new ObjectMapper();
try {
AuthInfo authInfo = mapper.readValue(bodyString, AuthInfo.class);
this.prevAuth = authInfo;
return this.prevAuth;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
And now how do I need to create service which checks if that access token valid if it hasn't expired and how to use refresh token. When access token expires I could ask new token with refresh token? Would be good to get any examples.
First of all, As I see in your code, you are using password grant type, not client credentials, and because of this, you pass also user credentials (username and password) in addition to the client credentials, client id and client secret.
Anyway, the reason because all the examples you found to check expiration are using jwt tokens is because these tokens have this information coded in the token itself, so you can parse it using some kind of library like Nimbus Jose and get the "exp" claim and check directly if that date is before or after the actual date.
If the token is an opaque one (not jwt). You don't have any way to check the expiration without call the server who issued that token. Normally the server (an oauth2 server) provides and endpoint called introspect in which you pass a token and it responds indicating if this token is valid or is not, because it has expired or it is revoked etc..

Spring Security 5.2 Password Flow

I am trying to authenticate the user using the password flow in the latest version of Spring Security - 5.2.
The docs seem to suggest how to do that.
#Bean
public OAuth2AuthorizedClientManager passwordFlowAuthorizedClientManager(
HttpClient httpClient,
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
DefaultPasswordTokenResponseClient c = new DefaultPasswordTokenResponseClient();
RestTemplate client = new RestTemplate(requestFactory);
client.setMessageConverters(Arrays.asList(
new FormHttpMessageConverter(),
new OAuth2AccessTokenResponseHttpMessageConverter()));
client.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
c.setRestOperations(client);
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.password(configurer -> configurer.accessTokenResponseClient(c))
.refreshToken()
.build();
DefaultOAuth2AuthorizedClientManager authorizedClientManager =
new DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
authorizedClientManager.setContextAttributesMapper(authorizeRequest -> {
Map<String, Object> contextAttributes = new HashMap<>();
String username = authorizeRequest.getAttribute(OAuth2ParameterNames.USERNAME);
String password = authorizeRequest.getAttribute(OAuth2ParameterNames.PASSWORD);
contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
return contextAttributes;
});
return authorizedClientManager;
}
I execute the request, I can see the access token returned in HTTP header but the SecurityContext is not populated and the session user remains anonymous.
String username = "joe";
String password = "joe";
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
ClientRegistration r = clientRegistrationRepository.findByRegistrationId("keycloak");
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId(r.getRegistrationId())
.principal(authentication)
.attributes(attrs -> {
attrs.put(OAuth2ParameterNames.USERNAME, username);
attrs.put(OAuth2ParameterNames.PASSWORD, password);
})
.build();
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
Any ideas?
After reading into the documentation a bit more I do not think that Oauth 2 password flow in Spring Security 5.2 is supported the same way authorisation flow is. Spring Security 5.2 has password flow support for the http client which can cache the authorization request and refresh the token before it expires - but there is no end user password flow support in which the client proxies the credentials to the authorization server.
Of course, it is entirely possible to authenticate the end user by harvesting the credentials, implementing a custom AuthenticationProvider that swaps the credentials for a token with the authorization server and returns an OAuth2AuthenticationToken that is persisted to the context.

OAuth2.0 authentication of Dynamics CRM WebAPIs from a background Java (Spring) application

I need to authenticate against OAuth2.0 Microsoft Dynamics CRM from a background Java application; background because it's an integration app between the ERP of the customer and its Dynamics online instance.
I tried to use spring-security-oauth2 classes to get an high level set of resource to handle authentication, but i can't retrieve the initial token, while I'm successful if I try with building "manually" the http requests needed.
I wrote a simple Java application to test the authentication and I had this piece of code working, with content that is the String representation of the access token JSon:
String accessTokenURL = "https://login.microsoftonline.com/common/oauth2/token";
CloseableHttpClient client = HttpClients.createDefault();
HttpPost requestToken = new HttpPost(accessTokenURL);
requestToken.addHeader("Cache-Control", "no-cache");
requestToken.addHeader("Content-Type", "application/x-www-form-urlencoded");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("grant_type", "password"));
params.add(new BasicNameValuePair("client_id", clientId));
params.add(new BasicNameValuePair("resource", resource));
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("client_secret", clientSecret));
requestToken.setEntity(new UrlEncodedFormEntity(params));
CloseableHttpResponse response = client.execute(requestToken);
InputStream is = response.getEntity().getContent();
String content = IOUtils.toString(is);
System.out.println(content);
client.close();
resource is the Dynamics online instance of the customer.
I tried something similar using Spring Security OAuth2 client classes but I always get "401 Unauthorized":
ResourceOwnerPasswordResourceDetails resourceObj = new ResourceOwnerPasswordResourceDetails();
resourceObj.setClientId(clientId);
resourceObj.setClientSecret(clientSecret);
resourceObj.setGrantType("password");
resourceObj.setAccessTokenUri(accessTokenURLWithResource);
// resourceObj.setId(resource);
resourceObj.setTokenName("bearer_token");
resourceObj.setUsername(username);
resourceObj.setPassword(password);
AccessTokenRequest atr = new DefaultAccessTokenRequest();
Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
headersMap.put("Cache-Control", Arrays.asList("no-cache"));
headersMap.put("Content-Type", Arrays.asList("application/x-www-form-urlencoded"));
atr.add("client_id", clientId);
atr.add("resource", resource);
atr.add("client_secret", clientSecret);
atr.add("username", username);
atr.add("password", password);
OAuth2ClientContext context = new DefaultOAuth2ClientContext(atr);
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceObj, context);
OAuth2AccessToken token = restTemplate.getAccessToken();
System.out.println(new Gson().toJson(token));
I tried using different ways to pass the access token URL and resource but the result is always the same.
Any help or any other advice about other high level library to be used in this case are appreciated, thanks.
Thanks to some hints of #fateddy I came to a solution. This piece of code works, now I'll try to integrate in my application
ResourceOwnerPasswordResourceDetails resourceObj = new ResourceOwnerPasswordResourceDetails();
// resourceObj.setClientId(clientId);
// resourceObj.setClientSecret(clientSecret);
resourceObj.setGrantType("password");
resourceObj.setAccessTokenUri(accessTokenURLWithResource);
// resourceObj.setId(resource);
resourceObj.setTokenName("bearer_token");
// resourceObj.setUsername(username);
// resourceObj.setPassword(password);
AccessTokenRequest atr = new DefaultAccessTokenRequest();
Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
headersMap.put("Cache-Control", Arrays.asList("no-cache"));
headersMap.put("Content-Type", Arrays.asList("application/x-www-form-urlencoded"));
atr.add("client_id", clientId);
atr.add("resource", resource);
atr.add("client_secret", clientSecret);
atr.add("username", username);
atr.add("password", password);
OAuth2ClientContext context = new DefaultOAuth2ClientContext(atr);
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceObj, context);
OAuth2AccessToken token = restTemplate.getAccessToken();
System.out.println(new Gson().toJson(token));

Spring SSO with facebook filter and JWT

here is my problem.
I got a first authentication with mail and JWT with Spring boot 1.5.3.
=> works perfectly
Then i made a SSO filter to allow facebook tokens
The thing is, on first authentication it's ok. My server get the Token, then check with fb that says ok then it says ok to my client.
After that if i don't encode my token with my JWT token enhancer, my server says that it is not able to decode it as JSON.
Just that i know, i would normally not have to encode myself as it should be done automatically after my chain filter if i say ok ??
This code works but i've done the jwt myself, is that possible i've missed something ????
public class MyOAuth2ClientAuthenticationProcessingFilter extends OAuth2ClientAuthenticationProcessingFilter {
public MyOAuth2ClientAuthenticationProcessingFilter(String defaultFilterProcessesUrl) {
super(defaultFilterProcessesUrl);
}
#Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException, ServletException {
log.info("[attemptAuthentication facebook]");
Authentication result = null;
try {
String token = request.getHeader("oauth_token");
oauth2ClientContext.setAccessToken(new DefaultOAuth2AccessToken(token));
result = super.attemptAuthentication(request, response);
if(result.isAuthenticated()) {
FacebookService facebookService = new BasicFacebookService(token);
User fbUser = facebookService.getUser();
if(fbUser == null) {
throw new IllegalArgumentException(" fb user cannot be null");
}
if(!userService.isLoginExists(fbUser.getId())) {
CreateSocialUserModel model = new CreateSocialUserModel(
token,
DateUtil.getNow(),
"facebook");
userService.createSocialUser(model, fbUser);
}
//--- Create custom JWT token from facebook token
UserInfoTokenServices tokenService = new UserInfoTokenServices(
"https://graph.facebook.com/me",
facebookProperties.getAppId());
OAuth2AccessToken enhancedToken = jwtTokenEnhancer.enhance(oauth2ClientContext.getAccessToken(),
tokenService.loadAuthentication(oauth2ClientContext.getAccessToken().getValue()));
TokenResponse tokenResponse = new TokenResponse(enhancedToken.getValue(),
enhancedToken.getTokenType(),
enhancedToken.getRefreshToken() != null ? enhancedToken.getRefreshToken().getValue() : "");
ObjectMapper mapper = new ObjectMapper();
String jsonTokenEnhancedJack = mapper.writeValueAsString(tokenResponse);
response.addHeader("Content-Type", "application/json");
response.getWriter().flush();
response.getWriter().print(jsonTokenEnhancedJack);
}
return result;
} catch (Exception e) {
log.info("error");
log.error("error", e);
e.printStackTrace();
} finally {
return result;
}
}
}
Thank you in advance
As asked by Son Goku just putting some code to help him
First you have to put the filter like this
#Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/**")
.addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class)
.authorizeRequests()
.anyRequest().permitAll()
.and().csrf().disable();
}
private Filter ssoFilter() {
OAuth2ClientAuthenticationProcessingFilter facebookFilter = new MyOAuth2ClientAuthenticationProcessingFilter("/user/social");
OAuth2RestTemplate facebookTemplate = new OAuth2RestTemplate(Oauth2facebook(), oauth2ClientContext);
facebookFilter.setRestTemplate(facebookTemplate);
facebookFilter.setTokenServices(new UserInfoTokenServices(
"https://graph.facebook.com/me",
facebookProperties.getAppId()
));
return facebookFilter;
}
After that you can use the OAuth2ClientAuthenticationProcessingFilter as in first question.
Also, in first question i customized this method a lot, it works but i was surprised to not find this as easy as these library use to be.
Hope it helps you, i have struggled a bit too on this.
Maybe now, spring boot handle this much more easily.

Resources