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

org.esfinge.guardian.rbac.authorizer.AllowRolesAuthorizer Maven / Gradle / Ivy

The newest version!
package org.esfinge.guardian.rbac.authorizer;

import java.util.HashSet;
import java.util.Set;

import org.esfinge.guardian.authorizer.Authorizer;
import org.esfinge.guardian.context.AuthorizationContext;
import org.esfinge.guardian.rbac.annotation.authorization.AllowRoles;
import org.esfinge.guardian.rbac.entity.Role;
import org.esfinge.guardian.rbac.exception.RbacMisuseException;
import org.esfinge.guardian.rbac.utils.RbacConfig;

public class AllowRolesAuthorizer implements Authorizer {
	
	@Override
	public Boolean authorize(AuthorizationContext context, AllowRoles allowRoles) {
		
		RbacConfig rbacConfig = new RbacConfig();
		Set subjectRoles = context.getSubject().get(rbacConfig.getRolesKey(), new HashSet());
		Set annotatedRoles = new HashSet();
		
		String[] annotatedRolesNames = allowRoles.value();
		for (String roleName : annotatedRolesNames) {
			annotatedRoles.add(new Role(roleName));
		}
		
		if (annotatedRoles.isEmpty() && !subjectRoles.isEmpty()) {
			throw new RbacMisuseException("A role must be defined to access the method: " + context.getGuardedMethod().getName());
		}
		
		boolean authorized = false;
		for (Role annotatedRole : annotatedRoles) {
			for (Role subjectRole : subjectRoles) {
				authorized = authorized || annotatedRole.isSubjectInRole(subjectRole);
			}
		}
		
		return authorized;
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy