Package org.keycloak.representations

Examples of org.keycloak.representations.AccessToken


    }



    protected AccessToken initToken(RealmModel realm, ClientModel client, UserModel user, UserSessionModel session) {
        AccessToken token = new AccessToken();
        token.id(KeycloakModelUtils.generateId());
        token.subject(user.getId());
        token.audience(client.getClientId());
        token.issuedNow();
        token.issuedFor(client.getClientId());
        token.issuer(realm.getName());
        if (session != null) {
            token.setSessionState(session.getId());
        }
        if (realm.getAccessTokenLifespan() > 0) {
            token.expiration(Time.currentTime() + realm.getAccessTokenLifespan());
        }
        Set<String> allowedOrigins = client.getWebOrigins();
        if (allowedOrigins != null) {
            token.setAllowedOrigins(allowedOrigins);
        }
        initClaims(token, client, user);
        return token;
    }
View Full Code Here


        }
    }

    public static Set<String> getRolesFromSecurityContext(RefreshableKeycloakSecurityContext session) {
        Set<String> roles = null;
        AccessToken accessToken = session.getToken();
        if (session.getDeployment().isUseResourceRoleMappings()) {
            if (log.isTraceEnabled()) {
                log.trace("useResourceRoleMappings");
            }
            AccessToken.Access access = accessToken.getResourceAccess(session.getDeployment().getResourceName());
            if (access != null) roles = access.getRoles();
        } else {
            if (log.isTraceEnabled()) {
                log.trace("use realm role mappings");
            }
            AccessToken.Access access = accessToken.getRealmAccess();
            if (access != null) roles = access.getRoles();
        }
        if (roles == null) roles = Collections.emptySet();
        if (log.isTraceEnabled()) {
            log.trace("Setting roles: ");
View Full Code Here

        if (!deployment.isCors()) return false;
        KeycloakSecurityContext securityContext = facade.getSecurityContext();
        String origin = facade.getRequest().getHeader(CorsHeaders.ORIGIN);
        log.debugv("Origin: {0} uri: {1}", origin, facade.getRequest().getURI());
        if (securityContext != null && origin != null) {
            AccessToken token = securityContext.getToken();
            Set<String> allowedOrigins = token.getAllowedOrigins();
            if (log.isDebugEnabled()) {
                for (String a : allowedOrigins) log.debug("   " + a);
            }
            if (allowedOrigins == null || (!allowedOrigins.contains("*") && !allowedOrigins.contains(origin))) {
                if (allowedOrigins == null) {
View Full Code Here

        String idTokenString = tokens[1];
        String refreshTokenString = tokens[2];

        try {
            // Skip check if token is active now. It's supposed to be done later by the caller
            AccessToken accessToken = RSATokenVerifier.verifyToken(accessTokenString, deployment.getRealmKey(), deployment.getRealm(), false);
            IDToken idToken;
            if (idTokenString != null && idTokenString.length() > 0) {
                JWSInput input = new JWSInput(idTokenString);
                try {
                    idToken = input.readJsonContent(IDToken.class);
View Full Code Here

        }
        if (log.isTraceEnabled()) {
            log.trace("received refresh response");
        }
        String tokenString = response.getToken();
        AccessToken token = null;
        try {
            token = RSATokenVerifier.verifyToken(tokenString, deployment.getRealmKey(), deployment.getRealm());
            log.debug("Token Verification succeeded!");
        } catch (VerificationException e) {
            log.error("failed verification of token");
View Full Code Here

    public Response validateAccessToken(@QueryParam("access_token") String tokenString) {
        if (!checkSsl()) {
            return createError("https_required", "HTTPS required", Response.Status.FORBIDDEN);
        }
        event.event(EventType.VALIDATE_ACCESS_TOKEN);
        AccessToken token = null;
        try {
            token = RSATokenVerifier.verifyToken(tokenString, realm.getPublicKey(), realm.getName());
        } catch (Exception e) {
            Map<String, String> err = new HashMap<String, String>();
            err.put(OAuth2Constants.ERROR, OAuthErrorException.INVALID_GRANT);
            err.put(OAuth2Constants.ERROR_DESCRIPTION, "Token invalid");
            event.error(Errors.INVALID_TOKEN);
            return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(err)
                    .build();
        }
        event.user(token.getSubject()).session(token.getSessionState()).detail(Details.VALIDATE_ACCESS_TOKEN, token.getId());

        if (token.isExpired()
                || token.getIssuedAt() < realm.getNotBefore()
                ) {
            Map<String, String> err = new HashMap<String, String>();
            err.put(OAuth2Constants.ERROR, OAuthErrorException.INVALID_GRANT);
            err.put(OAuth2Constants.ERROR_DESCRIPTION, "Token expired");
            event.error(Errors.INVALID_TOKEN);
            return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(err)
                    .build();
        }


        UserModel user = session.users().getUserById(token.getSubject(), realm);
        if (user == null) {
            Map<String, String> err = new HashMap<String, String>();
            err.put(OAuth2Constants.ERROR, OAuthErrorException.INVALID_GRANT);
            err.put(OAuth2Constants.ERROR_DESCRIPTION, "User does not exist");
            event.error(Errors.USER_NOT_FOUND);
            return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(err)
                    .build();
        }

        if (!user.isEnabled()) {
            Map<String, String> err = new HashMap<String, String>();
            err.put(OAuth2Constants.ERROR, OAuthErrorException.INVALID_GRANT);
            err.put(OAuth2Constants.ERROR_DESCRIPTION, "User disabled");
            event.error(Errors.USER_DISABLED);
            return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(err)
                    .build();
        }

        UserSessionModel userSession = session.sessions().getUserSession(realm, token.getSessionState());
        if (!AuthenticationManager.isSessionValid(realm, userSession)) {
            Map<String, String> err = new HashMap<String, String>();
            err.put(OAuth2Constants.ERROR, OAuthErrorException.INVALID_GRANT);
            err.put(OAuth2Constants.ERROR_DESCRIPTION, "Expired session");
            event.error(Errors.USER_SESSION_NOT_FOUND);
            return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(err)
                    .build();
        }

        ClientModel client = realm.findClient(token.getIssuedFor());
        if (client == null) {
            Map<String, String> err = new HashMap<String, String>();
            err.put(OAuth2Constants.ERROR, OAuthErrorException.INVALID_CLIENT);
            err.put(OAuth2Constants.ERROR_DESCRIPTION, "Issued for client no longer exists");
            event.error(Errors.CLIENT_NOT_FOUND);
            return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(err)
                    .build();

        }

        if (token.getIssuedAt() < client.getNotBefore()) {
            Map<String, String> err = new HashMap<String, String>();
            err.put(OAuth2Constants.ERROR, OAuthErrorException.INVALID_CLIENT);
            err.put(OAuth2Constants.ERROR_DESCRIPTION, "Issued for client no longer exists");
            event.error(Errors.INVALID_TOKEN);
            return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(err)
View Full Code Here

            error.put(OAuth2Constants.ERROR, OAuthErrorException.INVALID_REQUEST);
            error.put(OAuth2Constants.ERROR_DESCRIPTION, "No refresh token");
            event.error(Errors.INVALID_TOKEN);
            return Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build();
        }
        AccessToken accessToken;
        try {
            accessToken = tokenManager.refreshAccessToken(session, uriInfo, clientConnection, realm, client, refreshToken, event);
        } catch (OAuthErrorException e) {
            Map<String, String> error = new HashMap<String, String>();
            error.put(OAuth2Constants.ERROR, e.getError());
View Full Code Here

            clientSession.setNote(AdapterConstants.APPLICATION_SESSION_STATE, adapterSessionId);
            event.detail(AdapterConstants.APPLICATION_SESSION_HOST, adapterSessionHost);
            clientSession.setNote(AdapterConstants.APPLICATION_SESSION_HOST, adapterSessionHost);
        }

        AccessToken token = tokenManager.createClientAccessToken(accessCode.getRequestedRoles(), realm, client, user, userSession);

        try {
            tokenManager.verifyAccess(token, realm, client, user);
        } catch (OAuthErrorException e) {
            Map<String, String> error = new HashMap<String, String>();
View Full Code Here

    protected AdminAuth authenticateRealmAdminRequest(HttpHeaders headers) {
        String tokenString = authManager.extractAuthorizationHeaderToken(headers);
        if (tokenString == null) throw new UnauthorizedException("Bearer");
        JWSInput input = new JWSInput(tokenString);
        AccessToken token;
        try {
            token = input.readJsonContent(AccessToken.class);
        } catch (IOException e) {
            throw new UnauthorizedException("Bearer token format error");
        }
        String realmName = token.getIssuer();
        RealmManager realmManager = new RealmManager(session);
        RealmModel realm = realmManager.getRealmByName(realmName);
        if (realm == null) {
            throw new UnauthorizedException("Unknown realm in token");
        }
        AuthenticationManager.AuthResult authResult = authManager.authenticateBearerToken(session, realm, uriInfo, clientConnection, headers);
        if (authResult == null) {
            logger.debug("Token not valid");
            throw new UnauthorizedException("Bearer");
        }

        ClientModel client = realm.findClient(token.getIssuedFor());
        if (client == null) {
            throw new NotFoundException("Could not find client for authorization");

        }
View Full Code Here

        session.sessions().removeUserSession(realm, userSession);
    }


    public static AccessToken createIdentityToken(RealmModel realm, UserModel user, UserSessionModel session) {
        AccessToken token = new AccessToken();
        token.id(KeycloakModelUtils.generateId());
        token.issuedNow();
        token.subject(user.getId());
        token.issuer(realm.getName());
        if (session != null) {
            token.setSessionState(session.getId());
        }
        if (realm.getSsoSessionMaxLifespan() > 0) {
            token.expiration(Time.currentTime() + realm.getSsoSessionMaxLifespan());
        }
        return token;
    }
View Full Code Here

TOP

Related Classes of org.keycloak.representations.AccessToken

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.