Interface AuthenticationCodec


public interface AuthenticationCodec

Keeps one kind of Authentication in the HTTP session, and makes it again on the next request.

A session stores plain values -- text, numbers, truth values, lists and maps of them -- because the database session store writes JSON and any server may take the client's next request. By default HttpSessionSecurityContextRepository therefore keeps a name and a list of authorities, and a later request sees a UsernamePasswordAuthenticationToken whatever signed the user in. A codec is how a way of signing in keeps more: which provider the user came through and what it said of them, which passkey they used.

Each mechanism that has a kind of its own registers its codec from its own configurer, so the repository names none of them and a server carries only the codecs of what its chains declare. An application with an authentication of its own does the same:

http.authenticationCodec(new AuthenticationCodec() {
    public String getKind() {
        return "badge";
    }

    public Map<String, Object> encode(Authentication authentication) {
        if (!(authentication instanceof BadgeAuthentication)) {
            return null;
        }
        Map<String, Object> kept = new HashMap<String, Object>();
        kept.put("door", ((BadgeAuthentication) authentication).getDoor());
        return kept;
    }

    public Authentication decode(String name, List<GrantedAuthority> authorities, Map stored) {
        Object door = stored.get("door");
        return door instanceof String
                ? new BadgeAuthentication(name, authorities, (String) door) : null;
    }
});

What decode(String, List, Map) is handed has been through the session store: a number that went in as an Integer may come back a Long, and nothing in it is to be cast without instanceof.

  • Method Details

    • getKind

      String getKind()
      The name this kind is stored under: short, and never reused for another.
    • encode

      Map<String,Object> encode(Authentication authentication)
      What to keep of authentication beside its name and authorities, as plain values; null when it is not of this codec's kind. A map that holds anything a session cannot store is not kept, and the authentication is then stored as a name and authorities alone.
    • decode

      Authentication decode(String name, List<GrantedAuthority> authorities, Map stored)
      The authentication encode(Authentication) kept, for a later request.
      Parameters:
      name - its name, as stored
      authorities - its authorities, as stored
      stored - what encode(Authentication) returned, after the session store
      Returns:
      the authentication, already authenticated; or null when stored is not something this codec can read, and the user is then the name and the authorities alone