private void writeAccessToken(ClientAccessToken obj, OutputStream os) throws IOException { StringBuilder sb = new StringBuilder(); sb.append("{"); appendJsonPair(sb, OAuthConstants.ACCESS_TOKEN, obj.getTokenKey()); sb.append(","); appendJsonPair(sb, OAuthConstants.ACCESS_TOKEN_TYPE, obj.getTokenType()); if (obj.getExpiresIn() != -1) { sb.append(","); appendJsonPair(sb, OAuthConstants.ACCESS_TOKEN_EXPIRES_IN, obj.getExpiresIn(), false); } if (obj.getApprovedScope() != null) { sb.append(","); appendJsonPair(sb, OAuthConstants.SCOPE, obj.getApprovedScope()); } if (obj.getRefreshToken() != null) { sb.append(","); appendJsonPair(sb, OAuthConstants.REFRESH_TOKEN, obj.getRefreshToken()); } Map<String, String> parameters = obj.getParameters(); for (Map.Entry<String, String> entry : parameters.entrySet()) { sb.append(","); appendJsonPair(sb, entry.getKey(), entry.getValue()); } sb.append("}"); String result = sb.toString(); os.write(result.getBytes(StandardCharsets.UTF_8)); os.flush(); }
ClientAccessToken token = new ClientAccessToken( tokenType, map.remove(OAuthConstants.ACCESS_TOKEN)); token.setRefreshToken(refreshToken); token.setExpiresIn(Long.parseLong(expiresInStr)); token.setIssuedAt(issuedAtStr != null ? Long.parseLong(issuedAtStr) : System.currentTimeMillis() / 1000); String scope = map.remove(OAuthConstants.SCOPE); if (scope != null) { token.setApprovedScope(scope); token.setParameters(map); return token;
private boolean expired(ClientAccessToken token) { if (token.getExpiresIn() != -1) { return (((token.getIssuedAt()+token.getExpiresIn())-System.currentTimeMillis()) < 0); } return false; }
protected AbstractAuthSupplier(String type) { clientAccessToken = new ClientAccessToken(); clientAccessToken.setTokenType(type); } public void setAccessToken(String accessToken) {
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; }
@org.junit.Test public void testAuthorizationCodeFlowWithScope() 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, "openid read_balance"); assertNotNull(code); // Now get the access token client = WebClient.create(address, OAuth2TestUtils.setupProviders(), "consumer-id", "this-is-a-secret", busFile.toString()); // Save the Cookie for the second request... WebClient.getConfig(client).getRequestContext().put( org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE); ClientAccessToken accessToken = OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code); assertNotNull(accessToken.getTokenKey()); assertTrue(accessToken.getApprovedScope().contains("openid")); assertTrue(accessToken.getApprovedScope().contains("read_balance")); String idToken = accessToken.getParameters().get("id_token"); assertNotNull(idToken); validateIdToken(idToken, null); if (isAccessTokenInJWTFormat()) { validateAccessToken(accessToken.getTokenKey()); } }
public static void validateAccessTokenHash(ClientAccessToken at, JwtToken jwt, boolean required) { validateAccessTokenHash(at.getTokenKey(), jwt, required); } public static void validateAccessTokenHash(String accessToken, JwtToken jwt, boolean required) {
@org.junit.Test public void testClientCredentialsGrant() throws Exception { URL busFile = AuthorizationGrantTest.class.getResource("client.xml"); String address = "https://localhost:" + port + "/services/"; WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(), "consumer-id", "this-is-a-secret", busFile.toString()); // Get Access Token client.type("application/x-www-form-urlencoded").accept("application/json"); client.path("token"); Form form = new Form(); form.param("grant_type", "client_credentials"); Response response = client.post(form); ClientAccessToken accessToken = response.readEntity(ClientAccessToken.class); assertNotNull(accessToken.getTokenKey()); assertNotNull(accessToken.getRefreshToken()); if (isAccessTokenInJWTFormat()) { // We don't have a Subject for the client credential grant, // so validate manually here as opposed to calling validateAccessToken JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(accessToken.getTokenKey()); 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)); } }
protected AbstractFormImplicitResponse prepareFormResponse(OAuthRedirectionState state, Client client, List<String> requestedScope, List<String> approvedScope, UserSubject userSubject, ServerAccessToken preAuthorizedToken) { ClientAccessToken clientToken = getClientAccessToken(state, client, requestedScope, approvedScope, userSubject, preAuthorizedToken); FormTokenResponse bean = new FormTokenResponse(); bean.setResponseType(OAuthConstants.TOKEN_RESPONSE_TYPE); bean.setRedirectUri(state.getRedirectUri()); bean.setState(state.getState()); bean.setAccessToken(clientToken.getTokenKey()); bean.setAccessTokenType(clientToken.getTokenType()); bean.setAccessTokenExpiresIn(clientToken.getExpiresIn()); bean.getParameters().putAll(clientToken.getParameters()); return bean; }
assertNotNull(accessToken.getTokenKey()); assertTrue(accessToken.getApprovedScope().contains("openid")); assertNotNull(accessToken.getRefreshToken()); String idToken = accessToken.getParameters().get("id_token"); assertNotNull(idToken); validateIdToken(idToken, null); form.param("refresh_token", accessToken.getRefreshToken()); form.param("client_id", "consumer-id"); form.param("scope", "openid"); assertNotNull(accessToken.getTokenKey()); assertNotNull(accessToken.getRefreshToken()); accessToken.getParameters().get("id_token"); assertNotNull(idToken); validateAccessToken(accessToken.getTokenKey());
assertNotNull(accessToken.getTokenKey()); assertTrue(accessToken.getApprovedScope().contains("read_balance")); client.accept("application/json").type("application/x-www-form-urlencoded"); Form form = new Form(); form.param("token", accessToken.getTokenKey()); client.path("introspect/"); Response response = client.post(form); assertEquals(tokenIntrospection.getUsername(), "alice"); assertEquals(tokenIntrospection.getClientId(), "consumer-id"); assertEquals(tokenIntrospection.getScope(), accessToken.getApprovedScope()); Long validity = tokenIntrospection.getExp() - tokenIntrospection.getIat(); assertTrue(validity == accessToken.getExpiresIn());
private static void appendTokenData(StringBuilder sb, ClientAccessToken token, HttpRequestProperties httpProps) throws OAuthServiceException { // this should all be handled by token specific serializers String tokenType = token.getTokenType().toLowerCase(); if (OAuthConstants.BEARER_TOKEN_TYPE.equalsIgnoreCase(tokenType)) { sb.append(OAuthConstants.BEARER_AUTHORIZATION_SCHEME); sb.append(" "); sb.append(token.getTokenKey()); } else if (OAuthConstants.HAWK_TOKEN_TYPE.equalsIgnoreCase(tokenType)) { if (httpProps == null) { throw new IllegalArgumentException("MAC scheme requires HTTP Request properties"); } HawkAuthorizationScheme macAuthData = new HawkAuthorizationScheme(httpProps, token); String macAlgo = token.getParameters().get(OAuthConstants.HAWK_TOKEN_ALGORITHM); String macKey = token.getParameters().get(OAuthConstants.HAWK_TOKEN_KEY); sb.append(macAuthData.toAuthorizationHeader(macAlgo, macKey)); } else { throw new ProcessingException(new OAuthServiceException("Unsupported token type")); } } }
@Override public String getAuthrorizationProperty(String key) { if (this.accessToken == null || expired(this.accessToken)) { this.accessToken = getAccessToken(); } return this.accessToken.getParameters().get(key); }
if (accessToken == null || accessToken.getTokenKey() == null) { LOG.warn("No Access Token received from the Facebook IdP"); return null; String subjectName = getSubjectName(apiEndpoint, accessToken.getTokenKey(), trustedIdp); try { String whr = (String) WebUtils.getAttributeFromFlowScope(context, IdpConstants.HOME_REALM); expires.setTime(expires.getTime() + (accessToken.getExpiresIn() * 1000L)); SecurityToken idpToken = new SecurityToken(IDGenerator.generateID(null), null, expires); SamlAssertionWrapper assertion =
private UserInfo getUserInfo( final String endpoint, final String accessToken, final IdToken idToken, final Consumer consumer) { WebClient userInfoServiceClient = WebClient.create(endpoint, Arrays.asList(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; }
@Override public void process(ClientAccessToken ct, ServerAccessToken st) { if (st.getResponseType() != null && OidcUtils.CODE_AT_RESPONSE_TYPE.equals(st.getResponseType()) && OAuthConstants.IMPLICIT_GRANT.equals(st.getGrantType())) { // token post-processing as part of the current hybrid (implicit) flow // so no id_token is returned now - however when the code gets exchanged later on // this filter will add id_token to the returned access token return; } // Only add an IdToken if the client has the "openid" scope if (ct.getApprovedScope() == null || !ct.getApprovedScope().contains(OidcUtils.OPENID_SCOPE)) { return; } String idToken = getProcessedIdToken(st); if (idToken != null) { ct.getParameters().put(OidcUtils.ID_TOKEN, idToken); } } private String getProcessedIdToken(ServerAccessToken st) {
System.out.println("Refresh Token="+clientToken.getRefreshToken()); System.out.println(""); System.out.println(MessageFormat.format(OAUTH2_0_DOMAIN, clientID, clientSecret, clientToken.getRefreshToken(), accessTokenURL));
public static ClientAccessToken refreshAccessToken(WebClient accessTokenService, Consumer consumer, ClientAccessToken at, String scope, boolean setAuthorizationHeader) throws OAuthServiceException { RefreshTokenGrant grant = new RefreshTokenGrant(at.getRefreshToken(), scope); return getAccessToken(accessTokenService, consumer, grant, null, at.getTokenType(), setAuthorizationHeader); }
@org.junit.Test public void testAuthorizationCodeOAuth() 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, "read_balance"); assertNotNull(code); // Now get the access token client = WebClient.create(address, OAuth2TestUtils.setupProviders(), "consumer-id", "this-is-a-secret", busFile.toString()); // Save the Cookie for the second request... WebClient.getConfig(client).getRequestContext().put( org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE); ClientAccessToken accessToken = OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code); assertNotNull(accessToken.getTokenKey()); // We should not have an IdToken here String idToken = accessToken.getParameters().get("id_token"); assertNull(idToken); assertFalse(accessToken.getApprovedScope().contains("openid")); if (isAccessTokenInJWTFormat()) { validateAccessToken(accessToken.getTokenKey()); } }
public static void validateAccessTokenHash(ClientAccessToken at, JwtToken jwt, boolean required) { validateAccessTokenHash(at.getTokenKey(), jwt, required); } public static void validateAccessTokenHash(String accessToken, JwtToken jwt, boolean required) {