org.springframework.security.oauth2.core.oidc.OidcIdToken Java Examples

The following examples show how to use org.springframework.security.oauth2.core.oidc.OidcIdToken. 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: 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 #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: LogoutResource.java    From java-microservices-examples with Apache License 2.0 5 votes vote down vote up
/**
 * {@code POST  /api/logout} : logout the current user.
 *
 * @param request the {@link HttpServletRequest}.
 * @param idToken the ID token.
 * @return the {@link ResponseEntity} with status {@code 200 (OK)} and a body with a global logout URL and ID token.
 */
@PostMapping("/api/logout")
public ResponseEntity<?> logout(HttpServletRequest request,
                                @AuthenticationPrincipal(expression = "idToken") OidcIdToken idToken) {
    String logoutUrl = this.registration.getProviderDetails()
        .getConfigurationMetadata().get("end_session_endpoint").toString();

    Map<String, String> logoutDetails = new HashMap<>();
    logoutDetails.put("logoutUrl", logoutUrl);
    logoutDetails.put("idToken", idToken.getTokenValue());
    request.getSession().invalidate();
    return ResponseEntity.ok().body(logoutDetails);
}
 
Example #5
Source File: LogoutResourceIT.java    From java-microservices-examples with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void before() throws Exception {
    Map<String, Object> claims = new HashMap<>();
    claims.put("groups", "ROLE_USER");
    claims.put("sub", 123);
    OidcIdToken idToken = new OidcIdToken(ID_TOKEN, Instant.now(),
        Instant.now().plusSeconds(60), claims);
    SecurityContextHolder.getContext().setAuthentication(authenticationToken(idToken));
    SecurityContextHolderAwareRequestFilter authInjector = new SecurityContextHolderAwareRequestFilter();
    authInjector.afterPropertiesSet();

    this.restLogoutMockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
 
Example #6
Source File: SecurityConfig.java    From oauth2-client with MIT License 5 votes vote down vote up
/**
 * 从user-info-uri 返回结果中抽取权限信息,如角色等,默认为scope
 * Mapping User Authorities
 * https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#oauth2login-advanced-map-authorities
 */
@Deprecated
private GrantedAuthoritiesMapper userAuthoritiesMapper() {
    return (authorities) -> {
        Set<GrantedAuthority> mappedAuthorities = new HashSet<>();

        authorities.forEach(authority -> {
            if (OidcUserAuthority.class.isInstance(authority)) {
                OidcUserAuthority oidcUserAuthority = (OidcUserAuthority) authority;
                OidcIdToken idToken = oidcUserAuthority.getIdToken();
                OidcUserInfo userInfo = oidcUserAuthority.getUserInfo();

                System.out.println(oidcUserAuthority);

                // Map the claims found in idToken and/or userInfo
                // to one or more GrantedAuthority's and add it to mappedAuthorities

            } else if (OAuth2UserAuthority.class.isInstance(authority)) {
                OAuth2UserAuthority oauth2UserAuthority = (OAuth2UserAuthority) authority;

                Map<String, Object> userAttributes = oauth2UserAuthority.getAttributes();
                System.out.println(userAttributes);
                // Map the attributes found in userAttributes
                // to one or more GrantedAuthority's and add it to mappedAuthorities

            } else if (SimpleGrantedAuthority.class.isInstance(authority)) {
                SimpleGrantedAuthority simpleGrantedAuthority = (SimpleGrantedAuthority) authority;

                System.out.println(simpleGrantedAuthority);

            }
        });

        return mappedAuthorities;
    };
}
 
Example #7
Source File: LogoutResource.java    From jhipster-registry with Apache License 2.0 5 votes vote down vote up
/**
 * {@code POST  /api/logout} : logout the current user.
 *
 * @param request the {@link HttpServletRequest}.
 * @param idToken the ID token.
 * @return the {@link ResponseEntity} with status {@code 200 (OK)} and a body with a global logout URL and ID token.
 */
@PostMapping("/api/logout")
public ResponseEntity<?> logout(HttpServletRequest request,
                                @AuthenticationPrincipal(expression = "idToken") OidcIdToken idToken) {
    String logoutUrl = this.registration.getProviderDetails()
        .getConfigurationMetadata().get("end_session_endpoint").toString();

    Map<String, String> logoutDetails = new HashMap<>();
    logoutDetails.put("logoutUrl", logoutUrl);
    logoutDetails.put("idToken", idToken.getTokenValue());
    request.getSession().invalidate();
    return ResponseEntity.ok().body(logoutDetails);
}
 
Example #8
Source File: LogoutResourceIT.java    From jhipster-registry with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void before() throws Exception {
    Map<String, Object> claims = new HashMap<>();
    claims.put("groups", "ROLE_USER");
    claims.put("sub", 123);
    OidcIdToken idToken = new OidcIdToken(ID_TOKEN, Instant.now(),
        Instant.now().plusSeconds(60), claims);
    SecurityContextHolder.getContext().setAuthentication(authenticationToken(idToken));
    SecurityContextHolderAwareRequestFilter authInjector = new SecurityContextHolderAwareRequestFilter();
    authInjector.afterPropertiesSet();

    this.restLogoutMockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
 
Example #9
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 #10
Source File: MappedOidcUser.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
MappedOidcUser(
    Set<GrantedAuthority> authorities,
    OidcIdToken idToken,
    OidcUserInfo userInfo,
    String nameAttributeKey,
    String username) {
  super(authorities, idToken, userInfo, nameAttributeKey);
  this.username = requireNonNull(username);
}
 
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");
}
 
Example #13
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")));
}