Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add custom claim converter in a microservice with oauth2 #12609

Merged
merged 5 commits into from
Jan 11, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions generators/server/files.js
Original file line number Diff line number Diff line change
Expand Up @@ -893,6 +893,30 @@ const serverFiles = {
templates: ['config/bootstrap.yml', 'config/bootstrap-prod.yml'],
},
],
serverMicroserviceAndOauth: [
{
condition: generator =>
!generator.reactive && generator.authenticationType === 'oauth2' && generator.applicationType === 'microservice',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This conditional (and others) should include applicationType === 'monolith' and gateway too. We configure these as resource servers by default for Ionic and React Native apps.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Falydoor I believe this comment still needs to be addressed.

path: SERVER_MAIN_SRC_DIR,
templates: [
{
file: 'package/security/oauth2/CustomClaimConverter.java',
renameTo: generator => `${generator.javaDir}security/oauth2/CustomClaimConverter.java`,
},
],
},
{
condition: generator =>
!generator.reactive && generator.authenticationType === 'oauth2' && generator.applicationType === 'microservice',
path: SERVER_TEST_SRC_DIR,
templates: [
{
file: 'package/security/oauth2/CustomClaimConverterIT.java',
renameTo: generator => `${generator.javaDir}security/oauth2/CustomClaimConverterIT.java`,
},
],
},
],
serverJavaApp: [
{
path: SERVER_MAIN_SRC_DIR,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@ import <%= packageName %>.security.oauth2.JwtGrantedAuthorityConverter;
<%_ if (authenticationType === 'jwt' && applicationType !== 'microservice') { _%>
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
<%_ } _%>
<%_ if (authenticationType === 'oauth2' && applicationType === 'microservice') { _%>
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.web.client.RestTemplate;
import <%= packageName %>.security.oauth2.CustomClaimConverter;
<%_ } _%>
import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter;
<%_ if (applicationType !== 'microservice') { _%>
import org.springframework.web.filter.CorsFilter;
Expand Down Expand Up @@ -341,14 +346,17 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
<%_ } _%>

@Bean
JwtDecoder jwtDecoder() {
JwtDecoder jwtDecoder(<%_ if (authenticationType === 'oauth2' && applicationType === 'microservice') { _%>ClientRegistrationRepository clientRegistrationRepository<%_ } _%>) {
NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder) JwtDecoders.fromOidcIssuerLocation(issuerUri);

OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator(jHipsterProperties.getSecurity().getOauth2().getAudience());
OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuerUri);
OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);

jwtDecoder.setJwtValidator(withAudience);
<%_ if (authenticationType === 'oauth2' && applicationType === 'microservice') { _%>
jwtDecoder.setClaimSetConverter(new CustomClaimConverter(clientRegistrationRepository.findByRegistrationId("oidc"), new RestTemplate()));
<%_ } _%>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using new RestTemplate causes so much pains in real world (for example, when your app is behind an outbound proxy).
please prefer RestTemplate rt = restTemplateBuilder.build();


return jwtDecoder;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<%#
Copyright 2013-2020 the original author or authors from the JHipster project.

This file is part of the JHipster project, see https://jhipster.github.io/
for more information.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-%>
package <%= packageName %>.security.oauth2;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.jwt.MappedJwtClaimSetConverter;
import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver;
import org.springframework.security.oauth2.server.resource.web.DefaultBearerTokenResolver;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
* Claim converter to add custom claims by retrieving the user from the userinfo endpoint.
*/
public class CustomClaimConverter implements Converter<Map<String, Object>, Map<String, Object>> {
private final BearerTokenResolver bearerTokenResolver = new DefaultBearerTokenResolver();

private final MappedJwtClaimSetConverter delegate = MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap());

private final RestTemplate restTemplate;

private final ClientRegistration registration;

private final Map<String, ObjectNode> users = new HashMap<>();

public CustomClaimConverter(ClientRegistration registration, RestTemplate restTemplate) {
this.registration = registration;
this.restTemplate = restTemplate;
}

public Map<String, Object> convert(Map<String, Object> claims) {
Map<String, Object> convertedClaims = this.delegate.convert(claims);
if (RequestContextHolder.getRequestAttributes() != null) {
// Retrieve and set the token
String token = bearerTokenResolver.resolve(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
HttpHeaders headers = new HttpHeaders() {{
set("Authorization", "Bearer " + token);
}};

// Retrieve user infos from OAuth provider if not already loaded
ObjectNode user = users.computeIfAbsent(claims.get("sub").toString(), s -> {
ResponseEntity<ObjectNode> userInfo = restTemplate.exchange(registration.getProviderDetails().getUserInfoEndpoint().getUri(), HttpMethod.GET, new HttpEntity<String>(headers), ObjectNode.class);
return userInfo.getBody();
});

// Add custom claims
if (user != null) {
convertedClaims.put("preferred_username", user.get("preferred_username").asText());
convertedClaims.put("given_name", user.get("given_name").asText());
convertedClaims.put("family_name", user.get("family_name").asText());
List<String> groups = StreamSupport.stream(user.get("groups").spliterator(), false)
.map(JsonNode::asText)
.collect(Collectors.toList());
convertedClaims.put("groups", groups);
}
}
return convertedClaims;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<%#
Copyright 2013-2020 the original author or authors from the JHipster project.

This file is part of the JHipster project, see https://jhipster.github.io/
for more information.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-%>
package <%= packageName %>.security.oauth2;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import <%= packageName %>.<%= mainClass %>;
import <%= packageName %>.config.TestSecurityConfiguration;
import <%= packageName %>.security.AuthoritiesConstants;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;

@SpringBootTest(classes = {<%= mainClass %>.class, TestSecurityConfiguration.class})
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use new @IntegrationTest plz, otherwise, it's broken for some config like Redis etc.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good! I opened #13462

@ExtendWith(MockitoExtension.class)
public class CustomClaimConverterIT {
private static final String USERNAME = "admin";
private static final String NAME = "John";
private static final String FAMILY_NAME = "Doe";

@Mock
private RestTemplate restTemplate;

@Autowired
private ClientRegistrationRepository clientRegistrationRepository;

private CustomClaimConverter customClaimConverter;

@BeforeEach
public void initTest() {
customClaimConverter = new CustomClaimConverter(clientRegistrationRepository.findByRegistrationId("oidc"), restTemplate);
ObjectMapper mapper = new ObjectMapper();
ObjectNode user = mapper.createObjectNode();
user.put("preferred_username", USERNAME);
user.put("given_name", NAME);
user.put("family_name", FAMILY_NAME);
user.putArray("groups").add(AuthoritiesConstants.ADMIN).add(AuthoritiesConstants.USER);
ResponseEntity<ObjectNode> userInfo = ResponseEntity.ok(user);
when(restTemplate.exchange(eq("https://api.jhipster.org/user"), eq(HttpMethod.GET), any(HttpEntity.class), ArgumentMatchers.<Class<ObjectNode>>any())).thenReturn(userInfo);
}

@Test
@Transactional
public void testConvert() {
Map<String, Object> claims = new HashMap<>();
claims.put("sub", "123");
Map<String, Object> convertedClaims = customClaimConverter.convert(claims);

assertThat(convertedClaims.get("preferred_username")).isEqualTo(USERNAME);
assertThat(convertedClaims.get("given_name")).isEqualTo(NAME);
assertThat(convertedClaims.get("family_name")).isEqualTo(FAMILY_NAME);
assertThat(convertedClaims.get("groups")).isEqualTo(List.of(AuthoritiesConstants.ADMIN, AuthoritiesConstants.USER));
}
}