Search in sources :

Example 16 with SimpleAuthorizationInfo

use of org.apache.shiro.authz.SimpleAuthorizationInfo in project killbill by killbill.

the class KillBillAuth0Realm method doGetAuthenticationInfo.

@Override
protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken token) throws AuthenticationException {
    if (token instanceof UsernamePasswordToken) {
        final UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        if (doAuthenticate(upToken)) {
            // Credentials are valid
            return new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), getName());
        }
    } else {
        final String bearerToken = (String) token.getPrincipal();
        final Claims claims = verifyJWT(bearerToken);
        // Credentials are valid
        // This config must match the one in Kaui
        final Object principal = claims.get(securityConfig.getShiroAuth0UsernameClaim());
        // For the JWT to contains the permissions, the `Add Permissions in the Access Token` setting must be turned on in Auth0
        if (claims.containsKey("permissions") && claims.get("permissions") instanceof Iterable) {
            // In order to use the permissions from the JWT (and avoid calling Auth0 later on), we need to eagerly cache them,
            // as doGetAuthorizationInfo won't have access to the token
            final org.apache.shiro.cache.Cache<Object, AuthorizationInfo> authorizationCache = getAuthorizationCache();
            // Should never be null (initialized via init())
            if (authorizationCache != null) {
                final SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(null);
                final Set<String> permissions = new HashSet<String>();
                for (final Object permission : (Iterable) claims.get("permissions")) {
                    permissions.add(permission.toString());
                }
                simpleAuthorizationInfo.setStringPermissions(permissions);
                final MutablePrincipalCollection principals = new SimplePrincipalCollection();
                principals.add(principal, getName());
                final Object authorizationCacheKey = getAuthorizationCacheKey(principals);
                authorizationCache.put(authorizationCacheKey, simpleAuthorizationInfo);
            }
        }
        return new SimpleAuthenticationInfo(principal, token.getCredentials(), getName());
    }
    throw new AuthenticationException("Auth0 authentication failed");
}
Also used : Claims(io.jsonwebtoken.Claims) SimpleAuthorizationInfo(org.apache.shiro.authz.SimpleAuthorizationInfo) SimpleAuthenticationInfo(org.apache.shiro.authc.SimpleAuthenticationInfo) AuthenticationException(org.apache.shiro.authc.AuthenticationException) SimplePrincipalCollection(org.apache.shiro.subject.SimplePrincipalCollection) AuthorizationInfo(org.apache.shiro.authz.AuthorizationInfo) SimpleAuthorizationInfo(org.apache.shiro.authz.SimpleAuthorizationInfo) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) MutablePrincipalCollection(org.apache.shiro.subject.MutablePrincipalCollection) HashSet(java.util.HashSet)

Example 17 with SimpleAuthorizationInfo

use of org.apache.shiro.authz.SimpleAuthorizationInfo in project airpal by airbnb.

the class AllowAllRealm method doGetAuthorizationInfo.

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    Set<String> roles = Sets.newHashSet("user");
    Set<Permission> permissions = Sets.newHashSet();
    Collection<AllowAllUser> principalsCollection = principals.byType(AllowAllUser.class);
    if (principalsCollection.isEmpty()) {
        throw new AuthorizationException("No principals!");
    }
    for (AllowAllUser user : principalsCollection) {
        for (UserGroup userGroup : groups) {
            if (userGroup.representedByGroupStrings(user.getGroups())) {
                permissions.addAll(userGroup.getPermissions());
                break;
            }
        }
    }
    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(roles);
    authorizationInfo.setObjectPermissions(permissions);
    return authorizationInfo;
}
Also used : SimpleAuthorizationInfo(org.apache.shiro.authz.SimpleAuthorizationInfo) AuthorizationException(org.apache.shiro.authz.AuthorizationException) Permission(org.apache.shiro.authz.Permission)

Example 18 with SimpleAuthorizationInfo

use of org.apache.shiro.authz.SimpleAuthorizationInfo in project graylog2-server by Graylog2.

the class MongoDbAuthorizationRealm method doGetAuthorizationInfo.

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    LOG.debug("Retrieving authorization information for: {}", principals);
    // This realm can handle both, user String principals and GRN principals.
    final GRN principal = getUserPrincipal(principals).orElseGet(() -> getGRNPrincipal(principals).orElse(null));
    if (principal == null) {
        return new SimpleAuthorizationInfo();
    }
    LOG.debug("GRN principal: {}", principal);
    final ImmutableSet.Builder<Permission> permissionsBuilder = ImmutableSet.builder();
    final ImmutableSet.Builder<String> rolesBuilder = ImmutableSet.builder();
    // Resolve grant permissions and roles for the GRN
    permissionsBuilder.addAll(permissionAndRoleResolver.resolvePermissionsForPrincipal(principal));
    rolesBuilder.addAll(permissionAndRoleResolver.resolveRolesForPrincipal(principal));
    if (GRNTypes.USER.equals(principal.grnType())) {
        // If the principal is a user, we also need to load permissions and roles from the user object
        final User user = userService.loadById(principal.entity());
        if (user != null) {
            final Set<Permission> userPermissions = user.getObjectPermissions();
            permissionsBuilder.addAll(userPermissions);
            rolesBuilder.addAll(user.getRoleIds());
        } else {
            LOG.warn("User <{}> not found for permission and role resolving", principal);
        }
    }
    final SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    info.setObjectPermissions(permissionsBuilder.build());
    info.setRoles(rolesBuilder.build());
    if (LOG.isDebugEnabled()) {
        LOG.debug("Authorization info for {} - permissions: {}", principal, info.getObjectPermissions());
        LOG.debug("Authorization info for {} - roles: {}", principal, info.getRoles());
    }
    return info;
}
Also used : GRN(org.graylog.grn.GRN) SimpleAuthorizationInfo(org.apache.shiro.authz.SimpleAuthorizationInfo) User(org.graylog2.plugin.database.users.User) ImmutableSet(com.google.common.collect.ImmutableSet) Permission(org.apache.shiro.authz.Permission)

Example 19 with SimpleAuthorizationInfo

use of org.apache.shiro.authz.SimpleAuthorizationInfo in project ddf by codice.

the class AbstractAuthorizingRealm method doGetAuthorizationInfo.

/**
 * Takes the security attributes about the subject of the incoming security token and builds sets
 * of permissions and roles for use in further checking.
 *
 * @param principalCollection holds the security assertions for the primary principal of this
 *     request
 * @return a new collection of permissions and roles corresponding to the security assertions
 * @throws AuthorizationException if there are no security assertions associated with this
 *     principal collection or if the token cannot be processed successfully.
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    LOGGER.debug("Retrieving authorization info for {}", principalCollection.getPrimaryPrincipal());
    Collection<SecurityAssertion> assertions = principalCollection.byType(SecurityAssertion.class);
    if (assertions.isEmpty()) {
        String msg = "No assertion found, cannot retrieve authorization info.";
        throw new AuthorizationException(msg);
    }
    List<AttributeStatement> attributeStatements = assertions.stream().map(SecurityAssertion::getAttributeStatements).flatMap(List::stream).collect(Collectors.toList());
    Set<Permission> permissions = new HashSet<>();
    Set<String> roles = new HashSet<>();
    Map<String, Set<String>> permissionsMap = new HashMap<>();
    Collection<Expansion> expansionServices = getUserExpansionServices();
    for (AttributeStatement curStatement : attributeStatements) {
        addAttributesToMap(curStatement.getAttributes(), permissionsMap, expansionServices);
    }
    for (Map.Entry<String, Set<String>> entry : permissionsMap.entrySet()) {
        permissions.add(new KeyValuePermissionImpl(entry.getKey(), entry.getValue()));
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Adding permission: {} : {}", entry.getKey(), StringUtils.join(entry.getValue(), ","));
        }
    }
    if (permissionsMap.containsKey(SAML_ROLE)) {
        roles.addAll(permissionsMap.get(SAML_ROLE));
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Adding roles to authorization info: {}", StringUtils.join(roles, ","));
        }
    }
    info.setObjectPermissions(permissions);
    info.setRoles(roles);
    return info;
}
Also used : SimpleAuthorizationInfo(org.apache.shiro.authz.SimpleAuthorizationInfo) HashSet(java.util.HashSet) Set(java.util.Set) AuthorizationException(org.apache.shiro.authz.AuthorizationException) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SecurityAssertion(ddf.security.assertion.SecurityAssertion) AttributeStatement(ddf.security.assertion.AttributeStatement) KeyValuePermissionImpl(ddf.security.permission.impl.KeyValuePermissionImpl) KeyValuePermission(ddf.security.permission.KeyValuePermission) Permission(org.apache.shiro.authz.Permission) KeyValueCollectionPermission(ddf.security.permission.KeyValueCollectionPermission) Expansion(ddf.security.expansion.Expansion) HashMap(java.util.HashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashSet(java.util.HashSet)

Example 20 with SimpleAuthorizationInfo

use of org.apache.shiro.authz.SimpleAuthorizationInfo in project ddf by codice.

the class AuthzRealmTest method setup.

@Before
public void setup() throws PdpException {
    String ruleClaim = "FineAccessControls";
    String countryClaim = "CountryOfAffiliation";
    // setup the subject permissions
    List<Permission> permissions = new ArrayList<>();
    KeyValuePermission rulePermission = new KeyValuePermissionImpl(ruleClaim);
    rulePermission.addValue("A");
    rulePermission.addValue("B");
    permissions.add(rulePermission);
    KeyValuePermission countryPermission = new KeyValuePermissionImpl(countryClaim);
    countryPermission.addValue("AUS");
    permissions.add(countryPermission);
    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
    authorizationInfo.addObjectPermission(rulePermission);
    authorizationInfo.addObjectPermission(countryPermission);
    authorizationInfo.addObjectPermission(new KeyValuePermissionImpl("role", Arrays.asList("admin")));
    authorizationInfo.addRole("admin");
    authorizationInfo.addStringPermission("wild");
    testRealm = new AuthzRealm("src/test/resources/policies", new XmlParser()) {

        @Override
        public AuthorizationInfo getAuthorizationInfo(PrincipalCollection principals) {
            return authorizationInfo;
        }
    };
    testRealm.setSecurityLogger(mock(SecurityLogger.class));
    mockSubjectPrincipal = mock(PrincipalCollection.class);
    when(mockSubjectPrincipal.getPrimaryPrincipal()).thenReturn("user");
    // setup the resource permissions
    permissionList = new ArrayList<>();
    security = new HashMap<>();
    security.put("country", Arrays.asList("AUS", "CAN", "GBR"));
    security.put("rule", Arrays.asList("A", "B"));
    testRealm.setMatchOneMappings(Arrays.asList("CountryOfAffiliation=country"));
    testRealm.setMatchAllMappings(Arrays.asList("FineAccessControls=rule"));
    testRealm.setRolePermissionResolver(roleString -> Arrays.asList(new KeyValuePermissionImpl("role", Arrays.asList(roleString))));
}
Also used : XmlParser(org.codice.ddf.parser.xml.XmlParser) AuthzRealm(ddf.security.pdp.realm.AuthzRealm) SimpleAuthorizationInfo(org.apache.shiro.authz.SimpleAuthorizationInfo) ArrayList(java.util.ArrayList) PrincipalCollection(org.apache.shiro.subject.PrincipalCollection) AuthorizationInfo(org.apache.shiro.authz.AuthorizationInfo) SimpleAuthorizationInfo(org.apache.shiro.authz.SimpleAuthorizationInfo) KeyValuePermissionImpl(ddf.security.permission.impl.KeyValuePermissionImpl) CollectionPermission(ddf.security.permission.CollectionPermission) KeyValuePermission(ddf.security.permission.KeyValuePermission) Permission(org.apache.shiro.authz.Permission) WildcardPermission(org.apache.shiro.authz.permission.WildcardPermission) KeyValueCollectionPermission(ddf.security.permission.KeyValueCollectionPermission) KeyValuePermission(ddf.security.permission.KeyValuePermission) SecurityLogger(ddf.security.audit.SecurityLogger) Before(org.junit.Before)

Aggregations

SimpleAuthorizationInfo (org.apache.shiro.authz.SimpleAuthorizationInfo)48 Permission (org.apache.shiro.authz.Permission)8 AuthorizationException (org.apache.shiro.authz.AuthorizationException)6 KeyValueCollectionPermission (ddf.security.permission.KeyValueCollectionPermission)5 KeyValuePermission (ddf.security.permission.KeyValuePermission)5 ArrayList (java.util.ArrayList)5 HashSet (java.util.HashSet)5 AuthenticationException (org.apache.shiro.authc.AuthenticationException)5 AuthorizationInfo (org.apache.shiro.authz.AuthorizationInfo)5 KeyValuePermissionImpl (ddf.security.permission.impl.KeyValuePermissionImpl)4 CollectionPermission (ddf.security.permission.CollectionPermission)3 HashMap (java.util.HashMap)3 PrincipalCollection (org.apache.shiro.subject.PrincipalCollection)3 Group (com.ganster.cms.core.pojo.Group)2 Permission (com.ganster.cms.core.pojo.Permission)2 User (com.ganster.cms.core.pojo.User)2 UserExample (com.ganster.cms.core.pojo.UserExample)2 TbRolePermission (com.netsteadfast.greenstep.po.hbm.TbRolePermission)2 TbUserRole (com.netsteadfast.greenstep.po.hbm.TbUserRole)2 Set (java.util.Set)2