org.apache.shiro.authz.Permission Java Examples
The following examples show how to use
org.apache.shiro.authz.Permission.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RepositoryPermissionChecker.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
private List<Repository> subjectHasAnyContentSelectorAccessTo(final Subject subject, final List<Repository> repositories) { List<String> repositoryNames = repositories.stream().map(r -> r.getName()).collect(Collectors.toList()); List<String> formats = repositories.stream().map(r -> r.getFormat().getValue()).distinct() .collect(Collectors.toList()); List<SelectorConfiguration> selectors = selectorManager.browseActive(repositoryNames, formats); if (selectors.isEmpty()) { return Collections.emptyList(); } List<Repository> permittedRepositories = new ArrayList<>(); for (Repository repository : repositories) { Permission[] permissions = selectors.stream() .map(s -> new RepositoryContentSelectorPermission(s, repository, singletonList(BROWSE))) .toArray(Permission[]::new); if (securityHelper.anyPermitted(subject, permissions)) { permittedRepositories.add(repository); } } return permittedRepositories; }
Example #2
Source File: SecurityHelper.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
/** * Check which permissions the subject has. * * @since 3.13 */ public boolean[] isPermitted(final Subject subject, final Permission... permissions) { checkNotNull(subject); checkNotNull(permissions); checkArgument(permissions.length != 0); boolean trace = log.isTraceEnabled(); if (trace) { log.trace("Checking which permissions subject '{}' has in: {}", subject.getPrincipal(), Arrays.toString(permissions)); } boolean[] results = subject.isPermitted(Arrays.asList(permissions)); if (trace) { log.trace("Subject '{}' has permissions: [{}] results {}", subject.getPrincipal(), Arrays.toString(permissions), results); } return results; }
Example #3
Source File: EnhancedWildcardPermission.java From super-cloudops with Apache License 2.0 | 6 votes |
@Override public boolean implies(Permission p) { if (!(p instanceof EnhancedWildcardPermission)) { return false; } EnhancedWildcardPermission gwp = (EnhancedWildcardPermission) p; // e.g: @RequiresPermissions(value="ci", "ci:list") List<Set<String>> defines = gwp.getPermitParts(); // e.g: Get the login-user permission info from the db "ci,ci:list" List<Set<String>> owns = getPermitParts(); for (Set<String> defineSet : defines) { // must all true boolean match = false; for (Set<String> ownSet : owns) {// one true if (doMatch(defineSet, ownSet)) { match = true; break; } } if (!match) { // not one match return false; } } return true; }
Example #4
Source File: SecurityHelper.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
/** * Check if subject has ALL of the given permissions. */ public boolean allPermitted(final Subject subject, final Permission... permissions) { checkNotNull(subject); checkNotNull(permissions); checkArgument(permissions.length != 0); boolean trace = log.isTraceEnabled(); if (trace) { log.trace("Checking if subject '{}' has ALL of these permissions: {}", subject.getPrincipal(), Arrays.toString(permissions)); } for (Permission permission : permissions) { if (!subject.isPermitted(permission)) { if (trace) { log.trace("Subject '{}' missing permission: {}", subject.getPrincipal(), permission); } return false; } } if (trace) { log.trace("Subject '{}' has required permissions: {}", subject.getPrincipal(), Arrays.toString(permissions)); } return true; }
Example #5
Source File: AbstractAuthorizingRealm.java From onedev with MIT License | 6 votes |
private Collection<Permission> getGroupPermissions(Group group, @Nullable User user) { Collection<Permission> permissions = new ArrayList<>(); if (group.isAdministrator()) { if (user != null) { permissions.add(new SystemAdministration()); } else { for (Project project: projectManager.query()) { permissions.add(new ProjectPermission(project, new ReadCode())); for (FieldSpec field: OneDev.getInstance(SettingManager.class).getIssueSetting().getFieldSpecs()) permissions.add(new ProjectPermission(project, new EditIssueField(Sets.newHashSet(field.getName())))); permissions.add(new ProjectPermission(project, new JobPermission("*", new AccessBuildLog()))); } } } if (user != null && group.isCreateProjects()) permissions.add(new CreateProjects()); for (GroupAuthorization authorization: group.getAuthorizations()) permissions.add(new ProjectPermission(authorization.getProject(), authorization.getRole())); return permissions; }
Example #6
Source File: ExampleLDAPRealm.java From airpal with Apache License 2.0 | 6 votes |
@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; }
Example #7
Source File: RepositoryPermissionCheckerTest.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
@Test public void testEnsureUserHasAnyPermissionOrAdminAccess() { Permission[] repositoryPermissions = createAdminPermissions(READ, RepositoryAdminPermission::new, repository, repository1, repository2); ApplicationPermission appPerm = new ApplicationPermission("blobstores", READ); Iterable<Permission> appPermissions = singletonList(appPerm); Iterable<Repository> repositories = Arrays.asList(repository, repository1, repository2); when(securityHelper.anyPermitted(same(subject), eq(appPermissions))).thenReturn(true); underTest.ensureUserHasAnyPermissionOrAdminAccess(appPermissions, READ, repositories); verify(securityHelper, never()).ensureAnyPermitted(subject, repositoryPermissions); Iterable<Permission> multipleAppPermissions = Arrays .asList(appPerm, new ApplicationPermission("blobstores", DELETE)); when(securityHelper.anyPermitted(same(subject), eq(multipleAppPermissions))).thenReturn(true); underTest.ensureUserHasAnyPermissionOrAdminAccess(multipleAppPermissions, READ, repositories); verify(securityHelper, never()).ensureAnyPermitted(subject, repositoryPermissions); when(securityHelper.anyPermitted(same(subject), eq(appPermissions))).thenReturn(false); underTest.ensureUserHasAnyPermissionOrAdminAccess(appPermissions, READ, repositories); verify(securityHelper).ensureAnyPermitted(subject, repositoryPermissions); }
Example #8
Source File: RepositoryPermissionChecker.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
/** * Ensures the user has any of the supplied permissions, or a RepositoryAdminPermission with the action to any * of the repositories. Throws an AuthorizationException if the user does not have the required permission. * * @since 3.17 * @param permissions the permissions to check first * @param action the action to use in the admin permission * @param repositories the repositories to check the action against * @throws AuthorizationException if the user doesn't have permission */ public void ensureUserHasAnyPermissionOrAdminAccess( final Iterable<Permission> permissions, final String action, final Iterable<Repository> repositories) { Subject subject = securityHelper.subject(); if (securityHelper.anyPermitted(subject, permissions)) { return; } Permission[] actionPermissions = StreamSupport.stream(repositories.spliterator(), false) .map(r -> new RepositoryAdminPermission(r, action)) .toArray(Permission[]::new); securityHelper.ensureAnyPermitted(subject, actionPermissions); }
Example #9
Source File: SecurityModule.java From emodb with Apache License 2.0 | 6 votes |
@Provides @Singleton PermissionManager providePermissionManager(@Named("dao") PermissionManager permissionManager, InvalidatableCacheManager cacheManager, final PermissionResolver permissionResolver) { ImmutableMap.Builder<String, Set<Permission>> defaultRolePermissions = ImmutableMap.builder(); for (DefaultRoles defaultRole : DefaultRoles.values()) { Set<Permission> rolePermissions = defaultRole.getPermissions() .stream() .map(permissionResolver::resolvePermission) .collect(Collectors.toSet()); defaultRolePermissions.put(PermissionIDs.forRole(defaultRole.toString()), rolePermissions); } PermissionManager deferring = new DeferringPermissionManager(permissionManager, defaultRolePermissions.build()); return new CacheManagingPermissionManager(deferring, cacheManager); }
Example #10
Source File: LocalSubjectUserAccessControl.java From emodb with Apache License 2.0 | 6 votes |
@Override public boolean checkApiKeyHasPermission(Subject subject, String id, String permission) { // Permission for this action is tied to the ability to read the key if (!subject.getId().equals(id)) { verifyPermission(subject, Permissions.readApiKey()); } ApiKey apiKey = _authIdentityManager.getIdentity(id); if (apiKey == null) { throw new EmoApiKeyNotFoundException(); } Permission resolvedPermission = resolvePermission(permission); for (String role : apiKey.getRoles()) { // We don't care if the API key has a non-existent role assigned, so don't raise an exception, just // move on to the next role. if (checkRoleHasPermission(RoleIdentifier.fromString(role), resolvedPermission, false)) { // All it takes is one return true; } } return false; }
Example #11
Source File: ApiKeyRealmTest.java From emodb with Apache License 2.0 | 6 votes |
@Test public void pseudoConcurrentNewExists() { Cache<String, RolePermissionSet> cache = _underTest.getAvailableRolesCache(); assertEquals(cache.size(), 0, "precondition: cache is empty"); Permission p1 = mock(Permission.class); when(p1.toString()).thenReturn("p1"); Permission p2 = mock(Permission.class); when(p2.toString()).thenReturn("p2"); when(_permissionManager.getPermissions(PermissionIDs.forRole("role"))).thenReturn(Sets.newHashSet(p1), Sets.newHashSet(p2)); Collection<Permission> resultPerms = _underTest.getRolePermissions("role"); assertEquals(resultPerms.iterator().next(), p1, "should have the first permission we added"); assertEquals(cache.size(), 1, "side effect: cache has one element"); resultPerms = _underTest.getRolePermissions("role"); assertEquals(resultPerms.iterator().next(), p2, "should have the last permission we added"); assertEquals(cache.size(), 1, "side effect: cache has one element"); }
Example #12
Source File: ApiKeyRealmTest.java From emodb with Apache License 2.0 | 6 votes |
@Test public void pseudoConcurrentNewThenCacheFlush() { Cache<String, RolePermissionSet> cache = _underTest.getAvailableRolesCache(); assertEquals(cache.size(), 0, "precondition: cache is empty"); Permission p1 = mock(Permission.class); when(p1.toString()).thenReturn("p1"); Permission p2 = mock(Permission.class); when(p2.toString()).thenReturn("p2"); when(_permissionManager.getPermissions(PermissionIDs.forRole("role"))) .thenReturn(Sets.newHashSet(p1)) .thenReturn(Sets.newHashSet(p2)); Collection<Permission> resultPerms = _underTest.getRolePermissions("role"); assertEquals(resultPerms.iterator().next(), p1, "should have the last permission we added"); assertEquals(cache.size(), 1, "side effect: cache has one element"); cache.clear(); resultPerms = _underTest.getRolePermissions("role"); assertEquals(resultPerms.iterator().next(), p2, "should again have the last permission we added"); assertEquals(cache.size(), 1, "side effect: cache again has one element"); }
Example #13
Source File: SecurityHelper.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
/** * Check if subject has ANY of the given permissions. */ public boolean anyPermitted(final Subject subject, final Permission... permissions) { checkNotNull(subject); checkNotNull(permissions); checkArgument(permissions.length != 0); boolean trace = log.isTraceEnabled(); if (trace) { log.trace("Checking if subject '{}' has ANY of these permissions: {}", subject.getPrincipal(), Arrays.toString(permissions)); } for (Permission permission : permissions) { if (subject.isPermitted(permission)) { if (trace) { log.trace("Subject '{}' has permission: {}", subject.getPrincipal(), permission); } return true; } } if (trace) { log.trace("Subject '{}' missing required permissions: {}", subject.getPrincipal(), Arrays.toString(permissions)); } return false; }
Example #14
Source File: TablePermissionManagerDAO.java From emodb with Apache License 2.0 | 5 votes |
private Set<Permission> extractPermissionsFromRecord(Map<String, Object> map) { Set<Permission> permissions = Sets.newHashSet(); for (String mapKey : map.keySet()) { if (mapKey.startsWith("perm_")) { permissions.add(_permissionResolver.resolvePermission(mapKey.substring(5))); } } return permissions; }
Example #15
Source File: ScopePermission.java From seed with Mozilla Public License 2.0 | 5 votes |
@Override public boolean implies(Permission p) { if (scope != null && p instanceof ScopePermission) { ScopePermission sp = (ScopePermission) p; return scope.includes(sp.getScope()) && permission.implies(sp.permission); } else { return permission.implies(p); } }
Example #16
Source File: ExceptionCatchingModularRealmAuthorizer.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Override public boolean isPermittedAll(PrincipalCollection subjectPrincipal, Collection<Permission> permissions) { for (Permission permission : permissions) { if (!isPermitted(subjectPrincipal, permission)) { return false; } } return true; }
Example #17
Source File: JobPermission.java From onedev with MIT License | 5 votes |
@Override public boolean implies(Permission p) { if (p instanceof JobPermission) { JobPermission jobPermission = (JobPermission) p; return getJobNamesPatternSet().matches(new StringMatcher(), jobPermission.jobNames) && privilege.implies(jobPermission.privilege); } return false; }
Example #18
Source File: ApiKeyRealm.java From emodb with Apache License 2.0 | 5 votes |
/** * Test for whether an API key has specific permissions using its ID. */ public boolean hasPermissionsById(String id, String... permissions) { List<Permission> resolvedPermissions = Lists.newArrayListWithCapacity(permissions.length); for (String permission : permissions) { resolvedPermissions.add(getPermissionResolver().resolvePermission(permission)); } return hasPermissionsById(id, resolvedPermissions); }
Example #19
Source File: UserGroup.java From airpal with Apache License 2.0 | 5 votes |
public void setPermissions(Set<String> permissions) { ImmutableSet.Builder<Permission> builder = ImmutableSet.builder(); for (String permission : permissions) { builder.add(new WildcardPermission(permission)); } this.permissions = builder.build(); }
Example #20
Source File: SecurityHelper.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
/** * Ensure subject has given permissions. * * @throws AuthorizationException */ public void ensurePermitted(final Subject subject, final Permission... permissions) { checkNotNull(subject); checkNotNull(permissions); checkArgument(permissions.length != 0); if (log.isTraceEnabled()) { log.trace("Ensuring subject '{}' has permissions: {}", subject.getPrincipal(), Arrays.toString(permissions)); } subject.checkPermissions(Arrays.asList(permissions)); }
Example #21
Source File: RepositoryAdminPrivilegeDescriptor.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Override public Permission createPermission(final CPrivilege privilege) { assert privilege != null; String format = readProperty(privilege, P_FORMAT, ALL); String name = readProperty(privilege, P_REPOSITORY, ALL); List<String> actions = readListProperty(privilege, P_ACTIONS, ALL); return new RepositoryAdminPermission(format, name, actions); }
Example #22
Source File: SystemAuthorizingRealm.java From easyweb with Apache License 2.0 | 5 votes |
@Override protected boolean[] isPermitted(List<Permission> permissions, AuthorizationInfo info) { if (permissions != null && !permissions.isEmpty()) { for (Permission permission : permissions) { authorizationValidate(permission); } } return super.isPermitted(permissions, info); }
Example #23
Source File: ApplicationPrivilegeDescriptor.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Override public Permission createPermission(final CPrivilege privilege) { assert privilege != null; String domain = readProperty(privilege, P_DOMAIN, ALL); List<String> actions = readListProperty(privilege, P_ACTIONS, ALL); return new ApplicationPermission(domain, actions); }
Example #24
Source File: RepositoryViewPrivilegeDescriptor.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Override public Permission createPermission(final CPrivilege privilege) { assert privilege != null; String format = readProperty(privilege, P_FORMAT, ALL); String name = readProperty(privilege, P_REPOSITORY, ALL); List<String> actions = readListProperty(privilege, P_ACTIONS, ALL); return new RepositoryViewPermission(format, name, actions); }
Example #25
Source File: SystemAuthorizingRealm.java From Shop-for-JavaWeb with MIT License | 5 votes |
@Override protected boolean[] isPermitted(List<Permission> permissions, AuthorizationInfo info) { if (permissions != null && !permissions.isEmpty()) { for (Permission permission : permissions) { authorizationValidate(permission); } } return super.isPermitted(permissions, info); }
Example #26
Source File: SystemAuthorizingRealm.java From Shop-for-JavaWeb with MIT License | 5 votes |
@Override protected boolean isPermittedAll(Collection<Permission> permissions, AuthorizationInfo info) { if (permissions != null && !permissions.isEmpty()) { for (Permission permission : permissions) { authorizationValidate(permission); } } return super.isPermittedAll(permissions, info); }
Example #27
Source File: ApiKeyRealmTest.java From emodb with Apache License 2.0 | 5 votes |
@Test public void simpleEmpty() { assertNotNull(_underTest.getAvailableRolesCache(), "precondition: there is a cache"); when(_permissionManager.getPermissions(PermissionIDs.forRole("role"))).thenReturn(Sets.<Permission>newHashSet()); Collection<Permission> resultPerms = _underTest.getRolePermissions("role"); assertTrue(resultPerms.isEmpty(), "should be no permissions yet"); }
Example #28
Source File: ApiKeyRealmTest.java From emodb with Apache License 2.0 | 5 votes |
@Test public void pseudoConcurrentNewAndCacheFlush() { final Cache<String, RolePermissionSet> cache = _underTest.getAvailableRolesCache(); assertEquals(cache.size(), 0, "precondition: cache is empty"); final Permission p1 = mock(Permission.class); when(p1.toString()).thenReturn("p1"); final Permission p2 = mock(Permission.class); when(p2.toString()).thenReturn("p2"); when(_permissionManager.getPermissions(PermissionIDs.forRole("role"))) .thenReturn(Sets.newHashSet(p1)) .thenAnswer(new Answer<Set<Permission>>() { @Override public Set<Permission> answer(InvocationOnMock invocationOnMock) throws Throwable { cache.clear(); return Sets.newHashSet(p2); } }) .thenReturn(Sets.newHashSet(p2)); Permission resultPerm = _underTest.getRolePermissions("role").iterator().next(); assertEquals(resultPerm, p1, "should have permission p1"); resultPerm = _underTest.getRolePermissions("role").iterator().next(); assertEquals(resultPerm, p2, "should have permission p2"); resultPerm = _underTest.getRolePermissions("role").iterator().next(); assertEquals(resultPerm, p2, "should have permission p2"); assertNotNull(cache.get("role"), "Cached value for role should have been present"); assertEquals(cache.get("role").permissions(), ImmutableSet.of(p2), "Cached values incorrect"); }
Example #29
Source File: ApiKeyRealmTest.java From emodb with Apache License 2.0 | 5 votes |
@Test public void testCachedPermissionCheckByInvalidId() { // Verify permission is not granted to a non-existing ID assertFalse(_underTest.hasPermissionById("id0", mock(Permission.class))); // Verify the ID was cached assertNotNull(_underTest.getIdAuthorizationCache().get("id0")); // Test again now that the authentication info is cached assertFalse(_underTest.hasPermissionById("id0", mock(Permission.class))); }
Example #30
Source File: TablePermissionManagerDAO.java From emodb with Apache License 2.0 | 5 votes |
@Override public Set<Permission> getPermissions(String id) { checkNotNull(id, "id"); validateTable(); Map<String, Object> map = _dataStore.get(_tableName, id, ReadConsistency.STRONG); return extractPermissionsFromRecord(map); }