Search in sources :

Example 31 with Client

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

the class DeviceAuthorizationRestWebServiceImpl method deviceAuthorization.

@Override
public Response deviceAuthorization(String clientId, String scope, HttpServletRequest httpRequest, HttpServletResponse httpResponse, SecurityContext securityContext) {
    // it may be encoded
    scope = ServerUtil.urlDecode(scope);
    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(httpRequest), Action.DEVICE_CODE_AUTHORIZATION);
    oAuth2AuditLog.setClientId(clientId);
    oAuth2AuditLog.setScope(scope);
    try {
        log.debug("Attempting to request device codes: clientId = {}, scope = {}", clientId, scope);
        SessionClient sessionClient = identity.getSessionClient();
        Client client = sessionClient != null ? sessionClient.getClient() : null;
        if (client == null) {
            client = clientService.getClient(clientId);
            if (!clientService.isPublic(client)) {
                log.trace("Client is not public and not authenticated. Skip device authorization, clientId: {}", clientId);
                throw errorResponseFactory.createWebApplicationException(Response.Status.UNAUTHORIZED, INVALID_CLIENT, "");
            }
        }
        if (client == null) {
            log.trace("Client is not unknown. Skip revoking.");
            throw errorResponseFactory.createWebApplicationException(Response.Status.UNAUTHORIZED, INVALID_CLIENT, "");
        }
        if (!deviceAuthorizationService.hasDeviceCodeCompatibility(client)) {
            throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, INVALID_GRANT, "");
        }
        List<String> scopes = new ArrayList<>();
        if (StringHelper.isNotEmpty(scope)) {
            Set<String> grantedScopes = scopeChecker.checkScopesPolicy(client, scope);
            scopes.addAll(grantedScopes);
        }
        // Entropy 20^8 which is suggested in the RFC8628 section 6.1
        String userCode = StringUtils.generateRandomReadableCode((byte) 8);
        // Entropy 160 bits which is over userCode entropy based on RFC8628 section 5.2
        String deviceCode = StringUtils.generateRandomCode((byte) 24);
        URI verificationUri = UriBuilder.fromUri(appConfiguration.getIssuer()).path("device-code").build();
        int expiresIn = appConfiguration.getDeviceAuthzRequestExpiresIn();
        int interval = appConfiguration.getDeviceAuthzTokenPollInterval();
        long lastAccess = System.currentTimeMillis();
        DeviceAuthorizationStatus status = DeviceAuthorizationStatus.PENDING;
        DeviceAuthorizationCacheControl deviceAuthorizationCacheControl = new DeviceAuthorizationCacheControl(userCode, deviceCode, client, scopes, verificationUri, expiresIn, interval, lastAccess, status);
        deviceAuthorizationService.saveInCache(deviceAuthorizationCacheControl, true, true);
        log.info("Device authorization flow initiated, userCode: {}, deviceCode: {}, clientId: {}, verificationUri: {}, expiresIn: {}, interval: {}", userCode, deviceCode, clientId, verificationUri, expiresIn, interval);
        applicationAuditLogger.sendMessage(oAuth2AuditLog);
        return Response.ok().entity(getResponseJSONObject(deviceAuthorizationCacheControl).toString(4).replace("\\/", "/")).type(MediaType.APPLICATION_JSON_TYPE).build();
    } catch (WebApplicationException wae) {
        throw wae;
    } catch (Exception e) {
        log.error("Problems processing device authorization init flow, clientId: {}, scope: {}", clientId, scope, e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    }
}
Also used : DeviceAuthorizationCacheControl(org.gluu.oxauth.model.common.DeviceAuthorizationCacheControl) WebApplicationException(javax.ws.rs.WebApplicationException) SessionClient(org.gluu.oxauth.model.session.SessionClient) OAuth2AuditLog(org.gluu.oxauth.model.audit.OAuth2AuditLog) ArrayList(java.util.ArrayList) URI(java.net.URI) JSONException(org.json.JSONException) WebApplicationException(javax.ws.rs.WebApplicationException) DeviceAuthorizationStatus(org.gluu.oxauth.model.common.DeviceAuthorizationStatus) SessionClient(org.gluu.oxauth.model.session.SessionClient) Client(org.gluu.oxauth.model.registration.Client)

Example 32 with Client

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

the class AuthenticationFilter method processBasicAuth.

private void processBasicAuth(HttpServletRequest servletRequest, HttpServletResponse servletResponse, FilterChain filterChain) {
    boolean requireAuth = true;
    try {
        String header = servletRequest.getHeader("Authorization");
        if (tokenService.isBasicAuthToken(header)) {
            String base64Token = tokenService.getBasicToken(header);
            String token = new String(Base64.decodeBase64(base64Token), StandardCharsets.UTF_8);
            String username = "";
            String password = "";
            int delim = token.indexOf(":");
            if (delim != -1) {
                // oxAuth #677 URL decode the username and password
                username = URLDecoder.decode(token.substring(0, delim), Util.UTF8_STRING_ENCODING);
                password = URLDecoder.decode(token.substring(delim + 1), Util.UTF8_STRING_ENCODING);
            }
            requireAuth = !StringHelper.equals(username, identity.getCredentials().getUsername()) || !identity.isLoggedIn();
            // and user isn't authenticated
            if (requireAuth) {
                if (!username.equals(identity.getCredentials().getUsername()) || !identity.isLoggedIn()) {
                    identity.getCredentials().setUsername(username);
                    identity.getCredentials().setPassword(password);
                    if (servletRequest.getRequestURI().endsWith("/token") || servletRequest.getRequestURI().endsWith("/revoke") || servletRequest.getRequestURI().endsWith("/revoke_session") || servletRequest.getRequestURI().endsWith("/userinfo") || servletRequest.getRequestURI().endsWith("/bc-authorize") || servletRequest.getRequestURI().endsWith("/device_authorization")) {
                        Client client = clientService.getClient(username);
                        if (client == null || AuthenticationMethod.CLIENT_SECRET_BASIC != client.getAuthenticationMethod()) {
                            throw new Exception("The Token Authentication Method is not valid.");
                        }
                        requireAuth = !authenticator.authenticateClient(servletRequest);
                    } else {
                        requireAuth = !authenticator.authenticateUser(servletRequest);
                    }
                }
            }
        }
        if (!requireAuth) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
    } catch (Exception ex) {
        log.info("Basic authentication failed", ex);
    }
    if (requireAuth && !identity.isLoggedIn()) {
        sendError(servletResponse);
    }
}
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 33 with Client

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

the class AuthenticationFilter method processAuthByAccessToken.

private void processAuthByAccessToken(String accessToken, HttpServletRequest httpRequest, HttpServletResponse httpResponse, FilterChain filterChain) {
    try {
        log.trace("Authenticating client by access token {} ...", accessToken);
        if (StringUtils.isBlank(accessToken)) {
            sendError(httpResponse);
            return;
        }
        AuthorizationGrant grant = authorizationGrantList.getAuthorizationGrantByAccessToken(accessToken);
        if (grant == null) {
            sendError(httpResponse);
            return;
        }
        final AbstractToken accessTokenObj = grant.getAccessToken(accessToken);
        if (accessTokenObj == null || !accessTokenObj.isValid()) {
            sendError(httpResponse);
            return;
        }
        Client client = grant.getClient();
        authenticator.configureSessionClient(client);
        filterChain.doFilter(httpRequest, httpResponse);
        return;
    } catch (Exception ex) {
        log.error("Failed to authenticate client by access_token", ex);
    }
    sendError(httpResponse);
}
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 34 with Client

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

the class AuthorizeAction method getRequestedClaims.

public List<String> getRequestedClaims() {
    Set<String> result = new HashSet<String>();
    String requestJwt = request;
    if (StringUtils.isBlank(requestJwt) && StringUtils.isNotBlank(requestUri)) {
        try {
            URI reqUri = new URI(requestUri);
            String reqUriHash = reqUri.getFragment();
            String reqUriWithoutFragment = reqUri.getScheme() + ":" + reqUri.getSchemeSpecificPart();
            javax.ws.rs.client.Client clientRequest = ClientBuilder.newClient();
            try {
                Response clientResponse = clientRequest.target(reqUriWithoutFragment).request().buildGet().invoke();
                clientRequest.close();
                int status = clientResponse.getStatus();
                if (status == 200) {
                    String entity = clientResponse.readEntity(String.class);
                    if (StringUtils.isBlank(reqUriHash)) {
                        requestJwt = entity;
                    } else {
                        String hash = Base64Util.base64urlencode(JwtUtil.getMessageDigestSHA256(entity));
                        if (StringUtils.equals(reqUriHash, hash)) {
                            requestJwt = entity;
                        }
                    }
                }
            } finally {
                clientRequest.close();
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
    if (StringUtils.isNotBlank(requestJwt)) {
        try {
            Client client = clientService.getClient(clientId);
            if (client != null) {
                JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(appConfiguration, cryptoProvider, request, client);
                if (jwtAuthorizationRequest.getUserInfoMember() != null) {
                    for (Claim claim : jwtAuthorizationRequest.getUserInfoMember().getClaims()) {
                        result.add(claim.getName());
                    }
                }
                if (jwtAuthorizationRequest.getIdTokenMember() != null) {
                    for (Claim claim : jwtAuthorizationRequest.getIdTokenMember().getClaims()) {
                        result.add(claim.getName());
                    }
                }
            }
        } catch (EntryPersistenceException | InvalidJwtException e) {
            log.error(e.getMessage(), e);
        }
    }
    return new ArrayList<>(result);
}
Also used : InvalidJwtException(org.gluu.oxauth.model.exception.InvalidJwtException) ArrayList(java.util.ArrayList) EntryPersistenceException(org.gluu.persist.exception.EntryPersistenceException) URI(java.net.URI) EntryPersistenceException(org.gluu.persist.exception.EntryPersistenceException) WebApplicationException(javax.ws.rs.WebApplicationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) AcrChangedException(org.gluu.oxauth.model.exception.AcrChangedException) InvalidJwtException(org.gluu.oxauth.model.exception.InvalidJwtException) IOException(java.io.IOException) Response(javax.ws.rs.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) JwtAuthorizationRequest(org.gluu.oxauth.model.authorize.JwtAuthorizationRequest) Client(org.gluu.oxauth.model.registration.Client) Claim(org.gluu.oxauth.model.authorize.Claim) HashSet(java.util.HashSet)

Example 35 with Client

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

the class CorsFilter method doFilterImpl.

protected Collection<String> doFilterImpl(ServletRequest servletRequest) throws UnsupportedEncodingException, IOException, ServletException {
    Collection<String> globalAllowedOrigins = getAllowedOrigins();
    if (StringHelper.isNotEmpty(servletRequest.getParameter("client_id"))) {
        String clientId = servletRequest.getParameter("client_id");
        Client client = clientService.getClient(clientId);
        if (client != null) {
            String[] authorizedOriginsArray = client.getAuthorizedOrigins();
            if (authorizedOriginsArray != null && authorizedOriginsArray.length > 0) {
                List<String> clientAuthorizedOrigins = Arrays.asList(authorizedOriginsArray);
                setAllowedOrigins(clientAuthorizedOrigins);
            }
        }
    } else {
        final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        String header = httpRequest.getHeader("Authorization");
        if (httpRequest.getRequestURI().endsWith("/token")) {
            if (header != null && header.startsWith("Basic ")) {
                String base64Token = header.substring(6);
                String token = new String(Base64.decodeBase64(base64Token), Util.UTF8_STRING_ENCODING);
                String username = "";
                int delim = token.indexOf(":");
                if (delim != -1) {
                    username = URLDecoder.decode(token.substring(0, delim), Util.UTF8_STRING_ENCODING);
                }
                Client client = clientService.getClient(username);
                if (client != null) {
                    String[] authorizedOriginsArray = client.getAuthorizedOrigins();
                    if (authorizedOriginsArray != null && authorizedOriginsArray.length > 0) {
                        List<String> clientAuthorizedOrigins = Arrays.asList(authorizedOriginsArray);
                        setAllowedOrigins(clientAuthorizedOrigins);
                    }
                }
            }
        }
    }
    return globalAllowedOrigins;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Client(org.gluu.oxauth.model.registration.Client)

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