Java Code Examples for org.apache.shiro.subject.Subject#hasRole()

The following examples show how to use org.apache.shiro.subject.Subject#hasRole() . 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: ShiroFacade.java    From thymeleaf-extras-shiro with Apache License 2.0 6 votes vote down vote up
public static boolean hasAllRoles(final Collection<String> roles) {
    if (SecurityUtils.getSubject() != null) {
        if (roles.isEmpty()) {
            return false;
        }

        final Subject subject = SecurityUtils.getSubject();
        for (final String role : roles) {
            if (!subject.hasRole(StringUtils.trim(role))) {
                return false;
            }
        }
        return true;
    }
    return false;
}
 
Example 2
Source File: ShiroPermissingTag.java    From mumu with Apache License 2.0 6 votes vote down vote up
/**
 * 验证用户是否具有以下任意一个角色。
 * @param roleNames 以 delimeter 为分隔符的角色列表
 * @param delimeter 角色列表分隔符
 * @return 用户是否具有以下任意一个角色
 */
public boolean hasAnyRoles(String roleNames, String delimeter) {
	Subject subject = SecurityUtils.getSubject();
	if (subject != null) {
		if (delimeter == null || delimeter.length() == 0) {
			delimeter = ROLE_NAMES_DELIMETER;
		}

		for (String role : roleNames.split(delimeter)) {
			if (subject.hasRole(role.trim()) == true) {
				return true;
			}
		}
	}

	return false;
}
 
Example 3
Source File: AppManagerController.java    From MultimediaDesktop with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/app/listHotApp")
public void listAllApplication(Model model, Integer page, Integer limit) {
	ArrayList<UserRole> roles = new ArrayList<>();
	roles.add(UserRole.用户);
	Subject subject = SecurityUtils.getSubject();
	if (subject.hasRole(UserRole.开发者.getRole())) {
		roles.add(UserRole.开发者);
	} else if (subject.hasRole(UserRole.管理员.getRole())) {
		roles.add(UserRole.管理员);
	}
	OrderDto order = new OrderDto(Direction.DESC, "useCount");
	PageDto<ApplicationDto> apps = applicationService.findBy(null, null,
			null, null, null, roles, Boolean.TRUE,
			new PageSize(page, limit), new SortDto(order));
	model.addAttribute("apps", apps.getValues());
	model.addAttribute("total", apps.getTotalElements());
}
 
Example 4
Source File: MenuSupportUtils.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
protected static List<SysMenuVO> loadSysMenuData(String system) throws ServiceException, Exception {
	List<SysMenuVO> menuList = null;
	TbSys sys = new TbSys();
	sys.setSysId(system);
	if (sysService.countByEntityUK(sys)!=1) { // 必需要有 TB_SYS 資料
		throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_ERRORS));
	}
	Subject subject = SecurityUtils.getSubject();
	String account = (String)subject.getPrincipal();
	if (StringUtils.isBlank(account)) {
		throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DATA_ERRORS)); 
	}		
	if (subject.hasRole(Constants.SUPER_ROLE_ADMIN) || subject.hasRole(Constants.SUPER_ROLE_ALL)) {
		account = null;
	} 
	DefaultResult<List<SysMenuVO>> result = sysMenuService.findForMenuGenerator(system, account);
	if (result.getValue()!=null) {
		menuList = result.getValue();
	}
	if (menuList==null) {
		menuList = new ArrayList<SysMenuVO>();
	}
	return menuList;
}
 
Example 5
Source File: SessionEvaluator.java    From jqm with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isSessionStorageEnabled(Subject subject)
{
    // If disabled in request (e.g. by using the noSessionCreation filter, it stays disabled.
    if (WebUtils.isWeb(subject))
    {
        HttpServletRequest request = WebUtils.getHttpRequest(subject);
        Object o = request.getAttribute(DefaultSubjectContext.SESSION_CREATION_ENABLED);
        if (o != null && !((Boolean) o))
        {
            return false;
        }
    }

    // Then only allow humans, not API-only users, to create a session
    if (subject.hasRole("human"))
    {
        return true;
    }

    // By default, no sessions allowed.
    return false;
}
 
Example 6
Source File: ShiroSubjectIdentityAdapter.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
  Subject subject = SecurityUtils.getSubject();

  // trigger call to shiro authorization realm
  // we use shiro authorization realm to look up groups
  subject.hasRole("authenticatedUser");

  CallableChain callableChain = new CallableChain(request, response, chain);
  SecurityUtils.getSubject().execute(callableChain);
}
 
Example 7
Source File: ShiroExt.java    From WebStack-Guns with MIT License 5 votes vote down vote up
/**
 * 验证当前用户是否属于以下所有角色。
 *
 * @param roleNames 角色列表
 * @return 属于:true,否则false
 */
public boolean hasAllRoles(String roleNames) {
    boolean hasAllRole = true;
    Subject subject = getSubject();
    if (subject != null && roleNames != null && roleNames.length() > 0) {
        for (String role : roleNames.split(NAMES_DELIMETER)) {
            if (!subject.hasRole(role.trim())) {
                hasAllRole = false;
                break;
            }
        }
    }
    return hasAllRole;
}
 
Example 8
Source File: ShiroKit.java    From WebStack-Guns with MIT License 5 votes vote down vote up
/**
 * 验证当前用户是否属于以下所有角色。
 *
 * @param roleNames 角色列表
 * @return 属于:true,否则false
 */
public static boolean hasAllRoles(String roleNames) {
    boolean hasAllRole = true;
    Subject subject = getSubject();
    if (subject != null && roleNames != null && roleNames.length() > 0) {
        for (String role : roleNames.split(NAMES_DELIMETER)) {
            if (!subject.hasRole(role.trim())) {
                hasAllRole = false;
                break;
            }
        }
    }
    return hasAllRole;
}
 
Example 9
Source File: SubjectUtils.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public static String getOrganizationName() {
    Subject currentUser = getSubject();
    if ( currentUser == null ) {
        return null;
    }
    if ( !currentUser.hasRole( ROLE_ORGANIZATION_ADMIN ) ) {
        return null;
    }
    Session session = currentUser.getSession();
    OrganizationInfo organization = ( OrganizationInfo ) session.getAttribute( "organization" );
    if ( organization == null ) {
        return null;
    }
    return organization.getName();
}
 
Example 10
Source File: SubjectUtils.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public static UUID getOrganizationId() {
    Subject currentUser = getSubject();
    if ( currentUser == null ) {
        return null;
    }
    if ( !currentUser.hasRole( ROLE_ORGANIZATION_ADMIN ) ) {
        return null;
    }
    Session session = currentUser.getSession();
    OrganizationInfo organization = ( OrganizationInfo ) session.getAttribute( "organization" );
    if ( organization == null ) {
        return null;
    }
    return organization.getUuid();
}
 
Example 11
Source File: SecurityServiceImpl.java    From tapestry-security with Apache License 2.0 5 votes vote down vote up
@Override
public boolean hasAllRoles(String roles)
{
	boolean hasAllRole = false; // no subject is false

	Subject subject = getSubject();

	if (subject != null)
	{

		hasAllRole = true; // but no roles is true

		// Iterate through roles and check to see if the user has one of the roles
		for (String role : roles.split(PERMISSIONS_OR_ROLES_DELIMETER))
		{

			if (!subject.hasRole(role.trim()))
			{
				hasAllRole = false;

				break;
			}
		}
	}

	return hasAllRole;
}
 
Example 12
Source File: ShiroKit.java    From MeetingFilm with Apache License 2.0 5 votes vote down vote up
/**
 * 验证当前用户是否属于以下所有角色。
 *
 * @param roleNames
 *            角色列表
 * @return 属于:true,否则false
 */
public static boolean hasAllRoles(String roleNames) {
    boolean hasAllRole = true;
    Subject subject = getSubject();
    if (subject != null && roleNames != null && roleNames.length() > 0) {
        for (String role : roleNames.split(NAMES_DELIMETER)) {
            if (!subject.hasRole(role.trim())) {
                hasAllRole = false;
                break;
            }
        }
    }
    return hasAllRole;
}
 
Example 13
Source File: SubjectUtils.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public static boolean isApplicationUser() {
    Subject currentUser = getSubject();
    if ( currentUser == null ) {
        return false;
    }
    return currentUser.hasRole( ROLE_APPLICATION_USER );
}
 
Example 14
Source File: MenusDirective.java    From mblog with GNU General Public License v3.0 5 votes vote down vote up
private List<Menu> filterMenu(Subject subject) {
    List<Menu> menus = MenuJsonUtils.getMenus();
    if (!subject.hasRole(Role.ROLE_ADMIN)) {
        menus = check(subject, menus);
    }
    return menus;
}
 
Example 15
Source File: ShiroSpringController.java    From tutorials with MIT License 5 votes vote down vote up
@GetMapping("/secure")
public String secure(ModelMap modelMap) {

    Subject currentUser = SecurityUtils.getSubject();
    String role = "", permission = "";

    if(currentUser.hasRole("admin")) {
        role = role  + "You are an Admin";
    }
    else if(currentUser.hasRole("editor")) {
        role = role + "You are an Editor";
    }
    else if(currentUser.hasRole("author")) {
        role = role + "You are an Author";
    }

    if(currentUser.isPermitted("articles:compose")) {
        permission = permission + "You can compose an article, ";
    } else {
        permission = permission + "You are not permitted to compose an article!, ";
    }

    if(currentUser.isPermitted("articles:save")) {
        permission = permission + "You can save articles, ";
    } else {
        permission = permission + "\nYou can not save articles, ";
    }

    if(currentUser.isPermitted("articles:publish")) {
        permission = permission  + "\nYou can publish articles";
    } else {
        permission = permission + "\nYou can not publish articles";
    }

    modelMap.addAttribute("username", currentUser.getPrincipal());
    modelMap.addAttribute("permission", permission);
    modelMap.addAttribute("role", role);

    return "secure";
}
 
Example 16
Source File: ShiroExt.java    From MeetingFilm with Apache License 2.0 5 votes vote down vote up
/**
 * 验证当前用户是否属于以下任意一个角色。
 *
 * @param roleNames 角色列表
 * @return 属于:true,否则false
 */
public boolean hasAnyRoles(String roleNames) {
    boolean hasAnyRole = false;
    Subject subject = getSubject();
    if (subject != null && roleNames != null && roleNames.length() > 0) {
        for (String role : roleNames.split(NAMES_DELIMETER)) {
            if (subject.hasRole(role.trim())) {
                hasAnyRole = true;
                break;
            }
        }
    }
    return hasAnyRole;
}
 
Example 17
Source File: Main.java    From tutorials with MIT License 4 votes vote down vote up
public static void main(String[] args) {

        IniRealm realm = new IniRealm();
        Ini ini = Ini.fromResourcePath(Main.class.getResource("/com/baeldung/shiro/permissions/custom/shiro.ini").getPath());
        realm.setIni(ini);
        realm.setPermissionResolver(new PathPermissionResolver());
        realm.init();
        SecurityManager securityManager = new DefaultSecurityManager(realm);

        SecurityUtils.setSecurityManager(securityManager);
        Subject currentUser = SecurityUtils.getSubject();

        if (!currentUser.isAuthenticated()) {
          UsernamePasswordToken token = new UsernamePasswordToken("paul.reader", "password4");
          token.setRememberMe(true);
          try {
              currentUser.login(token);
          } catch (UnknownAccountException uae) {
              log.error("Username Not Found!", uae);
          } catch (IncorrectCredentialsException ice) {
              log.error("Invalid Credentials!", ice);
          } catch (LockedAccountException lae) {
              log.error("Your Account is Locked!", lae);
          } catch (AuthenticationException ae) {
              log.error("Unexpected Error!", ae);
          }
        }

        log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

        if (currentUser.hasRole("admin")) {
            log.info("Welcome Admin");
        } else if(currentUser.hasRole("editor")) {
            log.info("Welcome, Editor!");
        } else if(currentUser.hasRole("author")) {
            log.info("Welcome, Author");
        } else {
            log.info("Welcome, Guest");
        }

        if(currentUser.isPermitted("/articles/drafts/new-article")) {
            log.info("You can access articles");
        } else {
            log.info("You cannot access articles!");
        }
        currentUser.logout();
    }
 
Example 18
Source File: StandaloneShiroTest.java    From attic-polygene-java with Apache License 2.0 4 votes vote down vote up
@Test
public void test()
{
    // get the currently executing user:
    Subject currentUser = SecurityUtils.getSubject();

    // Do some stuff with a Session (no need for a web or EJB container!!!)
    Session session = currentUser.getSession();
    session.setAttribute( "someKey", "aValue" );
    String value = ( String ) session.getAttribute( "someKey" );
    assertEquals( "aValue", value );
    LOG.info( "Retrieved the correct value! [" + value + "]" );

    // let's login the current user so we can check against roles and permissions:
    if ( !currentUser.isAuthenticated() ) {
        UsernamePasswordToken token = new UsernamePasswordToken( "lonestarr", "vespa" );
        token.setRememberMe( true );
        try {
            currentUser.login( token );
        } catch ( UnknownAccountException uae ) {
            fail( "There is no user with username of " + token.getPrincipal() );
        } catch ( IncorrectCredentialsException ice ) {
            fail( "Password for account " + token.getPrincipal() + " was incorrect!" );
        } catch ( LockedAccountException lae ) {
            fail( "The account for username " + token.getPrincipal() + " is locked.  "
                  + "Please contact your administrator to unlock it." );
        } // ... catch more exceptions here (maybe custom ones specific to your application?
        catch ( AuthenticationException ae ) {
            //unexpected condition?  error?
            throw ae;
        }
    }

    //say who they are:
    //print their identifying principal (in this case, a username):
    assertNotNull( currentUser.getPrincipal() );
    LOG.info( "User [" + currentUser.getPrincipal() + "] logged in successfully." );

    //test a role:
    if ( currentUser.hasRole( "schwartz" ) ) {
        LOG.info( "May the Schwartz be with you!" );
    } else {
        fail( "Hello, mere mortal." );
    }

    //test a typed permission (not instance-level)
    if ( currentUser.isPermitted( "lightsaber:weild" ) ) {
        LOG.info( "You may use a lightsaber ring.  Use it wisely." );
    } else {
        fail( "Sorry, lightsaber rings are for schwartz masters only." );
    }

    //a (very powerful) Instance Level permission:
    if ( currentUser.isPermitted( "winnebago:drive:eagle5" ) ) {
        LOG.info( "You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  "
                  + "Here are the keys - have fun!" );
    } else {
        fail( "Sorry, you aren't allowed to drive the 'eagle5' winnebago!" );
    }

    //all done - log out!
    currentUser.logout();
}
 
Example 19
Source File: ShiroAuthenticationService.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
/**
 * 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
 */
@Override
public Set<String> getAssociatedRoles() {
  Subject subject = org.apache.shiro.SecurityUtils.getSubject();
  HashSet<String> roles = new HashSet<>();
  Map allRoles = null;

  if (subject.isAuthenticated()) {
    Collection<Realm> realmsList = getRealmsList();
    for (Realm realm : realmsList) {
      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;
}
 
Example 20
Source File: ControllerAuthorityCheckInterceptor.java    From bamboobsc with Apache License 2.0 4 votes vote down vote up
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
	String actionName = actionInvocation.getProxy().getActionName();
	String url = actionName + Constants._S2_ACTION_EXTENSION;		
	Subject subject = SecurityUtils.getSubject();
	if ( !Constants.getSystem().equals(Constants.getMainSystem()) ) {
		SecurityUtils.setSecurityManager( (DefaultSecurityManager)AppContext.getBean("securityManager") );
		subject = SecurityUtils.getSubject();			
	}
	if (subject.hasRole(Constants.SUPER_ROLE_ALL) || subject.hasRole(Constants.SUPER_ROLE_ADMIN)) {
		SysEventLogSupport.log( (String)subject.getPrincipal(), Constants.getSystem(), url, true );
		return actionInvocation.invoke();
	}		
	Annotation[] annotations = actionInvocation.getAction().getClass().getAnnotations();
	Annotation[] actionMethodAnnotations = null;
	Method[] methods = actionInvocation.getAction().getClass().getMethods();
	for (Method method : methods) {
		if (actionInvocation.getProxy().getMethod().equals(method.getName())) {
			actionMethodAnnotations = method.getAnnotations();
		}
	}		
	if (this.isControllerAuthority(annotations, actionMethodAnnotations, subject)) {
		SysEventLogSupport.log( (String)subject.getPrincipal(), Constants.getSystem(), url, true );
		return actionInvocation.invoke();
	}		
	if (subject.isPermitted(url) || subject.isPermitted("/"+url)) {
		SysEventLogSupport.log( (String)subject.getPrincipal(), Constants.getSystem(), url, true );
		return actionInvocation.invoke();
	}
	logger.warn("[decline] user=" + subject.getPrincipal() + " url=" + url);
	String isDojoxContentPane = ServletActionContext.getRequest().getParameter(Constants.IS_DOJOX_CONTENT_PANE_XHR_LOAD);
	if (YesNo.YES.equals(isDojoxContentPane)) { // dojox.layout.ContentPane 它的 X-Requested-With 是 XMLHttpRequest
		SysEventLogSupport.log( (String)subject.getPrincipal(), Constants.getSystem(), url, false );
		return Constants._S2_RESULT_NO_AUTHORITH;
	}
	String header = ServletActionContext.getRequest().getHeader("X-Requested-With");
	if ("XMLHttpRequest".equalsIgnoreCase(header)) {
		PrintWriter printWriter = ServletActionContext.getResponse().getWriter();
		printWriter.print(Constants.NO_AUTHZ_JSON_DATA);
           printWriter.flush();
           printWriter.close();
           SysEventLogSupport.log( (String)subject.getPrincipal(), Constants.getSystem(), url, false );
		return null;
	}
	SysEventLogSupport.log( (String)subject.getPrincipal(), Constants.getSystem(), url, false );
	return Constants._S2_RESULT_NO_AUTHORITH;
}