org.springframework.security.oauth2.core.oidc.user.OidcUser Java Examples

The following examples show how to use org.springframework.security.oauth2.core.oidc.user.OidcUser. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SecurityUtilsUnitTest.java    From java-microservices-examples with Apache License 2.0 7 votes vote down vote up
@Test
public void testGetCurrentUserLoginForOAuth2() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    Map<String, Object> claims = new HashMap<>();
    claims.put("groups", "ROLE_USER");
    claims.put("sub", 123);
    claims.put("preferred_username", "admin");
    OidcIdToken idToken = new OidcIdToken(ID_TOKEN, Instant.now(),
        Instant.now().plusSeconds(60), claims);
    Collection<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
    OidcUser user = new DefaultOidcUser(authorities, idToken);
    OAuth2AuthenticationToken bla = new OAuth2AuthenticationToken(user, authorities, "oidc");
    securityContext.setAuthentication(bla);
    SecurityContextHolder.setContext(securityContext);

    Optional<String> login = SecurityUtils.getCurrentUserLogin();

    assertThat(login).contains("admin");
}
 
Example #2
Source File: MessagingController.java    From messaging-app with Apache License 2.0 7 votes vote down vote up
@PostMapping
public String save(@RegisteredOAuth2AuthorizedClient("messaging") OAuth2AuthorizedClient messagingClient,
					@Valid Message message,
					@AuthenticationPrincipal OidcUser oidcUser) {
	message.setFromId(oidcUser.getClaimAsString("user_name"));
	message = this.webClient
			.post()
			.uri(this.messagesBaseUri)
			.contentType(MediaType.APPLICATION_JSON)
			.syncBody(message)
			.attributes(oauth2AuthorizedClient(messagingClient))
			.retrieve()
			.bodyToMono(Message.class)
			.block();
	return "redirect:/messages/sent";
}
 
Example #3
Source File: SecurityUtilsUnitTest.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCurrentUserLoginForOAuth2() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    Map<String, Object> claims = new HashMap<>();
    claims.put("groups", "ROLE_USER");
    claims.put("sub", 123);
    claims.put("preferred_username", "admin");
    OidcIdToken idToken = new OidcIdToken(ID_TOKEN, Instant.now(),
        Instant.now().plusSeconds(60), claims);
    Collection<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
    OidcUser user = new DefaultOidcUser(authorities, idToken);
    OAuth2AuthenticationToken bla = new OAuth2AuthenticationToken(user, authorities, "oidc");
    securityContext.setAuthentication(bla);
    SecurityContextHolder.setContext(securityContext);

    Optional<String> login = SecurityUtils.getCurrentUserLogin();

    assertThat(login).contains("admin");
}
 
Example #4
Source File: SecurityUtilsUnitTest.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCurrentUserLoginForOAuth2() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    Map<String, Object> claims = new HashMap<>();
    claims.put("groups", "ROLE_USER");
    claims.put("sub", 123);
    claims.put("preferred_username", "admin");
    OidcIdToken idToken = new OidcIdToken(ID_TOKEN, Instant.now(),
        Instant.now().plusSeconds(60), claims);
    Collection<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
    OidcUser user = new DefaultOidcUser(authorities, idToken);
    OAuth2AuthenticationToken bla = new OAuth2AuthenticationToken(user, authorities, "oidc");
    securityContext.setAuthentication(bla);
    SecurityContextHolder.setContext(securityContext);

    Optional<String> login = SecurityUtils.getCurrentUserLogin();

    assertThat(login).contains("admin");
}
 
Example #5
Source File: AbstractFlowController.java    From oauth2-protocol-patterns with Apache License 2.0 6 votes vote down vote up
protected ServiceCallResponse fromUiApp(OAuth2AuthenticationToken oauth2Authentication,
										HttpServletRequest request,
										ServiceCallResponse... serviceCallResponses) {

	OidcUser oidcUser = (OidcUser) oauth2Authentication.getPrincipal();

	ServiceCallResponse serviceCallResponse = new ServiceCallResponse();
	serviceCallResponse.setServiceName(ServicesConfig.UI_APP);
	serviceCallResponse.setServiceUri(request.getRequestURL().toString());
	serviceCallResponse.setJti("(opaque to client)");
	serviceCallResponse.setSub(oidcUser.getSubject());
	serviceCallResponse.setAud(oidcUser.getAudience());
	serviceCallResponse.setAuthorities(oauth2Authentication.getAuthorities().stream()
			.map(GrantedAuthority::getAuthority).sorted().collect(Collectors.toList()));
	if (serviceCallResponses != null) {
		serviceCallResponse.setServiceCallResponses(Arrays.asList(serviceCallResponses));
	}

	return serviceCallResponse;
}
 
Example #6
Source File: OidcUserMapperImpl.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
private User createUserMapping(OidcUser oidcUser, OidcUserRequest userRequest) {
  User user =
      dataService
          .query(UserMetadata.USER, User.class)
          .eq(UserMetadata.EMAIL, oidcUser.getEmail())
          .findOne();
  if (user == null) {
    user = createUser(oidcUser);
  }

  OidcClient oidcClient = getOidcClient(userRequest);

  OidcUserMapping oidcUserMapping = oidcUserMappingFactory.create();
  oidcUserMapping.setLabel(
      userRequest.getClientRegistration().getRegistrationId() + ':' + oidcUser.getSubject());
  oidcUserMapping.setOidcClient(oidcClient);
  oidcUserMapping.setOidcUsername(oidcUser.getSubject());
  oidcUserMapping.setUser(user);
  dataService.add(OIDC_USER_MAPPING, oidcUserMapping);

  return user;
}
 
Example #7
Source File: UserDetailsFormatter.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
public static UserDetails getCurrentUser() {
    final SecurityContext context = (SecurityContext) VaadinService.getCurrentRequest().getWrappedSession()
            .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
    Authentication authentication = context.getAuthentication();
    if (authentication instanceof OAuth2AuthenticationToken) {
        OidcUser oidcUser = (OidcUser) authentication.getPrincipal();
        Object details = authentication.getDetails();
        String tenant = "DEFAULT";
        if (details instanceof TenantAwareAuthenticationDetails) {
            tenant = ((TenantAwareAuthenticationDetails) details).getTenant();
        }
        return new UserPrincipal(oidcUser.getPreferredUsername(), "***", oidcUser.getGivenName(),
                oidcUser.getFamilyName(), oidcUser.getPreferredUsername(), oidcUser.getEmail(), tenant,
                oidcUser.getAuthorities());
    } else {
        return (UserDetails) authentication.getPrincipal();
    }
}
 
Example #8
Source File: OidcUserManagementAutoConfiguration.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void logout(final HttpServletRequest request, final HttpServletResponse response,
        final Authentication authentication) {
    super.logout(request, response, authentication);

    final Object principal = authentication.getPrincipal();
    if (principal instanceof OidcUser) {
        final OidcUser user = (OidcUser) authentication.getPrincipal();
        final String endSessionEndpoint = user.getIssuer() + "/protocol/openid-connect/logout";

        final UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(endSessionEndpoint)
                .queryParam("id_token_hint", user.getIdToken().getTokenValue());

        final RestTemplate restTemplate = new RestTemplate();
        restTemplate.getForEntity(builder.toUriString(), String.class);
    }
}
 
Example #9
Source File: TravelGatewayApplication.java    From spring-security-samples with MIT License 5 votes vote down vote up
@GetMapping("/whoami")
@ResponseBody
public Map<String, Object> index(
		@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient,
		@AuthenticationPrincipal OidcUser oidcUser) {
	Map<String, Object> model = new HashMap<>();
	model.put("clientName", authorizedClient.getClientRegistration().getClientName());
	model.put("userName", oidcUser.getName());
	model.put("userAttributes", oidcUser.getAttributes());
	return model;
}
 
Example #10
Source File: OidcUserMapperImpl.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Transactional
@Override
public User toUser(OidcUser oidcUser, OidcUserRequest userRequest) {
  verifyOidcUser(oidcUser);
  return runAsSystem(
      () ->
          getUser(oidcUser, userRequest)
              .orElseGet(() -> createUserMapping(oidcUser, userRequest)));
}
 
Example #11
Source File: OidcUserMapperImpl.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void verifyOidcUser(OidcUser oidcUser) {
  if (oidcUser.getEmail() == null) {
    throw new OidcUserMissingEmailException(oidcUser);
  }
  Boolean emailVerified = oidcUser.getEmailVerified();
  if (emailVerified != null && !emailVerified) {
    throw new OidcUserEmailVerificationException(oidcUser);
  }
}
 
Example #12
Source File: OidcUserMapperImpl.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Optional<User> getUser(OidcUser oidcUser, OidcUserRequest userRequest) {
  OidcUserMapping oidcUserMapping =
      dataService
          .query(OIDC_USER_MAPPING, OidcUserMapping.class)
          .eq(OIDC_CLIENT, userRequest.getClientRegistration().getRegistrationId())
          .and()
          .eq(OIDC_USERNAME, oidcUser.getSubject())
          .findOne();
  return oidcUserMapping != null ? Optional.of(oidcUserMapping.getUser()) : Optional.empty();
}
 
Example #13
Source File: OidcUserMapperImpl.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
private User createUser(OidcUser oidcUser) {
  User user = userFactory.create();
  user.setUsername(oidcUser.getEmail());
  user.setPassword(UUID.randomUUID().toString());
  user.setEmail(oidcUser.getEmail());
  user.setActive(true);
  user.setFirstName(oidcUser.getGivenName());
  user.setLastName(oidcUser.getFamilyName());

  dataService.add(UserMetadata.USER, user);

  return user;
}
 
Example #14
Source File: MappedOidcUserService.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
private MappedOidcUser createOidcUser(OidcUser oidcUser, OidcUserRequest userRequest) {
  User user = oidcUserMapper.toUser(oidcUser, userRequest);
  String userNameAttributeName = getUserNameAttributeName(userRequest);
  Set<GrantedAuthority> authorities = new HashSet<>(userDetailsServiceImpl.getAuthorities(user));
  return new MappedOidcUser(
      authorities,
      oidcUser.getIdToken(),
      oidcUser.getUserInfo(),
      userNameAttributeName,
      user.getUsername());
}
 
Example #15
Source File: OidcUserMapperImplTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testToUserExistingUserMapping() {
  String email = "[email protected]";
  String username = "username";

  OidcUser oidcUser = mock(OidcUser.class);
  when(oidcUser.getEmail()).thenReturn(email);
  when(oidcUser.getEmailVerified()).thenReturn(true);
  when(oidcUser.getSubject()).thenReturn(username);

  String registrationId = "google";
  ClientRegistration clientRegistration =
      CommonOAuth2Provider.GOOGLE
          .getBuilder(registrationId)
          .clientId("clientId")
          .clientSecret("clientSecret")
          .build();

  OidcUserRequest oidcUserRequest = mock(OidcUserRequest.class);
  when(oidcUserRequest.getClientRegistration()).thenReturn(clientRegistration);

  User user = mock(User.class);

  OidcUserMapping oidcUserMapping = mock(OidcUserMapping.class);
  when(oidcUserMapping.getUser()).thenReturn(user);

  @SuppressWarnings("unchecked")
  Query<OidcUserMapping> query = mock(Query.class, RETURNS_SELF);
  when(dataService.query(OIDC_USER_MAPPING, OidcUserMapping.class)).thenReturn(query);
  when(query.eq(OIDC_CLIENT, registrationId).and().eq(OIDC_USERNAME, username).findOne())
      .thenReturn(oidcUserMapping);

  assertEquals(user, oidcUserMapperImpl.toUser(oidcUser, oidcUserRequest));
}
 
Example #16
Source File: OidcUserMapperImplTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testToUserEmailMissing() {
  OidcUser oidcUser = mock(OidcUser.class);
  OidcUserRequest oidcUserRequest = mock(OidcUserRequest.class);
  assertThrows(
      OidcUserMissingEmailException.class,
      () -> oidcUserMapperImpl.toUser(oidcUser, oidcUserRequest));
}
 
Example #17
Source File: OidcUserMapperImplTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testToUserEmailNotVerified() {
  OidcUser oidcUser = mock(OidcUser.class);
  when(oidcUser.getEmail()).thenReturn("[email protected]");
  when(oidcUser.getEmailVerified()).thenReturn(false);
  OidcUserRequest oidcUserRequest = mock(OidcUserRequest.class);
  assertThrows(
      OidcUserEmailVerificationException.class,
      () -> oidcUserMapperImpl.toUser(oidcUser, oidcUserRequest));
}
 
Example #18
Source File: UserService.java    From tutorials with MIT License 5 votes vote down vote up
public Map<String, Object> getUserClaims() {
    Authentication authentication = SecurityContextHolder.getContext()
        .getAuthentication();
    if (authentication.getPrincipal() instanceof OidcUser) {
        OidcUser principal = ((OidcUser) authentication.getPrincipal());
        return principal.getClaims();
    }
    return Collections.emptyMap();
}
 
Example #19
Source File: PrincipalToRequestHeaderFilterFactory.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public GatewayFilter apply(final NameConfig config) {
    return (exchange, chain) -> exchange.getSession().
            flatMap(session -> Mono.justOrEmpty(Optional.ofNullable(
            cacheManager.getCache(SessionConfig.DEFAULT_CACHE).get(session.getId(), Session.class)).
            map(cachedSession -> {
                String principal = null;

                SecurityContext ctx = cachedSession.getAttribute(
                        WebSessionServerSecurityContextRepository.DEFAULT_SPRING_SECURITY_CONTEXT_ATTR_NAME);
                if (ctx != null && ctx.getAuthentication() != null) {
                    if (ctx.getAuthentication().getPrincipal() instanceof OidcUser) {
                        principal = ((OidcUser) ctx.getAuthentication().getPrincipal()).
                                getIdToken().getTokenValue();
                    } else if (ctx.getAuthentication().getPrincipal() instanceof OAuth2User) {
                        principal = Objects.toString(((OAuth2User) ctx.getAuthentication().getPrincipal()).
                                getAttributes().get(StandardClaimNames.PREFERRED_USERNAME), null);
                    } else {
                        principal = ctx.getAuthentication().getName();
                    }
                }

                return principal;
            }))).
            transform(principal -> principal.flatMap(p -> StringUtils.isEmpty(p)
            ? chain.filter(exchange)
            : chain.filter(exchange.mutate().
                    request(exchange.getRequest().mutate().
                            headers(headers -> headers.add(config.getName(), p)).build()).
                    build()))).
            switchIfEmpty(chain.filter(exchange));
}
 
Example #20
Source File: OidcClientInitiatedServerLogoutSuccessHandler.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> onLogoutSuccess(final WebFilterExchange exchange, final Authentication authentication) {
    return Mono.just(authentication).
            filter(OAuth2AuthenticationToken.class::isInstance).
            filter(token -> authentication.getPrincipal() instanceof OidcUser).
            map(OAuth2AuthenticationToken.class::cast).
            flatMap(this::endSessionEndpoint).
            map(endSessionEndpoint -> endpointUri(exchange, endSessionEndpoint, authentication)).
            switchIfEmpty(serverLogoutSuccessHandler.onLogoutSuccess(exchange, authentication).then(Mono.empty())).
            flatMap(endpointUri -> redirectStrategy.sendRedirect(exchange.getExchange(), endpointUri));
}
 
Example #21
Source File: SpringSecurityAuditorAware.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
private static String getCurrentAuditor(final Authentication authentication) {
    if (authentication.getPrincipal() instanceof UserDetails) {
        return ((UserDetails) authentication.getPrincipal()).getUsername();
    }
    if (authentication.getPrincipal() instanceof OidcUser) {
        return ((OidcUser) authentication.getPrincipal()).getPreferredUsername();
    }
    return authentication.getPrincipal().toString();
}
 
Example #22
Source File: OidcUserManagementAutoConfiguration.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @return the oauth2 user details service to load a user from oidc user
 *         manager
 */
@Bean
@ConditionalOnMissingBean
public OAuth2UserService<OidcUserRequest, OidcUser> oidcUserDetailsService(
        final JwtAuthoritiesExtractor extractor) {
    return new JwtAuthoritiesOidcUserService(extractor);
}
 
Example #23
Source File: DefaultControllerAdvice.java    From oauth2-protocol-patterns with Apache License 2.0 5 votes vote down vote up
@ModelAttribute("idTokenClaims")
Map<String, Object> idTokenClaims(OAuth2AuthenticationToken oauth2Authentication) {
	if (oauth2Authentication == null) {
		return Collections.emptyMap();
	}
	OidcUser oidcUser = (OidcUser) oauth2Authentication.getPrincipal();
	final List<String> claimNames = Arrays.asList("iss", "sub", "aud", "azp", "given_name", "family_name", "email");
	return oidcUser.getClaims().entrySet().stream()
			.filter(e -> claimNames.contains(e.getKey()))
			.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
 
Example #24
Source File: RoleAwareOAuth2UserService.java    From ods-provisioning-app with Apache License 2.0 5 votes vote down vote up
@Override
public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
  // Delegate to the default implementation for loading a user
  OidcUser oidcUser = delegate.loadUser(userRequest);

  // Fetch the authority information from the protected resource using idToken
  Collection<GrantedAuthority> mappedAuthorities =
      extractAuthorities(userRequest, extractOnlyOpendevstackRoles);
  mappedAuthorities.addAll(oidcUser.getAuthorities());

  // Create a copy of oidcUser but use the mappedAuthorities instead
  DefaultOidcUser oidcUserWithAuthorities =
      new DefaultOidcUser(mappedAuthorities, oidcUser.getIdToken(), oidcUser.getUserInfo());
  return oidcUserWithAuthorities;
}
 
Example #25
Source File: HomeController.java    From tutorials with MIT License 4 votes vote down vote up
@GetMapping("/")
public String home(@AuthenticationPrincipal OidcUser user) {
    return "Welcome, "+ user.getFullName() +"!";
}
 
Example #26
Source File: RouteProviderTest.java    From syncope with Apache License 2.0 4 votes vote down vote up
@Test
public void principalToRequestHeader() throws IllegalArgumentException, IllegalAccessException {
    // first mock...
    OidcIdToken oidcIdToken = mock(OidcIdToken.class);
    when(oidcIdToken.getTokenValue()).thenReturn("john.doe");

    OidcUser user = mock(OidcUser.class);
    when(user.getIdToken()).thenReturn(oidcIdToken);

    Authentication authentication = mock(Authentication.class);
    when(authentication.getPrincipal()).thenReturn(user);

    MapSession session = new MapSession();
    session.setAttribute(
            WebSessionServerSecurityContextRepository.DEFAULT_SPRING_SECURITY_CONTEXT_ATTR_NAME,
            new SecurityContextImpl(authentication));

    Cache cache = mock(Cache.class);
    when(cache.get(anyString(), eq(Session.class))).thenReturn(session);

    CacheManager cacheManager = mock(CacheManager.class);
    when(cacheManager.getCache(eq(SessionConfig.DEFAULT_CACHE))).thenReturn(cache);

    PrincipalToRequestHeaderFilterFactory factory = new PrincipalToRequestHeaderFilterFactory();
    ReflectionTestUtils.setField(factory, "cacheManager", cacheManager);
    ctx.getBeanFactory().registerSingleton(PrincipalToRequestHeaderFilterFactory.class.getName(), factory);

    // ...then test
    stubFor(get(urlEqualTo("/principalToRequestHeader")).willReturn(aResponse()));

    SRARouteTO route = new SRARouteTO();
    route.setKey("principalToRequestHeader");
    route.setTarget(URI.create("http://localhost:" + wiremockPort));
    route.setType(SRARouteType.PROTECTED);
    route.getFilters().add(new SRARouteFilter.Builder().
            factory(SRARouteFilterFactory.PRINCIPAL_TO_REQUEST_HEADER).args("HTTP_REMOTE_USER").build());

    SyncopeCoreTestingServer.ROUTES.put(route.getKey(), route);
    routeRefresher.refresh();

    webClient.get().uri("/principalToRequestHeader").exchange().
            expectStatus().isOk();

    verify(getRequestedFor(urlEqualTo("/principalToRequestHeader")).
            withHeader("HTTP_REMOTE_USER", equalTo("john.doe")));
}
 
Example #27
Source File: UserRestController.java    From tutorials with MIT License 4 votes vote down vote up
@GetMapping("/oidc-principal")
public OidcUser getOidcUserPrincipal(@AuthenticationPrincipal OidcUser principal) {
    return principal;
}
 
Example #28
Source File: LogoutResourceIT.java    From java-microservices-examples with Apache License 2.0 4 votes vote down vote up
private OAuth2AuthenticationToken authenticationToken(OidcIdToken idToken) {
    Collection<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
    OidcUser user = new DefaultOidcUser(authorities, idToken);
    return new OAuth2AuthenticationToken(user, authorities, "oidc");
}
 
Example #29
Source File: UserRestController.java    From tutorials with MIT License 4 votes vote down vote up
@GetMapping("/oidc-principal")
public OidcUser getOidcUserPrincipal(@AuthenticationPrincipal OidcUser principal) {
    return principal;
}
 
Example #30
Source File: UserRestController.java    From tutorials with MIT License 4 votes vote down vote up
@GetMapping("/oidc-principal")
public OidcUser getOidcUserPrincipal(@AuthenticationPrincipal OidcUser principal) {
    return principal;
}