SecurityContextUtil.java
/*
* Copyright 2020 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.genesys.blocks.security;
import java.util.Arrays;
import java.util.List;
import org.genesys.blocks.security.model.AclSid;
import org.genesys.blocks.security.model.BasicUser;
import org.genesys.blocks.security.serialization.Permissions;
import org.genesys.blocks.util.CurrentApplicationContext;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.acls.domain.BasePermission;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.AbstractOAuth2TokenAuthenticationToken;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import lombok.extern.slf4j.Slf4j;
/**
* The Class SecurityContextUtil.
*/
@Slf4j
public class SecurityContextUtil {
/** The permission evaluator. */
private static PermissionEvaluator permissionEvaluator;
private final static Authentication ANONYMOUS_AUTH = new PreAuthenticatedAuthenticationToken("Anyone", null, Arrays.asList(new SimpleGrantedAuthority("ROLE_EVERYONE")));
// Context initialization
static {
updatePermissionEvaluator();
}
/**
* Try to obtain permissionEvaluator bean from context
*
* @return true if obtained, false if not obtained.
*/
private static synchronized boolean updatePermissionEvaluator() {
return (permissionEvaluator = updateBean(PermissionEvaluator.class)) != null;
}
/**
* Update bean.
*
* @param <T> the generic type
* @param clazz the clazz
* @return the t
*/
static final <T> T updateBean(Class<T> clazz) {
ApplicationContext context = CurrentApplicationContext.getContext();
if (context != null) {
try {
return context.getBean(clazz);
} catch (BeansException e) {
log.warn("Could not find {} instance in your context: {}", clazz, e.getMessage());
}
} else {
log.warn("You should initialize a bean instance of org.genesys.blocks.util.CurrentApplicationContext in your context");
}
return null;
}
/**
* Gets the username.
*
* @return the username
*/
public static String getUsername() {
final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null && auth.getPrincipal() instanceof UserDetails) {
return ((UserDetails) auth.getPrincipal()).getUsername();
} else {
return null;
}
}
/**
* Gets the me.
*
* @param <T> the generic type
* @return current user
*/
@SuppressWarnings("unchecked")
public static <T extends BasicUser<?>> T getMe() {
final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
Object principal = auth.getPrincipal();
if (principal instanceof BasicUser) {
return (T) principal;
} else {
log.warn("Principal {} is not BasicUser, but type {}", principal, principal.getClass());
}
}
return null;
}
/**
* Gets the current principal (User or OAuthClient).
*
* @param <T> the generic type
* @return the current security principal
*/
@SuppressWarnings("unchecked")
public static <T extends AclSid> T getCurrentUser() {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
Object principal = authentication.getPrincipal();
if (principal instanceof AclSid) {
return (T) principal;
} else {
log.warn("Principal {} is not AclSid, but type {}. Auth of type {}", principal, principal.getClass(), authentication.getClass());
}
}
return null;
}
/**
* Checks for role.
*
* @param role the role
* @return true, if successful
*/
public static boolean hasRole(String role) {
final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
for (GrantedAuthority authority : auth.getAuthorities()) {
if (authority.getAuthority().equals("ROLE_" + role)) {
return true;
}
}
}
return false;
}
/**
* Checks if any role is granted.
*
* @param roles the roles
* @return true, if successful
*/
public static boolean hasAnyRole(String... roles) {
final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
for (GrantedAuthority authority : auth.getAuthorities()) {
for (String role : roles) {
if (authority.getAuthority().equals("ROLE_" + role)) {
return true;
}
}
}
}
return false;
}
/**
* Check if authority is granted.
*
* @param authorityName the authority name
* @return true, if successful
*/
public static boolean hasAuthority(String authorityName) {
final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
for (GrantedAuthority authority : auth.getAuthorities()) {
if (authority.getAuthority().equals(authorityName)) {
return true;
}
}
}
return false;
}
/**
* Checks for permission.
*
* @param targetDomainObject the target domain object
* @param permission the permission
* @return true, if successful
*/
public static boolean hasPermission(Object targetDomainObject, Object permission) {
final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
return hasPermission(auth, targetDomainObject, permission);
}
/**
* Checks for permission.
*
* @param auth authentication object
* @param targetDomainObject the target domain object
* @param permission the permission
* @return true, if successful
*/
public static boolean hasPermission(final Authentication auth, Object targetDomainObject, Object permission) {
if (permissionEvaluator == null) {
log.info("permissionEvaluator not available. Checking context again");
if (!updatePermissionEvaluator()) {
log.warn("permissionEvaluator not available. No permissions.");
return false;
}
}
if (auth != null) {
return permissionEvaluator.hasPermission(auth, targetDomainObject, permission);
} else {
return false;
}
}
public static Permissions getPermissions(final Authentication authentication, Object targetDomainObject) {
var perms = new Permissions().grantNone();
if (permissionEvaluator == null) {
log.info("permissionEvaluator not available. Checking context again");
if (!updatePermissionEvaluator()) {
log.warn("permissionEvaluator not available. No permissions.");
return perms;
}
}
if (authentication != null) {
perms.create = permissionEvaluator.hasPermission(authentication, targetDomainObject, BasePermission.CREATE);
perms.read = permissionEvaluator.hasPermission(authentication, targetDomainObject, BasePermission.READ);
perms.write = permissionEvaluator.hasPermission(authentication, targetDomainObject, BasePermission.WRITE);
perms.delete = permissionEvaluator.hasPermission(authentication, targetDomainObject, BasePermission.DELETE);
perms.manage = permissionEvaluator.hasPermission(authentication, targetDomainObject, BasePermission.ADMINISTRATION);
perms.isPublic = anyoneHasPermission(targetDomainObject, BasePermission.READ);
}
return perms;
}
/**
* Check if ROLE_EVERYONE has permission on target object.
*
* @param targetDomainObject the target domain object
* @param permission the permission
* @return true, if successful
*/
public static boolean anyoneHasPermission(Object targetDomainObject, Object permission) {
if (permissionEvaluator == null) {
log.info("permissionEvaluator not available. Checking context again");
if (!updatePermissionEvaluator()) {
log.warn("permissionEvaluator not available. No permissions.");
return false;
}
}
if (ANONYMOUS_AUTH != null) {
return permissionEvaluator.hasPermission(ANONYMOUS_AUTH, targetDomainObject, permission);
} else {
return false;
}
}
/**
* Gets the OAuth Client ID of the current authentication object.
*
* @return the OAuth client ID
*/
public static String getOAuthClientId() {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication instanceof AbstractOAuth2TokenAuthenticationToken<?>) {
var oauthAuth = (AbstractOAuth2TokenAuthenticationToken<?>) authentication;
log.debug("OAuth authentication: {}", oauthAuth);
var token = (Jwt) oauthAuth.getToken();
var aud = token.getClaim("aud");
if (aud instanceof List<?> && !((List<?>)aud).isEmpty()) {
return String.valueOf(((List<?>) aud).get(0));
}
return String.valueOf(aud);
} else if (authentication == null) {
// No authentication
return null;
} else {
// Not OAuth authentication
log.warn("TODO {} {}", authentication.getClass(), authentication);
return null;
}
}
}