Class AuthService


public class AuthService extends Object
Basic authentication service.

This class presents an basic authentication service, which offers authentication functionality that is not specific to an authentication mechanism (such as password authentication or OAuth authentication).

Like all service classes, this class holds only configuration state. Thus, once configured, it can be safely shared between multiple sessions since its state (the configuration) is read-only.

The class provides the following services (and relevant configuration):

  • Constructor Details

    • AuthService

      public AuthService()
  • Method Details

    • setRandomTokenLength

      public void setRandomTokenLength(int length)
      Sets the token length.

      Configures the length used for random tokens. Random tokens are generated for authentication tokens, and email tokens.

      The default length is 32 characters.

    • getRandomTokenLength

      public int getRandomTokenLength()
      Returns the token length.

      See Also:
    • setIdentityPolicy

      public void setIdentityPolicy(IdentityPolicy identityPolicy)
      Configures the identity policy.

      The identity policy has an impact on the login and registration procedure.

    • getIdentityPolicy

      public IdentityPolicy getIdentityPolicy()
      Returns the identity policy.

      See Also:
    • identifyUser

      public User identifyUser(Identity identity, AbstractUserDatabase users)
      Tries to match the identity to an existing user.

      When authenticating using a 3rd party Identity Provider, the identity is matched against the existing users, based on the id (with AbstractUserDatabase#findWithIdentity()), or if not matched, based on whether there is a user with the same verified email address as the one indicated by the identity.

    • setAuthTokensEnabled

      public void setAuthTokensEnabled(boolean enabled, String cookieName, String cookieDomain)
      Configures authentication token support.

      This method allows you to configure whether authentication tokens are in use. Authentication tokens are used for the user to bypass a more elaborate authentication method, and are a secret shared with the user's user agent, usually in a cookie. They are typically presented in the user interfaces as a "remember me" option.

      Whenever a valid authentication token is presented in processToken(), it is invalidated a new token is generated and stored for the user.

      The tokens are generated and subsequently hashed using the token hash function. Only the hash values are stored in the user database so that a compromised user database does not compromise these tokens.

      Authentication tokens are disabled by default.

      See Also:
    • setAuthTokensEnabled

      public final void setAuthTokensEnabled(boolean enabled)
      Configures authentication token support.

      Calls setAuthTokensEnabled(enabled, "wtauth", "")

    • setAuthTokensEnabled

      public final void setAuthTokensEnabled(boolean enabled, String cookieName)
      Configures authentication token support.

      Calls setAuthTokensEnabled(enabled, cookieName, "")

    • isAuthTokensEnabled

      public boolean isAuthTokensEnabled()
      Returns whether authentication tokens are enabled.

      See Also:
    • setAuthTokenUpdateEnabled

      public void setAuthTokenUpdateEnabled(boolean enabled)
      Set whether processAuthToken() updates the auth token.

      If this option is enabled, processAuthToken() will replace the auth token with a new token. This is a bit more secure, because an auth token can only be used once. This is enabled by default.

      However, this means that if a user concurrently opens multiple sessions within the same browsers (e.g. multiple tabs being restored at the same time) or refreshes before they receive the new cookie, the user will be logged out, unless the AbstractUserDatabase implementation takes this into account (e.g. keeps the old token valid for a little bit longer)

      The default Dbo UserDatabase does not handle concurrent token updates well, so disable this option if you want to prevent that issue.

      See Also:
    • isAuthTokenUpdateEnabled

      public boolean isAuthTokenUpdateEnabled()
      Returns whether the auth token is updated.

      See Also:
    • getAuthTokenCookieName

      public String getAuthTokenCookieName()
      Returns the authentication token cookie name.

      This is the default cookie name used for storing the authentication token in the user's browser.

      See Also:
    • getAuthTokenCookieDomain

      public String getAuthTokenCookieDomain()
      Returns the authentication token cookie domain.

      This is the domain used for the authentication cookie. By default this is empty, which means that a cookie will be set for this application.

      You may want to set a more general domain if you are sharing the authentication with multiple applications.

      See Also:
    • setTokenHashFunction

      public void setTokenHashFunction(HashFunction function)
      Sets the token hash function.

      Sets the hash function used to safely store authentication tokens in the database. Ownership of the hash function is transferred.

      The default token hash function is an MD5HashFunction.

    • getTokenHashFunction

      public HashFunction getTokenHashFunction()
      Returns the token hash function.

      See Also:
    • createAuthToken

      public String createAuthToken(User user)
      Creates and stores an authentication token for the user.

      This creates and stores a new authentication token for the given user.

      The returned value is the token that may be used to re-identify the user in processAuthToken().

    • processAuthToken

      public AuthTokenResult processAuthToken(String token, AbstractUserDatabase users)
      Processes an authentication token.

      This verifies an authentication token, and considers whether it matches with a token hash value stored in database. If it matches and auth token update is enabled, the token is updated with a new hash.

      See Also:
    • setAuthTokenValidity

      public void setAuthTokenValidity(int minutes)
      Configures the duration for an authenticaton to remain valid.

      The default duration is two weeks (14 * 24 * 60 minutes).

    • getAuthTokenValidity

      public int getAuthTokenValidity()
      Returns the authentication token validity.

      See Also:
    • setEmailVerificationEnabled

      public void setEmailVerificationEnabled(boolean enabled)
      Configures email verification.

      Email verification is useful for a user to recover a lost password, or to be able to confidently confirm other events with this user (such as order processing).

    • isEmailVerificationEnabled

      public boolean isEmailVerificationEnabled()
      Returns whether email verification is configured.

      See Also:
    • setEmailVerificationRequired

      public void setEmailVerificationRequired(boolean enabled)
      Configure email verificiation to be required for login.

      When enabled, a user will not be able to login if the email-address was not verified.

    • isEmailVerificationRequired

      public boolean isEmailVerificationRequired()
      \ Returns whether email verification is required for login.

      See Also:
    • setEmailRedirectInternalPath

      public void setEmailRedirectInternalPath(String internalPath)
      Sets the internal path used to present tokens in emails.

      The default path is "/auth/mail/".

    • getEmailRedirectInternalPath

      public String getEmailRedirectInternalPath()
      Returns the internal path used for email tokens.

      See Also:
    • parseEmailToken

      public String parseEmailToken(String internalPath)
      Parses the emailtoken from an internal path.

      This method parses an internal path and if it matches the email redirection path, it returns the token contained.

      It returns an empty string if the internal path does not contain an email token.

    • verifyEmailAddress

      public void verifyEmailAddress(User user, String address) throws javax.mail.MessagingException, UnsupportedEncodingException, IOException
      Verifies an email address.

      This registers a new email token with the user.

      Then it sends an email to the user's unverified email address with instructions that redirect him to this site, using sendConfirmEmail().

      See Also:
    • lostPassword

      public void lostPassword(String emailAddress, AbstractUserDatabase users) throws javax.mail.MessagingException, UnsupportedEncodingException, IOException
      Implements lost password functionality.

      If email address verification is enabled, then a user may recover his password (or rather, chose a new password) using a procedure which involves sending an email to a verified email address.

      This method triggers this process, starting from an email address, if this email address corresponds to a verified email address in the database. The current password is not invalidated.

      See Also:
    • processEmailToken

      public EmailTokenResult processEmailToken(String token, AbstractUserDatabase users)
      Processes an email token.

      This processes a token received through an email. If it is an email verification token, the token is removed from the database.

      This may return two successful results:

      Note: Since JWt 4.3.0, the behavior of this function changed. The lost password token is no longer removed by processEmailToken(). Instead, it is now removed in User#setPassword().

      See Also:
    • setEmailTokenValidity

      public void setEmailTokenValidity(int minutes)
      Configures the duration for an email token to remain valid.

      The default duration is three days (3 * 24 * 60 minutes). Three is a divine number.

    • getEmailTokenValidity

      public int getEmailTokenValidity()
      Returns the duration for an email token to remain valid.

      See Also:
    • sendMail

      public void sendMail(javax.mail.Message message) throws javax.mail.MessagingException, UnsupportedEncodingException, IOException
      Sends an email.

      Sends an email to the given address with subject and body.

      The default implementation will consult configuration properties to add a sender address if it hasn't already been set:

      • "auth-mail-sender-name": the sender name, with default value "Wt Auth module"
      • "auth-mail-sender-address": the sender email address, with default value ""

      Then it uses the JavaMail API to send the message, the SMTP settings are configured using the and smpt.port JWt configuration variables (see Configuration.setProperties(HashMap properties)).

    • sendConfirmMail

      protected void sendConfirmMail(String address, User user, String token) throws javax.mail.MessagingException, UnsupportedEncodingException, IOException
      Sends a confirmation email to the user to verify his email address.

      Sends a confirmation email to the given address.

      The email content is provided by the following string keys:

      • subject: tr("Wt.auth.verification-mail.subject")
      • body: tr("Wt.auth.verification-mail.body") with {1} a place holder for the identity, and {2} a placeholder for the redirection URL.
      • HTML body: tr("Wt.auth.verification-mail.htmlbody") with the same place holders.
    • sendLostPasswordMail

      protected void sendLostPasswordMail(String address, User user, String token) throws javax.mail.MessagingException, UnsupportedEncodingException, IOException
      Sends an email to the user to enter a new password.

      This sends a lost password email to the given address, with a given token .

      The default implementation will call sendMail() with the following message:

      • tr("Wt.Auth.lost-password-mail.subject") as subject,
      • tr("Wt.Auth.lost-password-mail.body") as body to which it passes user.identity() and token as arguments.
      • tr("Wt.Auth.lost-password-mail.htmlbody") as HTML body to which it passes user.identity() and token as arguments.
    • createRedirectUrl

      protected String createRedirectUrl(String token)