All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.optionfactory.spring.authentication.bearer.token.StaticBearerTokenAuthenticationProvider Maven / Gradle / Ivy

There is a newer version: 21.2
Show newest version
package net.optionfactory.spring.authentication.bearer.token;

import java.util.List;
import java.util.Map;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;

/**
 * Authenticates by matching the configured static token with the request Bearer
 * token, granting the configured authorities on authentication success.
 */
public class StaticBearerTokenAuthenticationProvider implements AuthenticationProvider {

    private final Map tokenToPrincipalAndAuthorities;

    public StaticBearerTokenAuthenticationProvider(Map tokenToPrincipalAndAuthorities) {
        this.tokenToPrincipalAndAuthorities = tokenToPrincipalAndAuthorities;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        final BearerToken bearer = (BearerToken) authentication;
        final PrincipalAndAuthorities got = tokenToPrincipalAndAuthorities.get(bearer.getCredentials());
        if (got == null) {
            return null;
        }
        final var token = new StaticBearerAuthenticatedToken(bearer.getCredentials(), got.principal, got.authorities);
        token.setDetails(bearer.getDetails());
        return token;
    }

    @Override
    public boolean supports(Class authentication) {
        return BearerToken.class.isAssignableFrom(authentication);
    }

    public static StaticBearerTokenAuthenticationProvider of(String token, Object principal, List authorities) {
        return new StaticBearerTokenAuthenticationProvider(Map.of(token, new PrincipalAndAuthorities(principal, authorities)));
    }

    public static class PrincipalAndAuthorities {

        public final Object principal;
        public final List authorities;

        public PrincipalAndAuthorities(Object principal, List authorities) {
            this.principal = principal;
            this.authorities = authorities;
        }

    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy