AuthUtil.java
package se.jobtechdev.personaldatagateway.api.util;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.Base64;
import static se.jobtechdev.personaldatagateway.api.util.MessageDigestProvider.sha256;
public final class AuthUtil {
private AuthUtil() {
}
public static void assertAuthKeyExists(String authKey) {
if (authKey == null)
throw new BadCredentialsException("Bad Request Header Credentials, provided authKey is null");
if (authKey.isEmpty())
throw new BadCredentialsException(
"Bad Request Header Credentials, provided authKey is empty");
}
public static byte[] decodeAuthKey(String authKey) {
try {
return Base64.getDecoder().decode(authKey);
} catch (Exception e) {
throw new BadCredentialsException(
"Bad Request Header Credentials, provided authKey could not be decoded");
}
}
public static byte[] hashDecodedAuthKey(byte[] decodedAuthKey) {
try {
return sha256(decodedAuthKey);
} catch (RuntimeException e) {
throw new BadCredentialsException(
"Bad Request Header Credentials, base64 decoded authKey could not be hashed");
}
}
public static String getLoggedInClientId() {
return SecurityContextHolder.getContext().getAuthentication().getName();
}
public static String getLoggedInRole() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication.getAuthorities().stream().findFirst().orElseThrow().getAuthority();
}
}