Example usage for org.apache.shiro.realm Realm getName

List of usage examples for org.apache.shiro.realm Realm getName

Introduction

In this page you can find the example usage for org.apache.shiro.realm Realm getName.

Prototype

String getName();

Source Link

Document

Returns the (application-unique) name assigned to this Realm.

Usage

From source file:cn.powerdash.libsystem.common.security.SecurityContext.java

License:Open Source License

/**
 * Description: ??//from   ww  w.j av a2 s .co  m
 * 
 * @param userId
 */
public static void clearAuthzCache(String userName) {
    RealmSecurityManager sm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
    for (Realm realm : sm.getRealms()) {
        if (realm instanceof ShiroJdbcRealm) {
            ShiroJdbcRealm jdbcRealm = (ShiroJdbcRealm) realm;
            SimplePrincipalCollection spc = new SimplePrincipalCollection(userName, realm.getName());
            jdbcRealm.clearAuthorizationCache(spc);
        }
    }
    LOGGER.info("Authorization cache cleared for user: {}", userName);
}

From source file:cn.powerdash.libsystem.common.security.SecurityContext.java

License:Open Source License

/**
 * Description: ??//from w  w w. j a v  a2  s. c  o m
 * 
 * @param userId
 */
public static void clearAuthcCache(String userName) {
    RealmSecurityManager sm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
    for (Realm realm : sm.getRealms()) {
        if (realm instanceof ShiroJdbcRealm) {
            ShiroJdbcRealm jdbcRealm = (ShiroJdbcRealm) realm;
            SimplePrincipalCollection spc = new SimplePrincipalCollection(userName, realm.getName());
            jdbcRealm.clearAuthenticationCache(spc);
        }
    }
}

From source file:com.sonicle.webtop.core.app.shiro.ShiroUtils.java

License:Open Source License

public static Realm getRealmByName(String name) {
    RealmSecurityManager realmMgr = getRealmSecurityManager();
    for (Realm realm : realmMgr.getRealms()) {
        if (realm.getName().equals(name))
            return realm;
    }//from   www  .java  2 s .  c o  m
    return null;
}

From source file:ddf.security.pep.redaction.plugin.test.RedactionPluginTest.java

License:Open Source License

@Before
public void setup() {
    plugin = new RedactionPlugin();

    QueryRequestImpl request = new QueryRequestImpl(new Query() {
        @Override//from w ww .  j  ava  2s.  c  o m
        public int getStartIndex() {
            return 0;
        }

        @Override
        public int getPageSize() {
            return 10;
        }

        @Override
        public SortBy getSortBy() {
            return null;
        }

        @Override
        public boolean requestsTotalResultsCount() {
            return false;
        }

        @Override
        public long getTimeoutMillis() {
            return 0;
        }

        @Override
        public boolean evaluate(Object o) {
            return true;
        }

        @Override
        public Object accept(FilterVisitor filterVisitor, Object o) {
            return null;
        }
    });

    Map<String, Serializable> properties = new HashMap<String, Serializable>();

    Realm realm = new SimpleAuthzRealm();
    ((SimpleAuthzRealm) realm).setAuthorizationInfo(new AuthorizationInfo() {
        @Override
        public Collection<String> getRoles() {
            return null;
        }

        @Override
        public Collection<String> getStringPermissions() {
            return null;
        }

        @Override
        public Collection<Permission> getObjectPermissions() {
            Collection<Permission> permissions = new ArrayList<Permission>();
            KeyValuePermission keyValuePermission = new KeyValuePermission("FineAccessControls");
            keyValuePermission.addValue("A");
            keyValuePermission.addValue("B");
            KeyValuePermission keyValuePermission1 = new KeyValuePermission("CountryOfAffiliation");
            keyValuePermission1.addValue("GBR");
            permissions.add(keyValuePermission);
            permissions.add(keyValuePermission1);
            return permissions;
        }
    });
    Collection<org.apache.shiro.realm.Realm> realms = new ArrayList<org.apache.shiro.realm.Realm>();
    realms.add(realm);

    DefaultSecurityManager manager = new DefaultSecurityManager();
    manager.setRealms(realms);

    SimplePrincipalCollection principalCollection = new SimplePrincipalCollection(new Principal() {
        @Override
        public String getName() {
            return "testuser";
        }
    }, realm.getName());

    Subject subject = new MockSubject(manager, principalCollection);
    properties.put(SecurityConstants.SECURITY_SUBJECT, subject);
    request.setProperties(properties);

    incomingResponse = new QueryResponseImpl(request);

    ResultImpl result1 = new ResultImpl(getHighMetacard());
    ResultImpl result2 = new ResultImpl(getLowMetacard());
    ResultImpl result3 = new ResultImpl(getLowMetacardReleaseToOne());
    incomingResponse.addResult(result1, false);
    incomingResponse.addResult(result2, false);
    incomingResponse.addResult(result3, true);

    ((SimpleAuthzRealm) realm).setMatchAllMappings(Arrays.asList("FineAccessControls=rule"));
    ((SimpleAuthzRealm) realm).setMatchOneMappings(Arrays.asList("CountryOfAffiliation=country"));
}

From source file:ddf.security.service.impl.SecurityManagerImplTest.java

License:Open Source License

/**
 * Creates mock objects and uses those to pass through the system when an authentication token is
 * used./* w  w  w .  j  a v a2  s .  c  o m*/
 *
 * @throws SecurityServiceException
 */
@Test
public void testAuthToken() throws SecurityServiceException {
    // mock setup
    SimplePrincipalCollection principals = new SimplePrincipalCollection();
    SecurityToken secToken = new SecurityToken();
    principals.add(secToken, REALM_NAME);

    AuthenticationToken authToken = mock(AuthenticationToken.class);
    when(authToken.getCredentials()).thenReturn("testUser");
    AuthenticationInfo info = mock(AuthenticationInfo.class);
    when(info.getPrincipals()).thenReturn(principals);

    // realm
    Realm realm = mock(Realm.class);
    when(realm.getAuthenticationInfo(authToken)).thenReturn(info);
    when(realm.supports(authToken)).thenReturn(Boolean.TRUE);
    when(realm.getName()).thenReturn(REALM_NAME);

    SecurityManagerImpl manager = new SecurityManagerImpl();
    manager.setRealms(Arrays.asList(new Realm[] { realm }));
    Subject subject = manager.getSubject(authToken);
    assertNotNull(subject);
}

From source file:io.bootique.shiro.ShiroModuleIT.java

License:Apache License

protected Realm mockRealm() {
    Realm mockRealm = mock(Realm.class);
    when(mockRealm.getName()).thenReturn("TestRealm");
    when(mockRealm.supports(any(AuthenticationToken.class))).then(invocation -> {
        AuthenticationToken token = invocation.getArgument(0);
        return token instanceof UsernamePasswordToken;
    });//from   w w w. j  a  v a  2  s  . c  o m

    when(mockRealm.getAuthenticationInfo(any(AuthenticationToken.class))).then(invocation -> {

        UsernamePasswordToken token = invocation.getArgument(0);
        if (!"password".equals(new String(token.getPassword()))) {
            throw new AuthenticationException("Bad password");
        }

        return new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), "TestRealm");
    });

    return mockRealm;
}

From source file:io.vertx.ext.auth.shiro.impl.ShiroAuthProviderImpl.java

License:Open Source License

public ShiroAuthProviderImpl(Vertx vertx, Realm realm) {
    this.vertx = vertx;
    this.securityManager = new DefaultSecurityManager(realm);
    this.realmName = realm.getName();
}

From source file:org.apache.isis.security.shiro.ShiroAuthenticatorOrAuthorizor.java

License:Apache License

/**
 * This method has protected visibility to allow for custom implementations
 * in the future that might obtain the list of roles for a principal from
 * somewherte other than Shiro's {@link RealmSecurityManager}.
 *//*from   w w  w . ja va2s.c  om*/
protected List<String> getRoles(final AuthenticationToken token) {
    final List<String> roles = Lists.newArrayList();

    RealmSecurityManager securityManager = getSecurityManager();
    if (securityManager == null) {
        return roles;
    }

    final Collection<Realm> realms = securityManager.getRealms();
    for (final Realm realm : realms) {
        if (realm.supports(token)) {
            continue;
        }
        final AuthenticationInfo authenticationInfo = realm.getAuthenticationInfo(token);
        if (authenticationInfo instanceof AuthorizationInfo) {
            final AuthorizationInfo authorizationInfo = (AuthorizationInfo) authenticationInfo;
            final Collection<String> realmRoles = authorizationInfo.getRoles();
            for (final String role : realmRoles) {
                roles.add(realm.getName() + ":" + role);
            }
        }
    }
    return roles;
}

From source file:org.apache.zeppelin.rest.SecurityRestApi.java

License:Apache License

/**
 * Get userlist/*  www.  j av  a2s . c  o  m*/
 * Returns list of all user from available realms
 *
 * @return 200 response
 */
@GET
@Path("userlist/{searchText}")
public Response getUserList(@PathParam("searchText") final String searchText) {

    List<String> usersList = new ArrayList<>();
    List<String> rolesList = new ArrayList<>();
    try {
        GetUserList getUserListObj = new GetUserList();
        Collection realmsList = SecurityUtils.getRealmsList();
        if (realmsList != null) {
            for (Iterator<Realm> iterator = realmsList.iterator(); iterator.hasNext();) {
                Realm realm = iterator.next();
                String name = realm.getName();
                if (name.equals("iniRealm")) {
                    usersList.addAll(getUserListObj.getUserList((IniRealm) realm));
                    rolesList.addAll(getUserListObj.getRolesList((IniRealm) realm));
                } else if (name.equals("ldapRealm")) {
                    usersList.addAll(getUserListObj.getUserList((JndiLdapRealm) realm, searchText));
                } else if (name.equals("activeDirectoryRealm")) {
                    usersList.addAll(getUserListObj.getUserList((ActiveDirectoryGroupRealm) realm, searchText));
                } else if (name.equals("jdbcRealm")) {
                    usersList.addAll(getUserListObj.getUserList((JdbcRealm) realm));
                }
            }
        }
    } catch (Exception e) {
        LOG.error("Exception in retrieving Users from realms ", e);
    }
    List<String> autoSuggestUserList = new ArrayList<>();
    List<String> autoSuggestRoleList = new ArrayList<>();
    Collections.sort(usersList);
    Collections.sort(rolesList);
    Collections.sort(usersList, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            if (o1.matches(searchText + "(.*)") && o2.matches(searchText + "(.*)")) {
                return 0;
            } else if (o1.matches(searchText + "(.*)")) {
                return -1;
            }
            return 0;
        }
    });
    int maxLength = 0;
    for (String user : usersList) {
        if (StringUtils.containsIgnoreCase(user, searchText)) {
            autoSuggestUserList.add(user);
            maxLength++;
        }
        if (maxLength == 5) {
            break;
        }
    }

    for (String role : rolesList) {
        if (StringUtils.containsIgnoreCase(role, searchText)) {
            autoSuggestRoleList.add(role);
        }
    }

    Map<String, List> returnListMap = new HashMap<>();
    returnListMap.put("users", autoSuggestUserList);
    returnListMap.put("roles", autoSuggestRoleList);

    return new JsonResponse<>(Response.Status.OK, "", returnListMap).build();
}

From source file:org.apache.zeppelin.service.ShiroAuthenticationService.java

License:Apache License

/**
 * Return the roles associated with the authenticated user if any otherwise returns empty set.
 * TODO(prasadwagle) Find correct way to get user roles (see SHIRO-492)
 *
 * @return shiro roles//from   w  w  w  .ja  va  2  s  .c om
 */
@Override
public Set<String> getAssociatedRoles() {
    Subject subject = org.apache.shiro.SecurityUtils.getSubject();
    HashSet<String> roles = new HashSet<>();
    Map allRoles = null;

    if (subject.isAuthenticated()) {
        Collection realmsList = getRealmsList();
        for (Iterator<Realm> iterator = realmsList.iterator(); iterator.hasNext();) {
            Realm realm = iterator.next();
            String name = realm.getClass().getName();
            if (name.equals("org.apache.shiro.realm.text.IniRealm")) {
                allRoles = ((IniRealm) realm).getIni().get("roles");
                break;
            } else if (name.equals("org.apache.zeppelin.realm.LdapRealm")) {
                try {
                    AuthorizationInfo auth = ((LdapRealm) realm).queryForAuthorizationInfo(
                            new SimplePrincipalCollection(subject.getPrincipal(), realm.getName()),
                            ((LdapRealm) realm).getContextFactory());
                    if (auth != null) {
                        roles = new HashSet<>(auth.getRoles());
                    }
                } catch (NamingException e) {
                    LOGGER.error("Can't fetch roles", e);
                }
                break;
            } else if (name.equals("org.apache.zeppelin.realm.ActiveDirectoryGroupRealm")) {
                allRoles = ((ActiveDirectoryGroupRealm) realm).getListRoles();
                break;
            }
        }
        if (allRoles != null) {
            Iterator it = allRoles.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry pair = (Map.Entry) it.next();
                if (subject.hasRole((String) pair.getKey())) {
                    roles.add((String) pair.getKey());
                }
            }
        }
    }
    return roles;
}