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

The following examples show how to use org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser. 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: SecurityUtils.java    From java-microservices-examples with Apache License 2.0 8 votes vote down vote up
/**
 * Get the login of the current user.
 *
 * @return the login of the current user.
 */
public static Optional<String> getCurrentUserLogin() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    return Optional.ofNullable(securityContext.getAuthentication())
        .map(authentication -> {
            if (authentication.getPrincipal() instanceof UserDetails) {
                UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
                return springSecurityUser.getUsername();
            } else if (authentication.getPrincipal() instanceof DefaultOidcUser) {
                Map<String, Object> attributes = ((DefaultOidcUser) authentication.getPrincipal()).getAttributes();
                if (attributes.containsKey("preferred_username")) {
                    return (String) attributes.get("preferred_username");
                }
            } else if (authentication.getPrincipal() instanceof String) {
                return (String) authentication.getPrincipal();
            }
            return null;
        });
}
 
Example #2
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 #3
Source File: SecurityUtils.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
/**
 * Get the login of the current user.
 *
 * @return the login of the current user.
 */
public static Optional<String> getCurrentUserLogin() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    return Optional.ofNullable(securityContext.getAuthentication())
        .map(authentication -> {
            if (authentication.getPrincipal() instanceof UserDetails) {
                UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
                return springSecurityUser.getUsername();
            } else if (authentication.getPrincipal() instanceof DefaultOidcUser) {
                Map<String, Object> attributes = ((DefaultOidcUser) authentication.getPrincipal()).getAttributes();
                if (attributes.containsKey("preferred_username")) {
                    return (String) attributes.get("preferred_username");
                }
            } else if (authentication.getPrincipal() instanceof String) {
                return (String) authentication.getPrincipal();
            }
            return null;
        });
}
 
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: SecurityUtils.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
/**
 * Get the login of the current user.
 *
 * @return the login of the current user.
 */
public static Optional<String> getCurrentUserLogin() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    return Optional.ofNullable(securityContext.getAuthentication())
        .map(authentication -> {
            if (authentication.getPrincipal() instanceof UserDetails) {
                UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
                return springSecurityUser.getUsername();
            } else if (authentication.getPrincipal() instanceof DefaultOidcUser) {
                Map<String, Object> attributes = ((DefaultOidcUser) authentication.getPrincipal()).getAttributes();
                if (attributes.containsKey("preferred_username")) {
                    return (String) attributes.get("preferred_username");
                }
            } else if (authentication.getPrincipal() instanceof String) {
                return (String) authentication.getPrincipal();
            }
            return null;
        });
}
 
Example #6
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 #7
Source File: Oauth2AuthenticationManager.java    From ods-provisioning-app with Apache License 2.0 5 votes vote down vote up
/** @see IODSAuthnzAdapter#getUserName() */
public String getUserName() {
  Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
  if (DefaultOidcUser.class.isInstance(principal)) {
    return ((DefaultOidcUser) principal).getEmail();
  } else if (CrowdUserDetails.class.isInstance(principal)) {
    return ((CrowdUserDetails) principal).getUsername();
  } else {
    throw new RuntimeException(
        String.format(
            "Unexpected error! Contact developers! Unsupported Principal object class '%s'! Supported Principal classes are String or DefaultOAuth2User",
            principal.getClass()));
  }
}
 
Example #8
Source File: Oauth2AuthenticationManager.java    From ods-provisioning-app with Apache License 2.0 5 votes vote down vote up
@Override
public String getUserEmail() {
  return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
      .filter(auth -> auth.getPrincipal() instanceof DefaultOidcUser)
      .map(auth -> (DefaultOidcUser) auth.getPrincipal())
      .map(StandardClaimAccessor::getEmail)
      .orElse(null);
}
 
Example #9
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 #10
Source File: OidcUserManagementAutoConfiguration.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {

    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication instanceof JwtAuthenticationToken) {
        final String defaultTenant = "DEFAULT";

        final JwtAuthenticationToken jwtAuthenticationToken = (JwtAuthenticationToken) authentication;
        final Jwt jwt = jwtAuthenticationToken.getToken();
        final OidcIdToken idToken = new OidcIdToken(jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getExpiresAt(),
                jwt.getClaims());
        final OidcUserInfo userInfo = new OidcUserInfo(jwt.getClaims());

        final Set<GrantedAuthority> authorities = authoritiesExtractor.extract(clientRegistration.getClientId(),
                jwt.getClaims());

        if (authorities.isEmpty()) {
            ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }

        final DefaultOidcUser user = new DefaultOidcUser(authorities, idToken, userInfo);

        final OAuth2AuthenticationToken oAuth2AuthenticationToken = new OAuth2AuthenticationToken(user, authorities,
                clientRegistration.getRegistrationId());

        oAuth2AuthenticationToken.setDetails(new TenantAwareAuthenticationDetails(defaultTenant, false));

        systemSecurityContext.runAsSystemAsTenant(systemManagement::getTenantMetadata, defaultTenant);
        SecurityContextHolder.getContext().setAuthentication(oAuth2AuthenticationToken);
    }

    chain.doFilter(request, response);
}
 
Example #11
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 #12
Source File: LogoutResourceIT.java    From jhipster-registry 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");
}