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

The following examples show how to use org.apache.shiro.subject.Subject#isPermitted() . 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: BaseSupportAction.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
/**
 * ControllerAuthorityCheckInterceptor 會去掉沒有權限的action, 只是配合 json 通一變數 "isAuthorize" 要用到
 * 
 * @return
 */
protected String isActionAuthorize() {
	((BaseSimpleActionInfo)this.baseActionInfoProvide).handlerActionAnnotations();
	Subject subject = SecurityUtils.getSubject();
	if (subject.hasRole(Constants.SUPER_ROLE_ALL) || subject.hasRole(Constants.SUPER_ROLE_ADMIN)) {
		return YesNo.YES;
	}
	if (this.isControllerAuthority( 
			((BaseSimpleActionInfo)this.baseActionInfoProvide).getActionAnnotations(), 
			((BaseSimpleActionInfo)this.baseActionInfoProvide).getActionMethodAnnotations() , 
			subject) ) {
		return YesNo.YES;
	}
	if (subject.isPermitted(this.baseActionInfoProvide.getPageInfoActionName()+Constants._S2_ACTION_EXTENSION)) {
		return YesNo.YES;
	}
	return YesNo.NO;
}
 
Example 2
Source File: ShiroAuthorizationFilter.java    From hunt-admin with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
    Subject subject = getSubject(request, response);
    String[] perms = (String[]) mappedValue;
    boolean isPermitted = true;
    if (perms != null && perms.length > 0) {
        if (perms.length == 1) {
            if (!subject.isPermitted(perms[0])) {
                log.debug("授权认证:未通过");
                isPermitted = false;
            }
        } else {
            if (!subject.isPermittedAll(perms)) {
                log.debug("授权认证:未通过");
                isPermitted = false;
            }
        }
    }
    return isPermitted;
}
 
Example 3
Source File: PermissionsAuthorizationFilter.java    From tapestry-security with Apache License 2.0 6 votes vote down vote up
public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {

        Subject subject = getSubject(request, response);
        String[] perms = (String[]) mappedValue;

        boolean isPermitted = true;
        if (perms != null && perms.length > 0) {
            if (perms.length == 1) {
                if (!subject.isPermitted(perms[0])) {
                    isPermitted = false;
                }
            } else {
                if (!subject.isPermittedAll(perms)) {
                    isPermitted = false;
                }
            }
        }

        return isPermitted;
    }
 
Example 4
Source File: HasAnyPermissionsTag.java    From Shop-for-JavaWeb with MIT License 6 votes vote down vote up
@Override
protected boolean showTagBody(String permissionNames) {
	boolean hasAnyPermission = false;

	Subject subject = getSubject();

	if (subject != null) {
		// Iterate through permissions and check to see if the user has one of the permissions
		for (String permission : permissionNames.split(PERMISSION_NAMES_DELIMETER)) {

			if (subject.isPermitted(permission.trim())) {
				hasAnyPermission = true;
				break;
			}

		}
	}

	return hasAnyPermission;
}
 
Example 5
Source File: SecurityHelper.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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 6
Source File: JsetsPermissionsAuthorizationFilter.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
    Subject subject = getSubject(request, response);
    String[] perms = (String[]) mappedValue;
    boolean isPermitted = true;
    if (perms != null && perms.length > 0) {
        if (perms.length == 1) {
            if (!subject.isPermitted(perms[0])) {
                isPermitted = false;
            }
        } else {
            if (!subject.isPermittedAll(perms)) {
                isPermitted = false;
            }
        }
    }
    return isPermitted;
}
 
Example 7
Source File: SecurityComponent.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private List<PermissionXO> calculatePermissions(final Subject subject) {
  log.debug("Calculating permissions");

  List<Permission> granted = new ArrayList<>();
  List<PermissionXO> result = new ArrayList<>();

  // find all privileges which we expose the UI, , which we can deconstruct and evaluate
  for (Privilege privilege : securitySystem.listPrivileges()) {
    // only WildcardPermission2 presently is supported due to toString() implementation
    if (privilege.getPermission() instanceof WildcardPermission2) {
      granted.add(privilege.getPermission());
    }
  }

  // determine which of the exposed privilege permissions the current subject is granted
  boolean[] boolResults = subject.isPermitted(granted);
  for (int i = 0; i < granted.size(); i++) {
    if (boolResults[i]) {
      PermissionXO entry = new PermissionXO();
      entry.setId(granted.get(i).toString());
      result.add(entry);
    }
  }

  return result;
}
 
Example 8
Source File: AbstractService.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public void checkPermissionsForPath( ServiceContext context, String path ) {
    Subject currentUser = SubjectUtils.getSubject();
    if ( currentUser == null ) {
        return;
    }

    if( isServiceAdmin() ){
        if(logger.isDebugEnabled()){
            logger.debug("Subject is the sysadmin, short-circuiting and allowing access");
        }
        return;
    }

    String perm = getPermissionFromPath(
        em.getApplicationRef().getUuid(), context.getAction().toString().toLowerCase(), path );
    boolean permitted = currentUser.isPermitted( perm );

    if ( logger.isDebugEnabled() ) {
        logger.debug( PATH_MSG, path, context.getAction(), perm, permitted );
    }

    SubjectUtils.checkPermission( perm );
    Subject subject = SubjectUtils.getSubject();

    if (logger.isDebugEnabled()) {
        logger.debug("Checked subject {} for perm {}", subject != null ? subject.toString() : "", perm);
        logger.debug("------------------------------------------------------------------------------");
    }
}
 
Example 9
Source File: PermissionsDomainTest.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Test
public void test()
        throws UnitOfWorkCompletionException
{
    // START SNIPPET: usage
    UnitOfWork uow = unitOfWorkFactory.newUnitOfWork();

    User user = userFactory.createNewUser( "foo", "bar" );
    Role role = roleFactory.create( "role-one", "permission-one", "permission-two" );
    role.assignTo( user );

    uow.complete();

    // END SNIPPET: usage
    // START SNIPPET: usage
    uow = unitOfWorkFactory.newUnitOfWork();

    Subject currentUser = SecurityUtils.getSubject();
    currentUser.login( new UsernamePasswordToken( "foo", "bar" ) );

    if ( !currentUser.hasRole( "role-one" ) ) {
        fail( "User 'foo' must have 'role-one' role." );
    }

    if ( !currentUser.isPermitted( "permission-one" ) ) {
        fail( "User 'foo' must have 'permission-one' permission." );
    }

    // END SNIPPET: usage
    assertThat( currentUser.hasRole( "role-one" ), is( true ) );
    assertThat( currentUser.hasRole( "role-two" ), is( false ) );

    assertThat( currentUser.isPermitted( "permission-one" ), is( true ) );
    assertThat( currentUser.isPermitted( "permission-two" ), is( true ) );
    assertThat( currentUser.isPermitted( "permission-three" ), is( false ) );

    // START SNIPPET: usage
    uow.discard();
    // END SNIPPET: usage
}
 
Example 10
Source File: ShiroPermissingTag.java    From mumu with Apache License 2.0 5 votes vote down vote up
/**
 * 验证用户是否具有以下任意一个权限。
 * @param permissions  权限列表
 * @return 用户是否具有以下任意一个权限
 */
public boolean hasAnyPermissions(Collection<String> permissions) {
	Subject subject = SecurityUtils.getSubject();

	if (subject != null && permissions != null) {
		for (String permission : permissions) {
			if (permission != null && subject.isPermitted(permission.trim()) == true) {
				return true;
			}
		}
	}

	return false;
}
 
Example 11
Source File: ShiroAuthorizingParamInterceptor.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
  checkState(initialized);

  Method method = invocation.getMethod();
  Subject subject = subjectProvider.get();

  Optional<IJobKey> jobKey = authorizingParamGetters
      .getUnchecked(invocation.getMethod())
      .apply(invocation.getArguments())
      .map(IJobKey::build);
  if (jobKey.isPresent() && JobKeys.isValid(jobKey.get())) {
    Permission targetPermission = makeTargetPermission(method.getName(), jobKey.get());
    if (subject.isPermitted(targetPermission)) {
      return invocation.proceed();
    } else {
      authorizationFailures.incrementAndGet();
      return Responses.addMessage(
          Responses.empty(),
          ResponseCode.AUTH_FAILED,
          "Subject " + subject.getPrincipal() + " is not permitted to " + targetPermission + ".");
    }
  } else {
    badRequests.incrementAndGet();
    return Responses.addMessage(
        Responses.empty(),
        ResponseCode.INVALID_REQUEST,
        "Missing or invalid job key from request.");
  }
}
 
Example 12
Source File: ShiroFacade.java    From thymeleaf-extras-shiro with Apache License 2.0 5 votes vote down vote up
public static boolean hasAnyPermissions(final Collection<String> permissions) {
    if (SecurityUtils.getSubject() != null) {
        final Subject subject = SecurityUtils.getSubject();
        for (final String permission : permissions) {
            if (subject.isPermitted(permission)) {
                return true;
            }
        }
    }
    return false;
}
 
Example 13
Source File: Permission.java    From shiro-velocity-support with Apache License 2.0 5 votes vote down vote up
/**
 * 验证用户是否具有以下任意一个权限。
 * 
 * @param permissions
 *        权限列表
 * @return 用户是否具有以下任意一个权限
 */
public boolean hasAnyPermissions(Collection<String> permissions) {
	Subject subject = SecurityUtils.getSubject();

	if (subject != null && permissions != null) {
		for (String permission : permissions) {
			if (permission != null && subject.isPermitted(permission.trim()) == true) {
				return true;
			}
		}
	}

	return false;
}
 
Example 14
Source File: HasAllPermissionsTagTest.java    From thymeleaf-extras-shiro with Apache License 2.0 4 votes vote down vote up
private static boolean hasAllFeaturesSanityCheck(Subject subject) {
    return subject.isPermitted(PERMISSION_TYPE_1_ACTION_1_INST_1.label()) &&
            subject.isPermitted(PERMISSION_TYPE_1_ACTION_2_EXAMPLE);
}
 
Example 15
Source File: Main.java    From java-course-ee with MIT License 4 votes vote down vote up
public static void main(String[] args) {


        // The easiest way to create a Shiro SecurityManager with configured
        // realms, users, roles and permissions is to use the simple INI config.
        // We'll do that by using a factory that can ingest a .ini file and
        // return a SecurityManager instance:

        // Use the shiro.ini file at the root of the classpath
        // (file: and url: prefixes load from files and urls respectively):
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();

        // for this simple example quickstart, make the SecurityManager
        // accessible as a JVM singleton.  Most applications wouldn't do this
        // and instead rely on their container configuration or web.xml for
        // webapps.  That is outside the scope of this simple quickstart, so
        // we'll just do the bare minimum so you can continue to get a feel
        // for things.
        SecurityUtils.setSecurityManager(securityManager);

        // Now that a simple Shiro environment is set up, let's see what you can do:

        // 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");
        if (value.equals("aValue")) {
            log("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) {
                log("There is no user with username of " + token.getPrincipal());
            } catch (IncorrectCredentialsException ice) {
                log("Password for account " + token.getPrincipal() + " was incorrect!");
            } catch (LockedAccountException lae) {
                log("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?
            }
        }

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

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

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

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

        //all done - log out!
        currentUser.logout();

        System.exit(0);

    }
 
Example 16
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;
}
 
Example 17
Source File: ResourceCheckFilter.java    From jeecg-boot with Apache License 2.0 3 votes vote down vote up
/**
 * 表示是否允许访问 ,如果允许访问返回true,否则false;
 * 
 * @param servletRequest
 * @param servletResponse
 * @param o               表示写在拦截器中括号里面的字符串 mappedValue 就是 [urls] 配置中拦截器参数部分
 * @return
 * @throws Exception
 */
@Override
protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
	Subject subject = getSubject(servletRequest, servletResponse);
	String url = getPathWithinApplication(servletRequest);
	log.info("当前用户正在访问的 url => " + url);
	return subject.isPermitted(url);
}
 
Example 18
Source File: ResourceCheckFilter.java    From teaching with Apache License 2.0 3 votes vote down vote up
/**
 * 表示是否允许访问 ,如果允许访问返回true,否则false;
 * 
 * @param servletRequest
 * @param servletResponse
 * @param o               表示写在拦截器中括号里面的字符串 mappedValue 就是 [urls] 配置中拦截器参数部分
 * @return
 * @throws Exception
 */
@Override
protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
	Subject subject = getSubject(servletRequest, servletResponse);
	String url = getPathWithinApplication(servletRequest);
	log.info("当前用户正在访问的 url => " + url);
	return subject.isPermitted(url);
}
 
Example 19
Source File: ShiroPermissingTag.java    From mumu with Apache License 2.0 2 votes vote down vote up
/**
 * 验证用户是否具备某权限。
 * @param permission 权限名称
 * @return 用户是否具备某权限
 */
public boolean hasPermission(String permission) {
	Subject subject = SecurityUtils.getSubject();
	return subject != null && subject.isPermitted(permission);
}
 
Example 20
Source File: Permission.java    From shiro-velocity-support with Apache License 2.0 2 votes vote down vote up
/**
 * 验证用户是否具备某权限。
 * 
 * @param permission
 *        权限名称
 * @return 用户是否具备某权限
 */
public boolean hasPermission(String permission) {
	Subject subject = SecurityUtils.getSubject();
	return subject != null && subject.isPermitted(permission);
}