org.keycloak.authentication.AuthenticationFlowContext Java Examples

The following examples show how to use org.keycloak.authentication.AuthenticationFlowContext. 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: DynamicIdpRedirectAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 6 votes vote down vote up
protected void redirect(AuthenticationFlowContext context, String providerId) {

        IdentityProviderModel identityProviderModel = selectIdp(context, providerId);
        if (identityProviderModel == null || !identityProviderModel.isEnabled()) {
            log.warnf("Provider not found or not enabled for realm %s", providerId);
            context.attempted();
            return;
        }

        String accessCode = new ClientSessionCode<>(context.getSession(), context.getRealm(), context.getAuthenticationSession()).getOrGenerateCode();
        String clientId = context.getAuthenticationSession().getClient().getClientId();
        String tabId = context.getAuthenticationSession().getTabId();
        URI location = Urls.identityProviderAuthnRequest(context.getUriInfo().getBaseUri(), providerId, context.getRealm().getName(), accessCode, clientId, tabId);
        if (context.getAuthenticationSession().getClientNote(OAuth2Constants.DISPLAY) != null) {
            location = UriBuilder.fromUri(location).queryParam(OAuth2Constants.DISPLAY, context.getAuthenticationSession().getClientNote(OAuth2Constants.DISPLAY)).build();
        }
        log.debugf("Redirecting to %s", providerId);
        Response response = Response.seeOther(location).build();
        context.forceChallenge(response);
    }
 
Example #2
Source File: NoCookieFlowRedirectAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    HttpRequest httpRequest = context.getHttpRequest();

    // only do redirects for GET requests
    if (HttpMethod.GET.equalsIgnoreCase(httpRequest.getHttpMethod())) {
        KeycloakUriInfo uriInfo = context.getSession().getContext().getUri();
        if (!uriInfo.getQueryParameters().containsKey(LoginActionsService.AUTH_SESSION_ID)) {
            Response response = Response.status(302).header(HttpHeaders.LOCATION, context.getRefreshUrl(true)).build();
            context.challenge(response);
            return;
        }
    }

    context.success();
}
 
Example #3
Source File: AbstractIdpAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void action(AuthenticationFlowContext context) {
    AuthenticationSessionModel clientSession = context.getAuthenticationSession();

    SerializedBrokeredIdentityContext serializedCtx = SerializedBrokeredIdentityContext.readFromAuthenticationSession(clientSession, BROKERED_CONTEXT_NOTE);
    if (serializedCtx == null) {
        throw new AuthenticationFlowException("Not found serialized context in clientSession", AuthenticationFlowError.IDENTITY_PROVIDER_ERROR);
    }
    BrokeredIdentityContext brokerContext = serializedCtx.deserialize(context.getSession(), clientSession);

    if (!brokerContext.getIdpConfig().isEnabled()) {
        sendFailureChallenge(context, Response.Status.BAD_REQUEST, Errors.IDENTITY_PROVIDER_ERROR, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR, AuthenticationFlowError.IDENTITY_PROVIDER_ERROR);
    }

    actionImpl(context, serializedCtx, brokerContext);
}
 
Example #4
Source File: ScriptBasedAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void tryInvoke(String functionName, AuthenticationFlowContext context) {

        if (!hasAuthenticatorConfig(context)) {
            // this is an empty not yet configured script authenticator
            // we mark this execution as success to not lock out users due to incompletely configured authenticators.
            context.success();
            return;
        }

        InvocableScriptAdapter invocableScriptAdapter = getInvocableScriptAdapter(context);

        if (!invocableScriptAdapter.isDefined(functionName)) {
            return;
        }

        try {
            //should context be wrapped in a read-only wrapper?
            invocableScriptAdapter.invokeFunction(functionName, context);
        } catch (ScriptExecutionException e) {
            LOGGER.error(e);
            context.failure(AuthenticationFlowError.INTERNAL_ERROR);
        }
    }
 
Example #5
Source File: ConditionalOtpFormAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private boolean tryConcludeBasedOn(OtpDecision state, AuthenticationFlowContext context) {

        switch (state) {

            case SHOW_OTP:
                showOtpForm(context);
                return true;

            case SKIP_OTP:
                context.success();
                return true;

            default:
                return false;
        }
    }
 
Example #6
Source File: DynamicIdpRedirectAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 6 votes vote down vote up
protected String determineTargetIdpViaUserEmail(UserModel user, AuthenticationFlowContext context) {

        String email = user.getEmail();
        if (email == null) {
            return null;
        }

        String mappingString = getConfigValueOrDefault(context.getAuthenticatorConfig(), EMAIL_TO_IDP_MAPPING_CONFIG_PROPERTY, "", String::valueOf);
        String[] mappings = mappingString.split(";");
        for (String mapping : mappings) {
            String[] emailSuffixPatternToIdpId = mapping.split("/");
            String emailSuffixPattern = emailSuffixPatternToIdpId[0];
            String idpId = emailSuffixPatternToIdpId[1];

            if (email.matches(emailSuffixPattern)) {
                return idpId;
            }
        }

        return null;
    }
 
Example #7
Source File: AbstractUsernameFormAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void dummyHash(AuthenticationFlowContext context) {
    PasswordPolicy policy = context.getRealm().getPasswordPolicy();
    if (policy == null) {
        runDefaultDummyHash(context);
        return;
    } else {
        PasswordHashProvider hash = context.getSession().getProvider(PasswordHashProvider.class, policy.getHashAlgorithm());
        if (hash == null) {
            runDefaultDummyHash(context);
            return;

        } else {
            hash.encode("dummypassword", policy.getHashIterations());
        }
    }

}
 
Example #8
Source File: ConditionalOnScopePresentAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 6 votes vote down vote up
@Override
public boolean matchCondition(AuthenticationFlowContext context) {

    AuthenticatorConfigModel authConfig = context.getAuthenticatorConfig();
    if (authConfig == null) {
        return false;
    }

    Map<String, String> config = authConfig.getConfig();
    String requiredScopeName = config != null ? config.get(CLIENT_SCOPE_NAME) : null;

    ClientModel client = context.getSession().getContext().getClient();
    Map<String, ClientScopeModel> clientScopes = client.getClientScopes(true, true);

    return clientScopes != null && clientScopes.containsKey(requiredScopeName);
}
 
Example #9
Source File: ConditionalRoleAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean matchCondition(AuthenticationFlowContext context) {
    UserModel user = context.getUser();
    RealmModel realm = context.getRealm();
    AuthenticatorConfigModel authConfig = context.getAuthenticatorConfig();
    if (user != null && authConfig!=null && authConfig.getConfig()!=null) {
        String requiredRole = authConfig.getConfig().get(ConditionalRoleAuthenticatorFactory.CONDITIONAL_USER_ROLE);
        RoleModel role = KeycloakModelUtils.getRoleFromString(realm, requiredRole);
        if (role == null) {
            logger.errorv("Invalid role name submitted: {0}", requiredRole);
            return false;
        }
        return user.hasRole(role);
    }
    return false;
}
 
Example #10
Source File: DynamicIdpRedirectAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 6 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {

    UserModel user = context.getUser();
    if (user == null) {
        context.attempted();
        return;
    }

    String targetIdp = determineTargetIdp(user, context);
    if (targetIdp != null) {
        redirect(context, targetIdp);
        return;
    }

    boolean fallbackToAuthFlow = getConfigValueOrDefault(context.getAuthenticatorConfig(), FALLBACK_TO_AUTHFLOW_CONFIG_PROPERTY, "true", Boolean::parseBoolean);
    if (fallbackToAuthFlow) {
        context.attempted();
        return;
    }

    context.getEvent().error(Errors.UNKNOWN_IDENTITY_PROVIDER);
    context.failure(AuthenticationFlowError.IDENTITY_PROVIDER_NOT_FOUND);
    context.cancelLogin();
    context.resetFlow();
}
 
Example #11
Source File: LoginFormsUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static List<IdentityProviderModel> filterIdentityProviders(List<IdentityProviderModel> providers, KeycloakSession session, RealmModel realm,
                                                                  Map<String, Object> attributes, MultivaluedMap<String, String> formData, AuthenticationFlowContext context) {

    if (context != null) {
        AuthenticationSessionModel authSession = context.getAuthenticationSession();
        SerializedBrokeredIdentityContext serializedCtx = SerializedBrokeredIdentityContext.readFromAuthenticationSession(authSession, AbstractIdpAuthenticator.BROKERED_CONTEXT_NOTE);

        if (serializedCtx != null) {
            IdentityProviderModel idp = serializedCtx.deserialize(session, authSession).getIdpConfig();
            return providers.stream()
                    .filter(p -> !Objects.equals(p.getAlias(), idp.getAlias()))
                    .collect(Collectors.toList());
        }
    }
    return providers;
}
 
Example #12
Source File: SimpleAuthenticatorForm.java    From keycloak-extension-playground with Apache License 2.0 6 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {

    // Note that you can use the `session` to access Keycloaks services.

    Random random = new Random();

    int x = random.nextInt(5);
    int y = random.nextInt(5);

    context.getAuthenticationSession().setAuthNote(EXPECTED_SUM, "" + (x + y));

    Response response = context.form()
            .setAttribute("username", context.getUser().getUsername())
            .setAttribute("x", x)
            .setAttribute("y", y)
            .createForm("simple-form.ftl");

    context.challenge(response);
}
 
Example #13
Source File: IdpUsernamePasswordForm.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected LoginFormsProvider setupForm(AuthenticationFlowContext context, MultivaluedMap<String, String> formData, Optional<UserModel> existingUser) {
    SerializedBrokeredIdentityContext serializedCtx = SerializedBrokeredIdentityContext.readFromAuthenticationSession(context.getAuthenticationSession(), AbstractIdpAuthenticator.BROKERED_CONTEXT_NOTE);
    if (serializedCtx == null) {
        throw new AuthenticationFlowException("Not found serialized context in clientSession", AuthenticationFlowError.IDENTITY_PROVIDER_ERROR);
    }

    existingUser.ifPresent(u -> formData.putSingle(AuthenticationManager.FORM_USERNAME, u.getUsername()));

    LoginFormsProvider form = context.form()
            .setFormData(formData)
            .setAttribute(LoginFormsProvider.REGISTRATION_DISABLED, true)
            .setInfo(Messages.FEDERATED_IDENTITY_CONFIRM_REAUTHENTICATE_MESSAGE, serializedCtx.getIdentityProviderId());

    SerializedBrokeredIdentityContext serializedCtx0 = SerializedBrokeredIdentityContext.readFromAuthenticationSession(context.getAuthenticationSession(), AbstractIdpAuthenticator.NESTED_FIRST_BROKER_CONTEXT);
    if (serializedCtx0 != null) {
        BrokeredIdentityContext ctx0 = serializedCtx0.deserialize(context.getSession(), context.getAuthenticationSession());
        form.setError(Messages.NESTED_FIRST_BROKER_FLOW_MESSAGE, ctx0.getIdpConfig().getAlias(), ctx0.getUsername());
        context.getAuthenticationSession().setAuthNote(AbstractIdpAuthenticator.NESTED_FIRST_BROKER_CONTEXT, null);
    }

    return form;
}
 
Example #14
Source File: RecaptchaUsernamePasswordForm.java    From keycloak-login-recaptcha with Apache License 2.0 6 votes vote down vote up
protected boolean validateRecaptcha(AuthenticationFlowContext context, boolean success, String captcha, String secret) {
	HttpClient httpClient = context.getSession().getProvider(HttpClientProvider.class).getHttpClient();
	HttpPost post = new HttpPost("https://www.google.com/recaptcha/api/siteverify");
	List<NameValuePair> formparams = new LinkedList<>();
	formparams.add(new BasicNameValuePair("secret", secret));
	formparams.add(new BasicNameValuePair("response", captcha));
	formparams.add(new BasicNameValuePair("remoteip", context.getConnection().getRemoteAddr()));
	try {
		UrlEncodedFormEntity form = new UrlEncodedFormEntity(formparams, "UTF-8");
		post.setEntity(form);
		HttpResponse response = httpClient.execute(post);
		InputStream content = response.getEntity().getContent();
		try {
			Map json = JsonSerialization.readValue(content, Map.class);
			Object val = json.get("success");
			success = Boolean.TRUE.equals(val);
		} finally {
			content.close();
		}
	} catch (Exception e) {
		ServicesLogger.LOGGER.recaptchaFailed(e);
	}
	return success;
}
 
Example #15
Source File: WebAuthn4jAuthenticator.java    From keycloak-webauthn-authenticator with Apache License 2.0 6 votes vote down vote up
public void authenticate(AuthenticationFlowContext context) {
    LoginFormsProvider form = context.form();
    Map<String, String> params = generateParameters(context.getRealm(), context.getUriInfo().getBaseUri());
    context.getAuthenticationSession().setAuthNote(WebAuthnConstants.AUTH_CHALLENGE_NOTE, params.get(WebAuthnConstants.CHALLENGE));
    UserModel user = context.getUser();
    boolean isUserIdentified = false;
    if (user != null) {
        // in 2 Factor Scenario where the user has already identified
        isUserIdentified = true;
        form.setAttribute("authenticators", new WebAuthnAuthenticatorsBean(user));
    } else {
        // in ID-less & Password-less Scenario
        // NOP
    }
    params.put("isUserIdentified", Boolean.toString(isUserIdentified));
    params.forEach(form::setAttribute);
    context.challenge(form.createForm("webauthn.ftl"));
}
 
Example #16
Source File: PasswordAuthenticatorForm.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
@Override
public void action(AuthenticationFlowContext context) {

    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    if (formData.containsKey("cancel")) {
        context.cancelLogin();
        context.resetFlow();
        return;
    }
    if (!validatePasswordForm(context, formData)) {
        return;
    }

    context.success();
}
 
Example #17
Source File: WebAuthn4jAuthenticatorTest.java    From keycloak-webauthn-authenticator with Apache License 2.0 5 votes vote down vote up
@Before
public void setupMock() throws Exception {
    this.session = mock(KeycloakSession.class, Mockito.RETURNS_DEEP_STUBS);
    this.authenticator = new WebAuthn4jAuthenticator(session);
    this.context = mock(AuthenticationFlowContext.class, Mockito.RETURNS_DEEP_STUBS);
    // avoid NPE
    when(context.getUriInfo().getBaseUri()).thenReturn(new URI("http://localhost:8080"));
    when(context.getRealm().getName()).thenReturn("webauthn");
}
 
Example #18
Source File: PasswordAuthenticatorForm.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
@Override
protected Response challenge(AuthenticationFlowContext context, String error) {

    LoginFormsProvider form = context.form();

    if (error != null) {
        form.setError(error);
    }

    String attemptedUsername = context.getAuthenticationSession().getAuthNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME);
    form.setAttribute(AuthenticationManager.FORM_USERNAME, attemptedUsername);

    Response response = form.createForm("validate-password-form.ftl");
    return response;
}
 
Example #19
Source File: SelectUserAuthenticatorForm.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
private boolean validateUsernameForm(AuthenticationFlowContext context, MultivaluedMap<String, String> inputData) {

        String username = inputData.getFirst(AuthenticationManager.FORM_USERNAME);
        if (username == null) {
            failWithUserNotFound(context);
            return false;
        }

        // remove leading and trailing whitespace
        username = username.trim();

        context.getEvent().detail(Details.USERNAME, username);
        context.getAuthenticationSession().setAuthNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME, username);

        UserModel user = lookupUser(context, username);

        if (user == null) {
            testInvalidUser(context, user);
            return false;
        }

        if (!enabledUser(context, user)) {
            return false;
        }

        String rememberMe = inputData.getFirst("rememberMe");
        boolean remember = rememberMe != null && rememberMe.equalsIgnoreCase("on");
        if (remember) {
            context.getAuthenticationSession().setAuthNote(Details.REMEMBER_ME, "true");
            context.getEvent().detail(Details.REMEMBER_ME, "true");
        } else {
            context.getAuthenticationSession().removeAuthNote(Details.REMEMBER_ME);
        }
        context.setUser(user);
        return true;
    }
 
Example #20
Source File: HttpBasicAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void authenticate(final AuthenticationFlowContext context) {
    final HttpRequest httpRequest = context.getHttpRequest();
    final HttpHeaders httpHeaders = httpRequest.getHttpHeaders();
    final String[] usernameAndPassword = getUsernameAndPassword(httpHeaders);

    context.attempted();

    if (usernameAndPassword != null) {
        final RealmModel realm = context.getRealm();
        final String username = usernameAndPassword[0];
        final UserModel user = context.getSession().users().getUserByUsername(username, realm);

        // to allow success/failure logging for brute force
        context.getEvent().detail(Details.USERNAME, username);
        context.getAuthenticationSession().setAuthNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME, username);

        if (user != null) {
            final String password = usernameAndPassword[1];
            final boolean valid = context.getSession().userCredentialManager().isValid(realm, user, UserCredentialModel.password(password));

            if (valid) {
                if (isTemporarilyDisabledByBruteForce(context, user)) {
                    userDisabledAction(context, realm, user, Errors.USER_TEMPORARILY_DISABLED);
                } else if (user.isEnabled()) {
                    userSuccessAction(context, user);
                } else {
                    userDisabledAction(context, realm, user, Errors.USER_DISABLED);
                }
            } else {
                notValidCredentialsAction(context, realm, user);
            }
        } else {
            nullUserAction(context, realm, username);
        }
    }
}
 
Example #21
Source File: IdpUsernamePasswordForm.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Optional<UserModel> getExistingUser(AuthenticationFlowContext context) {
    try {
        return Optional.of(AbstractIdpAuthenticator.getExistingUser(context.getSession(), context.getRealm(), context.getAuthenticationSession()));
    } catch (AuthenticationFlowException ex) {
        log.debug("No existing user in authSession", ex);
        return Optional.empty();
    }
}
 
Example #22
Source File: SessionPropagationAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
private String getConfigProperty(AuthenticationFlowContext context, String key, String defaultValue) {

        if (context.getAuthenticatorConfig() == null) {
            return defaultValue;
        }

        Map<String, String> config = context.getAuthenticatorConfig().getConfig();
        if (config == null) {
            return defaultValue;
        }

        return config.getOrDefault(key, defaultValue);
    }
 
Example #23
Source File: IdpEmailVerificationAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void showEmailSentPage(AuthenticationFlowContext context, BrokeredIdentityContext brokerContext) {
    String accessCode = context.generateAccessCode();
    URI action = context.getActionUrl(accessCode);

    Response challenge = context.form()
            .setStatus(Response.Status.OK)
            .setAttribute(LoginFormsProvider.IDENTITY_PROVIDER_BROKER_CONTEXT, brokerContext)
            .setActionUri(action)
            .setExecution(context.getExecution().getId())
            .createIdpLinkEmailPage();
    context.forceChallenge(challenge);
}
 
Example #24
Source File: ConsolePasswordAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected ConsoleDisplayMode challenge(AuthenticationFlowContext context) {
    return ConsoleDisplayMode.challenge(context)
            .header()
            .param("password")
            .label("console-password")
            .mask(true)
            .challenge();
}
 
Example #25
Source File: KeycloakSmsAuthenticator.java    From keycloak-sms-authenticator with Eclipse Public License 2.0 5 votes vote down vote up
public void action(AuthenticationFlowContext context) {
    logger.debug("action called ... context = " + context);
    CODE_STATUS status = validateCode(context);
    Response challenge = null;
    switch (status) {
        case EXPIRED:
            challenge =  context.form()
                    .setError("code is expired")
                    .createForm("sms-validation.ftl");
            context.failureChallenge(AuthenticationFlowError.EXPIRED_CODE, challenge);
            break;

        case INVALID:
            if(context.getExecution().getRequirement() == AuthenticationExecutionModel.Requirement.OPTIONAL ||
                    context.getExecution().getRequirement() == AuthenticationExecutionModel.Requirement.ALTERNATIVE) {
                logger.debug("Calling context.attempted()");
                context.attempted();
            } else if(context.getExecution().getRequirement() == AuthenticationExecutionModel.Requirement.REQUIRED) {
                challenge =  context.form()
                        .setError("badCode")
                        .createForm("sms-validation.ftl");
                context.failureChallenge(AuthenticationFlowError.INVALID_CREDENTIALS, challenge);
            } else {
                // Something strange happened
                logger.warn("Undefined execution ...");
            }
            break;

        case VALID:
            context.success();
            break;

    }
}
 
Example #26
Source File: KeycloakSmsAuthenticator.java    From keycloak-sms-authenticator with Eclipse Public License 2.0 5 votes vote down vote up
private void storeSMSCode(AuthenticationFlowContext context, String code, Long expiringAt) {
    UserCredentialModel credentials = new UserCredentialModel();
    credentials.setType(SMSAuthenticatorContstants.USR_CRED_MDL_SMS_CODE);
    credentials.setValue(code);
    context.getSession().users().updateCredential(context.getRealm(), context.getUser(), credentials);

    credentials.setType(SMSAuthenticatorContstants.USR_CRED_MDL_SMS_EXP_TIME);
    credentials.setValue((expiringAt).toString());
    context.getSession().users().updateCredential(context.getRealm(), context.getUser(), credentials);
}
 
Example #27
Source File: AccessPolicyAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {

    AuthenticatorConfigModel configModel = context.getAuthenticatorConfig();

    if (configModel == null) {
        context.attempted();
        return;
    }

    String accessPolicyJson = configModel.getConfig().get(AccessPolicyAuthenticatorFactory.ACCESS_POLICY);
    if (accessPolicyJson == null) {
        context.attempted();
        return;
    }

    AccessPolicy accessPolicy = accessPolicyParser.parse(accessPolicyJson);

    RealmModel realm = context.getRealm();
    ClientModel client = context.getAuthenticationSession().getClient();
    UserModel user = context.getUser();

    if (!accessPolicy.hasAccess(realm, user, client)) {

        log.debugf("Access denied because of access policy. realm=%s client=%s username=%s", realm.getName(), client.getClientId(), user.getUsername());
        context.getEvent().user(user);
        context.getEvent().error(Errors.NOT_ALLOWED);
        context.forkWithErrorMessage(new FormMessage(Messages.NO_ACCESS));
        return;
    }


    context.success();
}
 
Example #28
Source File: HttpBasicAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void notValidCredentialsAction(final AuthenticationFlowContext context, final RealmModel realm, final UserModel user) {
    context.getEvent().user(user);
    context.getEvent().error(Errors.INVALID_USER_CREDENTIALS);
    context.failure(AuthenticationFlowError.INVALID_USER, Response.status(Response.Status.UNAUTHORIZED)
            .header(HttpHeaders.WWW_AUTHENTICATE, BASIC_PREFIX + "realm=\"" + realm.getName() + "\"")
            .build());
}
 
Example #29
Source File: X509ClientCertificateAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Response createErrorResponse(AuthenticationFlowContext context,
                                     String subjectDN,
                                     String errorMessage,
                                     String ... errorParameters) {

    return createResponse(context, subjectDN, false, errorMessage, errorParameters);
}
 
Example #30
Source File: LoginNotifyEmailAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
private Map<String, String> createMailAttributes(AuthenticationFlowContext context) {

        RealmModel realm = context.getRealm();

        Map<String, String> attributes = new HashMap<>();
        attributes.put("username", context.getUser().getUsername());
        attributes.put("ipAddress", context.getConnection().getRemoteAddr());
        URI accountUrl = context.getUriInfo().getRequestUriBuilder().replaceQuery("").replacePath("/auth/realms/{realm}/account").build(realm.getName());
        attributes.put("accountUrl", accountUrl.toString());
        String realmDisplayName = realm.getDisplayName() != null ? realm.getDisplayName() : realm.getName();
        attributes.put("realmDisplayName", realmDisplayName);

        return attributes;
    }