org.apache.cxf.rs.security.oauth2.common.ClientAccessToken Java Examples
The following examples show how to use
org.apache.cxf.rs.security.oauth2.common.ClientAccessToken.
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: PushNotificationServiceImpl.java From g-suite-identity-sync with Apache License 2.0 | 6 votes |
private void startPushChannel(String hostname) { WebClient webClient = WebClient.fromClient(directoryApiClient, true) .path("/admin/reports/v1/activity/users/all/applications/admin/watch"); ClientAccessToken accessToken = tokenCache.getToken(); webClient.authorization(accessToken); String url = "https://" + hostname + "/cxf/push/notify"; StartPushChannel watchRequest = new StartPushChannel(url, Duration.ofHours(6)); try { PushChannel ch = webClient.post(watchRequest, PushChannel.class); channel = Optional.of(ch); store(ch); } catch (ClientErrorException e) { String body = e.getResponse().readEntity(String.class); log.error("Cannot register push notification channel for {}.\nResponse: {}", config.getGSuiteDomain(), body); throw new RuntimeException("Cannot register push notification channel for " + hostname); } }
Example #2
Source File: AbstractImplicitGrantService.java From cxf with Apache License 2.0 | 6 votes |
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; }
Example #3
Source File: ClientCodeRequestFilter.java From cxf with Apache License 2.0 | 6 votes |
protected void processCodeResponse(ContainerRequestContext rc, UriInfo ui, MultivaluedMap<String, String> requestParams) { MultivaluedMap<String, String> state = null; if (clientStateManager != null) { state = clientStateManager.fromRedirectState(mc, requestParams); } String codeParam = requestParams.getFirst(OAuthConstants.AUTHORIZATION_CODE_VALUE); ClientAccessToken at = null; if (codeParam != null) { AuthorizationCodeGrant grant = prepareCodeGrant(codeParam, getAbsoluteRedirectUri(ui)); if (state != null) { grant.setCodeVerifier(state.getFirst(OAuthConstants.AUTHORIZATION_CODE_VERIFIER)); } at = OAuthClientUtils.getAccessToken(accessTokenServiceClient, consumer, grant, useAuthorizationHeader); } ClientTokenContext tokenContext = initializeClientTokenContext(rc, at, requestParams, state); if (at != null && clientTokenContextManager != null) { clientTokenContextManager.setClientTokenContext(mc, tokenContext); } setClientCodeRequest(tokenContext); }
Example #4
Source File: AuthorizationGrantTest.java From cxf with Apache License 2.0 | 6 votes |
@org.junit.Test public void testPasswordsCredentialsGrant() throws Exception { String address = "https://localhost:" + port + "/services/"; WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(), "consumer-id", "this-is-a-secret", null); // Get Access Token client.type("application/x-www-form-urlencoded").accept("application/json"); client.path("token"); Form form = new Form(); form.param("grant_type", "password"); form.param("username", "alice"); form.param("password", "security"); ClientAccessToken accessToken = client.post(form, ClientAccessToken.class); assertNotNull(accessToken.getTokenKey()); assertNotNull(accessToken.getRefreshToken()); if (isAccessTokenInJWTFormat()) { validateAccessToken(accessToken.getTokenKey()); } }
Example #5
Source File: AuthorizationGrantTest.java From cxf with Apache License 2.0 | 6 votes |
@org.junit.Test public void testAuthorizationCodeGrantWithScope() throws Exception { String address = "https://localhost:" + port + "/services/"; WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(), "alice", "security", null); // 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, "consumer-id", "this-is-a-secret", null); ClientAccessToken accessToken = OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code); assertNotNull(accessToken.getTokenKey()); }
Example #6
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 #7
Source File: OAuthClientUtilsTest.java From cxf with Apache License 2.0 | 6 votes |
@Test public void fromMapToClientToken() { final Map<String, String> map = new HashMap<>(); final String accessToken = "SlAV32hkKG"; map.put(OAuthConstants.ACCESS_TOKEN, accessToken); final String tokenType = "Bearer"; map.put(OAuthConstants.ACCESS_TOKEN_TYPE, tokenType); final String refreshToken = "8xLOxBtZp8"; map.put(OAuthConstants.REFRESH_TOKEN, refreshToken); final String expiresIn = "3600"; map.put(OAuthConstants.ACCESS_TOKEN_EXPIRES_IN, expiresIn); final ClientAccessToken token = OAuthClientUtils.fromMapToClientToken(map); assertEquals(accessToken, token.getTokenKey()); assertEquals(tokenType, token.getTokenType()); assertEquals(refreshToken, token.getRefreshToken()); assertEquals(Long.parseLong(expiresIn), token.getExpiresIn()); }
Example #8
Source File: OIDCClientLogic.java From syncope with Apache License 2.0 | 6 votes |
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; }
Example #9
Source File: AuthorizationGrantTest.java From cxf with Apache License 2.0 | 6 votes |
@org.junit.Test public void testAuthorizationCodeGrant() throws Exception { String address = "https://localhost:" + port + "/services/"; WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(), "alice", "security", null); // 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); assertNotNull(code); // Now get the access token client = WebClient.create(address, "consumer-id", "this-is-a-secret", null); ClientAccessToken accessToken = OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code); assertNotNull(accessToken.getTokenKey()); if (isAccessTokenInJWTFormat()) { validateAccessToken(accessToken.getTokenKey()); } }
Example #10
Source File: OAuth2Test.java From openwebbeans-meecrowave with Apache License 2.0 | 6 votes |
@Test public void getPasswordTokenNoClient() { final Client client = ClientBuilder.newClient().register(new OAuthJSONProvider()); try { final ClientAccessToken token = client.target("http://localhost:" + MEECROWAVE.getConfiguration().getHttpPort()) .path("oauth2/token") .request(APPLICATION_JSON_TYPE) .post(entity( new Form() .param("grant_type", "password") .param("username", "test") .param("password", "pwd"), APPLICATION_FORM_URLENCODED_TYPE), ClientAccessToken.class); assertNotNull(token); assertEquals("Bearer", token.getTokenType()); assertNotNull(token.getTokenKey()); assertIsJwt(token.getTokenKey(), "__default"); assertEquals(3600, token.getExpiresIn()); assertNotEquals(0, token.getIssuedAt()); assertNotNull(token.getRefreshToken()); validateJwt(token); } finally { client.close(); } }
Example #11
Source File: OAuthJSONProvider.java From cxf with Apache License 2.0 | 6 votes |
public Object readFrom(Class<Object> cls, Type t, Annotation[] anns, MediaType mt, MultivaluedMap<String, String> headers, InputStream is) throws IOException, WebApplicationException { if (TokenIntrospection.class.isAssignableFrom(cls)) { return fromMapToTokenIntrospection(is); } Map<String, String> params = readJSONResponse(is); if (Map.class.isAssignableFrom(cls)) { return params; } ClientAccessToken token = OAuthClientUtils.fromMapToClientToken(params); if (token == null) { throw new WebApplicationException(500); } return token; }
Example #12
Source File: OAuthJSONProviderTest.java From cxf with Apache License 2.0 | 6 votes |
@Test public void testWriteHawkClientAccessToken() throws Exception { ClientAccessToken token = new ClientAccessToken("hawk", "1234"); token.setExpiresIn(12345); token.setRefreshToken("5678"); token.setApprovedScope("read"); Map<String, String> params = new LinkedHashMap<>(); params.put(OAuthConstants.HAWK_TOKEN_KEY, "test_mac_secret"); params.put(OAuthConstants.HAWK_TOKEN_ALGORITHM, OAuthConstants.HMAC_ALGO_SHA_1); params.put("my_parameter", "http://abc"); token.setParameters(params); OAuthJSONProvider provider = new OAuthJSONProvider(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); provider.writeTo(token, ClientAccessToken.class, ClientAccessToken.class, new Annotation[] {}, MediaType.APPLICATION_JSON_TYPE, new MetadataMap<String, Object>(), bos); doReadClientAccessToken(bos.toString(), OAuthConstants.HAWK_TOKEN_TYPE, params); }
Example #13
Source File: OAuthClientUtils.java From cxf with Apache License 2.0 | 6 votes |
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")); } }
Example #14
Source File: JAXRSOAuth2Test.java From cxf with Apache License 2.0 | 6 votes |
@Test public void testPublicClientIdOnly() throws Exception { String pubPort = JCACHE_PORT_PUBLIC; if (JWT_JCACHE_PORT.equals(port)) { pubPort = JWT_JCACHE_PORT_PUBLIC; } else if (JPA_PORT.equals(port)) { pubPort = JPA_PORT_PUBLIC; } else if (JWT_NON_PERSIST_JCACHE_PORT.equals(port)) { pubPort = JWT_NON_PERSIST_JCACHE_PORT_PUBLIC; } String address = "http://localhost:" + pubPort + "/oauth2Public/token"; WebClient wc = WebClient.create(address); ClientAccessToken at = OAuthClientUtils.getAccessToken(wc, new Consumer("fredPublic"), new CustomGrant(), false); assertNotNull(at.getTokenKey()); }
Example #15
Source File: IntrospectionServiceTest.java From cxf with Apache License 2.0 | 6 votes |
@org.junit.Test public void testInvalidToken() throws Exception { URL busFile = IntrospectionServiceTest.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); 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()); // Now query the token introspection service client = WebClient.create(address, OAuth2TestUtils.setupProviders(), "consumer-id", "this-is-a-secret", busFile.toString()); client.accept("application/json").type("application/x-www-form-urlencoded"); Form form = new Form(); form.param("token", accessToken.getTokenKey() + "-xyz"); client.path("introspect/"); Response response = client.post(form); TokenIntrospection tokenIntrospection = response.readEntity(TokenIntrospection.class); assertFalse(tokenIntrospection.isActive()); }
Example #16
Source File: OAuthClientUtils.java From cxf with Apache License 2.0 | 5 votes |
public static void setAuthorizationHeader(WebClient wc, ClientAccessToken accessToken, String httpVerb) { wc.replaceHeader(HttpHeaders.AUTHORIZATION, createAuthorizationHeader(accessToken, new HttpRequestProperties(wc, httpVerb))); }
Example #17
Source File: AuthorizationGrantNegativeTest.java From cxf with Apache License 2.0 | 5 votes |
@org.junit.Test public void testNonMatchingClientDifferentClientIds() throws Exception { URL busFile = AuthorizationGrantTest.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); assertNotNull(code); // Now get the access token using a different client id client = WebClient.create(address, OAuth2TestUtils.setupProviders(), "consumer-id-aud", "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); client.type("application/x-www-form-urlencoded").accept("application/json"); client.path("token"); Form form = new Form(); form.param("grant_type", "authorization_code"); form.param("code", code); form.param("client_id", "consumer-id"); // Now try to get a token Response response = client.post(form); try { response.readEntity(ClientAccessToken.class); fail("Failure expected on trying to get a token"); } catch (ResponseProcessingException ex) { //expected } }
Example #18
Source File: AuthorizationGrantNegativeTest.java From cxf with Apache License 2.0 | 5 votes |
@org.junit.Test public void testJWTUnsigned() throws Exception { URL busFile = AuthorizationGrantNegativeTest.class.getResource("client.xml"); String address = "https://localhost:" + port + "/services/"; WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(), "alice", "security", busFile.toString()); // Create the JWT Token String token = OAuth2TestUtils.createToken("DoubleItSTSIssuer", "consumer-id", "https://localhost:" + port + "/services/token", true, false); // Get Access Token client.type("application/x-www-form-urlencoded").accept("application/json"); client.path("token"); Form form = new Form(); form.param("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"); form.param("assertion", token); form.param("client_id", "consumer-id"); Response response = client.post(form); try { response.readEntity(ClientAccessToken.class); fail("Failure expected on an unsigned token"); } catch (Exception ex) { // expected } }
Example #19
Source File: AuthorizationGrantNegativeTest.java From cxf with Apache License 2.0 | 5 votes |
@org.junit.Test public void testJWTNoIssuer() throws Exception { URL busFile = AuthorizationGrantNegativeTest.class.getResource("client.xml"); String address = "https://localhost:" + port + "/services/"; WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(), "alice", "security", busFile.toString()); // Create the JWT Token String token = OAuth2TestUtils.createToken(null, "consumer-id", "https://localhost:" + port + "/services/token", true, true); // Get Access Token client.type("application/x-www-form-urlencoded").accept("application/json"); client.path("token"); Form form = new Form(); form.param("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"); form.param("assertion", token); form.param("client_id", "consumer-id"); Response response = client.post(form); try { response.readEntity(ClientAccessToken.class); fail("Failure expected on no issuer"); } catch (Exception ex) { // expected } }
Example #20
Source File: OAuth2FiltersTest.java From cxf with Apache License 2.0 | 5 votes |
@org.junit.Test public void testServiceWithTokenAndScope() throws Exception { // Get Authorization Code String oauthService = "https://localhost:" + OAUTH_PORT + "/services/"; WebClient oauthClient = WebClient.create(oauthService, OAuth2TestUtils.setupProviders(), "alice", "security", null); // Save the Cookie for the second request... WebClient.getConfig(oauthClient).getRequestContext().put( org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE); String code = OAuth2TestUtils.getAuthorizationCode(oauthClient, "create_book"); assertNotNull(code); // Now get the access token oauthClient = WebClient.create(oauthService, "consumer-id", "this-is-a-secret", null); ClientAccessToken accessToken = OAuth2TestUtils.getAccessTokenWithAuthorizationCode(oauthClient, code); assertNotNull(accessToken.getTokenKey()); // Now invoke on the service with the access token String address = "https://localhost:" + PORT + "/secured/bookstore/books"; WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders()) .authorization(new ClientAccessToken(BEARER_AUTHORIZATION_SCHEME, accessToken.getTokenKey())); Response response = client.type("application/xml").post(new Book("book", 123L)); assertEquals(response.getStatus(), 200); Book returnedBook = response.readEntity(Book.class); assertEquals(returnedBook.getName(), "book"); assertEquals(returnedBook.getId(), 123L); }
Example #21
Source File: JAXRSOAuth2Test.java From cxf with Apache License 2.0 | 5 votes |
@Test public void testSAML2BearerAuthenticationDirect() throws Exception { String address = "https://localhost:" + port + "/oauth2-auth/token"; WebClient wc = createWebClient(address); Crypto crypto = new CryptoLoader().loadCrypto(CRYPTO_RESOURCE_PROPERTIES); SelfSignInfo signInfo = new SelfSignInfo(crypto, "alice", "password"); SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(true); samlCallbackHandler.setIssuer("alice"); String audienceURI = "https://localhost:" + port + "/oauth2-auth/token"; samlCallbackHandler.setAudience(audienceURI); SamlAssertionWrapper assertionWrapper = SAMLUtils.createAssertion(samlCallbackHandler, signInfo); Document doc = DOMUtils.newDocument(); Element assertionElement = assertionWrapper.toDOM(doc); String assertion = DOM2Writer.nodeToString(assertionElement); String encodedAssertion = Base64UrlUtility.encode(assertion); Map<String, String> extraParams = new HashMap<>(); extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE, Constants.CLIENT_AUTH_SAML2_BEARER); extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, encodedAssertion); ClientAccessToken at = OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams); assertNotNull(at.getTokenKey()); }
Example #22
Source File: JAXRSOAuth2Test.java From cxf with Apache License 2.0 | 5 votes |
@Test public void testConfidentialClientIdAndSecret() throws Exception { String address = "https://localhost:" + port + "/oauth2/token"; WebClient wc = createWebClient(address); ClientAccessToken at = OAuthClientUtils.getAccessToken(wc, new Consumer("fred", "password"), new CustomGrant(), false); assertNotNull(at.getTokenKey()); }
Example #23
Source File: JAXRSOAuth2Test.java From cxf with Apache License 2.0 | 5 votes |
@Test public void testTwoWayTLSAuthenticationCustomGrant() throws Exception { if (JPA_PORT.equals(port)) { // We don't run this test for the JPA provider due to: // java.sql.BatchUpdateException: data exception: string data, right truncation; // table: CLIENT_APPLICATIONCERTIFICATES column: APPLICATIONCERTIFICATES return; } String address = "https://localhost:" + port + "/oauth2/token"; WebClient wc = createWebClient(address); ClientAccessToken at = OAuthClientUtils.getAccessToken(wc, new CustomGrant()); assertNotNull(at.getTokenKey()); }
Example #24
Source File: AuthorizationGrantNegativeTest.java From cxf with Apache License 2.0 | 5 votes |
@org.junit.Test public void testSAMLUnsigned() throws Exception { URL busFile = AuthorizationGrantNegativeTest.class.getResource("client.xml"); String address = "https://localhost:" + port + "/services/"; WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(), "alice", "security", busFile.toString()); // Create the SAML Assertion String assertion = OAuth2TestUtils.createToken(address + "token", true, false); // Get Access Token client.type("application/x-www-form-urlencoded").accept("application/json"); client.path("token"); Form form = new Form(); form.param("grant_type", "urn:ietf:params:oauth:grant-type:saml2-bearer"); form.param("assertion", Base64UrlUtility.encode(assertion)); form.param("client_id", "consumer-id"); try { Response response = client.post(form); response.readEntity(ClientAccessToken.class); fail("Failure expected on an unsigned assertion"); } catch (Exception ex) { // expected } }
Example #25
Source File: OAuthJSONProvider.java From cxf with Apache License 2.0 | 5 votes |
public void writeTo(Object obj, Class<?> cls, Type t, Annotation[] anns, MediaType mt, MultivaluedMap<String, Object> headers, OutputStream os) throws IOException, WebApplicationException { if (obj instanceof ClientAccessToken) { writeAccessToken((ClientAccessToken)obj, os); } else if (obj instanceof TokenIntrospection) { writeTokenIntrospection((TokenIntrospection)obj, os); } else { writeOAuthError((OAuthError)obj, os); } }
Example #26
Source File: OAuthJSONProvider.java From cxf with Apache License 2.0 | 5 votes |
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(); }
Example #27
Source File: AuthorizationGrantTest.java From cxf with Apache License 2.0 | 5 votes |
@org.junit.Test public void testAuthorizationCodeGrantWithAudience() throws Exception { String address = "https://localhost:" + port + "/services/"; WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(), "alice", "security", null); // 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, null, "consumer-id-aud"); assertNotNull(code); // Now get the access token client = WebClient.create(address, "consumer-id-aud", "this-is-a-secret", null); String audPort = JCACHE_PORT2; if (JWT_JCACHE_SERVER.getPort().equals(port)) { audPort = JWT_JCACHE_PORT2; } else if (JPA_SERVER.getPort().equals(port)) { audPort = JPA_PORT2; } else if (JWT_NON_PERSIST_JCACHE_SERVER.getPort().equals(port)) { audPort = JWT_NON_PERSIST_JCACHE_PORT2; } String audience = "https://localhost:" + audPort + "/secured/bookstore/books"; ClientAccessToken accessToken = OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code, "consumer-id-aud", audience); assertNotNull(accessToken.getTokenKey()); }
Example #28
Source File: JAXRSOAuth2TlsTest.java From cxf with Apache License 2.0 | 5 votes |
@Test public void testTwoWayTLSClientIdIsSubjectDn() throws Exception { String atServiceAddress = "https://localhost:" + PORT + "/oauth2/token"; WebClient wc = createOAuth2WebClient(atServiceAddress); ClientAccessToken at = OAuthClientUtils.getAccessToken(wc, new CustomGrant()); assertNotNull(at.getTokenKey()); String protectedRsAddress = "https://localhost:" + PORT + "/rs/bookstore/books/123"; WebClient wcRs = createRsWebClient(protectedRsAddress, at, "client.xml"); Book book = wcRs.get(Book.class); assertEquals(123L, book.getId()); String protectedRsAddress2 = "https://localhost:" + PORT + "/rs2/bookstore/books/123"; WebClient wcRs2 = createRsWebClient(protectedRsAddress2, at, "client.xml"); book = wcRs2.get(Book.class); assertEquals(123L, book.getId()); String unprotectedRsAddress = "https://localhost:" + PORT + "/rsUnprotected/bookstore/books/123"; WebClient wcRsDiffClientCert = createRsWebClient(unprotectedRsAddress, at, "client2.xml"); // Unprotected resource book = wcRsDiffClientCert.get(Book.class); assertEquals(123L, book.getId()); // Protected resource, access token was created with Morpit.jks key, RS is accessed with // Bethal.jks key, thus 401 is expected wcRsDiffClientCert = createRsWebClient(protectedRsAddress, at, "client2.xml"); assertEquals(401, wcRsDiffClientCert.get().getStatus()); wcRsDiffClientCert = createRsWebClient(protectedRsAddress2, at, "client2.xml"); assertEquals(401, wcRsDiffClientCert.get().getStatus()); }
Example #29
Source File: OAuth2FiltersTest.java From cxf with Apache License 2.0 | 5 votes |
@org.junit.Test public void testServiceWithToken() throws Exception { // Get Authorization Code String oauthService = "https://localhost:" + OAUTH_PORT + "/services/"; WebClient oauthClient = WebClient.create(oauthService, OAuth2TestUtils.setupProviders(), "alice", "security", null); // Save the Cookie for the second request... WebClient.getConfig(oauthClient).getRequestContext().put( org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE); String code = OAuth2TestUtils.getAuthorizationCode(oauthClient); assertNotNull(code); // Now get the access token oauthClient = WebClient.create(oauthService, "consumer-id", "this-is-a-secret", null); ClientAccessToken accessToken = OAuth2TestUtils.getAccessTokenWithAuthorizationCode(oauthClient, code); assertNotNull(accessToken.getTokenKey()); // Now invoke on the service with the access token String address = "https://localhost:" + PORT + "/secured/bookstore/books"; WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders()) .authorization(new ClientAccessToken(BEARER_AUTHORIZATION_SCHEME, accessToken.getTokenKey())); Response response = client.type("application/xml").post(new Book("book", 123L)); assertEquals(response.getStatus(), 200); Book returnedBook = response.readEntity(Book.class); assertEquals(returnedBook.getName(), "book"); assertEquals(returnedBook.getId(), 123L); }
Example #30
Source File: PublicClientTest.java From cxf with Apache License 2.0 | 5 votes |
private void testPKCE(CodeVerifierTransformer transformer, String tokenServiceAddress) { URL busFile = PublicClientTest.class.getResource("publicclient.xml"); String address = "https://localhost:" + JCACHE_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 AuthorizationCodeParameters parameters = new AuthorizationCodeParameters(); parameters.setConsumerId("consumer-id"); String codeVerifier = Base64UrlUtility.encode(CryptoUtils.generateSecureRandomBytes(32)); parameters.setCodeChallenge(transformer.transformCodeVerifier(codeVerifier)); parameters.setCodeChallengeMethod(transformer.getChallengeMethod()); parameters.setResponseType(OAuthConstants.CODE_RESPONSE_TYPE); parameters.setPath("authorize/"); String location = OAuth2TestUtils.getLocation(client, parameters); String code = OAuth2TestUtils.getSubstring(location, "code"); assertNotNull(code); // Now get the access token client = WebClient.create(tokenServiceAddress, busFile.toString()); ClientAccessToken accessToken = OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code, "consumer-id", null, codeVerifier); assertNotNull(accessToken.getTokenKey()); }