List of usage examples for org.apache.shiro.authc SimpleAccount addRole
public void addRole(Collection<String> roles)
From source file:com.enioka.jqm.webui.shiro.JpaRealm.java
License:Open Source License
private SimpleAccount getUser(String login) { EntityManager em = null;//from w w w . j a va 2 s . co m try { em = Helpers.getEm(); RUser user = em.createQuery("SELECT u FROM RUser u WHERE UPPER(u.login) = UPPER(:l)", RUser.class) .setParameter("l", login).getSingleResult(); // Credential is a password - in token, it is as a char array SimpleAccount res = new SimpleAccount(user.getLogin(), user.getPassword(), getName()); if (user.getExpirationDate() != null) { res.setCredentialsExpired(user.getExpirationDate().before(Calendar.getInstance())); } else { // No limit = never expires res.setCredentialsExpired(false); } if (user.getHashSalt() != null) { res.setCredentialsSalt(ByteSource.Util.bytes(Hex.decode(user.getHashSalt()))); } else { res.setCredentialsSalt(null); } res.setLocked(user.getLocked()); // Roles for (RRole r : user.getRoles()) { res.addRole(r.getName()); for (RPermission p : r.getPermissions()) { res.addStringPermission(p.getName()); } } return res; } catch (NoResultException e) { // No such user in realm return null; } catch (RuntimeException e) { e.printStackTrace(); throw e; } finally { em.close(); } }
From source file:com.rainy.shiro.demo.MyRealm.java
License:Apache License
/** * Simulates a call to an underlying data store - in a 'real' application, this call would communicate with * an underlying data store via an EIS API (JDBC, JPA, Hibernate, etc). * <p/>//w w w. ja va 2 s . com * Note that when implementing your own realm, there is no need to check against a password (or other credentials) * in this method. The {@link org.apache.shiro.realm.AuthenticatingRealm AuthenticatingRealm} superclass will do * that automatically via the use of a configured * {@link org.apache.shiro.authc.credential.CredentialsMatcher CredentialsMatcher} (see this example's corresponding * {@code shiro.ini} file to see a configured credentials matcher). * <p/> * All that is required is that the account information include directly the credentials found in the EIS. * * @param username the username for the account data to retrieve * @return the Account information corresponding to the specified username: */ protected SimpleAccount getAccount(String username) { //just create a dummy. A real app would construct one based on EIS access. SimpleAccount account = new SimpleAccount(username, "sha256EncodedPasswordFromDatabase", getName()); //simulate some roles and permissions: account.addRole("user"); account.addRole("admin"); //most applications would assign permissions to Roles instead of users directly because this is much more //flexible (it is easier to configure roles and then change role-to-user assignments than it is to maintain // permissions for each user). // But these next lines assign permissions directly to this trivial account object just for simulation's sake: account.addStringPermission("blogEntry:edit"); //this user is allowed to 'edit' _any_ blogEntry //fine-grained instance level permission: account.addStringPermission("printer:print:laserjet2000"); //allowed to 'print' to the 'printer' identified //by the id 'laserjet2000' return account; }
From source file:org.apache.zeppelin.realm.jwt.KnoxJwtRealm.java
License:Apache License
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) { JWTAuthenticationToken upToken = (JWTAuthenticationToken) token; if (validateToken(upToken.getToken())) { try {/*w w w. ja v a2s. c o m*/ SimpleAccount account = new SimpleAccount(getName(upToken), upToken.getToken(), getName()); account.addRole(mapGroupPrincipals(getName(upToken))); return account; } catch (ParseException e) { LOGGER.error("ParseException in doGetAuthenticationInfo", e); } } return null; }
From source file:org.apache.zeppelin.realm.kerberos.KerberosRealm.java
License:Apache License
/** * This is called when Kerberos authentication is done and a {@link KerberosToken} has * been acquired.//from w ww . ja v a 2 s . c om * This function returns a Shiro {@link SimpleAccount} based on the {@link KerberosToken} * provided. Null otherwise. */ @Override protected AuthenticationInfo doGetAuthenticationInfo( org.apache.shiro.authc.AuthenticationToken authenticationToken) throws org.apache.shiro.authc.AuthenticationException { if (null != authenticationToken) { KerberosToken kerberosToken = (KerberosToken) authenticationToken; SimpleAccount account = new SimpleAccount(kerberosToken.getPrincipal(), kerberosToken.getCredentials(), kerberosToken.getClass().getName()); account.addRole(mapGroupPrincipals((String) kerberosToken.getPrincipal())); return account; } return null; }
From source file:org.i3xx.step.zero.security.impl.shiro.NaMyRealm.java
License:Apache License
protected SimpleAccount getAccount(String username, Object credentials) { //TODO: Remove the System.out System.out.println("get account user: " + username); //Account account = new SimpleAccount(username, "sha256EncodedPasswordFromDatabase", getName()); if (username == null) throw new AccountException("Null usernames are not allowed by this realm."); //Account account=_store.getAccounts().get(username); //if (account == null) throw new UnknownAccountException("No account found for user [" + username + "]"); String hash = _hash/*account.getPasswordHash()*/; ByteSource salt = new SimpleByteSource(_salt/*account.getSalt()*/); SimpleAccount account = new SimpleAccount(username, hash, salt, getName()); //SimpleAccount account = new SimpleAccount(username, "sha256EncodedPasswordFromDatabase", getName()); account.addRole("user"); account.addRole("admin"); account.addStringPermission("blogEntry:edit"); account.addStringPermission("printer:print:laserjet"); //The password or private key account.setCredentials(credentials); return account; }
From source file:org.ms123.common.permission.PermissionServiceImpl.java
License:Open Source License
public boolean loginInternal(String namespace, String username, String password) { SimpleAccount sa = new SimpleAccount(username, password, namespace); org.ms123.common.system.thread.ThreadContext.loadThreadContext(namespace, username); sa.addRole("admin"); MyRealm realm = new MyRealm(); realm.add(sa);/*w w w . j a va2 s. c o m*/ DefaultSecurityManager sm = createSecurityManager(realm); Subject currentUser = newSubject(sm); UsernamePasswordToken token = new UsernamePasswordToken("admin", "admin"); try { currentUser.login(token); } catch (UnknownAccountException uae) { info("2.There is no user with username of " + token.getPrincipal() + "/" + uae); return false; } catch (IncorrectCredentialsException ice) { info("Password for account " + token.getPrincipal() + " was incorrect!"); return false; } catch (LockedAccountException lae) { info("The account for username " + token.getPrincipal() + " is locked. " + "Please contact your administrator to unlock it."); return false; } catch (AuthenticationException ae) { ae.printStackTrace(); return false; } return true; }
From source file:org.ms123.common.permission.PermissionServiceImpl.java
License:Open Source License
public boolean login(String namespace, String username, String password) { info("PermissionServiceImpl:login:" + username + "/" + password + "/namespace:" + namespace + "/RC:" + org.ms123.common.system.thread.ThreadContext.getThreadContext()); if (org.ms123.common.system.thread.ThreadContext.getThreadContext() == null) { org.ms123.common.system.thread.ThreadContext.loadThreadContext(namespace, username); }// www.ja v a 2 s.c om Map userProps = null; try { if (noAuth()) { userProps = new HashMap(); userProps.put("admin", true); username = m_authService.getAdminUser(); } else { userProps = m_authService.getUserProperties(username); } } catch (Exception e) { e.printStackTrace(); return false; } if (userProps == null) { info("1.There is no user with username of " + username); return false; } debug("PermissionServiceImpl.login:" + userProps); String _password = (String) userProps.get("password"); if (_password != null) { if (password == null) password = ""; if (!_password.trim().equals(password.trim()) && !(_password.equals("") && password.equals("admin"))) { debug("_password:" + password + "/" + _password + "|"); throw new RuntimeException("Login failed"); } } SimpleAccount sa = new SimpleAccount(username, password, namespace); if ("guest".equals(username) && "guest".equals(password)) { sa.addRole("global.guest"); } boolean isAdmin = getBoolean(userProps.get("admin"), false); if (isAdmin) { sa.addRole("admin"); } else { try { //List<Map> permissions = getPermissions(userProps, "^.*:entities:.*"); List<Map> permissions = getPermissions(userProps, null); Iterator<Map> pit = permissions.iterator(); while (pit.hasNext()) { Map p = pit.next(); String permission = p.get("permission") + ":" + p.get("actions"); debug("\tpermission:" + permission); sa.addObjectPermission( new WildcardPermission((String) p.get("permission"), (String) p.get("actions"))); } sa.addObjectPermission(new WildcardPermission("*:entities:aid", "read")); sa.addObjectPermission(new WildcardPermission("*:entities:*:filter", "read,write")); sa.addObjectPermission(new WildcardPermission("*:entities:*:importing", "read,write")); sa.addObjectPermission(new WildcardPermission("*:entities:*:report", "read,write")); sa.addObjectPermission(new WildcardPermission("global", "read")); //if( getBoolean(userProps.get("team_manage"), false)){ sa.addObjectPermission(new WildcardPermission("*:entities:*:teamintern", "read,write")); sa.addObjectPermission(new WildcardPermission("*:entities:*:team", "read")); sa.addObjectPermission(new WildcardPermission("*:entities:*:user:userid", "read")); //} sa.addObjectPermission(new WildcardPermission("*:entities:*:enumeration", "read")); } catch (Exception e) { e.printStackTrace(); return false; } } System.out.println("isAdmin:" + isAdmin); MyRealm realm = new MyRealm(); realm.add(sa); DefaultSecurityManager sm = createSecurityManager(realm); Subject currentUser = newSubject(sm); UsernamePasswordToken token = new UsernamePasswordToken(username, password); try { currentUser.login(token); } catch (UnknownAccountException uae) { info("2.There is no user with username of " + token.getPrincipal() + "/" + uae); return false; } catch (IncorrectCredentialsException ice) { info("Password for account " + token.getPrincipal() + " was incorrect!"); return false; } catch (LockedAccountException lae) { info("The account for username " + token.getPrincipal() + " is locked. " + "Please contact your administrator to unlock it."); return false; } catch (AuthenticationException ae) { ae.printStackTrace(); return false; } return true; }
From source file:org.pepstock.jem.gwt.server.security.Authorizator.java
License:Open Source License
/** * Methods usually used by Shiro to get all authorizations. * /*w w w .j a v a2s . c om*/ * @param realm * realm which is the caller * @param principals * principals to check * @return account with all roles and permissions * @throws JemException * if any errors occurs */ public AuthorizationInfo doGetAuthorizationInfo(Realm realm, PrincipalCollection principals) throws JemException { // gets user object from principal User user = (User) getAvailablePrincipal(realm, principals); // creates account (without credentials) SimpleAccount account = new SimpleAccount(user, "nothing", realm.getName()); // creates Hazelcast predicate to extract all roles and permissions // assigned to user RolesQueuePredicate predicate = new RolesQueuePredicate(); predicate.setUser(user); try { // gets map and performs predicate! IMap<String, Role> roles = SharedObjects.getInstance().getHazelcastClient().getMap(Queues.ROLES_MAP); Collection<Role> myroles = null; boolean isLock = false; Lock lock = SharedObjects.getInstance().getHazelcastClient().getLock(Queues.ROLES_MAP_LOCK); try { isLock = lock.tryLock(10, TimeUnit.SECONDS); if (isLock) { myroles = roles.values(predicate); } else { throw new MessageException(UserInterfaceMessage.JEMG022E, Queues.ROLES_MAP); } } catch (InterruptedException e) { throw new MessageException(UserInterfaceMessage.JEMG022E, e, Queues.ROLES_MAP); } finally { if (isLock) { lock.unlock(); } } Collection<Permission> perms = new ArrayList<Permission>(); // scans roles for (Role role : myroles) { // adds roles account.addRole(role.getName()); // scans permissions for (String permission : role.getPermissions()) { // if the permission is for SEARCH, uses a regular // expression permission if (permission.startsWith(Permissions.SEARCH) || permission.startsWith(Permissions.DATASOURCES) || permission.startsWith(Permissions.FILES_READ) || permission.startsWith(Permissions.FILES_WRITE) || permission.startsWith(Permissions.FILES_EXECUTE) || permission.startsWith(Permissions.SURROGATE)) { RegExpPermission perm = new RegExpPermission(permission); account.addObjectPermission(perm); perms.add(perm); } else { // otherwise a wildcard permisison account.addStringPermission(permission); // at the moment not added } } } user.setPermissions(perms); } catch (MessageException e) { LogAppl.getInstance().emit(UserInterfaceMessage.JEMG031E, e, user.getId()); } return account; }
From source file:org.wicketstuff.shiro.example.realm.SillyRealm.java
License:Apache License
/** * Simulates a call to an underlying data store - in a 'real' application, this call would * communicate with an underlying data store via an EIS API (JDBC, JPA, Hibernate, etc). * <p/>// w ww . ja v a 2 s . c o m * Note that when implementing your own realm, there is no need to check against a password (or * other credentials) in this method. The {@link org.apache.shiro.realm.AuthenticatingRealm * AuthenticatingRealm} superclass will do that automatically via the use of a configured * {@link org.apache.shiro.authc.credential.CredentialsMatcher CredentialsMatcher} (see this * example's corresponding <code>shiro.ini</code> file to see a configured credentials matcher). * <p/> * All that is required is that the account information include directly the credentials found * in the EIS. * * @param username * the username for the account data to retrieve * @return the Account information corresponding to the specified username: */ protected SimpleAccount getAccount(String username) { log.info("get account: " + username); // just create a dummy. A real app would construct one based on EIS access. SimpleAccount account = new SimpleAccount(username, "pass", getName()); // simulate some roles and permissions: account.addRole("user"); if ("admin".equals(username)) { account.addRole("admin"); } // most applications would assign permissions to Roles instead of users directly because // this is much more // flexible (it is easier to configure roles and then change role-to-user assignments than // it is to maintain // permissions for each user). // But these next lines assign permissions directly to this trivial account object just for // simulation's sake: account.addStringPermission("blogEntry:edit"); // this user is allowed to 'edit' _any_ // blogEntry // fine-grained instance level permission: account.addStringPermission("printer:print:laserjet2000"); // allowed to 'print' to the // 'printer' identified // by the id 'laserjet2000' account.addStringPermission("view"); // all users have view permission return account; }