org.apache.cxf.rs.security.oauth2.utils.OAuthUtils Java Examples
The following examples show how to use
org.apache.cxf.rs.security.oauth2.utils.OAuthUtils.
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: OidcImplicitService.java From cxf with Apache License 2.0 | 6 votes |
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)); }
Example #2
Source File: SubjectCreatorImpl.java From cxf with Apache License 2.0 | 6 votes |
@Override public OidcUserSubject createUserSubject(MessageContext mc, MultivaluedMap<String, String> params) { OidcUserSubject oidcSub = new OidcUserSubject(OAuthUtils.createSubject(mc, (SecurityContext)mc.get(SecurityContext.class.getName()))); final List<String> scopes; String requestedScope = params.getFirst(OAuthConstants.SCOPE); if (requestedScope != null && !requestedScope.isEmpty()) { scopes = OidcUtils.getScopeClaims(requestedScope.split(" ")); } else { scopes = Collections.emptyList(); } oidcSub.setIdToken(ID_TOKEN_PROVIDER.getIdToken(null, oidcSub, scopes)); return oidcSub; }
Example #3
Source File: BigQueryServer.java From cxf with Apache License 2.0 | 6 votes |
private static ClientAccessToken getAccessToken(PrivateKey privateKey, String issuer) { JwsHeaders headers = new JwsHeaders(JoseType.JWT, SignatureAlgorithm.RS256); JwtClaims claims = new JwtClaims(); claims.setIssuer(issuer); claims.setAudience("https://www.googleapis.com/oauth2/v3/token"); long issuedAt = OAuthUtils.getIssuedAt(); claims.setIssuedAt(issuedAt); claims.setExpiryTime(issuedAt + 60 * 60); claims.setProperty("scope", "https://www.googleapis.com/auth/bigquery.readonly"); JwtToken token = new JwtToken(headers, claims); JwsJwtCompactProducer p = new JwsJwtCompactProducer(token); String base64UrlAssertion = p.signWith(privateKey); JwtBearerGrant grant = new JwtBearerGrant(base64UrlAssertion); WebClient accessTokenService = WebClient.create("https://www.googleapis.com/oauth2/v3/token", Arrays.asList(new OAuthJSONProvider(), new AccessTokenGrantWriter())); WebClient.getConfig(accessTokenService).getInInterceptors().add(new LoggingInInterceptor()); accessTokenService.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON); return accessTokenService.post(grant, ClientAccessToken.class); }
Example #4
Source File: AbstractGrantHandler.java From cxf with Apache License 2.0 | 6 votes |
protected ServerAccessToken getPreAuthorizedToken(Client client, UserSubject subject, String requestedGrant, List<String> requestedScopes, List<String> audiences) { if (!OAuthUtils.validateScopes(requestedScopes, client.getRegisteredScopes(), partialMatchScopeValidation)) { throw new OAuthServiceException(new OAuthError(OAuthConstants.INVALID_SCOPE)); } if (!OAuthUtils.validateAudiences(audiences, client.getRegisteredAudiences())) { throw new OAuthServiceException(new OAuthError(OAuthConstants.INVALID_GRANT)); } // Get a pre-authorized token if available return dataProvider.getPreauthorizedToken( client, requestedScopes, subject, requestedGrant); }
Example #5
Source File: DirectAuthorizationService.java From cxf with Apache License 2.0 | 6 votes |
protected UserSubject createUserSubject(SecurityContext securityContext, MultivaluedMap<String, String> params) { UserSubject subject = null; if (subjectCreator != null) { subject = subjectCreator.createUserSubject(getMessageContext(), params); if (subject != null) { return subject; } } subject = getMessageContext().getContent(UserSubject.class); if (subject != null) { return subject; } return OAuthUtils.createSubject(securityContext); }
Example #6
Source File: RedirectionBasedGrantService.java From cxf with Apache License 2.0 | 6 votes |
private boolean compareRequestAndSessionTokens(String requestToken, MultivaluedMap<String, String> params, UserSubject subject) { final String sessionToken; if (this.sessionAuthenticityTokenProvider != null) { sessionToken = sessionAuthenticityTokenProvider.removeSessionToken(getMessageContext(), params, subject); } else { sessionToken = OAuthUtils.getSessionToken(getMessageContext()); } if (StringUtils.isEmpty(sessionToken)) { return false; } return requestToken.equals(sessionToken); }
Example #7
Source File: AbstractTokenService.java From cxf with Apache License 2.0 | 6 votes |
protected void checkCertificateBinding(Client client, TLSSessionInfo tlsSessionInfo) { String subjectDn = client.getProperties().get(OAuthConstants.TLS_CLIENT_AUTH_SUBJECT_DN); if (subjectDn == null && client.getApplicationCertificates().isEmpty()) { LOG.warning("Client \"" + client.getClientId() + "\" can not be bound to the TLS certificate"); reportInvalidClient(); } X509Certificate cert = OAuthUtils.getRootTLSCertificate(tlsSessionInfo); if (subjectDn != null && !subjectDn.equals(OAuthUtils.getSubjectDnFromTLSCertificates(cert))) { LOG.warning("Client \"" + client.getClientId() + "\" can not be bound to the TLS certificate"); reportInvalidClient(); } String issuerDn = client.getProperties().get(OAuthConstants.TLS_CLIENT_AUTH_ISSUER_DN); if (issuerDn != null && !issuerDn.equals(OAuthUtils.getIssuerDnFromTLSCertificates(cert))) { LOG.warning("Client \"" + client.getClientId() + "\" can not be bound to the TLS certificate"); reportInvalidClient(); } if (!client.getApplicationCertificates().isEmpty()) { compareTlsCertificates(tlsSessionInfo, client.getApplicationCertificates()); } OAuthUtils.setCertificateThumbprintConfirmation(getMessageContext(), cert); }
Example #8
Source File: AbstractTokenService.java From cxf with Apache License 2.0 | 6 votes |
protected Client getClientFromTLSCertificates(SecurityContext sc, TLSSessionInfo tlsSessionInfo, MultivaluedMap<String, String> params) { Client client = null; if (OAuthUtils.isMutualTls(sc, tlsSessionInfo)) { X509Certificate cert = OAuthUtils.getRootTLSCertificate(tlsSessionInfo); String subjectDn = OAuthUtils.getSubjectDnFromTLSCertificates(cert); if (!StringUtils.isEmpty(subjectDn)) { client = getClient(subjectDn, params); validateClientAuthenticationMethod(client, OAuthConstants.TOKEN_ENDPOINT_AUTH_TLS); // The certificates must be registered with the client and match TLS certificates // in case of the binding where Client's clientId is a subject distinguished name compareTlsCertificates(tlsSessionInfo, client.getApplicationCertificates()); OAuthUtils.setCertificateThumbprintConfirmation(getMessageContext(), cert); } } return client; }
Example #9
Source File: AbstractImplicitGrantService.java From cxf with Apache License 2.0 | 6 votes |
protected ClientAccessToken getClientAccessToken(OAuthRedirectionState state, Client client, List<String> requestedScope, List<String> approvedScope, UserSubject userSubject, ServerAccessToken preAuthorizedToken) { ServerAccessToken token = null; if (preAuthorizedToken == null) { AccessTokenRegistration reg = createTokenRegistration(state, client, requestedScope, approvedScope, userSubject); token = getDataProvider().createAccessToken(reg); } else { token = preAuthorizedToken; if (state.getNonce() != null) { JAXRSUtils.getCurrentMessage().getExchange().put(OAuthConstants.NONCE, state.getNonce()); } } ClientAccessToken clientToken = OAuthUtils.toClientAccessToken(token, isWriteOptionalParameters()); processClientAccessToken(clientToken, token); return clientToken; }
Example #10
Source File: MemoryClientCodeStateManager.java From cxf with Apache License 2.0 | 6 votes |
@Override public MultivaluedMap<String, String> toRedirectState(MessageContext mc, MultivaluedMap<String, String> requestState) { String stateParam = OAuthUtils.generateRandomTokenKey(); MultivaluedMap<String, String> redirectMap = new MetadataMap<>(); if (generateNonce) { String nonceParam = MessageDigestUtils.generate(CryptoUtils.generateSecureRandomBytes(32)); requestState.putSingle(OAuthConstants.NONCE, nonceParam); redirectMap.putSingle(OAuthConstants.NONCE, nonceParam); } map.put(stateParam, requestState); OAuthUtils.setSessionToken(mc, stateParam, "state", 0); redirectMap.putSingle(OAuthConstants.STATE, stateParam); return redirectMap; }
Example #11
Source File: JoseClientCodeStateManager.java From cxf with Apache License 2.0 | 6 votes |
@Override public MultivaluedMap<String, String> fromRedirectState(MessageContext mc, MultivaluedMap<String, String> redirectState) { String stateParam = redirectState.getFirst(OAuthConstants.STATE); if (storeInSession) { stateParam = OAuthUtils.getSessionToken(mc, stateParam); } JweDecryptionProvider jwe = getInitializedDecryptionProvider(); if (jwe != null) { stateParam = jwe.decrypt(stateParam).getContentText(); } JwsCompactConsumer jws = new JwsCompactConsumer(stateParam); JwsSignatureVerifier theSigVerifier = getInitializedSigVerifier(); if (!jws.verifySignatureWith(theSigVerifier)) { throw new SecurityException(); } String json = jws.getUnsignedEncodedSequence(); //CHECKSTYLE:OFF Map<String, List<String>> map = CastUtils.cast((Map<?, ?>)jsonp.fromJson(json)); return (MultivaluedMap<String, String>)map; //NOPMD //CHECKSTYLE:ON }
Example #12
Source File: AbstractOAuthDataProvider.java From cxf with Apache License 2.0 | 6 votes |
@Override public ServerAccessToken getPreauthorizedToken(Client client, List<String> requestedScopes, UserSubject sub, String grantType) throws OAuthServiceException { if (!isSupportPreauthorizedTokens()) { return null; } ServerAccessToken token = null; for (ServerAccessToken at : getAccessTokens(client, sub)) { if (at.getClient().getClientId().equals(client.getClientId()) && at.getGrantType().equals(grantType) && (sub == null && at.getSubject() == null || sub != null && at.getSubject().getLogin().equals(sub.getLogin()))) { if (!OAuthUtils.isExpired(at.getIssuedAt(), at.getExpiresIn())) { token = at; } else { revokeToken(client, at.getTokenKey(), OAuthConstants.ACCESS_TOKEN); } break; } } return token; }
Example #13
Source File: OAuthRequestFilter.java From cxf with Apache License 2.0 | 6 votes |
protected boolean checkRequestURI(HttpServletRequest request, List<String> uris, Message m) { if (uris.isEmpty()) { return true; } String servletPath = request.getPathInfo(); if (servletPath == null) { servletPath = (String)m.get(Message.PATH_INFO); } boolean foundValidScope = false; for (String uri : uris) { if (OAuthUtils.checkRequestURI(servletPath, uri)) { foundValidScope = true; break; } } if (!foundValidScope) { String message = "Invalid request URI: " + request.getRequestURL().toString(); LOG.fine(message); } return foundValidScope; }
Example #14
Source File: JoseClientCodeStateManager.java From cxf with Apache License 2.0 | 5 votes |
@Override public MultivaluedMap<String, String> toRedirectState(MessageContext mc, MultivaluedMap<String, String> requestState) { JweEncryptionProvider theEncryptionProvider = getInitializedEncryptionProvider(); JwsSignatureProvider theSigProvider = getInitializedSigProvider(theEncryptionProvider); if (theEncryptionProvider == null && theSigProvider == null) { throw new OAuthServiceException("The state can not be protected"); } MultivaluedMap<String, String> redirectMap = new MetadataMap<>(); if (generateNonce && theSigProvider != null) { JwsCompactProducer nonceProducer = new JwsCompactProducer(OAuthUtils.generateRandomTokenKey()); String nonceParam = nonceProducer.signWith(theSigProvider); requestState.putSingle(OAuthConstants.NONCE, nonceParam); redirectMap.putSingle(OAuthConstants.NONCE, nonceParam); } Map<String, Object> stateMap = CastUtils.cast((Map<?, ?>)requestState); String json = jsonp.toJson(stateMap); String stateParam = null; if (theSigProvider != null) { JwsCompactProducer stateProducer = new JwsCompactProducer(json); stateParam = stateProducer.signWith(theSigProvider); } if (theEncryptionProvider != null) { stateParam = theEncryptionProvider.encrypt(StringUtils.toBytesUTF8(stateParam), null); } if (storeInSession) { String sessionStateAttribute = OAuthUtils.generateRandomTokenKey(); OAuthUtils.setSessionToken(mc, stateParam, sessionStateAttribute, 0); stateParam = sessionStateAttribute; } redirectMap.putSingle(OAuthConstants.STATE, stateParam); return redirectMap; }
Example #15
Source File: IdTokenProviderImpl.java From cxf with Apache License 2.0 | 5 votes |
@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; }
Example #16
Source File: HawkAccessToken.java From cxf with Apache License 2.0 | 5 votes |
public HawkAccessToken(Client client, HmacAlgorithm macAlgo, long lifetime) { this(client, macAlgo, OAuthUtils.generateRandomTokenKey(), lifetime, OAuthUtils.getIssuedAt()); }
Example #17
Source File: BearerAccessToken.java From cxf with Apache License 2.0 | 5 votes |
public BearerAccessToken(Client client, long lifetime) { super(client, OAuthConstants.BEARER_TOKEN_TYPE, OAuthUtils.generateRandomTokenKey(), lifetime, OAuthUtils.getIssuedAt()); }
Example #18
Source File: AccessTokenIntrospectionClient.java From cxf with Apache License 2.0 | 5 votes |
private AccessTokenValidation convertIntrospectionToValidation(TokenIntrospection response) { AccessTokenValidation atv = new AccessTokenValidation(); atv.setInitialValidationSuccessful(response.isActive()); if (response.getClientId() != null) { atv.setClientId(response.getClientId()); } if (response.getIat() != null) { atv.setTokenIssuedAt(response.getIat()); } else { atv.setTokenIssuedAt(OAuthUtils.getIssuedAt()); } if (response.getExp() != null) { atv.setTokenLifetime(response.getExp() - atv.getTokenIssuedAt()); } if (response.getNbf() != null) { atv.setTokenNotBefore(response.getNbf()); } if (!StringUtils.isEmpty(response.getAud())) { atv.setAudiences(response.getAud()); } if (response.getIss() != null) { atv.setTokenIssuer(response.getIss()); } if (response.getScope() != null) { String[] scopes = response.getScope().split(" "); List<OAuthPermission> perms = new LinkedList<>(); for (String s : scopes) { if (!StringUtils.isEmpty(s)) { perms.add(new OAuthPermission(s.trim())); } } atv.setTokenScopes(perms); } if (response.getUsername() != null) { atv.setTokenSubject(new UserSubject(response.getUsername())); } atv.getExtraProps().putAll(response.getExtensions()); return atv; }
Example #19
Source File: EncryptingDataProvider.java From cxf with Apache License 2.0 | 5 votes |
private void createRefreshToken(ServerAccessToken token) { RefreshToken refreshToken = new RefreshToken(token.getClient(), "refresh", 1200L, OAuthUtils.getIssuedAt()); String encryptedRefreshToken = ModelEncryptionSupport.encryptRefreshToken(refreshToken, key); token.setRefreshToken(encryptedRefreshToken); }
Example #20
Source File: TokenCache.java From g-suite-identity-sync with Apache License 2.0 | 5 votes |
private ClientAccessToken getAccessToken() throws NoPrivateKeyException { JwsHeaders headers = new JwsHeaders(JoseType.JWT, SignatureAlgorithm.RS256); JwtClaims claims = new JwtClaims(); claims.setIssuer(config.getServiceAccountEmail()); claims.setAudience(config.getServiceAccountTokenUri()); claims.setSubject(config.getServiceAccountSubject()); long issuedAt = OAuthUtils.getIssuedAt(); long tokenTimeout = config.getServiceAccountTokenLifetime(); claims.setIssuedAt(issuedAt); claims.setExpiryTime(issuedAt + tokenTimeout); String scopes = String.join(" ", config.getServiceAccountScopes()); claims.setProperty("scope", scopes); JwtToken token = new JwtToken(headers, claims); JwsJwtCompactProducer p = new JwsJwtCompactProducer(token); String base64UrlAssertion = p.signWith(config.readServiceAccountKey()); JwtBearerGrant grant = new JwtBearerGrant(base64UrlAssertion); WebClient accessTokenService = WebClient.create(config.getServiceAccountTokenUri(), Arrays.asList(new OAuthJSONProvider(), new AccessTokenGrantWriter())); accessTokenService.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON); return accessTokenService.post(grant, ClientAccessToken.class); }
Example #21
Source File: RefreshToken.java From cxf with Apache License 2.0 | 5 votes |
public RefreshToken(Client client, long lifetime) { super(client, OAuthConstants.REFRESH_TOKEN_TYPE, OAuthUtils.generateRandomTokenKey(), lifetime, OAuthUtils.getIssuedAt()); }
Example #22
Source File: JoseSessionTokenProvider.java From cxf with Apache License 2.0 | 5 votes |
@Override public String createSessionToken(MessageContext mc, MultivaluedMap<String, String> params, UserSubject subject, OAuthRedirectionState secData) { String stateString = convertStateToString(secData); String sessionToken = protectStateString(stateString); return OAuthUtils.setSessionToken(mc, sessionToken, maxDefaultSessionInterval); }
Example #23
Source File: AbstractGrantHandler.java From cxf with Apache License 2.0 | 5 votes |
protected ServerAccessToken doCreateAccessToken(Client client, UserSubject subject, MultivaluedMap<String, String> params) { return doCreateAccessToken(client, subject, OAuthUtils.parseScope(params.getFirst(OAuthConstants.SCOPE)), getAudiences(client, params.getFirst(OAuthConstants.CLIENT_AUDIENCE))); }
Example #24
Source File: ClientCodeRequestFilter.java From cxf with Apache License 2.0 | 5 votes |
private ClientAccessToken refreshAccessTokenIfExpired(ClientAccessToken at) { if (at.getRefreshToken() != null && ((expiryThreshold > 0 && OAuthUtils.isExpired(at.getIssuedAt(), at.getExpiresIn() - expiryThreshold)) || OAuthUtils.isExpired(at.getIssuedAt(), at.getExpiresIn()))) { return OAuthClientUtils.refreshAccessToken(accessTokenServiceClient, consumer, at); } return null; }
Example #25
Source File: MemoryClientTokenContextManager.java From cxf with Apache License 2.0 | 5 votes |
@Override public void setClientTokenContext(MessageContext mc, ClientTokenContext request) { String key = getKey(mc, false); if (key == null) { key = OAuthUtils.generateRandomTokenKey(); OAuthUtils.setSessionToken(mc, key, "org.apache.cxf.websso.context", 0); } map.put(key, request); }
Example #26
Source File: MemoryClientCodeStateManager.java From cxf with Apache License 2.0 | 5 votes |
@Override public MultivaluedMap<String, String> fromRedirectState(MessageContext mc, MultivaluedMap<String, String> redirectState) { String stateParam = redirectState.getFirst(OAuthConstants.STATE); String sessionToken = OAuthUtils.getSessionToken(mc, "state"); if (sessionToken == null || !sessionToken.equals(stateParam)) { throw new OAuthServiceException("Invalid session token"); } return map.remove(stateParam); }
Example #27
Source File: BearerAuthSupplier.java From cxf with Apache License 2.0 | 5 votes |
private void refreshAccessTokenIfExpired(AuthorizationPolicy authPolicy) { ClientAccessToken at = getClientAccessToken(); if (OAuthUtils.isExpired(at.getIssuedAt(), at.getExpiresIn())) { refreshAccessToken(authPolicy); } }
Example #28
Source File: AccessTokenService.java From cxf with Apache License 2.0 | 5 votes |
protected void checkAudience(Client c, MultivaluedMap<String, String> params) { String audienceParam = params.getFirst(OAuthConstants.CLIENT_AUDIENCE); if (!OAuthUtils.validateAudience(audienceParam, c.getRegisteredAudiences())) { LOG.log(Level.FINE, "Error validating the audience parameter. Supplied audience {0} " + "does not match with the registered audiences {1}", new Object[] {audienceParam, c.getRegisteredAudiences() }); throw new OAuthServiceException(new OAuthError(OAuthConstants.ACCESS_DENIED)); } }
Example #29
Source File: AccessTokenService.java From cxf with Apache License 2.0 | 5 votes |
@Override protected void injectContextIntoOAuthProviders() { super.injectContextIntoOAuthProviders(); for (AccessTokenGrantHandler grantHandler : grantHandlers) { OAuthUtils.injectContextIntoOAuthProvider(getMessageContext(), grantHandler); } }
Example #30
Source File: AbstractOAuthDataProvider.java From cxf with Apache License 2.0 | 5 votes |
@Override public ServerAccessToken refreshAccessToken(Client client, String refreshTokenKey, List<String> restrictedScopes) throws OAuthServiceException { RefreshToken currentRefreshToken = recycleRefreshTokens ? revokeRefreshToken(client, refreshTokenKey) : getRefreshToken(refreshTokenKey); if (currentRefreshToken == null) { throw new OAuthServiceException(OAuthConstants.ACCESS_DENIED); } if (OAuthUtils.isExpired(currentRefreshToken.getIssuedAt(), currentRefreshToken.getExpiresIn())) { if (!recycleRefreshTokens) { revokeRefreshToken(client, refreshTokenKey); } throw new OAuthServiceException(OAuthConstants.ACCESS_DENIED); } if (recycleRefreshTokens) { revokeAccessTokens(client, currentRefreshToken); } ServerAccessToken at = doRefreshAccessToken(client, currentRefreshToken, restrictedScopes); saveAccessToken(at); if (recycleRefreshTokens) { createNewRefreshToken(at); } else { updateExistingRefreshToken(currentRefreshToken, at); } return at; }