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

com.fivefaces.structureclient.config.security.unmanned.UnmannedApiAuthenticationProvider Maven / Gradle / Ivy

The newest version!
package com.fivefaces.structureclient.config.security.unmanned;

import com.fivefaces.structureclient.config.security.NoTokenProvidedException;
import com.fivefaces.structureclient.config.security.UserAuthenticationToken;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Slf4j
@RequiredArgsConstructor
@Component
public class UnmannedApiAuthenticationProvider implements AuthenticationProvider {

    @Value("${structure.unmanned.api.token}")
    protected String unmannedApiToken;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        return Optional.ofNullable(authentication)
                .filter(auth -> supports(auth.getClass()))
                .map(auth -> (UserAuthenticationToken) auth)
                .map(auth -> {
                    validateApiToken(auth.getApiToken());
                    auth.setAuthenticated(true);
                    return auth;
                })
                .orElse(null);
    }

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

    private void validateApiToken(String token) {
        if (StringUtils.isBlank(token)) {
            throw new NoTokenProvidedException("Token has expired");
        }
        if (!unmannedApiToken.equals(token)) {
            throw new BadCredentialsException("Invalid token");
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy