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

com.fivefaces.structureclient.config.security.patient.PatientApiAuthenticationProvider Maven / Gradle / Ivy

There is a newer version: 1.0.62
Show newest version
package com.fivefaces.structureclient.config.security.patient;

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 PatientApiAuthenticationProvider implements AuthenticationProvider {

    @Value("${structure.patient.api.token:NONE}")
    protected String userApiToken;
    @Value("${structure.patient.api.require-token:false}")
    protected boolean requireApiToken;

    @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 (!requireApiToken) {
            return;
        }
        if (StringUtils.isBlank(token)) {
            throw new NoTokenProvidedException("Token has expired");
        }
        if (!userApiToken.equals(token)) {
            throw new BadCredentialsException("Invalid token");
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy