Search in sources :

Example 6 with EmailException

use of org.keycloak.email.EmailException in project keycloak by keycloak.

the class IdpEmailVerificationAuthenticator method sendVerifyEmail.

private void sendVerifyEmail(KeycloakSession session, AuthenticationFlowContext context, UserModel existingUser, BrokeredIdentityContext brokerContext) throws UriBuilderException, IllegalArgumentException {
    RealmModel realm = session.getContext().getRealm();
    UriInfo uriInfo = session.getContext().getUri();
    AuthenticationSessionModel authSession = context.getAuthenticationSession();
    int validityInSecs = realm.getActionTokenGeneratedByUserLifespan(IdpVerifyAccountLinkActionToken.TOKEN_TYPE);
    int absoluteExpirationInSecs = Time.currentTime() + validityInSecs;
    EventBuilder event = context.getEvent().clone().event(EventType.SEND_IDENTITY_PROVIDER_LINK).user(existingUser).detail(Details.USERNAME, existingUser.getUsername()).detail(Details.EMAIL, existingUser.getEmail()).detail(Details.CODE_ID, authSession.getParentSession().getId()).removeDetail(Details.AUTH_METHOD).removeDetail(Details.AUTH_TYPE);
    String authSessionEncodedId = AuthenticationSessionCompoundId.fromAuthSession(authSession).getEncodedId();
    IdpVerifyAccountLinkActionToken token = new IdpVerifyAccountLinkActionToken(existingUser.getId(), existingUser.getEmail(), absoluteExpirationInSecs, authSessionEncodedId, brokerContext.getUsername(), brokerContext.getIdpConfig().getAlias(), authSession.getClient().getClientId());
    UriBuilder builder = Urls.actionTokenBuilder(uriInfo.getBaseUri(), token.serialize(session, realm, uriInfo), authSession.getClient().getClientId(), authSession.getTabId());
    String link = builder.queryParam(Constants.EXECUTION, context.getExecution().getId()).build(realm.getName()).toString();
    long expirationInMinutes = TimeUnit.SECONDS.toMinutes(validityInSecs);
    try {
        context.getSession().getProvider(EmailTemplateProvider.class).setRealm(realm).setAuthenticationSession(authSession).setUser(existingUser).setAttribute(EmailTemplateProvider.IDENTITY_PROVIDER_BROKER_CONTEXT, brokerContext).sendConfirmIdentityBrokerLink(link, expirationInMinutes);
        event.success();
    } catch (EmailException e) {
        event.error(Errors.EMAIL_SEND_FAILED);
        ServicesLogger.LOGGER.confirmBrokerEmailFailed(e);
        Response challenge = context.form().setError(Messages.EMAIL_SENT_ERROR).createErrorPage(Response.Status.INTERNAL_SERVER_ERROR);
        context.failure(AuthenticationFlowError.INTERNAL_ERROR, challenge);
        return;
    }
    showEmailSentPage(context, brokerContext);
}
Also used : RealmModel(org.keycloak.models.RealmModel) Response(javax.ws.rs.core.Response) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) EventBuilder(org.keycloak.events.EventBuilder) EmailTemplateProvider(org.keycloak.email.EmailTemplateProvider) EmailException(org.keycloak.email.EmailException) IdpVerifyAccountLinkActionToken(org.keycloak.authentication.actiontoken.idpverifyemail.IdpVerifyAccountLinkActionToken) UriBuilder(javax.ws.rs.core.UriBuilder)

Example 7 with EmailException

use of org.keycloak.email.EmailException in project keycloak by keycloak.

the class ConsoleVerifyEmail method sendVerifyEmail.

private Response sendVerifyEmail(RequiredActionContext context) throws UriBuilderException, IllegalArgumentException {
    KeycloakSession session = context.getSession();
    UserModel user = context.getUser();
    AuthenticationSessionModel authSession = context.getAuthenticationSession();
    EventBuilder event = context.getEvent().clone().event(EventType.SEND_VERIFY_EMAIL).detail(Details.EMAIL, user.getEmail());
    String code = SecretGenerator.getInstance().randomString(8);
    authSession.setAuthNote(Constants.VERIFY_EMAIL_CODE, code);
    RealmModel realm = session.getContext().getRealm();
    Map<String, Object> attributes = new HashMap<>();
    attributes.put("code", code);
    try {
        session.getProvider(EmailTemplateProvider.class).setAuthenticationSession(authSession).setRealm(realm).setUser(user).send("emailVerificationSubject", "email-verification-with-code.ftl", attributes);
        event.success();
    } catch (EmailException e) {
        logger.error("Failed to send verification email", e);
        event.error(Errors.EMAIL_SEND_FAILED);
    }
    return challenge(context).text(context.form().getMessage("console-verify-email", user.getEmail()));
}
Also used : AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) EventBuilder(org.keycloak.events.EventBuilder) HashMap(java.util.HashMap) EmailException(org.keycloak.email.EmailException)

Example 8 with EmailException

use of org.keycloak.email.EmailException in project keycloak by keycloak.

the class ResetCredentialEmail method authenticate.

@Override
public void authenticate(AuthenticationFlowContext context) {
    UserModel user = context.getUser();
    AuthenticationSessionModel authenticationSession = context.getAuthenticationSession();
    String username = authenticationSession.getAuthNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME);
    // just reset login for with a success message
    if (user == null) {
        context.forkWithSuccessMessage(new FormMessage(Messages.EMAIL_SENT));
        return;
    }
    String actionTokenUserId = authenticationSession.getAuthNote(DefaultActionTokenKey.ACTION_TOKEN_USER_ID);
    if (actionTokenUserId != null && Objects.equals(user.getId(), actionTokenUserId)) {
        logger.debugf("Forget-password triggered when reauthenticating user after authentication via action token. Skipping " + PROVIDER_ID + " screen and using user '%s' ", user.getUsername());
        context.success();
        return;
    }
    EventBuilder event = context.getEvent();
    // we don't want people guessing usernames, so if there is a problem, just continuously challenge
    if (user.getEmail() == null || user.getEmail().trim().length() == 0) {
        event.user(user).detail(Details.USERNAME, username).error(Errors.INVALID_EMAIL);
        context.forkWithSuccessMessage(new FormMessage(Messages.EMAIL_SENT));
        return;
    }
    int validityInSecs = context.getRealm().getActionTokenGeneratedByUserLifespan(ResetCredentialsActionToken.TOKEN_TYPE);
    int absoluteExpirationInSecs = Time.currentTime() + validityInSecs;
    // We send the secret in the email in a link as a query param.
    String authSessionEncodedId = AuthenticationSessionCompoundId.fromAuthSession(authenticationSession).getEncodedId();
    ResetCredentialsActionToken token = new ResetCredentialsActionToken(user.getId(), user.getEmail(), absoluteExpirationInSecs, authSessionEncodedId, authenticationSession.getClient().getClientId());
    String link = UriBuilder.fromUri(context.getActionTokenUrl(token.serialize(context.getSession(), context.getRealm(), context.getUriInfo()))).build().toString();
    long expirationInMinutes = TimeUnit.SECONDS.toMinutes(validityInSecs);
    try {
        context.getSession().getProvider(EmailTemplateProvider.class).setRealm(context.getRealm()).setUser(user).setAuthenticationSession(authenticationSession).sendPasswordReset(link, expirationInMinutes);
        event.clone().event(EventType.SEND_RESET_PASSWORD).user(user).detail(Details.USERNAME, username).detail(Details.EMAIL, user.getEmail()).detail(Details.CODE_ID, authenticationSession.getParentSession().getId()).success();
        context.forkWithSuccessMessage(new FormMessage(Messages.EMAIL_SENT));
    } catch (EmailException e) {
        event.clone().event(EventType.SEND_RESET_PASSWORD).detail(Details.USERNAME, username).user(user).error(Errors.EMAIL_SEND_FAILED);
        ServicesLogger.LOGGER.failedToSendPwdResetEmail(e);
        Response challenge = context.form().setError(Messages.EMAIL_SENT_ERROR).createErrorPage(Response.Status.INTERNAL_SERVER_ERROR);
        context.failure(AuthenticationFlowError.INTERNAL_ERROR, challenge);
    }
}
Also used : ResetCredentialsActionToken(org.keycloak.authentication.actiontoken.resetcred.ResetCredentialsActionToken) Response(javax.ws.rs.core.Response) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) EventBuilder(org.keycloak.events.EventBuilder) EmailException(org.keycloak.email.EmailException) FormMessage(org.keycloak.models.utils.FormMessage)

Example 9 with EmailException

use of org.keycloak.email.EmailException in project keycloak by keycloak.

the class UserResource method executeActionsEmail.

/**
 * Send a update account email to the user
 *
 * An email contains a link the user can click to perform a set of required actions.
 * The redirectUri and clientId parameters are optional. If no redirect is given, then there will
 * be no link back to click after actions have completed.  Redirect uri must be a valid uri for the
 * particular clientId.
 *
 * @param redirectUri Redirect uri
 * @param clientId Client id
 * @param lifespan Number of seconds after which the generated token expires
 * @param actions required actions the user needs to complete
 * @return
 */
@Path("execute-actions-email")
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public Response executeActionsEmail(@QueryParam(OIDCLoginProtocol.REDIRECT_URI_PARAM) String redirectUri, @QueryParam(OIDCLoginProtocol.CLIENT_ID_PARAM) String clientId, @QueryParam("lifespan") Integer lifespan, List<String> actions) {
    auth.users().requireManage(user);
    if (user.getEmail() == null) {
        return ErrorResponse.error("User email missing", Status.BAD_REQUEST);
    }
    if (!user.isEnabled()) {
        throw new WebApplicationException(ErrorResponse.error("User is disabled", Status.BAD_REQUEST));
    }
    if (redirectUri != null && clientId == null) {
        throw new WebApplicationException(ErrorResponse.error("Client id missing", Status.BAD_REQUEST));
    }
    if (clientId == null) {
        clientId = Constants.ACCOUNT_MANAGEMENT_CLIENT_ID;
    }
    ClientModel client = realm.getClientByClientId(clientId);
    if (client == null) {
        logger.debugf("Client %s doesn't exist", clientId);
        throw new WebApplicationException(ErrorResponse.error("Client doesn't exist", Status.BAD_REQUEST));
    }
    if (!client.isEnabled()) {
        logger.debugf("Client %s is not enabled", clientId);
        throw new WebApplicationException(ErrorResponse.error("Client is not enabled", Status.BAD_REQUEST));
    }
    String redirect;
    if (redirectUri != null) {
        redirect = RedirectUtils.verifyRedirectUri(session, redirectUri, client);
        if (redirect == null) {
            throw new WebApplicationException(ErrorResponse.error("Invalid redirect uri.", Status.BAD_REQUEST));
        }
    }
    if (lifespan == null) {
        lifespan = realm.getActionTokenGeneratedByAdminLifespan();
    }
    int expiration = Time.currentTime() + lifespan;
    ExecuteActionsActionToken token = new ExecuteActionsActionToken(user.getId(), user.getEmail(), expiration, actions, redirectUri, clientId);
    try {
        UriBuilder builder = LoginActionsService.actionTokenProcessor(session.getContext().getUri());
        builder.queryParam("key", token.serialize(session, realm, session.getContext().getUri()));
        String link = builder.build(realm.getName()).toString();
        this.session.getProvider(EmailTemplateProvider.class).setAttribute(Constants.TEMPLATE_ATTR_REQUIRED_ACTIONS, token.getRequiredActions()).setRealm(realm).setUser(user).sendExecuteActions(link, TimeUnit.SECONDS.toMinutes(lifespan));
        // audit.user(user).detail(Details.EMAIL, user.getEmail()).detail(Details.CODE_ID, accessCode.getCodeId()).success();
        adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).success();
        return Response.noContent().build();
    } catch (EmailException e) {
        ServicesLogger.LOGGER.failedToSendActionsEmail(e);
        return ErrorResponse.error("Failed to send execute actions email", Status.INTERNAL_SERVER_ERROR);
    }
}
Also used : ClientModel(org.keycloak.models.ClientModel) WebApplicationException(javax.ws.rs.WebApplicationException) EmailException(org.keycloak.email.EmailException) ExecuteActionsActionToken(org.keycloak.authentication.actiontoken.execactions.ExecuteActionsActionToken) UriBuilder(javax.ws.rs.core.UriBuilder) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) PUT(javax.ws.rs.PUT)

Aggregations

EmailException (org.keycloak.email.EmailException)9 IOException (java.io.IOException)3 EventBuilder (org.keycloak.events.EventBuilder)3 AuthenticationSessionModel (org.keycloak.sessions.AuthenticationSessionModel)3 Locale (java.util.Locale)2 Response (javax.ws.rs.core.Response)2 UriBuilder (javax.ws.rs.core.UriBuilder)2 RealmModel (org.keycloak.models.RealmModel)2 FreeMarkerException (org.keycloak.theme.FreeMarkerException)2 URI (java.net.URI)1 MessageFormat (java.text.MessageFormat)1 HashMap (java.util.HashMap)1 Properties (java.util.Properties)1 Consumes (javax.ws.rs.Consumes)1 PUT (javax.ws.rs.PUT)1 Path (javax.ws.rs.Path)1 WebApplicationException (javax.ws.rs.WebApplicationException)1 ExecuteActionsActionToken (org.keycloak.authentication.actiontoken.execactions.ExecuteActionsActionToken)1 IdpVerifyAccountLinkActionToken (org.keycloak.authentication.actiontoken.idpverifyemail.IdpVerifyAccountLinkActionToken)1 ResetCredentialsActionToken (org.keycloak.authentication.actiontoken.resetcred.ResetCredentialsActionToken)1