io.vertx.ext.auth.oauth2.AccessToken Java Examples
The following examples show how to use
io.vertx.ext.auth.oauth2.AccessToken.
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: CodeAuthenticationMechanism.java From quarkus with Apache License 2.0 | 6 votes |
private void processSuccessfulAuthentication(RoutingContext context, TenantConfigContext configContext, AccessToken result, SecurityIdentity securityIdentity) { removeCookie(context, configContext, getSessionCookieName(configContext)); String cookieValue = new StringBuilder(result.opaqueIdToken()) .append(COOKIE_DELIM) .append(result.opaqueAccessToken()) .append(COOKIE_DELIM) .append(result.opaqueRefreshToken()).toString(); long maxAge = result.idToken().getLong("exp") - result.idToken().getLong("iat"); if (configContext.oidcConfig.token.lifespanGrace.isPresent()) { maxAge += configContext.oidcConfig.token.lifespanGrace.get(); } createCookie(context, configContext, getSessionCookieName(configContext), cookieValue, maxAge); }
Example #2
Source File: Oauth2TokenTest.java From vertx-auth with Apache License 2.0 | 6 votes |
@Test public void testNullScope() throws Exception { super.setUp(); oauth2 = KeycloakAuth.create(vertx, OAuth2FlowType.AUTH_CODE, keycloakConfig); JsonObject json = new JsonObject( "{\n" + " \"access_token\":\"xyz\",\n" + " \"expires_in\":60,\n" + " \"token_type\":\"bearer\",\n" + " \"not-before-policy\":0,\n" + " \"scope\":null\n" + "}" ); try { AccessToken token = new AccessTokenImpl(json, oauth2); } catch (RuntimeException e) { fail(); } }
Example #3
Source File: KeycloakRBACImpl.java From vertx-auth with Apache License 2.0 | 6 votes |
/** * Determine if this token has an associated role. * <p> * This method is only functional if the token is constructed * with a `clientId` parameter. * <p> * The parameter matches a role specification using the following rules: * <p> * - If the name contains no colons, then the name is taken as the entire * name of a role within the current application, as specified via * `clientId`. * - If the name starts with the literal `realm:`, the subsequent portion * is taken as the name of a _realm-level_ role. * - Otherwise, the name is split at the colon, with the first portion being * taken as the name of an arbitrary application, and the subsequent portion * as the name of a role with that app. * * @param authority The role name specifier. * @param handler `true` if this token has the specified role, otherwise `false`. */ @Override public void isAuthorized(AccessToken user, String authority, Handler<AsyncResult<Boolean>> handler) { JsonObject accessToken = user.accessToken(); if (accessToken == null) { handler.handle(Future.failedFuture("AccessToken is not a valid JWT")); return; } String[] parts = authority.split(":"); if (parts.length == 1) { handler.handle(Future.succeededFuture(hasApplicationRole(accessToken, options.getClientID(), parts[0]))); return; } if ("realm".equals(parts[0])) { handler.handle(Future.succeededFuture(hasRealmRole(accessToken, parts[1]))); return; } handler.handle(Future.succeededFuture(hasApplicationRole(accessToken, parts[0], parts[1]))); }
Example #4
Source File: KeycloakOAuth2.java From apiman with Apache License 2.0 | 5 votes |
@Override public Authenticator authenticate(Vertx vertx, Map<String, String> config, MultiMap headerMap, Handler<AsyncResult<Void>> resultHandler) { OAuth2FlowType flowType = getFlowType(config.get("flowType")); JsonObject params = new JsonObject(); if (config.get("username") != null) { params.put("username", config.get("username")); } if (config.get("password") != null) { params.put("password", config.get("password")); } OAuth2Auth oauth2 = KeycloakAuth.create(vertx, flowType, mapToJson(config)); oauth2.getToken(params, tokenResult -> { if (tokenResult.succeeded()) { log.debug("OAuth2 Keycloak exchange succeeded."); AccessToken token = tokenResult.result(); headerMap.set("Authorization", "Bearer " + token.principal().getString("access_token")); resultHandler.handle(Future.succeededFuture()); } else { log.error("Access Token Error: {0}.", tokenResult.cause().getMessage()); resultHandler.handle(Future.failedFuture(tokenResult.cause())); } }); return this; }
Example #5
Source File: OAuth2.java From apiman with Apache License 2.0 | 5 votes |
@Override public Authenticator authenticate(Vertx vertx, Map<String, String> config, MultiMap headerMap, Handler<AsyncResult<Void>> resultHandler) { OAuth2ClientOptions credentials = new OAuth2ClientOptions(mapToJson(config)); if (config.get("oauthUri") != null) { credentials.setSite(config.get("oauthUri")); } if (config.get("clientId") != null) { credentials.setClientID(config.get("clientId")); } OAuth2FlowType flowType = getFlowType(config.get("flowType")); JsonObject params = new JsonObject(); if (config.get("username") != null) { params.put("username", config.get("username")); } if (config.get("password") != null) { params.put("password", config.get("password")); } OAuth2Auth oauth2 = OAuth2Auth.create(vertx, flowType, credentials); oauth2.getToken(params, tokenResult -> { if (tokenResult.succeeded()) { log.debug("OAuth2 exchange succeeded."); AccessToken token = tokenResult.result(); headerMap.set("Authorization", "Bearer " + token.principal().getString("access_token")); resultHandler.handle(Future.succeededFuture()); } else { log.error("Access Token Error: {0}.", tokenResult.cause().getMessage()); resultHandler.handle(Future.failedFuture(tokenResult.cause())); } }); return this; }
Example #6
Source File: Oauth2TokenTest.java From vertx-auth with Apache License 2.0 | 5 votes |
@Test public void keycloakTest() throws Exception { super.setUp(); oauth2 = KeycloakAuth.create(vertx, OAuth2FlowType.AUTH_CODE, keycloakConfig); AccessToken token = new AccessTokenImpl(keycloakToken, oauth2); assertNotNull(token.opaqueAccessToken()); assertNotNull(token.opaqueRefreshToken()); assertNull(token.accessToken()); }
Example #7
Source File: AccessTokenImpl.java From vertx-auth with Apache License 2.0 | 5 votes |
@Override public AccessToken revoke(String token_type, Handler<AsyncResult<Void>> callback) { oAuth2Auth.revoke(this, token_type, revoke -> { if (revoke.failed()) { callback.handle(Future.failedFuture(revoke.cause())); } else { // clear properties principal().remove(token_type); callback.handle(Future.succeededFuture()); } }); return this; }
Example #8
Source File: AccessTokenImpl.java From vertx-auth with Apache License 2.0 | 5 votes |
@Override public AccessToken refresh(Handler<AsyncResult<Void>> callback) { oAuth2Auth.refresh(this, refresh -> { if (refresh.failed()) { callback.handle(Future.failedFuture(refresh.cause())); } else { User user = refresh.result(); // merge properties attributes().mergeIn(user.attributes()); principal().mergeIn(user.principal()); callback.handle(Future.succeededFuture()); } }); return this; }
Example #9
Source File: AccessTokenImpl.java From vertx-auth with Apache License 2.0 | 4 votes |
@Override public AccessToken logout(Handler<AsyncResult<Void>> callback) { LOG.warn("This operation is not supported, this was a Keycloak specific feature not a standard"); callback.handle(Future.failedFuture(new UnsupportedOperationException())); return this; }
Example #10
Source File: AccessTokenImpl.java From vertx-auth with Apache License 2.0 | 4 votes |
@Override public AccessToken introspect(Handler<AsyncResult<Void>> callback) { LOG.warn("This operation is not supported, authenticate the user instead"); callback.handle(Future.failedFuture(new UnsupportedOperationException())); return this; }
Example #11
Source File: AccessTokenImpl.java From vertx-auth with Apache License 2.0 | 4 votes |
@Override public AccessToken introspect(String tokenType, Handler<AsyncResult<Void>> callback) { LOG.warn("This operation is not supported, authenticate the user instead"); callback.handle(Future.failedFuture(new UnsupportedOperationException())); return this; }
Example #12
Source File: AccessTokenImpl.java From vertx-auth with Apache License 2.0 | 4 votes |
@Override public AccessToken userInfo(Handler<AsyncResult<JsonObject>> callback) { oAuth2Auth.userInfo(this, callback); return this; }
Example #13
Source File: AccessTokenImpl.java From vertx-auth with Apache License 2.0 | 4 votes |
@Override public AccessToken fetch(HttpMethod method, String resource, JsonObject headers, Buffer payload, Handler<AsyncResult<OAuth2Response>> callback) { LOG.warn("This operation is not supported, use a WebClient instead"); callback.handle(Future.failedFuture(new UnsupportedOperationException())); return this; }
Example #14
Source File: AccessTokenImpl.java From vertx-auth with Apache License 2.0 | 4 votes |
@Override public AccessToken setTrustJWT(boolean trust) { LOG.warn("This operation is not supported."); return this; }
Example #15
Source File: CookiePostHandler.java From nassh-relay with GNU General Public License v2.0 | 4 votes |
@Override public void handle(final RoutingContext context) { logger.debug("got request"); final HttpServerRequest request = context.request(); final HttpServerResponse response = context.response(); response.putHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0"); response.putHeader("Pragma", "no-cache"); response.putHeader("Content-Type", "no-cache"); response.putHeader("Content-Type", "application/json"); final Cookie cookie = context.getCookie(Constants.SESSIONCOOKIE); UUID sessioncookie; if (cookie == null) { sessioncookie = null; } else { sessioncookie = UUID.fromString(cookie.getValue()); } final AuthSession session = AuthSessionManager.getSession(sessioncookie); if (session == null) { response.setStatusCode(403); response.end("\"Invalid session cookie.\""); return; } final String token = session.get("token"); final String state = session.get("state"); if (token != null) { response.setStatusCode(200); response.end("\"Current user is already connected.\""); return; } if (!request.params().contains("state") || !request.params().get("state").equals(state)) { response.setStatusCode(403); response.end("\"Invalid state parameter.\""); return; } request.bodyHandler(body -> { final JsonObject tokenConfig = new JsonObject() .put("code", body.toString()) .put("redirect_uri", "postmessage"); oauth2.authenticate(tokenConfig, ar -> { if (ar.succeeded() && ar.result() instanceof AccessToken) { final AccessToken accessToken = (AccessToken) ar.result(); accessToken.setTrustJWT(true); final JsonObject user = accessToken.idToken(); final String id = user.getString("sub"); final String email = user.getString("email"); final String hostedDomain = user.getString("hd"); logger.info("Google User: id: " + id + " email: " + email + " domain: " + hostedDomain + " logged in"); session.put("token", accessToken.opaqueAccessToken()); session.put("id", id); session.put("email", email); session.put("domain", hostedDomain); response.setStatusCode(200); response.end("\"Successfully connected user.\""); } else { response.setStatusCode(500); response.end("\"Failed to read token data from Google. " + ar.cause().getMessage() + "\""); } }); }); }
Example #16
Source File: OIDCTest.java From vertx-auth with Apache License 2.0 | 4 votes |
@Ignore @Test public void testFullCycle() { OpenIDConnectAuth.discover( vertx, new OAuth2Options() .setFlow(OAuth2FlowType.PASSWORD) .setClientID("vertx") .setSite("http://localhost:8080/auth/realms/master"), res -> { if (res.failed()) { fail(res.cause()); return; } final OAuth2Auth oidc = res.result(); oidc.authenticate(new JsonObject().put("username", "admin").put("password", "admin"), res1 -> { if (res1.failed()) { fail(res1.cause().getMessage()); return; } AccessToken token = (AccessToken) res1.result(); assertNotNull(token); assertNotNull(token.principal()); assertNotNull(token.accessToken()); assertNotNull(token.opaqueRefreshToken()); token.userInfo(res2 -> { if (res2.failed()) { fail(res2.cause().getMessage()); return; } assertEquals("admin", res2.result().getString("preferred_username")); token.logout(res3 -> { if (res3.failed()) { fail(res3.cause().getMessage()); return; } testComplete(); }); }); }); }); await(); }
Example #17
Source File: WikiResource.java From redpipe with Apache License 2.0 | 4 votes |
private String getUserName() { AccessToken tok = (AccessToken) user.getDelegate(); return tok.accessToken().getString("preferred_username"); }
Example #18
Source File: OidcIdentityProvider.java From quarkus with Apache License 2.0 | 4 votes |
@SuppressWarnings("deprecation") private Uni<SecurityIdentity> validateTokenWithOidcServer(TokenAuthenticationRequest request, TenantConfigContext resolvedContext) { return Uni.createFrom().emitter(new Consumer<UniEmitter<? super SecurityIdentity>>() { @Override public void accept(UniEmitter<? super SecurityIdentity> uniEmitter) { resolvedContext.auth.decodeToken(request.getToken().getToken(), new Handler<AsyncResult<AccessToken>>() { @Override public void handle(AsyncResult<AccessToken> event) { if (event.failed()) { uniEmitter.fail(new AuthenticationFailedException(event.cause())); return; } // Token has been verified, as a JWT or an opaque token, possibly involving // an introspection request. final TokenCredential tokenCred = request.getToken(); JsonObject tokenJson = event.result().accessToken(); if (tokenJson == null) { // JSON token representation may be null not only if it is an opaque access token // but also if it is JWT and no JWK with a matching kid is available, asynchronous // JWK refresh has not finished yet, but the fallback introspection request has succeeded. tokenJson = OidcUtils.decodeJwtContent(tokenCred.getToken()); } if (tokenJson != null) { try { uniEmitter.complete( validateAndCreateIdentity(tokenCred, resolvedContext.oidcConfig, tokenJson)); } catch (Throwable ex) { uniEmitter.fail(ex); } } else if (tokenCred instanceof IdTokenCredential || tokenCred instanceof AccessTokenCredential && !((AccessTokenCredential) tokenCred).isOpaque()) { uniEmitter .fail(new AuthenticationFailedException("JWT token can not be converted to JSON")); } else { // Opaque access token QuarkusSecurityIdentity.Builder builder = QuarkusSecurityIdentity.builder(); builder.addCredential(tokenCred); if (event.result().principal().containsKey("username")) { final String userName = event.result().principal().getString("username"); builder.setPrincipal(new Principal() { @Override public String getName() { return userName; } }); } uniEmitter.complete(builder.build()); } } }); } }); }