org.apache.shiro.subject.SimplePrincipalCollection Java Examples
The following examples show how to use
org.apache.shiro.subject.SimplePrincipalCollection.
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: ShiroCache.java From usergrid with Apache License 2.0 | 6 votes |
/** get cache for application scope */ private ScopedCache<String, V> getCacheScope( K key ) { PrincipalIdentifier principal; if ( key instanceof SimplePrincipalCollection) { SimplePrincipalCollection spc = (SimplePrincipalCollection) key; principal = (PrincipalIdentifier) spc.getPrimaryPrincipal(); } else { principal = (PrincipalIdentifier)key; } CacheScope scope = new CacheScope(new SimpleId(principal.getApplicationId(), "application")); ScopedCache<String, V> scopedCache = cacheFactory.getScopedCache(scope); return scopedCache; }
Example #2
Source File: UserNameRealm.java From Shiro-Action with MIT License | 6 votes |
public void clearAuthCacheByUserId(Integer userId) { // 获取所有 session Collection<Session> sessions = sessionDAO.getActiveSessions(); for (Session session : sessions) { // 获取 session 登录信息。 Object obj = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY); if (obj instanceof SimplePrincipalCollection) { // 强转 SimplePrincipalCollection spc = (SimplePrincipalCollection) obj; User user = new User(); BeanUtils.copyProperties(spc.getPrimaryPrincipal(), user); // 判断用户, 匹配用户ID. if (userId.equals(user.getUserId())) { this.doClearCache(spc); } } } }
Example #3
Source File: PrincipalCollectionTypeAdapter.java From arcusplatform with Apache License 2.0 | 6 votes |
@SuppressWarnings("rawtypes") @Override public JsonElement serialize(SimplePrincipalCollection src, Type typeOfSrc, JsonSerializationContext context) { JsonObject response = new JsonObject(); JsonArray principals = new JsonArray(); Set<String> realms = src.getRealmNames(); if (realms != null) { for (String realm : realms) { JsonObject jsonRealm = new JsonObject(); JsonArray realmPrincipals = new JsonArray(); Collection principalCollection = src.fromRealm(realm); if (principalCollection != null && !principalCollection.isEmpty()) { for (Object value : principalCollection) { realmPrincipals.add(context.serialize(value)); } } jsonRealm.add(realm, realmPrincipals); principals.add(jsonRealm); } } response.add(ATTR_PRINCIPAL_MAP, principals); return response; }
Example #4
Source File: ShiroTest.java From EasyEE with MIT License | 6 votes |
public static void main(String[] args) { String base64="zGkG0zevFbnIioooS3MfnnbWeBUeiZrScKVJms0CZAdJ2MYTddPkvBHGmMhvgdKA5QJk8FSb9T1Y1tFlUnnCsIvcK+iX4cfrwD7voGdU5bW9AWjwNvl3BDrAgRf+hvjrI3T5nBTFeW7uI6GzfFrIx92qER9lQ97g19Dn555uwIzf0ULvc8jICZTraLLrf2avh1hy2kUJJblO6u5IHiBbAXBNitZ6W1yjLEWmSFnb+EsEWAGB3WwV1u1HZO045LB4G57UIH4QGM0xfJjWWeahiTS4j9IAEJBbghwfL1A5pdzFiXJzzA5GF85vtP+6jLwQfGaQJyv35PvNNsDmCqFe8eUSBLji5z5y/y+yKfZk9izXiEvFjKQ5kqMqKfLMp+Vn5OuO+syc4CfJL4PLI16vwVUPV1EWAzyxUhK7DtD5OMVcLPwVtwZ11dG88wkZtjXvBymLyGCj5/Tk8gTWYsdcNKD5i8WvbMLT45S4iWsZxa/5offIiCipkkqoqvxCppJLTzBoaR/wlqoa1Bc/cvpijiJTIbSCj+iFloQRdax1mMQ"; base64 = ensurePadding(base64); byte[] decoded = Base64.decode(base64); byte[] serialized = decoded; CipherService cipherService = new AesCipherService(); if (cipherService != null) { ByteSource byteSource = cipherService.decrypt(decoded, new byte[]{-112, -15, -2, 108, -116, 100, -28, 61, -99, 121, -104, -120, -59, -58, -102, 104}); serialized = byteSource.getBytes(); } Serializer<PrincipalCollection> serializer = new DefaultSerializer<PrincipalCollection>(); ; System.out.println(serializer.deserialize(serialized)); SimplePrincipalCollection p=(SimplePrincipalCollection) serializer.deserialize(serialized); System.out.println(p.getPrimaryPrincipal()); System.out.println(p.getRealmNames()); System.out.println(p); }
Example #5
Source File: ShiroTest.java From EasyEE with MIT License | 6 votes |
public static void main(String[] args) { String base64="zGkG0zevFbnIioooS3MfnnbWeBUeiZrScKVJms0CZAdJ2MYTddPkvBHGmMhvgdKA5QJk8FSb9T1Y1tFlUnnCsIvcK+iX4cfrwD7voGdU5bW9AWjwNvl3BDrAgRf+hvjrI3T5nBTFeW7uI6GzfFrIx92qER9lQ97g19Dn555uwIzf0ULvc8jICZTraLLrf2avh1hy2kUJJblO6u5IHiBbAXBNitZ6W1yjLEWmSFnb+EsEWAGB3WwV1u1HZO045LB4G57UIH4QGM0xfJjWWeahiTS4j9IAEJBbghwfL1A5pdzFiXJzzA5GF85vtP+6jLwQfGaQJyv35PvNNsDmCqFe8eUSBLji5z5y/y+yKfZk9izXiEvFjKQ5kqMqKfLMp+Vn5OuO+syc4CfJL4PLI16vwVUPV1EWAzyxUhK7DtD5OMVcLPwVtwZ11dG88wkZtjXvBymLyGCj5/Tk8gTWYsdcNKD5i8WvbMLT45S4iWsZxa/5offIiCipkkqoqvxCppJLTzBoaR/wlqoa1Bc/cvpijiJTIbSCj+iFloQRdax1mMQ"; base64 = ensurePadding(base64); byte[] decoded = Base64.decode(base64); byte[] serialized = decoded; CipherService cipherService = new AesCipherService(); if (cipherService != null) { ByteSource byteSource = cipherService.decrypt(decoded, new byte[]{-112, -15, -2, 108, -116, 100, -28, 61, -99, 121, -104, -120, -59, -58, -102, 104}); serialized = byteSource.getBytes(); } Serializer<PrincipalCollection> serializer = new DefaultSerializer<PrincipalCollection>(); ; System.out.println(serializer.deserialize(serialized)); SimplePrincipalCollection p=(SimplePrincipalCollection) serializer.deserialize(serialized); System.out.println(p.getPrimaryPrincipal()); System.out.println(p.getRealmNames()); System.out.println(p); }
Example #6
Source File: AuthorizingRealmImplTest.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
@Test public void testAuthorization() throws Exception { buildTestAuthorizationConfig(); // Fails because the configuration requirement in nexus authorizing realm isn't initialized // thus NPE SimplePrincipalCollection principal = new SimplePrincipalCollection("username", realm.getName()); Assert.assertTrue(realm.hasRole(principal, "role")); // Verify the permission Assert.assertTrue(realm.isPermitted(principal, new WildcardPermission("app:config:read"))); // Verify other method not allowed Assert.assertFalse(realm.isPermitted(principal, new WildcardPermission("app:config:create"))); Assert.assertFalse(realm.isPermitted(principal, new WildcardPermission("app:config:update"))); Assert.assertFalse(realm.isPermitted(principal, new WildcardPermission("app:config:delete"))); // Verify other permission not allowed Assert.assertFalse(realm.isPermitted(principal, new WildcardPermission("app:ui:read"))); Assert.assertFalse(realm.isPermitted(principal, new WildcardPermission("app:ui:create"))); Assert.assertFalse(realm.isPermitted(principal, new WildcardPermission("app:ui:update"))); Assert.assertFalse(realm.isPermitted(principal, new WildcardPermission("app:ui:delete"))); }
Example #7
Source File: CachingTest.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
@Test public void testCacheClearing() throws Exception { SecuritySystem securitySystem = this.lookup(SecuritySystem.class); MockRealmB mockRealmB = (MockRealmB) this.lookup(Realm.class, "MockRealmB"); // cache should be empty to start Assert.assertTrue(mockRealmB.getAuthorizationCache().keys().isEmpty()); Assert.assertTrue(securitySystem.isPermitted( new SimplePrincipalCollection("jcool", mockRealmB.getName()), "test:heHasIt")); // now something will be in the cache, just make sure Assert.assertFalse(mockRealmB.getAuthorizationCache().keys().isEmpty()); // now if we update a user the cache should be cleared User user = securitySystem.getUser("bburton", "MockUserManagerB"); // different user, doesn't matter, in the future we should get a little more fine grained securitySystem.updateUser(user); // empty again Assert.assertTrue(mockRealmB.getAuthorizationCache().keys().isEmpty()); }
Example #8
Source File: MockRealm.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken upToken = (UsernamePasswordToken) token; String password = new String(upToken.getPassword()); String userId = upToken.getUsername(); // username == password try { if (userId.endsWith(password) && userManager.getUser(userId) != null) { return new SimpleAuthenticationInfo(new SimplePrincipalCollection(token.getPrincipal(), this.getName()), userId); } else { throw new IncorrectCredentialsException("User [" + userId + "] bad credentials."); } } catch (UserNotFoundException e) { throw new UnknownAccountException("User [" + userId + "] not found."); } }
Example #9
Source File: OktaRealm.java From okta-auth-java with Apache License 2.0 | 6 votes |
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { AuthenticationResponse authenticationResponse = ((OktaSuccessLoginToken) token).getAuthenticationResponse(); // auth already verified, just check the status if (authenticationResponse != null && authenticationResponse.getStatus() == AuthenticationStatus.SUCCESS && authenticationResponse.getSessionToken() != null) { // if we have a valid User (see below) return an AuthenticationInfo User result = authenticationResponse.getUser(); if (result != null) { SimplePrincipalCollection principalCollection = new SimplePrincipalCollection(result.getLogin(), getName()); principalCollection.add(result, getName()); return new SimpleAuthenticationInfo(principalCollection, null); } } return null; // returning null means the user is NOT authenticated }
Example #10
Source File: ShiroJwtVerifyingFilter.java From cassandra-reaper with Apache License 2.0 | 5 votes |
static Subject getJwtSubject(Subject nonJwt, ServletRequest req, ServletResponse res) { return null != nonJwt.getPrincipal() && (nonJwt.isRemembered() || nonJwt.isAuthenticated()) ? nonJwt : new WebSubject.Builder(req, res) .principals(new SimplePrincipalCollection(getJwtUser(req).get(), "jwtRealm")) .buildSubject(); }
Example #11
Source File: UserPrincipalsHelperTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
private PrincipalCollection getPrincipalsWithNoUsrMgrPrimary() { final SimplePrincipalCollection principals = new SimplePrincipalCollection(PRIMARY_PRINCIPAL, NO_USER_MANAGER_REALM); principals.addAll(getPrincipals()); return principals; }
Example #12
Source File: UserPrincipalsHelperTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Test public void testGetUserStatus_NoUserManagerFound() { final SimplePrincipalCollection principals = new SimplePrincipalCollection(); principals.add(PRIMARY_PRINCIPAL, "foo"); principals.add(PRIMARY_PRINCIPAL, "boo"); principals.add(PRIMARY_PRINCIPAL, "hoo"); try { underTest.getUserStatus(principals); } catch (UserNotFoundException userNotFoundEx) { assertThat(userNotFoundEx.getMessage(), CoreMatchers.is("User not found: JoeUser; User-manager not found for realm(s): [foo, boo, hoo]")); } }
Example #13
Source File: UserPrincipalsHelperTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Test public void testFindUserManagerForPrincipals_NotFound() { final SimplePrincipalCollection principals = new SimplePrincipalCollection(); principals.add(PRIMARY_PRINCIPAL, "foo"); try { underTest.findUserManager(principals); } catch (NoSuchUserManagerException noSuchUserEx) { assertThat(noSuchUserEx.getMessage(), CoreMatchers.is("User-manager not found for realm(s): [foo]")); } }
Example #14
Source File: ShiroUtils.java From supplierShop with MIT License | 5 votes |
public static void setSysUser(SysUser user) { Subject subject = getSubject(); PrincipalCollection principalCollection = subject.getPrincipals(); String realmName = principalCollection.getRealmNames().iterator().next(); PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(user, realmName); // 重新加载Principal subject.runAs(newPrincipalCollection); }
Example #15
Source File: AbstractPermittingAuthorizingRealm.java From super-cloudops with Apache License 2.0 | 5 votes |
/** * Setup merge authorized roles and permission string. * * @param authzInfo * @return */ @SuppressWarnings("unchecked") protected SimpleAuthorizationInfo mergeAuthorizedString(PrincipalCollection principals, SimpleAuthorizationInfo authzInfo) { // Retrieve principal account info. SimplePrincipalCollection principals0 = (SimplePrincipalCollection) principals; Map<String, String> principalMap = (Map<String, String>) principals0.asList().get(1); // Principal roles. String roles = principalMap.get(KEY_ROLES_ATTRIBUTE_NAME); mergeRoles(authzInfo, splitPermitString(roles)); // Principal permissions. String permissions = principalMap.get(KEY_PERMITS_ATTRIBUTE_NAME); return mergePermissions(authzInfo, splitPermitString(permissions)); }
Example #16
Source File: ShiroCustomRealm.java From phone with Apache License 2.0 | 5 votes |
/** * 更新用户授权信息缓存. */ public void clearCachedAuthorizationInfo(String principal) { if (logger.isDebugEnabled()) { logger.debug("clearCachedAuthorizationInfo(String) - start"); //$NON-NLS-1$ } SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName()); clearCachedAuthorizationInfo(principals); if (logger.isDebugEnabled()) { logger.debug("clearCachedAuthorizationInfo(String) - end"); //$NON-NLS-1$ } }
Example #17
Source File: ApiKeyAuthenticationInfo.java From emodb with Apache License 2.0 | 5 votes |
public ApiKeyAuthenticationInfo(String authenticationId, ApiKey apiKey, String realm) { checkNotNull(authenticationId, "authenticationId"); checkNotNull(apiKey, "apiKey"); checkNotNull(realm, "realm"); // Identify the principal by API key PrincipalWithRoles principal = new PrincipalWithRoles(authenticationId, apiKey.getId(), apiKey.getRoles()); _principals = new SimplePrincipalCollection(principal, realm); // Use the API key as the credentials _credentials = authenticationId; }
Example #18
Source File: GuavaCacheManager.java From emodb with Apache License 2.0 | 5 votes |
private String extractStringKey(Object key) { if(key instanceof SimplePrincipalCollection) { SimplePrincipalCollection coll = (SimplePrincipalCollection) key; return "SimplePrincipalCollection:" + coll.getPrimaryPrincipal(); } else { return key.toString(); } }
Example #19
Source File: AbstractPermittingAuthorizingRealm.java From super-cloudops with Apache License 2.0 | 5 votes |
/** * New create and merge {@link IamPrincipalInfo} to * {@link PrincipalCollection} * * @param principal * @param info * @return */ protected PrincipalCollection createPermitPrincipalCollection(String principal, IamPrincipalInfo info) { notNull(principal, "Principal can't null"); notNull(info, "IamPrincipalInfo can't null"); // Authenticate attributes.(roles/permissions/rememberMe) Map<String, String> principalMap = info.getAttributes(); principalMap.put(KEY_ROLES_ATTRIBUTE_NAME, info.getRoles()); principalMap.put(KEY_PERMITS_ATTRIBUTE_NAME, info.getPermissions()); // Create simple-authentication info List<Object> principals = CollectionUtils.asList(principal, principalMap); return new SimplePrincipalCollection(principals, getName()); }
Example #20
Source File: PrincipalCollectionTypeHandlerTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Test public void shouldSetEncryptedPrincipalCollectionBytes() throws Exception { when(databaseCipher.encrypt(any(byte[].class))).thenReturn(PRINCIPAL_COLLECTION_BYTES); principalCollectionTypeHandler.setNonNullParameter(preparedStatement, AN_INDEX, new SimplePrincipalCollection("p1", "r1"), null); verify(preparedStatement).setBytes(AN_INDEX, PRINCIPAL_COLLECTION_BYTES); }
Example #21
Source File: UserPrincipalsHelperTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
private PrincipalCollection getPrincipals() { final SimplePrincipalCollection principals = new SimplePrincipalCollection(); //Set the primary principal principals.add(PRIMARY_PRINCIPAL, userManagerAlpha.getAuthenticationRealmName()); principals.add(PRIMARY_PRINCIPAL, userManagerBeta.getAuthenticationRealmName()); return principals; }
Example #22
Source File: ExternalRoleMappedTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Test public void testUserHasPermissionFromExternalRole() throws Exception { SecuritySystem securitySystem = this.lookup(SecuritySystem.class); Map<String, String> properties = new HashMap<String, String>(); properties.put(WildcardPrivilegeDescriptor.P_PATTERN, "permissionOne:read"); securitySystem.getAuthorizationManager("default").addPrivilege(new Privilege( "randomId", "permissionOne", "permissionOne", WildcardPrivilegeDescriptor.TYPE, properties, false)); securitySystem.getAuthorizationManager("default").addRole(new Role("mockrole1", "mockrole1", "mockrole1", "default", false, null, Collections.singleton("randomId"))); // add MockRealm to config RealmManager realmManager = lookup(RealmManager.class); RealmConfiguration realmConfiguration = new TestRealmConfiguration(); realmConfiguration.setRealmNames(ImmutableList.of("Mock", AuthorizingRealmImpl.NAME)); realmManager.setConfiguration(realmConfiguration); // jcohen has the role mockrole1, there is also test role with the same ID, which means jcohen automaticly has // this test role PrincipalCollection jcohen = new SimplePrincipalCollection("jcohen", MockRealm.NAME); try { securitySystem.checkPermission(jcohen, "permissionOne:invalid"); Assert.fail("Expected AuthorizationException"); } catch (AuthorizationException e) { // expected } securitySystem.checkPermission(jcohen, "permissionOne:read"); // throws on error, so this is all we need to do }
Example #23
Source File: DefaultSecuritySystemTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Test public void testAuthorization() throws Exception { SecuritySystem securitySystem = this.getSecuritySystem(); PrincipalCollection principal = new SimplePrincipalCollection("jcool", "ANYTHING"); try { securitySystem.checkPermission(principal, "INVALID-ROLE:*"); fail("expected: AuthorizationException"); } catch (AuthorizationException e) { // expected } securitySystem.checkPermission(principal, "test:read"); }
Example #24
Source File: OrientApiKeyStore.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Subscribe @AllowConcurrentEvents public void on(final UserPrincipalsExpired event) { final String userId = event.getUserId(); if (userId != null) { deleteApiKeys(new SimplePrincipalCollection(userId, event.getSource())); } else { purgeApiKeys(); } }
Example #25
Source File: ApiKeyStoreImpl.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Subscribe @AllowConcurrentEvents public void on(final UserPrincipalsExpired event) { final String userId = event.getUserId(); if (userId != null) { deleteApiKeys(new SimplePrincipalCollection(userId, event.getSource())); } else { purgeApiKeys(); } }
Example #26
Source File: AbstractSSOComponent.java From nano-framework with Apache License 2.0 | 5 votes |
protected boolean validationPrincipalsSession(final Object value) { if(value != null && value instanceof SimplePrincipalCollection) { if(!((SimplePrincipalCollection) value).isEmpty()) { return true; } } return false; }
Example #27
Source File: AuthenticationComponentImpl.java From nano-framework with Apache License 2.0 | 5 votes |
@Override public Map<String, Object> findUserInfo() { try { final HttpServletRequest request = HttpContext.get(HttpServletRequest.class); final String principal = (String) ((SimplePrincipalCollection) request.getSession().getAttribute(PRINCIPALS_SESSION_KEY)).getPrimaryPrincipal(); final Map<String, Object> map = HttpStatus.OK.to().beanToMap(); map.put("username", principal); return map; } catch (final Throwable e) { LOGGER.error("Find user info error: {}", e.getMessage()); return ResultMap.create("Find user info error: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR).beanToMap(); } }
Example #28
Source File: CreateShiroAuthProviderTest.java From vertx-auth with Apache License 2.0 | 5 votes |
@Override public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { return new AuthenticationInfo() { @Override public PrincipalCollection getPrincipals() { return new SimplePrincipalCollection(token.getPrincipal(), getClass().getName()); } @Override public Object getCredentials() { return token.getCredentials(); } }; }
Example #29
Source File: RedisCacheTest.java From shiro-redis with MIT License | 5 votes |
private void scaffold() { RedisManager redisManager = scaffoldStandaloneRedisManager(); prefix = scaffoldPrefix(); redisCache = scaffoldRedisCache(redisManager, new StringSerializer(), new ObjectSerializer(), prefix, NumberUtils.toInt(properties.getProperty("cacheManager.expire")), RedisCacheManager.DEFAULT_PRINCIPAL_ID_FIELD_NAME); redisCacheWithPrincipalIdFieldName = scaffoldRedisCache(redisManager, new StringSerializer(), new ObjectSerializer(), prefix, NumberUtils.toInt(properties.getProperty("cacheManager.expire")), properties.getProperty("cacheManager.principalIdFieldName")); redisCacheWithEmptyPrincipalIdFieldName = scaffoldRedisCache(redisManager, new StringSerializer(), new ObjectSerializer(), prefix, NumberUtils.toInt(properties.getProperty("cacheManager.expire")), ""); redisCacheWithStrings = scaffoldRedisCache(redisManager, new StringSerializer(), new ObjectSerializer(), prefix, NumberUtils.toInt(properties.getProperty("cacheManager.expire")), properties.getProperty("cacheManager.principalIdFieldName")); user1 = scaffoldAuthKey(scaffoldUser()); user2 = scaffoldAuthKey(scaffoldUser()); user3 = scaffoldAuthKey(scaffoldUser()); user4 = new SimplePrincipalCollection(Faker.instance().gameOfThrones().character(), Faker.instance().gameOfThrones().city()); users1_2_3 = scaffoldKeys(user1, user2, user3); }
Example #30
Source File: TestIniRealm.java From thymeleaf-extras-shiro with Apache License 2.0 | 5 votes |
@Override protected void add(SimpleAccount account) { String username = (String) account.getPrincipals().getPrimaryPrincipal(); // Let's add some additional principals for testing SimplePrincipalCollection principalCollection = new SimplePrincipalCollection(); principalCollection.addAll(account.getPrincipals()); principalCollection.add(counter.getAndIncrement(), "integerRealm"); TestObjPrincipal objPrinc = new TestObjPrincipal(username.toUpperCase() + " " + username.toUpperCase()); principalCollection.add(objPrinc, "objRealm"); account.setPrincipals(principalCollection); super.add(account); }