com.fivefaces.structureclient.config.security.patient.PatientApiAuthenticationProvider Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of common-structure-client Show documentation
Show all versions of common-structure-client Show documentation
structure Client for Five Faces
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");
}
}
}