Java源码示例:org.apache.cxf.rs.security.oidc.common.IdToken

示例1
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    OidcSecurityContext secCtx = (OidcSecurityContext) requestContext.getSecurityContext();
    OidcClientTokenContext tokenCtx = secCtx.getOidcContext();
    IdToken idToken = tokenCtx.getIdToken();
    String email = idToken.getEmail();
    boolean configured = false;
    try {
        configured = googleConfig.getServiceAccountEmail() != null && googleConfig.readServiceAccountKey() != null;
    } catch (NoPrivateKeyException e) {
    }
    if (configured) {
        log.error("Unauthorized access from {}. Application is already configured!", email);
        ServerError err = new ServerError("E002", "Unauthorized access to Configuration API");
        requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).entity(err).type(MediaType.APPLICATION_JSON).build());
    }
}
 
示例2
private static IdToken getValidatedIdToken(final OIDCProvider op, final Consumer consumer,
                                           final String jwtIdToken) {
    IdTokenReader idTokenReader = new IdTokenReader();
    idTokenReader.setClockOffset(10);
    idTokenReader.setIssuerId(op.getIssuer());
    idTokenReader.setJwkSetClient(WebClient.create(op.getJwksUri(), List.of(new JsonWebKeysProvider())).
            accept(MediaType.APPLICATION_JSON));
    IdToken idToken;
    try {
        idToken = idTokenReader.getIdToken(jwtIdToken, consumer);
    } catch (Exception e) {
        LOG.error("While validating the id_token", e);
        SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
        sce.getElements().add(e.getMessage());
        throw sce;
    }
    return idToken;
}
 
示例3
private static UserInfo getUserInfo(
    final String endpoint,
    final String accessToken,
    final IdToken idToken,
    final Consumer consumer) {

    WebClient userInfoServiceClient = WebClient.create(endpoint, List.of(new JsonMapObjectProvider())).
            accept(MediaType.APPLICATION_JSON);
    ClientAccessToken clientAccessToken =
            new ClientAccessToken(OAuthConstants.BEARER_AUTHORIZATION_SCHEME, accessToken);
    UserInfoClient userInfoClient = new UserInfoClient();
    userInfoClient.setUserInfoServiceClient(userInfoServiceClient);
    UserInfo userInfo = null;
    try {
        userInfo = userInfoClient.getUserInfo(clientAccessToken, idToken, consumer);
    } catch (Exception e) {
        LOG.error("While getting the userInfo", e);
        SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
        sce.getElements().add(e.getMessage());
        throw sce;
    }
    return userInfo;
}
 
示例4
private void validateIdToken(String idToken, String nonce)
    throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(idToken);
    JwtToken jwt = jwtConsumer.getJwtToken();

    // Validate claims
    assertEquals("alice", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
    assertEquals("OIDC IdP", jwt.getClaim(JwtConstants.CLAIM_ISSUER));
    assertEquals("consumer-id", jwt.getClaim(JwtConstants.CLAIM_AUDIENCE));
    assertNotNull(jwt.getClaim(JwtConstants.CLAIM_EXPIRY));
    assertNotNull(jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT));
    if (nonce != null) {
        assertEquals(nonce, jwt.getClaim(IdToken.NONCE_CLAIM));
    }

    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(ClassLoaderUtils.getResourceAsStream("keys/alice.jks", this.getClass()),
                  "password".toCharArray());
    Certificate cert = keystore.getCertificate("alice");
    assertNotNull(cert);

    assertTrue(jwtConsumer.verifySignatureWith((X509Certificate)cert,
                                                      SignatureAlgorithm.RS256));
}
 
示例5
private void validateIdToken(String idToken, String nonce)
    throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(idToken);
    JwtToken jwt = jwtConsumer.getJwtToken();

    // Validate claims
    assertEquals("alice", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
    assertEquals("OIDC IdP", jwt.getClaim(JwtConstants.CLAIM_ISSUER));
    assertEquals("consumer-id", jwt.getClaim(JwtConstants.CLAIM_AUDIENCE));
    assertNotNull(jwt.getClaim(JwtConstants.CLAIM_EXPIRY));
    assertNotNull(jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT));
    if (nonce != null) {
        assertEquals(nonce, jwt.getClaim(IdToken.NONCE_CLAIM));
    }

    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(ClassLoaderUtils.getResourceAsStream("keys/alice.jks", this.getClass()),
                  "password".toCharArray());
    Certificate cert = keystore.getCertificate("alice");
    assertNotNull(cert);

    assertTrue(jwtConsumer.verifySignatureWith((X509Certificate)cert,
                                                      SignatureAlgorithm.RS256));
}
 
示例6
@Override
public IdTokenContext createContext(Message m) {

    OidcClientTokenContext ctx = (OidcClientTokenContext)m.getContent(ClientTokenContext.class);
    final IdToken idToken = ctx != null ? ctx.getIdToken() : m.getContent(IdToken.class);
    if (idToken != null) {
        return new IdTokenContext() {

            @Override
            public IdToken getIdToken() {
                return idToken;
            }

        };
    }
    return null;
}
 
示例7
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    MultivaluedMap<String, String> form = toFormData(requestContext);
    String idTokenParamValue = form.getFirst(tokenFormParameter);
    if (idTokenParamValue == null) {
        requestContext.abortWith(Response.status(401).build());
        return;
    }

    IdToken idToken = idTokenReader.getIdToken(idTokenParamValue, consumer);
    JAXRSUtils.getCurrentMessage().setContent(IdToken.class, idToken);

    OidcSecurityContext oidcSecCtx = new OidcSecurityContext(idToken);
    oidcSecCtx.setRoleClaim(roleClaim);
    requestContext.setSecurityContext(oidcSecCtx);
}
 
示例8
protected boolean checkSecurityContext(ContainerRequestContext rc) {
    OidcClientTokenContext tokenContext = (OidcClientTokenContext)stateManager.getClientTokenContext(mc);
    if (tokenContext == null) {
        return false;
    }
    IdToken idToken = tokenContext.getIdToken();
    try {
        // If ID token has expired then the context is no longer valid
        JwtUtils.validateJwtExpiry(idToken, 0, idToken.getExpiryTime() != null);
    } catch (JwtException ex) {
        stateManager.removeClientTokenContext(new MessageContextImpl(JAXRSUtils.getCurrentMessage()));
        return false;
    }
    OidcClientTokenContextImpl newTokenContext = new OidcClientTokenContextImpl();
    newTokenContext.setToken(tokenContext.getToken());
    newTokenContext.setIdToken(idToken);
    newTokenContext.setUserInfo(tokenContext.getUserInfo());
    newTokenContext.setState(toRequestState(rc));
    JAXRSUtils.getCurrentMessage().setContent(ClientTokenContext.class, newTokenContext);

    OidcSecurityContext oidcSecCtx = new OidcSecurityContext(newTokenContext);
    oidcSecCtx.setRoleClaim(roleClaim);
    rc.setSecurityContext(oidcSecCtx);
    return true;
}
 
示例9
private void validateIdToken(IdToken idToken, MultivaluedMap<String, String> state) {

        String nonce = state.getFirst(IdToken.NONCE_CLAIM);
        String tokenNonce = idToken.getNonce();
        if (nonce != null && (tokenNonce == null || !nonce.equals(tokenNonce))) {
            throw new OAuthServiceException(OAuthConstants.INVALID_REQUEST);
        }
        if (maxAgeOffset != null) {
            long authTime = Long.parseLong(state.getFirst(MAX_AGE_PARAMETER));
            Long tokenAuthTime = idToken.getAuthenticationTime();
            if (tokenAuthTime > authTime) {
                throw new OAuthServiceException(OAuthConstants.INVALID_REQUEST);
            }
        }

        String acr = idToken.getAuthenticationContextRef();
        // Skip the check if the acr is not set given it is a voluntary claim
        if (acr != null && authenticationContextRef != null && !authenticationContextRef.contains(acr)) {
            throw new OAuthServiceException(OAuthConstants.INVALID_REQUEST);
        }

    }
 
示例10
@Override
public UserInfoContext createContext(Message m) {
    final OidcClientTokenContext ctx = (OidcClientTokenContext)
        m.getContent(ClientTokenContext.class);
    final UserInfo userInfo = ctx != null ? ctx.getUserInfo() : m.getContent(UserInfo.class);
    if (userInfo != null) {
        final IdToken idToken = ctx != null ? ctx.getIdToken() : m.getContent(IdToken.class);
        return new UserInfoContext() {

            @Override
            public UserInfo getUserInfo() {
                return userInfo;
            }

            @Override
            public IdToken getIdToken() {
                return idToken;
            }

        };
    }
    return null;

}
 
示例11
protected String processIdToken(OAuthRedirectionState state, IdToken idToken) {
    OAuthJoseJwtProducer processor = idTokenHandler == null ? new OAuthJoseJwtProducer() : idTokenHandler;

    String code =
        (String)JAXRSUtils.getCurrentMessage().getExchange().get(OAuthConstants.AUTHORIZATION_CODE_VALUE);
    if (code != null) {
        // this service is invoked as part of the hybrid flow
        Properties props = JwsUtils.loadSignatureOutProperties(false);
        SignatureAlgorithm sigAlgo = null;
        if (processor.isSignWithClientSecret()) {
            sigAlgo = OAuthUtils.getClientSecretSignatureAlgorithm(props);
        } else {
            sigAlgo = JwsUtils.getSignatureAlgorithm(props, SignatureAlgorithm.RS256);
        }
        idToken.setAuthorizationCodeHash(OidcUtils.calculateAuthorizationCodeHash(code, sigAlgo));
    }

    idToken.setNonce(state.getNonce());
    return processor.processJwt(new JwtToken(idToken));
}
 
示例12
@Override
public IdToken getIdToken(String clientId, UserSubject authenticatedUser, List<String> scopes) {
    IdToken token = new IdToken();

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.SECOND, 60);
    token.setExpiryTime(cal.getTimeInMillis() / 1000L);
    token.setIssuedAt(new Date().getTime() / 1000L);
    token.setAudience(clientId);
    token.setTokenId(UUID.randomUUID().toString());
    token.setSubject(authenticatedUser.getLogin().toLowerCase());
    token.setClaim("preferred_username", authenticatedUser.getLogin().toLowerCase());
    token.setIssuer("OIDC IdP");
    token.setClaim("role", "user");

    return token;
}
 
示例13
protected Response doInitiateLogout(MultivaluedMap<String, String> params) {

        IdToken idTokenHint = getIdTokenHint(params);
        Client client = getClient(params, idTokenHint);

        if (!allowAnonymousLogout || mc.getSecurityContext().getUserPrincipal() != null) {
            OidcUserSubject subject = subjectCreator.createUserSubject(mc, params);

            if (backChannelLogoutHandler != null) {
                backChannelLogoutHandler.handleLogout(client, subject, idTokenHint);
            }
            if (logoutHandlers != null) {

                for (LogoutHandler handler : logoutHandlers) {
                    handler.handleLogout(client, subject);
                }
            }
        }

        // Clear OIDC session now
        mc.getHttpServletRequest().getSession().invalidate();

        // Redirect to the core IDP
        URI idpLogoutUri = getAbsoluteIdpLogoutUri(client, params);
        return Response.seeOther(idpLogoutUri).build();
    }
 
示例14
private Client getClient(MultivaluedMap<String, String> params, IdToken idTokenHint) {
    String clientId = params.getFirst(OAuthConstants.CLIENT_ID);
    if (clientId == null && idTokenHint != null) {
        clientId = idTokenHint.getAudience();
        mc.getHttpServletRequest().setAttribute(OAuthConstants.CLIENT_ID, clientId);
    }
    if (clientId == null) {
        throw new BadRequestException();
    }
    Client c = dataProvider.getClient(clientId);
    if (c == null) {
        throw new BadRequestException();
    }
    if (StringUtils.isEmpty(c.getProperties().get(CLIENT_LOGOUT_URIS))) {
        throw new BadRequestException();
    }
    return c;
}
 
示例15
public void handleLogout(Client client, OidcUserSubject subject, IdToken idTokenHint) {
    // At the moment the only way to find out which RPs a given User is logged in is
    // to check the access tokens - it can not offer a complete solution, for ex
    // in cases when ATs have expired or been revoked or Implicit id_token flow is used.
    // Most likely a 'visited sites' cookie as suggested by the spec will need to be used.
    List<ServerAccessToken> accessTokens = dataProvider.getAccessTokens(null,  subject);
    Set<String> processedClients = new HashSet<>();
    for (ServerAccessToken at : accessTokens) {
        Client atClient = at.getClient();
        if (client.getClientId().equals(atClient.getClientId())
            || processedClients.contains(atClient.getClientId())) {
            continue;
        }
        String uri = atClient.getProperties().get(BACK_CHANNEL_LOGOUT_URI);
        if (uri != null) {
            processedClients.add(atClient.getClientId());
            submitBackChannelLogoutRequest(atClient, subject, idTokenHint, uri);
        }
    }
    
    

}
 
示例16
@Override
public OidcUserSubject createUserSubject(MessageContext mc, MultivaluedMap<String, String> params) {
    Principal principal = mc.getSecurityContext().getUserPrincipal();

    if (!(principal instanceof FedizPrincipal)) {
        throw new OAuthServiceException("Unsupported Principal");
    }
    FedizPrincipal fedizPrincipal = (FedizPrincipal) principal;

    // In the future FedizPrincipal will likely have JWT claims already prepared,
    // with IdToken being initialized here from those claims
    OidcUserSubject oidcSub = new OidcUserSubject();
    oidcSub.setLogin(fedizPrincipal.getName());

    // REVISIT: use fedizPrincipal.getId() to guarantee the uniqueness once FEDIZ-207 is resolved
    oidcSub.setId(fedizPrincipal.getName());

    IdToken idToken = convertToIdToken(mc, fedizPrincipal.getLoginToken(), oidcSub.getLogin(), oidcSub.getId(),
            fedizPrincipal.getClaims(), fedizPrincipal.getRoleClaims(), params);
    oidcSub.setIdToken(idToken);
    oidcSub.setRoles(fedizPrincipal.getRoleClaims());
    // UserInfo can be populated and set on OidcUserSubject too.
    // UserInfoService will create it otherwise.

    return oidcSub;
}
 
示例17
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    OidcSecurityContext secCtx = (OidcSecurityContext) requestContext.getSecurityContext();
    OidcClientTokenContext tokenCtx = secCtx.getOidcContext();
    IdToken idToken = tokenCtx.getIdToken();
    String email = idToken.getEmail();
    String userDomain = idToken.getStringProperty("hd");
    String appDomain = gsuiteDirService.getDomainName();
    if (appDomain == null) {
        throw serverError(SERVICE_UNAVAILABLE, "E002", "Service not configured!");
    }

    boolean internal = gsuiteDirService.getDomainName().equalsIgnoreCase(userDomain);
    boolean external = false;
    Set<String> roles = new HashSet<>();
    String masterRole = null;
    if (internal) {
        roles.add(AuthzRole.INTERNAL);
        masterRole = AuthzRole.INTERNAL;
    } else if (externalUsersCache.get().contains(email)) {
        roles.add(AuthzRole.EXTERNAL);
        masterRole = AuthzRole.EXTERNAL;
        external = true;
    }
    if (adminUsersCache.get().contains(email)) {
        roles.add(AuthzRole.ADMIN);
        masterRole = AuthzRole.ADMIN;
    }
    if (internal || external) {
    } else {
        LOG.error("Unauthorized access from {}", userDomain);
        ServerError err = new ServerError("E001", "Sorry you are not allowed to enter this site");
        requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).entity(err).type(MediaType.APPLICATION_JSON).build());
    }
    secCtx.getOidcContext().getUserInfo().setProperty("securityRoles", roles);
    secCtx.getOidcContext().getUserInfo().setProperty("masterRole", masterRole);
    secCtx.setRoleClaim("masterRole");
}
 
示例18
@org.junit.Test
public void testAuthorizationCodeFlowRefreshToken() throws Exception {
    URL busFile = OIDCFlowTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Get Authorization Code
    String code = OAuth2TestUtils.getAuthorizationCode(client,
        String.join(" ", OidcUtils.getOpenIdScope(), OAuthConstants.REFRESH_TOKEN_SCOPE),
        "consumer-id-oidc");
    assertNotNull(code);

    // Now get the access token
    client = WebClient.create(address, "consumer-id-oidc", "this-is-a-secret", busFile.toString());

    ClientAccessToken accessToken =
        OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code, "consumer-id-oidc", null);
    assertNotNull(accessToken.getTokenKey());
    assertTrue(accessToken.getApprovedScope().contains("openid"));

    IdToken idToken = getIdToken(accessToken, address + "keys/", "consumer-id-oidc");
    assertNotNull(idToken);
    Long issuedAt = idToken.getIssuedAt();

    TimeUnit.SECONDS.sleep(1L);

    accessToken = OAuthClientUtils.refreshAccessToken(
        client,
        new Consumer("consumer-id-oidc"),
        accessToken);
    idToken = getIdToken(accessToken, address + "keys/", "consumer-id-oidc");

    assertNotEquals(issuedAt, idToken.getIssuedAt());
}
 
示例19
private static IdToken getIdToken(ClientAccessToken accessToken, String jwksUri, String clientId) {
    WebClient c = WebClient.create(jwksUri,
        Collections.singletonList(new JsonWebKeysProvider()),
        "alice", "security",
        OIDCFlowTest.class.getResource("client.xml").toString())
        .accept(MediaType.APPLICATION_JSON);
    IdTokenReader idTokenReader = new IdTokenReader();
    idTokenReader.setJwkSetClient(c);
    idTokenReader.setIssuerId("OIDC IdP");

    return idTokenReader.getIdToken(accessToken, new Consumer(clientId));
}
 
示例20
@Override
public IdToken getIdToken(String clientId, UserSubject authenticatedUser, List<String> scopes) {
    IdToken token = new IdToken();

    token.setIssuedAt(OAuthUtils.getIssuedAt());
    token.setExpiryTime(token.getIssuedAt() + 60L);
    token.setAudience(clientId);
    token.setSubject(authenticatedUser.getLogin());
    token.setIssuer("OIDC IdP");

    return token;
}
 
示例21
public static void validateAccessTokenHash(String accessToken, JwtToken jwt, boolean required) {
    String hashClaim = (String)jwt.getClaims().getClaim(IdToken.ACCESS_TOKEN_HASH_CLAIM);
    if (hashClaim == null && required) {
        throw new OAuthServiceException("Invalid hash");
    }
    if (hashClaim != null) {
        validateHash(accessToken,
                     (String)jwt.getClaims().getClaim(IdToken.ACCESS_TOKEN_HASH_CLAIM),
                     jwt.getJwsHeaders().getSignatureAlgorithm());
    }
}
 
示例22
public static void validateCodeHash(String code, JwtToken jwt, boolean required) {
    String hashClaim = (String)jwt.getClaims().getClaim(IdToken.AUTH_CODE_HASH_CLAIM);
    if (hashClaim == null && required) {
        throw new OAuthServiceException("Invalid hash");
    }
    if (hashClaim != null) {
        validateHash(code,
                     (String)jwt.getClaims().getClaim(IdToken.AUTH_CODE_HASH_CLAIM),
                     jwt.getJwsHeaders().getSignatureAlgorithm());
    }
}
 
示例23
public void validateUserInfo(UserInfo profile, IdToken idToken, Consumer client) {
    validateJwtClaims(profile, client.getClientId(), false);
    // validate subject
    if (!idToken.getSubject().equals(profile.getSubject())) {
        throw new OAuthServiceException("Invalid subject");
    }
}
 
示例24
@Override
protected ClientTokenContext createTokenContext(ContainerRequestContext rc,
                                                ClientAccessToken at,
                                                MultivaluedMap<String, String> requestParams,
                                                MultivaluedMap<String, String> state) {
    if (rc.getSecurityContext() instanceof OidcSecurityContext) {
        return ((OidcSecurityContext)rc.getSecurityContext()).getOidcContext();
    }
    OidcClientTokenContextImpl ctx = new OidcClientTokenContextImpl();
    if (at != null) {
        if (idTokenReader == null) {
            throw new OAuthServiceException(OAuthConstants.SERVER_ERROR);
        }
        IdToken idToken = idTokenReader.getIdToken(at,
                              requestParams.getFirst(OAuthConstants.AUTHORIZATION_CODE_VALUE),
                              getConsumer());
        // Validate the properties set up at the redirection time.
        validateIdToken(idToken, state);

        ctx.setIdToken(idToken);
        if (userInfoClient != null) {
            ctx.setUserInfo(userInfoClient.getUserInfo(at,
                                                       ctx.getIdToken(),
                                                       getConsumer()));
        }
        OidcSecurityContext oidcSecCtx = new OidcSecurityContext(ctx);
        oidcSecCtx.setRoleClaim(roleClaim);
        rc.setSecurityContext(oidcSecCtx);
    }

    return ctx;
}
 
示例25
@Override
protected void setAdditionalCodeRequestParams(UriBuilder ub,
                                              MultivaluedMap<String, String> redirectState,
                                              MultivaluedMap<String, String> codeRequestState) {
    if (redirectState != null) {
        if (redirectState.getFirst(IdToken.NONCE_CLAIM) != null) {
            ub.queryParam(IdToken.NONCE_CLAIM, redirectState.getFirst(IdToken.NONCE_CLAIM));
        }
        if (redirectState.getFirst(MAX_AGE_PARAMETER) != null) {
            ub.queryParam(MAX_AGE_PARAMETER, redirectState.getFirst(MAX_AGE_PARAMETER));
        }
    }
    if (codeRequestState != null && codeRequestState.getFirst(LOGIN_HINT_PARAMETER) != null) {
        ub.queryParam(LOGIN_HINT_PARAMETER, codeRequestState.getFirst(LOGIN_HINT_PARAMETER));
    }
    if (claims != null) {
        ub.queryParam("claims", claims);
    }
    if (claimsLocales != null) {
        ub.queryParam("claims_locales", claimsLocales);
    }
    if (authenticationContextRef != null) {
        ub.queryParam(ACR_PARAMETER, authenticationContextRef);
    }
    if (promptLogin != null) {
        ub.queryParam(PROMPT_PARAMETER, promptLogin);
    }

}
 
示例26
@Override
protected void validateRefreshedToken(ClientTokenContext tokenContext, ClientAccessToken refreshedToken) {
    if (refreshedToken.getParameters().containsKey(OidcUtils.ID_TOKEN)) {
        IdToken newIdToken = idTokenReader.getIdToken(refreshedToken, getConsumer());

        OidcClientTokenContextImpl oidcContext = (OidcClientTokenContextImpl)tokenContext;
        IdToken currentIdToken = oidcContext.getIdToken();

        if (!newIdToken.getIssuer().equals(currentIdToken.getIssuer())) {
            throw new OAuthServiceException("Invalid id token issuer");
        }
        if (!newIdToken.getSubject().equals(currentIdToken.getSubject())) {
            throw new OAuthServiceException("Invalid id token subject");
        }
        if (!newIdToken.getAudiences().containsAll(currentIdToken.getAudiences())) {
            throw new OAuthServiceException("Invalid id token audience(s)");
        }
        Long newAuthTime = newIdToken.getAuthenticationTime();
        if (newAuthTime != null && !newAuthTime.equals(currentIdToken.getAuthenticationTime())) {
            throw new OAuthServiceException("Invalid id token auth_time");
        }
        String newAzp = newIdToken.getAuthorizedParty();
        String origAzp = currentIdToken.getAuthorizedParty();
        if (newAzp != null && origAzp == null
            || newAzp == null && origAzp != null
            || newAzp != null && origAzp != null && !newAzp.equals(origAzp)) {
            throw new OAuthServiceException("Invalid id token authorized party");
        }
        Long newIssuedTime = newIdToken.getIssuedAt();
        Long origIssuedTime = currentIdToken.getIssuedAt();
        if (newIssuedTime < origIssuedTime) {
            throw new OAuthServiceException("Invalid id token issued time");
        }

        oidcContext.setIdToken(newIdToken);

    }
}
 
示例27
protected UserInfo createFromIdToken(IdToken idToken) {
    UserInfo userInfo = new UserInfo();
    userInfo.setSubject(idToken.getSubject());

    if (super.isJwsRequired()) {
        userInfo.setIssuer(idToken.getIssuer());
        userInfo.setAudience(idToken.getAudience());
    }
    if (idToken.getPreferredUserName() != null) {
        userInfo.setPreferredUserName(idToken.getPreferredUserName());
    }
    if (idToken.getName() != null) {
        userInfo.setName(idToken.getName());
    }
    if (idToken.getGivenName() != null) {
        userInfo.setGivenName(idToken.getGivenName());
    }
    if (idToken.getFamilyName() != null) {
        userInfo.setFamilyName(idToken.getFamilyName());
    }
    if (idToken.getEmail() != null) {
        userInfo.setEmail(idToken.getEmail());
    }
    if (idToken.getNickName() != null) {
        userInfo.setNickName(idToken.getNickName());
    }

    if (additionalClaims != null && !additionalClaims.isEmpty()) {
        for (String additionalClaim : additionalClaims) {
            if (idToken.containsProperty(additionalClaim)) {
                userInfo.setClaim(additionalClaim, idToken.getClaim(additionalClaim));
            }
        }
    }

    //etc
    return userInfo;
}
 
示例28
@Test
public void testAccessTokenWithOidcUserSubject() {
    Client c = addClient("101", "bob");

    AccessTokenRegistration atr = new AccessTokenRegistration();
    atr.setClient(c);
    atr.setApprovedScope(Collections.singletonList("a"));

    OidcUserSubject oidcSubject = new OidcUserSubject();
    oidcSubject.setLogin("bob");
    IdToken idToken = new IdToken();
    idToken.setAudience(c.getClientId());
    oidcSubject.setIdToken(idToken);
    atr.setSubject(oidcSubject);

    ServerAccessToken at = getProvider().createAccessToken(atr);
    ServerAccessToken at2 = getProvider().getAccessToken(at.getTokenKey());
    assertEquals(at.getTokenKey(), at2.getTokenKey());

    OidcUserSubject oidcSubject2 = (OidcUserSubject)at2.getSubject();
    assertEquals(c.getClientId(), oidcSubject2.getIdToken().getAudience());

    OidcUserSubject oidcSubject3 = new OidcUserSubject();
    oidcSubject3.setLogin("bob");
    IdToken idToken2 = new IdToken();
    idToken2.setAudience(c.getClientId());
    oidcSubject3.setIdToken(idToken2);
    atr.setSubject(oidcSubject3);

    ServerAccessToken at3 = getProvider().createAccessToken(atr);
    ServerAccessToken at4 = getProvider().getAccessToken(at3.getTokenKey());
    OidcUserSubject oidcSubject4 = (OidcUserSubject)at4.getSubject();
    assertEquals(c.getClientId(), oidcSubject4.getIdToken().getAudience());
}
 
示例29
private IdToken getIdTokenHint(MultivaluedMap<String, String> params) {
    String tokenHint = params.getFirst(ID_TOKEN_HINT);
    if (tokenHint == null) {
        return null;
    }
    JwtToken token = null;
    try {
        token = super.getJwtToken(tokenHint);
    } catch (JoseException ex) {
        throw new BadRequestException(ex);
    }
    return new IdToken(token.getClaims());
}
 
示例30
private void submitBackChannelLogoutRequest(final Client client, final OidcUserSubject subject,
        final IdToken idTokenHint, final String uri) {
    // Application context is expected to contain HttpConduit HTTPS configuration
    final WebClient wc = WebClient.create(uri);
    IdToken idToken = idTokenHint != null ? idTokenHint : subject.getIdToken(); 
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(idToken.getIssuer());
    claims.setSubject(idToken.getSubject());
    claims.setAudience(client.getClientId());
    claims.setIssuedAt(System.currentTimeMillis() / 1000);
    claims.setTokenId(Base64UrlUtility.encode(CryptoUtils.generateSecureRandomBytes(16)));
    claims.setClaim(EVENTS_PROPERTY, 
            Collections.singletonMap(BACK_CHANNEL_LOGOUT_EVENT, Collections.emptyMap()));
    if (idToken.getName() != null) {
        claims.setClaim(IdToken.NAME_CLAIM, idToken.getName());    
    }
    
    final String logoutToken = super.processJwt(new JwtToken(claims));
    executorService.submit(new Runnable() {

        @Override
        public void run() {
            try {
                wc.form(new Form().param(LOGOUT_TOKEN, logoutToken));
            } catch (Exception ex) {
                LOG.info(String.format("Back channel request to %s to log out %s from client %s has failed",
                    uri, subject.getLogin(), client.getClientId()));
                LOG.fine(String.format("%s request failure: %s", uri, ExceptionUtils.getStackTrace(ex)));
            }
        }
    
    });
    
}