Java Code Examples for org.keycloak.services.managers.AuthenticationManager#AuthResult

The following examples show how to use org.keycloak.services.managers.AuthenticationManager#AuthResult . 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: LogoutEndpoint.java    From keycloak-protocol-cas with Apache License 2.0 6 votes vote down vote up
@GET
@NoCache
public Response logout(@QueryParam(CASLoginProtocol.SERVICE_PARAM) String service) {
    checkClient(service);

    AuthenticationManager.AuthResult authResult = AuthenticationManager.authenticateIdentityCookie(session, realm, false);
    if (authResult != null) {
        UserSessionModel userSession = authResult.getSession();
        userSession.setNote(AuthenticationManager.KEYCLOAK_LOGOUT_PROTOCOL, CASLoginProtocol.LOGIN_PROTOCOL);
        if (redirectUri != null) userSession.setNote(CASLoginProtocol.LOGOUT_REDIRECT_URI, redirectUri);

        logger.debug("Initiating CAS browser logout");
        Response response =  AuthenticationManager.browserLogout(session, realm, authResult.getSession(), session.getContext().getUri(), clientConnection, headers, null);
        logger.debug("finishing CAS browser logout");
        return response;
    }
    return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.FAILED_LOGOUT);
}
 
Example 2
Source File: CookieAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    AuthenticationManager.AuthResult authResult = AuthenticationManager.authenticateIdentityCookie(context.getSession(),
            context.getRealm(), true);
    if (authResult == null) {
        context.attempted();
    } else {
        AuthenticationSessionModel clientSession = context.getAuthenticationSession();
        LoginProtocol protocol = context.getSession().getProvider(LoginProtocol.class, clientSession.getProtocol());

        // Cookie re-authentication is skipped if re-authentication is required
        if (protocol.requireReauthentication(authResult.getSession(), clientSession)) {
            context.attempted();
        } else {
            context.getSession().setAttribute(AuthenticationManager.SSO_AUTH, "true");

            context.setUser(authResult.getUser());
            context.attachUserSession(authResult.getSession());
            context.success();
        }
    }

}
 
Example 3
Source File: ExportResourceProvider.java    From keycloak-export with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * This code has been copied from keycloak org.keycloak.services.resources.admin.AdminRoot;
 * it allows to check if a user as realm/master admin
 * at each upgrade check that it hasn't been modified
 */
private AdminAuth authenticateRealmAdminRequest(HttpHeaders headers, UriInfo uriInfo) {
    String tokenString = authManager.extractAuthorizationHeaderToken(headers);
    if (tokenString == null) throw new NotAuthorizedException("Bearer");
    AccessToken token;
    try {
        JWSInput input = new JWSInput(tokenString);
        token = input.readJsonContent(AccessToken.class);
    } catch (JWSInputException e) {
        throw new NotAuthorizedException("Bearer token format error", e);
    }
    String realmName = token.getIssuer().substring(token.getIssuer().lastIndexOf('/') + 1);
    RealmManager realmManager = new RealmManager(session);
    RealmModel realm = realmManager.getRealmByName(realmName);
    if (realm == null) {
        throw new NotAuthorizedException("Unknown realm in token");
    }
    session.getContext().setRealm(realm);
    AuthenticationManager.AuthResult authResult = authManager.authenticateBearerToken(session, realm, uriInfo, clientConnection, headers);
    if (authResult == null) {
        logger.debug("Token not valid");
        throw new NotAuthorizedException("Bearer");
    }

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

    }

    return new AdminAuth(realm, authResult.getToken(), authResult.getUser(), client);
}
 
Example 4
Source File: AdminRoot.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected AdminAuth authenticateRealmAdminRequest(HttpHeaders headers) {
    String tokenString = authManager.extractAuthorizationHeaderToken(headers);
    if (tokenString == null) throw new NotAuthorizedException("Bearer");
    AccessToken token;
    try {
        JWSInput input = new JWSInput(tokenString);
        token = input.readJsonContent(AccessToken.class);
    } catch (JWSInputException e) {
        throw new NotAuthorizedException("Bearer token format error");
    }
    String realmName = token.getIssuer().substring(token.getIssuer().lastIndexOf('/') + 1);
    RealmManager realmManager = new RealmManager(session);
    RealmModel realm = realmManager.getRealmByName(realmName);
    if (realm == null) {
        throw new NotAuthorizedException("Unknown realm in token");
    }
    session.getContext().setRealm(realm);
    AuthenticationManager.AuthResult authResult = authManager.authenticateBearerToken(session, realm, session.getContext().getUri(), clientConnection, headers);
    if (authResult == null) {
        logger.debug("Token not valid");
        throw new NotAuthorizedException("Bearer");
    }

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

    }

    return new AdminAuth(realm, authResult.getToken(), authResult.getUser(), client);
}
 
Example 5
Source File: AdminConsole.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Permission information
 *
 * @param headers
 * @return
 */
@Path("whoami")
@GET
@Produces(MediaType.APPLICATION_JSON)
@NoCache
public Response whoAmI(final @Context HttpHeaders headers) {
    RealmManager realmManager = new RealmManager(session);
    AuthenticationManager.AuthResult authResult = authManager.authenticateBearerToken(session, realm, session.getContext().getUri(), clientConnection, headers);
    if (authResult == null) {
        return Response.status(401).build();
    }
    UserModel user= authResult.getUser();
    String displayName;
    if ((user.getFirstName() != null && !user.getFirstName().trim().equals("")) || (user.getLastName() != null && !user.getLastName().trim().equals(""))) {
        displayName = user.getFirstName();
        if (user.getLastName() != null) {
            displayName = displayName != null ? displayName + " " + user.getLastName() : user.getLastName();
        }
    } else {
        displayName = user.getUsername();
    }

    RealmModel masterRealm = getAdminstrationRealm(realmManager);
    Map<String, Set<String>> realmAccess = new HashMap<String, Set<String>>();
    if (masterRealm == null)
        throw new NotFoundException("No realm found");
    boolean createRealm = false;
    if (realm.equals(masterRealm)) {
        logger.debug("setting up realm access for a master realm user");
        createRealm = user.hasRole(masterRealm.getRole(AdminRoles.CREATE_REALM));
        addMasterRealmAccess(realm, user, realmAccess);
    } else {
        logger.debug("setting up realm access for a realm user");
        addRealmAccess(realm, user, realmAccess);
    }

    Locale locale = session.getContext().resolveLocale(user);

    return Response.ok(new WhoAmI(user.getId(), realm.getName(), displayName, createRealm, realmAccess, locale)).build();
}
 
Example 6
Source File: LogoutEndpoint.java    From keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * Logout user session.  User must be logged in via a session cookie.
 *
 * When the logout is initiated by a remote idp, the parameter "initiating_idp" can be supplied. This param will
 * prevent upstream logout (since the logout procedure has already been started in the remote idp).
 *
 * @param redirectUri
 * @param initiatingIdp The alias of the idp initiating the logout.
 * @return
 */
@GET
@NoCache
public Response logout(@QueryParam(OIDCLoginProtocol.REDIRECT_URI_PARAM) String redirectUri, // deprecated
                       @QueryParam("id_token_hint") String encodedIdToken,
                       @QueryParam("post_logout_redirect_uri") String postLogoutRedirectUri,
                       @QueryParam("state") String state,
                       @QueryParam("initiating_idp") String initiatingIdp) {
    String redirect = postLogoutRedirectUri != null ? postLogoutRedirectUri : redirectUri;

    if (redirect != null) {
        String validatedUri = RedirectUtils.verifyRealmRedirectUri(session, redirect);
        if (validatedUri == null) {
            event.event(EventType.LOGOUT);
            event.detail(Details.REDIRECT_URI, redirect);
            event.error(Errors.INVALID_REDIRECT_URI);
            return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REDIRECT_URI);
        }
        redirect = validatedUri;
    }

    UserSessionModel userSession = null;
    IDToken idToken = null;
    if (encodedIdToken != null) {
        try {
            idToken = tokenManager.verifyIDTokenSignature(session, encodedIdToken);
            TokenVerifier.createWithoutSignature(idToken).tokenType(TokenUtil.TOKEN_TYPE_ID).verify();
            userSession = session.sessions().getUserSession(realm, idToken.getSessionState());

            if (userSession != null) {
                checkTokenIssuedAt(idToken, userSession);
            }
        } catch (OAuthErrorException | VerificationException e) {
            event.event(EventType.LOGOUT);
            event.error(Errors.INVALID_TOKEN);
            return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.SESSION_NOT_ACTIVE);
        }
    }

    // authenticate identity cookie, but ignore an access token timeout as we're logging out anyways.
    AuthenticationManager.AuthResult authResult = AuthenticationManager.authenticateIdentityCookie(session, realm, false);
    if (authResult != null) {
        userSession = userSession != null ? userSession : authResult.getSession();
        return initiateBrowserLogout(userSession, redirect, state, initiatingIdp);
    }
    else if (userSession != null) {
        // identity cookie is missing but there's valid id_token_hint which matches session cookie => continue with browser logout
        if (idToken != null && idToken.getSessionState().equals(AuthenticationManager.getSessionIdFromSessionCookie(session))) {
            return initiateBrowserLogout(userSession, redirect, state, initiatingIdp);
        }
        // non browser logout
        event.event(EventType.LOGOUT);
        AuthenticationManager.backchannelLogout(session, realm, userSession, session.getContext().getUri(), clientConnection, headers, true);
        event.user(userSession.getUser()).session(userSession).success();
    }

    if (redirect != null) {
        UriBuilder uriBuilder = UriBuilder.fromUri(redirect);
        if (state != null) uriBuilder.queryParam(OIDCLoginProtocol.STATE_PARAM, state);
        return Response.status(302).location(uriBuilder.build()).build();
    } else {
        // TODO Empty content with ok makes no sense. Should it display a page? Or use noContent?
        session.getProvider(SecurityHeadersProvider.class).options().allowEmptyContentType();
        return Response.ok().build();
    }
}
 
Example 7
Source File: SamlService.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected Response handleSamlResponse(String samlResponse, String relayState) {
    event.event(EventType.LOGOUT);
    SAMLDocumentHolder holder = extractResponseDocument(samlResponse);

    if (! (holder.getSamlObject() instanceof StatusResponseType)) {
        event.detail(Details.REASON, "invalid_saml_response");
        event.error(Errors.INVALID_SAML_RESPONSE);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
    }

    StatusResponseType statusResponse = (StatusResponseType) holder.getSamlObject();
    // validate destination
    if (statusResponse.getDestination() == null && containsUnencryptedSignature(holder)) {
        event.detail(Details.REASON, "missing_required_destination");
        event.error(Errors.INVALID_SAML_LOGOUT_RESPONSE);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
    }
    if (! destinationValidator.validate(this.getExpectedDestinationUri(session), statusResponse.getDestination())) {
        event.detail(Details.REASON, "invalid_destination");
        event.error(Errors.INVALID_SAML_LOGOUT_RESPONSE);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
    }

    AuthenticationManager.AuthResult authResult = authManager.authenticateIdentityCookie(session, realm, false);
    if (authResult == null) {
        logger.warn("Unknown saml response.");
        event.event(EventType.LOGOUT);
        event.error(Errors.INVALID_TOKEN);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
    }
    // assume this is a logout response
    UserSessionModel userSession = authResult.getSession();
    if (userSession.getState() != UserSessionModel.State.LOGGING_OUT) {
        logger.warn("Unknown saml response.");
        logger.warn("UserSession is not tagged as logging out.");
        event.event(EventType.LOGOUT);
        event.error(Errors.INVALID_SAML_LOGOUT_RESPONSE);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
    }
    String issuer = statusResponse.getIssuer().getValue();
    ClientModel client = realm.getClientByClientId(issuer);
    if (client == null) {
        event.event(EventType.LOGOUT);
        event.client(issuer);
        event.error(Errors.CLIENT_NOT_FOUND);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.CLIENT_NOT_FOUND);
    }

    if (!isClientProtocolCorrect(client)) {
        event.event(EventType.LOGOUT);
        event.error(Errors.INVALID_CLIENT);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, "Wrong client protocol.");
    }

    session.getContext().setClient(client);
    logger.debug("logout response");
    Response response = authManager.browserLogout(session, realm, userSession, session.getContext().getUri(), clientConnection, headers, null);
    event.success();
    return response;
}
 
Example 8
Source File: AccountConsole.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public void init() {
    AuthenticationManager.AuthResult authResult = authManager.authenticateIdentityCookie(session, realm);
    if (authResult != null) {
        auth = new Auth(realm, authResult.getToken(), authResult.getUser(), client, authResult.getSession(), true);
    }
}
 
Example 9
Source File: AccountFormService.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public void init() {
    eventStore = session.getProvider(EventStoreProvider.class);

    account = session.getProvider(AccountProvider.class).setRealm(realm).setUriInfo(session.getContext().getUri()).setHttpHeaders(headers);

    AuthenticationManager.AuthResult authResult = authManager.authenticateIdentityCookie(session, realm);
    if (authResult != null) {
        stateChecker = (String) session.getAttribute("state_checker");
        auth = new Auth(realm, authResult.getToken(), authResult.getUser(), client, authResult.getSession(), true);
        account.setStateChecker(stateChecker);
    }

    String requestOrigin = UriUtils.getOrigin(session.getContext().getUri().getBaseUri());

    String origin = headers.getRequestHeaders().getFirst("Origin");
    if (origin != null && !requestOrigin.equals(origin)) {
        throw new ForbiddenException();
    }

    if (!request.getHttpMethod().equals("GET")) {
        String referrer = headers.getRequestHeaders().getFirst("Referer");
        if (referrer != null && !requestOrigin.equals(UriUtils.getOrigin(referrer))) {
            throw new ForbiddenException();
        }
    }

    if (authResult != null) {
        UserSessionModel userSession = authResult.getSession();
        if (userSession != null) {
            AuthenticatedClientSessionModel clientSession = userSession.getAuthenticatedClientSessionByClient(client.getId());
            if (clientSession == null) {
                clientSession = session.sessions().createClientSession(userSession.getRealm(), client, userSession);
            }
            auth.setClientSession(clientSession);
        }

        account.setUser(auth.getUser());
    }

    account.setFeatures(realm.isIdentityFederationEnabled(), eventStore != null && realm.isEventsEnabled(), true, true);
}
 
Example 10
Source File: AccountLoader.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public Object getAccountService(KeycloakSession session, EventBuilder event) {
    RealmModel realm = session.getContext().getRealm();

    ClientModel client = realm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);
    if (client == null || !client.isEnabled()) {
        logger.debug("account management not enabled");
        throw new NotFoundException("account management not enabled");
    }

    HttpRequest request = session.getContext().getContextObject(HttpRequest.class);
    HttpHeaders headers = session.getContext().getRequestHeaders();
    MediaType content = headers.getMediaType();
    List<MediaType> accepts = headers.getAcceptableMediaTypes();

    Theme theme = getTheme(session);
    boolean deprecatedAccount = isDeprecatedFormsAccountConsole(theme);
    UriInfo uriInfo = session.getContext().getUri();

    if (request.getHttpMethod().equals(HttpMethod.OPTIONS)) {
        return new CorsPreflightService(request);
    } else if ((accepts.contains(MediaType.APPLICATION_JSON_TYPE) || MediaType.APPLICATION_JSON_TYPE.equals(content)) && !uriInfo.getPath().endsWith("keycloak.json")) {
        AuthenticationManager.AuthResult authResult = new AppAuthManager().authenticateBearerToken(session);
        if (authResult == null) {
            throw new NotAuthorizedException("Bearer token required");
        }

        if (authResult.getUser().getServiceAccountClientLink() != null) {
            throw new NotAuthorizedException("Service accounts are not allowed to access this service");
        }

        Auth auth = new Auth(session.getContext().getRealm(), authResult.getToken(), authResult.getUser(), client, authResult.getSession(), false);
        AccountRestService accountRestService = new AccountRestService(session, auth, client, event);
        ResteasyProviderFactory.getInstance().injectProperties(accountRestService);
        accountRestService.init();
        return accountRestService;
    } else {
        if (deprecatedAccount) {
            AccountFormService accountFormService = new AccountFormService(realm, client, event);
            ResteasyProviderFactory.getInstance().injectProperties(accountFormService);
            accountFormService.init();
            return accountFormService;
        } else {
            AccountConsole console = new AccountConsole(realm, client, theme);
            ResteasyProviderFactory.getInstance().injectProperties(console);
            console.init();
            return console;
        }
    }
}