Search in sources :

Example 6 with Client

use of org.gluu.oxauth.model.registration.Client in project oxAuth by GluuFederation.

the class AuthenticationFilter method processPostAuth.

private void processPostAuth(ClientFilterService clientFilterService, HttpServletRequest servletRequest, HttpServletResponse servletResponse, FilterChain filterChain, boolean tokenEndpoint) {
    try {
        String clientId = "";
        String clientSecret = "";
        boolean isExistUserPassword = false;
        if (StringHelper.isNotEmpty(servletRequest.getParameter("client_id")) && StringHelper.isNotEmpty(servletRequest.getParameter("client_secret"))) {
            clientId = servletRequest.getParameter("client_id");
            clientSecret = servletRequest.getParameter("client_secret");
            isExistUserPassword = true;
        }
        log.trace("isExistUserPassword: {}", isExistUserPassword);
        boolean requireAuth = !StringHelper.equals(clientId, identity.getCredentials().getUsername()) || !identity.isLoggedIn();
        log.debug("requireAuth: '{}'", requireAuth);
        if (requireAuth) {
            if (isExistUserPassword) {
                Client client = clientService.getClient(clientId);
                if (client != null && AuthenticationMethod.CLIENT_SECRET_POST == client.getAuthenticationMethod()) {
                    // Identity.username and user isn't authenticated
                    if (!clientId.equals(identity.getCredentials().getUsername()) || !identity.isLoggedIn()) {
                        identity.logout();
                        identity.getCredentials().setUsername(clientId);
                        identity.getCredentials().setPassword(clientSecret);
                        requireAuth = !authenticator.authenticateClient(servletRequest);
                    } else {
                        authenticator.configureSessionClient(client);
                    }
                }
            } else if (Boolean.TRUE.equals(appConfiguration.getClientAuthenticationFiltersEnabled())) {
                String clientDn = clientFilterService.processAuthenticationFilters(servletRequest.getParameterMap());
                if (clientDn != null) {
                    Client client = clientService.getClientByDn(clientDn);
                    identity.logout();
                    identity.getCredentials().setUsername(client.getClientId());
                    identity.getCredentials().setPassword(null);
                    requireAuth = !authenticator.authenticateClient(servletRequest, true);
                }
            } else if (tokenEndpoint) {
                Client client = clientService.getClient(servletRequest.getParameter("client_id"));
                if (client != null && client.getAuthenticationMethod() == AuthenticationMethod.NONE) {
                    identity.logout();
                    identity.getCredentials().setUsername(client.getClientId());
                    identity.getCredentials().setPassword(null);
                    requireAuth = !authenticator.authenticateClient(servletRequest, true);
                }
            }
        }
        if (!requireAuth) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        if (!identity.isLoggedIn()) {
            sendError(servletResponse);
        }
    } catch (Exception ex) {
        log.error("Post authentication failed: {}", ex);
    }
}
Also used : Client(org.gluu.oxauth.model.registration.Client) InvalidJwtException(org.gluu.oxauth.model.exception.InvalidJwtException) IOException(java.io.IOException) WebApplicationException(javax.ws.rs.WebApplicationException)

Example 7 with Client

use of org.gluu.oxauth.model.registration.Client in project oxAuth by GluuFederation.

the class Authenticator method clientAuthentication.

public boolean clientAuthentication(Credentials credentials, boolean interactive, boolean skipPassword) {
    boolean isServiceUsesExternalAuthenticator = !interactive && externalAuthenticationService.isEnabled(AuthenticationScriptUsageType.SERVICE);
    if (isServiceUsesExternalAuthenticator) {
        CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService.determineCustomScriptConfiguration(AuthenticationScriptUsageType.SERVICE, 1, this.authAcr);
        if (customScriptConfiguration == null) {
            logger.error("Failed to get CustomScriptConfiguration. acr: '{}'", this.authAcr);
        } else {
            this.authAcr = customScriptConfiguration.getCustomScript().getName();
            boolean result = externalAuthenticationService.executeExternalAuthenticate(customScriptConfiguration, null, 1);
            logger.info("Authentication result for user '{}', result: '{}'", credentials.getUsername(), result);
            if (result) {
                Client client = authenticationService.configureSessionClient();
                showClientAuthenticationLog(client);
                return true;
            }
        }
    }
    boolean loggedIn = skipPassword;
    if (!loggedIn) {
        loggedIn = clientService.authenticate(credentials.getUsername(), credentials.getPassword());
    }
    if (loggedIn) {
        Client client = authenticationService.configureSessionClient();
        showClientAuthenticationLog(client);
        return true;
    }
    return false;
}
Also used : Client(org.gluu.oxauth.model.registration.Client) CustomScriptConfiguration(org.gluu.model.custom.script.conf.CustomScriptConfiguration)

Example 8 with Client

use of org.gluu.oxauth.model.registration.Client in project oxAuth by GluuFederation.

the class UmaTokenService method requestRpt.

public Response requestRpt(String grantType, String ticket, String claimToken, String claimTokenFormat, String pctCode, String rptCode, String scope, HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    try {
        log.trace("requestRpt grant_type: {}, ticket: {}, claim_token: {}, claim_token_format: {}, pct: {}, rpt: {}, scope: {}", grantType, ticket, claimToken, claimTokenFormat, pctCode, rptCode, scope);
        umaValidationService.validateGrantType(grantType);
        List<UmaPermission> permissions = umaValidationService.validateTicket(ticket);
        Jwt idToken = umaValidationService.validateClaimToken(claimToken, claimTokenFormat);
        UmaPCT pct = umaValidationService.validatePct(pctCode);
        UmaRPT rpt = umaValidationService.validateRPT(rptCode);
        Client client = umaValidationService.validate(identity.getSessionClient().getClient());
        Map<Scope, Boolean> scopes = umaValidationService.validateScopes(scope, permissions, client);
        // creates new pct if pct is null in request
        pct = pctService.updateClaims(pct, idToken, client.getClientId(), permissions);
        Claims claims = new Claims(idToken, pct, claimToken);
        Map<UmaScriptByScope, UmaAuthorizationContext> scriptMap = umaNeedsInfoService.checkNeedsInfo(claims, scopes, permissions, pct, httpRequest, client);
        if (!scriptMap.isEmpty()) {
            expressionService.evaluate(scriptMap, permissions);
        } else {
            log.warn("There are no any policies that protects scopes. Scopes: " + UmaScopeService.asString(scopes.keySet()) + ". Configuration property umaGrantAccessIfNoPolicies: " + appConfiguration.getUmaGrantAccessIfNoPolicies());
            if (appConfiguration.getUmaGrantAccessIfNoPolicies() != null && appConfiguration.getUmaGrantAccessIfNoPolicies()) {
                log.warn("Access granted because there are no any protection. Make sure it is intentional behavior.");
            } else {
                log.warn("Access denied because there are no any protection. Make sure it is intentional behavior.");
                throw errorResponseFactory.createWebApplicationException(Response.Status.FORBIDDEN, UmaErrorResponseType.FORBIDDEN_BY_POLICY, "Access denied because there are no any protection. Make sure it is intentional behavior.");
            }
        }
        log.trace("Access granted.");
        updatePermissionsWithClientRequestedScope(permissions, scopes);
        addPctToPermissions(permissions, pct);
        boolean upgraded = false;
        if (rpt == null) {
            ExecutionContext executionContext = new ExecutionContext(httpRequest, httpResponse);
            executionContext.setClient(client);
            rpt = rptService.createRPTAndPersist(executionContext, permissions);
            rptCode = rpt.getNotHashedCode();
        } else if (rptService.addPermissionToRPT(rpt, permissions)) {
            upgraded = true;
        }
        UmaTokenResponse response = new UmaTokenResponse();
        response.setAccessToken(rptCode);
        response.setUpgraded(upgraded);
        response.setTokenType("Bearer");
        response.setPct(pct.getCode());
        return Response.ok(ServerUtil.asJson(response)).build();
    } catch (Exception ex) {
        log.error("Exception happened", ex);
        if (ex instanceof WebApplicationException) {
            throw (WebApplicationException) ex;
        }
    }
    log.error("Failed to handle request to UMA Token Endpoint.");
    throw errorResponseFactory.createWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR, UmaErrorResponseType.SERVER_ERROR, "Failed to handle request to UMA Token Endpoint.");
}
Also used : UmaTokenResponse(org.gluu.oxauth.model.uma.UmaTokenResponse) WebApplicationException(javax.ws.rs.WebApplicationException) Jwt(org.gluu.oxauth.model.jwt.Jwt) WebApplicationException(javax.ws.rs.WebApplicationException) ExecutionContext(org.gluu.oxauth.model.common.ExecutionContext) Scope(org.oxauth.persistence.model.Scope) UmaPermission(org.gluu.oxauth.model.uma.persistence.UmaPermission) Client(org.gluu.oxauth.model.registration.Client)

Example 9 with Client

use of org.gluu.oxauth.model.registration.Client in project oxAuth by GluuFederation.

the class UmaRptService method createRptJwt.

private String createRptJwt(ExecutionContext executionContext, List<UmaPermission> permissions, Date creationDate, Date expirationDate) throws Exception {
    Client client = executionContext.getClient();
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(appConfiguration.getDefaultSignatureAlgorithm());
    if (client.getAccessTokenSigningAlg() != null && SignatureAlgorithm.fromString(client.getAccessTokenSigningAlg()) != null) {
        signatureAlgorithm = SignatureAlgorithm.fromString(client.getAccessTokenSigningAlg());
    }
    final JwtSigner jwtSigner = new JwtSigner(appConfiguration, webKeysConfiguration, signatureAlgorithm, client.getClientId(), clientService.decryptSecret(client.getClientSecret()));
    final Jwt jwt = jwtSigner.newJwt();
    jwt.getClaims().setClaim("client_id", client.getClientId());
    jwt.getClaims().setExpirationTime(expirationDate);
    jwt.getClaims().setIssuedAt(creationDate);
    Audience.setAudience(jwt.getClaims(), client);
    if (permissions != null && !permissions.isEmpty()) {
        String pctCode = permissions.iterator().next().getAttributes().get(UmaPermission.PCT);
        if (StringHelper.isNotEmpty(pctCode)) {
            UmaPCT pct = pctService.getByCode(pctCode);
            if (pct != null) {
                jwt.getClaims().setClaim("pct_claims", pct.getClaims().toJsonObject());
            } else {
                log.error("Failed to find PCT with code: " + pctCode + " which is taken from permission object: " + permissions.iterator().next().getDn());
            }
        }
        jwt.getClaims().setClaim("permissions", buildPermissionsJSONObject(permissions));
    }
    runScriptAndInjectValuesIntoJwt(jwt, executionContext);
    return jwtSigner.sign().toString();
}
Also used : JwtSigner(org.gluu.oxauth.model.token.JwtSigner) UmaPCT(org.gluu.oxauth.uma.authorization.UmaPCT) Jwt(org.gluu.oxauth.model.jwt.Jwt) SignatureAlgorithm(org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm) Client(org.gluu.oxauth.model.registration.Client)

Example 10 with Client

use of org.gluu.oxauth.model.registration.Client in project oxAuth by GluuFederation.

the class CleanerTimerTest method token_whichIsExpiredAndDeletable_MustBeRemoved.

@Test
public void token_whichIsExpiredAndDeletable_MustBeRemoved() throws StringEncrypter.EncryptionException {
    final Client client = createClient();
    clientService.persist(client);
    // 1. create token
    final ClientCredentialsGrant grant = authorizationGrantList.createClientCredentialsGrant(new User(), client);
    final AccessToken accessToken = grant.createAccessToken(null, new ExecutionContext(null, null));
    // 2. token exists
    assertNotNull(grantService.getGrantByCode(accessToken.getCode()));
    // 3. clean up
    cleanerTimer.processImpl();
    cacheService.clear();
    // 4. token exists
    final TokenLdap grantLdap = grantService.getGrantByCode(accessToken.getCode());
    assertNotNull(grantLdap);
    final Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.MINUTE, -10);
    grantLdap.setExpirationDate(calendar.getTime());
    grantService.merge(grantLdap);
    // 5. clean up
    cleanerTimer.processImpl();
    cacheService.clear();
    // 6. no token in persistence
    assertNull(grantService.getGrantByCode(accessToken.getCode()));
}
Also used : Client(org.gluu.oxauth.model.registration.Client) TokenLdap(org.gluu.oxauth.model.ldap.TokenLdap) Test(org.testng.annotations.Test) BaseComponentTest(org.gluu.oxauth.BaseComponentTest)

Aggregations

Client (org.gluu.oxauth.model.registration.Client)55 WebApplicationException (javax.ws.rs.WebApplicationException)15 Test (org.testng.annotations.Test)14 BaseComponentTest (org.gluu.oxauth.BaseComponentTest)12 InvalidJwtException (org.gluu.oxauth.model.exception.InvalidJwtException)10 OAuth2AuditLog (org.gluu.oxauth.model.audit.OAuth2AuditLog)8 JSONException (org.json.JSONException)8 Response (javax.ws.rs.core.Response)6 EntryPersistenceException (org.gluu.persist.exception.EntryPersistenceException)6 JSONObject (org.json.JSONObject)6 IOException (java.io.IOException)5 Date (java.util.Date)5 Jwt (org.gluu.oxauth.model.jwt.Jwt)5 SessionClient (org.gluu.oxauth.model.session.SessionClient)5 URI (java.net.URI)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4 JwtAuthorizationRequest (org.gluu.oxauth.model.authorize.JwtAuthorizationRequest)4 ArrayList (java.util.ArrayList)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 Claim (org.gluu.oxauth.model.authorize.Claim)3