io.quarkus.security.identity.SecurityIdentity Java Examples

The following examples show how to use io.quarkus.security.identity.SecurityIdentity. 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: JpaIdentityProvider.java    From quarkus with Apache License 2.0 7 votes vote down vote up
@Override
public Uni<SecurityIdentity> authenticate(UsernamePasswordAuthenticationRequest request,
        AuthenticationRequestContext context) {
    return context.runBlocking(new Supplier<SecurityIdentity>() {
        @Override
        public SecurityIdentity get() {
            // FIXME: unit name
            EntityManager em = jpaConfig.getEntityManagerFactory(null).createEntityManager();
            ((org.hibernate.Session) em).setHibernateFlushMode(FlushMode.MANUAL);
            ((org.hibernate.Session) em).setDefaultReadOnly(true);
            try {
                return authenticate(em, request);
            } catch (SecurityException e) {
                log.debug("Authentication failed", e);
                throw new AuthenticationFailedException();
            } finally {
                em.close();
            }
        }
    });
}
 
Example #2
Source File: VertxHttpFacade.java    From quarkus with Apache License 2.0 7 votes vote down vote up
@Override
public KeycloakSecurityContext getSecurityContext() {
    SecurityIdentity identity = QuarkusHttpUser.getSecurityIdentityBlocking(routingContext, null);
    if (identity == null) {
        return null;
    }
    TokenCredential credential = identity.getCredential(AccessTokenCredential.class);

    if (credential == null) {
        return null;
    }

    String token = credential.getToken();

    try {
        return new KeycloakSecurityContext(token, new JWSInput(token).readJsonContent(AccessToken.class), null, null);
    } catch (JWSInputException e) {
        throw new RuntimeException("Failed to create access token", e);
    }
}
 
Example #3
Source File: MpJwtValidator.java    From quarkus with Apache License 2.0 7 votes vote down vote up
@Override
public Uni<SecurityIdentity> authenticate(TokenAuthenticationRequest request,
        AuthenticationRequestContext context) {
    return Uni.createFrom().emitter(new Consumer<UniEmitter<? super SecurityIdentity>>() {
        @Override
        public void accept(UniEmitter<? super SecurityIdentity> uniEmitter) {
            try {
                JsonWebToken jwtPrincipal = parser.parse(request.getToken().getToken());
                uniEmitter.complete(QuarkusSecurityIdentity.builder().setPrincipal(jwtPrincipal)
                        .addRoles(jwtPrincipal.getGroups())
                        .addAttribute(SecurityIdentity.USER_ATTRIBUTE, jwtPrincipal).build());

            } catch (ParseException e) {
                log.debug("Authentication failed", e);
                uniEmitter.fail(new AuthenticationFailedException(e));
            }
        }
    });

}
 
Example #4
Source File: JpaTrustedIdentityProvider.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public Uni<SecurityIdentity> authenticate(TrustedAuthenticationRequest request,
        AuthenticationRequestContext context) {
    return context.runBlocking(new Supplier<SecurityIdentity>() {
        @Override
        public SecurityIdentity get() {
            // FIXME: unit name
            EntityManager em = jpaConfig.getEntityManagerFactory(null).createEntityManager();
            ((org.hibernate.Session) em).setHibernateFlushMode(FlushMode.MANUAL);
            ((org.hibernate.Session) em).setDefaultReadOnly(true);
            try {
                return authenticate(em, request);
            } catch (SecurityException e) {
                log.debug("Authentication failed", e);
                throw new AuthenticationFailedException();
            } finally {
                em.close();
            }
        }
    });
}
 
Example #5
Source File: VertxRequestHandler.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private FunqyServerResponse dispatch(CloudEvent event, RoutingContext routingContext, FunctionInvoker invoker,
        Object input) {
    ManagedContext requestContext = beanContainer.requestContext();
    requestContext.activate();
    if (association != null) {
        ((Consumer<Uni<SecurityIdentity>>) association).accept(QuarkusHttpUser.getSecurityIdentity(routingContext, null));
    }
    currentVertxRequest.setCurrent(routingContext);
    try {
        RequestContextImpl funqContext = new RequestContextImpl();
        if (event != null) {
            funqContext.setContextData(CloudEvent.class, event);
        }
        FunqyRequestImpl funqyRequest = new FunqyRequestImpl(funqContext, input);
        FunqyResponseImpl funqyResponse = new FunqyResponseImpl();
        invoker.invoke(funqyRequest, funqyResponse);
        return funqyResponse;
    } finally {
        if (requestContext.isActive()) {
            requestContext.terminate();
        }
    }
}
 
Example #6
Source File: CodeAuthenticationMechanism.java    From quarkus with Apache License 2.0 6 votes vote down vote up
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 #7
Source File: CodeAuthenticationMechanism.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static QuarkusSecurityIdentity augmentIdentity(SecurityIdentity securityIdentity,
        String accessToken,
        String refreshToken,
        RoutingContext context) {
    IdTokenCredential idTokenCredential = securityIdentity.getCredential(IdTokenCredential.class);
    RefreshToken refreshTokenCredential = new RefreshToken(refreshToken);
    return QuarkusSecurityIdentity.builder()
            .setPrincipal(securityIdentity.getPrincipal())
            .addCredential(idTokenCredential)
            .addCredential(new AccessTokenCredential(accessToken, refreshTokenCredential, context))
            .addCredential(refreshTokenCredential)
            .addRoles(securityIdentity.getRoles())
            .addAttributes(securityIdentity.getAttributes())
            .addPermissionChecker(new Function<Permission, Uni<Boolean>>() {
                @Override
                public Uni<Boolean> apply(Permission permission) {
                    return securityIdentity.checkPermission(permission);
                }
            }).build();
}
 
Example #8
Source File: OAuth2Augmentor.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public Uni<SecurityIdentity> augment(SecurityIdentity identity, AuthenticationRequestContext context) {
    if (identity.getPrincipal() instanceof ElytronOAuth2CallerPrincipal) {

        return Uni.createFrom().item(new Supplier<SecurityIdentity>() {
            @Override
            public SecurityIdentity get() {
                QuarkusSecurityIdentity.Builder builder = QuarkusSecurityIdentity.builder()
                        .setPrincipal(identity.getPrincipal())
                        .addAttributes(identity.getAttributes())
                        .addCredentials(identity.getCredentials())
                        .addRoles(identity.getRoles());
                String[] roles = extractRoles(((ElytronOAuth2CallerPrincipal) identity.getPrincipal()));
                if (roles != null) {
                    for (String i : roles) {
                        builder.addRole(i);
                    }
                }
                return builder.build();
            }
        });
    } else {
        return Uni.createFrom().item(identity);
    }
}
 
Example #9
Source File: QuarkusHttpUser.java    From quarkus with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the current user from the routing context. This method may block if proactive authentication is disabled,
 * as it may need to perform a potentially blocking operation.
 * If an IPM is provided this method will return the anonymous
 * identity if there is no active user, otherwise it will return null if there is no user.
 */
public static SecurityIdentity getSecurityIdentityBlocking(RoutingContext routingContext,
        IdentityProviderManager identityProviderManager) {
    QuarkusHttpUser existing = (QuarkusHttpUser) routingContext.user();
    if (existing != null) {
        return existing.getSecurityIdentity();
    }
    Uni<SecurityIdentity> deferred = routingContext.get(DEFERRED_IDENTITY_KEY);
    if (deferred != null) {
        return deferred.await().indefinitely();
    }
    if (identityProviderManager != null) {
        return identityProviderManager.authenticate(AnonymousAuthenticationRequest.INSTANCE).await().indefinitely();
    }
    return null;
}
 
Example #10
Source File: QuarkusHttpUser.java    From quarkus with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the current user from the routing context. If an IPM is provided this method will return the anonymous
 * identity if there is no active user, otherwise the Uni will resolve to null if there is no user.
 */
public static Uni<SecurityIdentity> getSecurityIdentity(RoutingContext routingContext,
        IdentityProviderManager identityProviderManager) {
    Uni<SecurityIdentity> deferred = routingContext.get(DEFERRED_IDENTITY_KEY);
    if (deferred != null) {
        return deferred;
    }
    QuarkusHttpUser existing = (QuarkusHttpUser) routingContext.user();
    if (existing != null) {
        return Uni.createFrom().item(existing.getSecurityIdentity());
    }
    if (identityProviderManager != null) {
        return identityProviderManager.authenticate(AnonymousAuthenticationRequest.INSTANCE);
    }
    return Uni.createFrom().nullItem();
}
 
Example #11
Source File: MtlsAuthenticationMechanism.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public Uni<SecurityIdentity> authenticate(RoutingContext context,
        IdentityProviderManager identityProviderManager) {
    HttpServerRequest request = context.request();

    if (!request.isSSL()) {
        return Uni.createFrom().nullItem();
    }

    Certificate certificate;

    try {
        certificate = request.sslSession().getPeerCertificates()[0];
    } catch (SSLPeerUnverifiedException e) {
        return Uni.createFrom().nullItem();
    }

    return identityProviderManager
            .authenticate(new CertificateAuthenticationRequest(
                    new CertificateCredential(X509Certificate.class.cast(certificate))));
}
 
Example #12
Source File: FormAuthenticationMechanism.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public Uni<SecurityIdentity> authenticate(RoutingContext context,
        IdentityProviderManager identityProviderManager) {

    PersistentLoginManager.RestoreResult result = loginManager.restore(context);
    if (result != null) {
        Uni<SecurityIdentity> ret = identityProviderManager
                .authenticate(new TrustedAuthenticationRequest(result.getPrincipal()));
        return ret.onItem().invoke(new Consumer<SecurityIdentity>() {
            @Override
            public void accept(SecurityIdentity securityIdentity) {
                loginManager.save(securityIdentity, context, result);
            }
        });
    }

    if (context.normalisedPath().endsWith(postLocation) && context.request().method().equals(HttpMethod.POST)) {
        return runFormAuth(context, identityProviderManager);
    } else {
        return Uni.createFrom().optional(Optional.empty());
    }
}
 
Example #13
Source File: HttpAuthenticator.java    From quarkus with Apache License 2.0 6 votes vote down vote up
/**
 * Attempts authentication with the contents of the request. If this is possible the Uni
 * will resolve to a valid SecurityIdentity when it is subscribed to. Note that Uni is lazy,
 * so this may not happen until the Uni is subscribed to.
 *
 * If invalid credentials are present then the completion stage will resolve to a
 * {@link io.quarkus.security.AuthenticationFailedException}
 *
 * If no credentials are present it will resolve to null.
 */
public Uni<SecurityIdentity> attemptAuthentication(RoutingContext routingContext) {

    Uni<SecurityIdentity> result = mechanisms[0].authenticate(routingContext, identityProviderManager);
    for (int i = 1; i < mechanisms.length; ++i) {
        HttpAuthenticationMechanism mech = mechanisms[i];
        result = result.onItem().produceUni(new Function<SecurityIdentity, Uni<SecurityIdentity>>() {
            @Override
            public Uni<SecurityIdentity> apply(SecurityIdentity data) {
                if (data != null) {
                    return Uni.createFrom().item(data);
                }
                return mech.authenticate(routingContext, identityProviderManager);
            }
        });
    }

    return result;
}
 
Example #14
Source File: TokenRealmUnitTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticator() throws Exception {
    KeyPair keyPair = generateKeyPair();
    PublicKey pk1 = keyPair.getPublic();
    PrivateKey pk1Priv = keyPair.getPrivate();
    JWTAuthContextInfo contextInfo = new JWTAuthContextInfo((RSAPublicKey) pk1, "https://server.example.com");
    MpJwtValidator jwtValidator = new MpJwtValidator(new DefaultJWTParser(contextInfo));
    QuarkusIdentityProviderManagerImpl authenticator = QuarkusIdentityProviderManagerImpl.builder()
            .addProvider(new AnonymousIdentityProvider())
            .setBlockingExecutor(new Executor() {
                @Override
                public void execute(Runnable command) {
                    command.run();
                }
            })
            .addProvider(jwtValidator).build();

    String jwt = TokenUtils.generateTokenString("/Token1.json", pk1Priv, "testTokenRealm");
    TokenAuthenticationRequest tokenEvidence = new TokenAuthenticationRequest(new TokenCredential(jwt, "bearer"));
    SecurityIdentity securityIdentity = authenticator.authenticate(tokenEvidence).await().indefinitely();
    Assertions.assertNotNull(securityIdentity);
    Assertions.assertEquals("[email protected]", securityIdentity.getPrincipal().getName());
}
 
Example #15
Source File: PrincipalNameFromParameterObjectSecurityCheck.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(SecurityIdentity identity, Method method, Object[] parameters) {
    if (index > parameters.length - 1) {
        throw genericNotApplicableException(method);
    }
    Object parameterValue = parameters[index];
    if (!expectedParameterClass.equals(parameterValue.getClass())) {
        throw genericNotApplicableException(method);
    }

    String parameterValueStr = getStringValue(parameterValue);

    if (identity.isAnonymous()) {
        throw new UnauthorizedException();
    }

    String name = identity.getPrincipal().getName();
    if (!name.equals(parameterValueStr)) {
        throw new ForbiddenException();
    }
}
 
Example #16
Source File: TestIdentityProvider.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public Uni<SecurityIdentity> authenticate(UsernamePasswordAuthenticationRequest request,
        AuthenticationRequestContext context) {
    TestIdentityController.TestIdentity ident = TestIdentityController.idenitities.get(request.getUsername());
    if (ident == null) {
        return Uni.createFrom().optional(Optional.empty());
    }
    if (!ident.password.equals(new String(request.getPassword().getPassword()))) {
        return Uni.createFrom().failure(new AuthenticationFailedException());
    }
    QuarkusSecurityIdentity identity = QuarkusSecurityIdentity.builder()
            .setPrincipal(new QuarkusPrincipal(ident.username))
            .addRoles(ident.roles)
            .addCredential(request.getPassword())
            .build();
    return Uni.createFrom().item(identity);
}
 
Example #17
Source File: UserEntityIdentityProvider.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public SecurityIdentity authenticate(EntityManager em,
        UsernamePasswordAuthenticationRequest request) {

    Session session = em.unwrap(Session.class);
    SimpleNaturalIdLoadAccess<PlainUserEntity> naturalIdLoadAccess = session.bySimpleNaturalId(PlainUserEntity.class);
    PlainUserEntity user = naturalIdLoadAccess.load(request.getUsername());
    //        Query query = em.createQuery("FROM PlainUserEntity WHERE name = :name");
    //        query.setParameter("name", request.getUsername());
    //        PlainUserEntity user = getSingleUser(query);
    if (user == null)
        return null;

    // for MCF:
    //               Password storedPassword = getMcfPasword(user.pass);
    // for clear:
    Password storedPassword = getClearPassword(user.pass);

    QuarkusSecurityIdentity.Builder builder = checkPassword(storedPassword, request);

    addRoles(builder, user.role);
    return builder.build();
}
 
Example #18
Source File: AnyDelegatingSecurityCheck.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(SecurityIdentity identity, Method method, Object[] parameters) {
    SecurityException thrownException = null;
    for (int i = 0; i < securityChecks.size(); i++) {
        try {
            securityChecks.get(i).apply(identity, method, parameters);
            // no exception was thrown so we can just return
            return;
        } catch (SecurityException e) {
            thrownException = e;
        }
    }
    if (thrownException != null) {
        throw thrownException;
    }
}
 
Example #19
Source File: QuarkusAuthMechanism.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {
    VertxHttpExchange delegate = (VertxHttpExchange) exchange.getDelegate();
    RoutingContext context = (RoutingContext) delegate.getContext();
    try {
        SecurityIdentity identity = QuarkusHttpUser.getSecurityIdentityBlocking(context, null);
        if (identity != null && !identity.isAnonymous()) {
            //associate the identity
            securityContext.authenticationComplete(new QuarkusUndertowAccount(identity), "Quarkus",
                    false);
            return AuthenticationMechanismOutcome.AUTHENTICATED;
        }
        return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
    } catch (AuthenticationFailedException e) {
        return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
    }
}
 
Example #20
Source File: BearerAuthenticationMechanism.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public Uni<SecurityIdentity> authenticate(RoutingContext context,
        IdentityProviderManager identityProviderManager,
        DefaultTenantConfigResolver resolver) {
    String token = extractBearerToken(context);

    // if a bearer token is provided try to authenticate
    if (token != null) {
        return authenticate(identityProviderManager, new AccessTokenCredential(token, context));
    }
    return Uni.createFrom().nullItem();
}
 
Example #21
Source File: PersistentLoginManager.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public void save(SecurityIdentity identity, RoutingContext context, RestoreResult restoreResult) {
    if (restoreResult != null) {
        if (!restoreResult.newCookieNeeded) {
            return;
        }
    }
    try {
        Cipher cipher = Cipher.getInstance(ENC_ALGORITHM);
        byte[] iv = new byte[12];
        secureRandom.nextBytes(iv);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, new GCMParameterSpec(ENC_TAG_LENGTH, iv));
        StringBuilder contents = new StringBuilder();
        long timeout = System.currentTimeMillis() + timeoutMillis;
        log.debugf("The new cookie will expire at %s", new Date(timeout).toString());
        contents.append(timeout);
        contents.append(":");
        contents.append(identity.getPrincipal().getName());
        byte[] encrypted = cipher.doFinal(contents.toString().getBytes(StandardCharsets.UTF_8));
        ByteBuffer message = ByteBuffer.allocate(1 + iv.length + encrypted.length);
        message.put((byte) iv.length);
        message.put(iv);
        message.put(encrypted);
        String cookieValue = Base64.getEncoder().encodeToString(message.array());
        context.addCookie(Cookie.cookie(cookieName, cookieValue).setPath("/"));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}
 
Example #22
Source File: TestTrustedIdentityProvider.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public Uni<SecurityIdentity> authenticate(TrustedAuthenticationRequest request,
        AuthenticationRequestContext context) {
    TestIdentityController.TestIdentity ident = TestIdentityController.idenitities.get(request.getPrincipal());
    if (ident == null) {
        return Uni.createFrom().optional(Optional.empty());
    }
    return Uni.createFrom().completionStage(CompletableFuture
            .completedFuture(QuarkusSecurityIdentity.builder().setPrincipal(new QuarkusPrincipal(request.getPrincipal()))
                    .addRoles(ident.roles).build()));
}
 
Example #23
Source File: KeycloakPolicyEnforcerAuthorizer.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public CheckResult apply(RoutingContext routingContext, SecurityIdentity identity) {
    VertxHttpFacade httpFacade = new VertxHttpFacade(routingContext, readTimeout);
    AuthorizationContext result = delegate.authorize(httpFacade);

    if (result.isGranted()) {
        SecurityIdentity newIdentity = enhanceSecurityIdentity(identity, result);
        return new CheckResult(true, newIdentity);
    }

    return CheckResult.DENY;
}
 
Example #24
Source File: KeycloakPolicyEnforcerAuthorizer.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private SecurityIdentity enhanceSecurityIdentity(SecurityIdentity current,
        AuthorizationContext context) {
    Map<String, Object> attributes = new HashMap<>(current.getAttributes());

    if (context != null) {
        attributes.put("permissions", context.getPermissions());
    }

    return new QuarkusSecurityIdentity.Builder()
            .addAttributes(attributes)
            .setPrincipal(current.getPrincipal())
            .addRoles(current.getRoles())
            .addCredentials(current.getCredentials())
            .addPermissionChecker(new Function<Permission, Uni<Boolean>>() {
                @Override
                public Uni<Boolean> apply(Permission permission) {
                    if (context != null) {
                        String scopes = permission.getActions();

                        if (scopes == null || "".equals(scopes)) {
                            return Uni.createFrom().item(context.hasResourcePermission(permission.getName()));
                        }

                        for (String scope : scopes.split(",")) {
                            if (!context.hasPermission(permission.getName(), scope)) {
                                return Uni.createFrom().item(false);
                            }
                        }

                        return Uni.createFrom().item(true);
                    }

                    return Uni.createFrom().item(false);
                }
            }).build();
}
 
Example #25
Source File: OAuth2AuthMechanism.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Extract the Authorization header and validate the bearer token if it exists. If it does, and is validated, this
 * builds the org.jboss.security.SecurityContext authenticated Subject that drives the container APIs as well as
 * the authorization layers.
 *
 * @param context - the http request exchange object
 * @param identityProviderManager - the current security context that
 * @return one of AUTHENTICATED, NOT_AUTHENTICATED or NOT_ATTEMPTED depending on the header and authentication outcome.
 */
@Override
public Uni<SecurityIdentity> authenticate(RoutingContext context,
        IdentityProviderManager identityProviderManager) {
    String authHeader = context.request().headers().get("Authorization");
    String bearerToken = authHeader != null ? authHeader.substring(7) : null;
    if (bearerToken != null) {
        // Install the OAuth2 principal as the caller
        return identityProviderManager
                .authenticate(new TokenAuthenticationRequest(new TokenCredential(bearerToken, "bearer")));

    }
    // No suitable header has been found in this request,
    return Uni.createFrom().nullItem();
}
 
Example #26
Source File: RolesAllowedHttpSecurityPolicy.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public Uni<CheckResult> checkPermission(RoutingContext request, Uni<SecurityIdentity> identity,
        AuthorizationRequestContext requestContext) {
    return identity.map(new Function<SecurityIdentity, CheckResult>() {
        @Override
        public CheckResult apply(SecurityIdentity securityIdentity) {
            for (String i : rolesAllowed) {
                if (securityIdentity.hasRole(i)) {
                    return CheckResult.PERMIT;
                }
            }
            return CheckResult.DENY;
        }
    });
}
 
Example #27
Source File: AbstractBeanMethodSecurityCheck.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(SecurityIdentity identity, Method method, Object[] parameters) {
    if (check(identity, parameters)) {
        return;
    }
    if (identity.isAnonymous()) {
        throw new UnauthorizedException();
    } else {
        throw new ForbiddenException();
    }
}
 
Example #28
Source File: PrincipalNameFromParameterSecurityCheck.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(SecurityIdentity identity, Method method, Object[] parameters) {
    if (index > parameters.length - 1) {
        throw genericNotApplicableException(method);
    }
    Object parameterValue = parameters[index];
    if (!(parameterValue instanceof String)) {
        throw genericNotApplicableException(method);
    }
    String parameterValueStr = (String) parameterValue;

    if (identity.isAnonymous()) {
        throw new UnauthorizedException();
    }

    String name = identity.getPrincipal().getName();
    if (checkType == CheckType.EQ) {
        if (!name.equals(parameterValueStr)) {
            throw new ForbiddenException();
        }
    } else if (checkType == CheckType.NEQ) {
        if (name.equals(parameterValueStr)) {
            throw new ForbiddenException();
        }
    }

}
 
Example #29
Source File: PathMatchingHttpSecurityPolicy.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private Uni<CheckResult> doPermissionCheck(RoutingContext routingContext,
        Uni<SecurityIdentity> identity, int index, SecurityIdentity augmentedIdentity,
        List<HttpSecurityPolicy> permissionCheckers, AuthorizationRequestContext requestContext) {
    if (index == permissionCheckers.size()) {
        return Uni.createFrom().item(new CheckResult(true, augmentedIdentity));
    }
    //get the current checker
    HttpSecurityPolicy res = permissionCheckers.get(index);
    return res.checkPermission(routingContext, identity, requestContext)
            .flatMap(new Function<CheckResult, Uni<? extends CheckResult>>() {
                @Override
                public Uni<? extends CheckResult> apply(CheckResult checkResult) {
                    if (!checkResult.isPermitted()) {
                        return Uni.createFrom().item(CheckResult.DENY);
                    } else {
                        if (checkResult.getAugmentedIdentity() != null) {

                            //attempt to run the next checker
                            return doPermissionCheck(routingContext,
                                    Uni.createFrom().item(checkResult.getAugmentedIdentity()), index + 1,
                                    checkResult.getAugmentedIdentity(),
                                    permissionCheckers,
                                    requestContext);
                        } else {
                            //attempt to run the next checker
                            return doPermissionCheck(routingContext, identity, index + 1, augmentedIdentity,
                                    permissionCheckers,
                                    requestContext);
                        }
                    }
                }
            });
}
 
Example #30
Source File: JWTAuthMechanism.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public Uni<SecurityIdentity> authenticate(RoutingContext context,
        IdentityProviderManager identityProviderManager) {
    String jwtToken = new VertxBearerTokenExtractor(authContextInfo, context).getBearerToken();
    if (jwtToken != null) {
        return identityProviderManager
                .authenticate(new TokenAuthenticationRequest(new TokenCredential(jwtToken, "bearer")));
    }
    return Uni.createFrom().optional(Optional.empty());
}