Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 38 ยท Security

Authentication Providers and Password Storage

Write a Micronaut authentication provider, enable the login endpoint, store passwords with salted slow hashes and lock out brute-force attempts. Runnable Java stand-ins.

Access rules need an identity to look at. Where does that identity come from? In Micronaut it comes from an authentication provider: a bean that receives a username and a password (or other credentials), checks them against your user store and answers "yes, and here are the roles" or "no".

The real framework code is read-only here. The two TryIt examples are stand-ins in plain Java: one shows how a provider chain works and the other shows how to store and check passwords without ever keeping the password itself.

The provider contract

In Micronaut Security 4 a provider for username and password login implements HttpRequestAuthenticationProvider. It receives the request and the submitted credentials and returns an AuthenticationResponse:

Java
import io.micronaut.http.HttpRequest;
import io.micronaut.security.authentication.AuthenticationFailureReason;
import io.micronaut.security.authentication.AuthenticationRequest;
import io.micronaut.security.authentication.AuthenticationResponse;
import io.micronaut.security.authentication.provider.HttpRequestAuthenticationProvider;
import jakarta.inject.Singleton;
import java.util.List;

@Singleton
class DatabaseAuthenticationProvider<B> implements HttpRequestAuthenticationProvider<B> {

    private final UserRepository users;
    private final PasswordHasher hasher;

    DatabaseAuthenticationProvider(UserRepository users, PasswordHasher hasher) {
        this.users = users;
        this.hasher = hasher;
    }

    @Override
    public AuthenticationResponse authenticate(HttpRequest<B> request,
                                               AuthenticationRequest<String, String> credentials) {
        return users.findByUsername(credentials.getIdentity())
                .filter(u -> hasher.matches(credentials.getSecret(), u.passwordHash()))
                .map(u -> AuthenticationResponse.success(u.username(), u.roles()))
                .orElseGet(() -> AuthenticationResponse.failure(
                        AuthenticationFailureReason.CREDENTIALS_DO_NOT_MATCH));
    }
}

AuthenticationResponse.success(name, roles) creates the Authentication object that the access rules from Security Fundamentals will inspect. A failure carries a reason, such as USER_NOT_FOUND, ACCOUNT_LOCKED or CREDENTIALS_DO_NOT_MATCH. Show the client one generic message ("invalid username or password") regardless of the reason, so attackers cannot probe which usernames exist.

Several providers may exist, for example one for staff in a database and one for service accounts in configuration. Micronaut tries them in turn and the first success authenticates the user.

The login endpoint

You do not write a controller to receive the credentials. Turn on the built-in endpoint:

YAML
micronaut:
  security:
    authentication: bearer
    endpoints:
      login:
        enabled: true

A client posts JSON to /login:

Terminal
curl -X POST http://localhost:8080/login \
  -H 'Content-Type: application/json' \
  -d '{"username":"alice","password":"secret"}'

With bearer authentication the answer contains an access token (see JWT Tokens); with authentication: cookie the server sets a cookie and redirects. Add logout the same way to clear that state.

Login in four steps

POST /login Client sends credentials.
Provider Looks up the user, checks the hash.
1 / 2

Never store passwords

A database leak must not reveal passwords. Store a salted, slow hash instead:

  • Salt: random bytes per user, so equal passwords give different hashes and precomputed tables are useless.
  • Slow: algorithms such as Argon2id, bcrypt, scrypt or PBKDF2 with many iterations make each guess expensive for an attacker. Plain SHA-256 or MD5 are far too fast.
  • Constant-time compare: compare hashes with a function that always takes the same time, such as MessageDigest.isEqual.

In production use a maintained library (Argon2 or bcrypt) rather than your own code. The stand-in below uses PBKDF2 from the JDK because it needs no dependency.

Try it: salted password hashing

Java Hash and verify a password

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Try it: provider chain and lockout

This stand-in runs a chain of providers, returns a generic error and locks an account after three failed attempts, the same policy ideas you would add to a real provider.

Java A provider chain with lockout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Common mistakes

  • Different error messages for "unknown user" and "wrong password". Return one generic message.
  • Hashing with a fast algorithm or without a salt.
  • Accepting unlimited attempts. Add lockouts or throttling; a reverse proxy rate limit also helps.
  • Logging the submitted password, even on failure.
  • Putting default accounts (such as admin with a documented password) into code that reaches production.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does an authentication provider return on success?

    AuthenticationResponse.success(name, roles) builds the Authentication used by the access rules.
  2. 2. Why does each user get a random salt?

    A unique salt defeats rainbow tables and hides that two users share a password.
  3. 3. Which is the best choice for storing passwords?

    Slow, salted algorithms make guessing expensive. Base64 is only an encoding, not protection.
  4. 4. How should login failures be reported to the client?

    A generic message avoids revealing which usernames exist.

Summary

  • A provider checks credentials and returns success with roles, or a failure reason.
  • The built-in /login endpoint calls your providers; you only write the lookup.
  • Store passwords as salted slow hashes and compare in constant time.
  • Return generic errors, lock out repeated failures and never log secrets.

Next: JWT Tokens