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

The following examples show how to use org.apache.shiro.subject.Subject#getPrincipals() . 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: ShiroUtils.java    From supplierShop with MIT License 5 votes vote down vote up
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 2
Source File: ShiroUtils.java    From ruoyiplus with MIT License 5 votes vote down vote up
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 3
Source File: ShiroUtils.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
public static void setSysUser(User 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 4
Source File: UserContext.java    From v-mock with MIT License 5 votes vote down vote up
public static void setSysUser(User 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 5
Source File: ShiroUtils.java    From RuoYi with Apache License 2.0 5 votes vote down vote up
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 6
Source File: SysLogAspect.java    From watchdog-framework with MIT License 5 votes vote down vote up
@AfterReturning("log()")
public void after(JoinPoint joinPoint){
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    PrincipalCollection spc = null;
    Subject subject = SecurityUtils.getSubject();
    if(subject.getPrincipals()!=null){
        spc = subject.getPrincipals();
    }
    SysLog sysLog = new SysLog();
    //获取动作Action释义
    sysLog.setActionName(getMethodSysLogsAnnotationValue(joinPoint));
    //获取IP
    sysLog.setIp(Tools.getClientIp(request));
    sysLog.setAjax(Tools.ajax(request) ? 1 : 0);
    sysLog.setUri(request.getRequestURI());
    String s = this.paramFilter(joinPoint.getArgs());
    //根据系统需求自定义
    sysLog.setParams(s.length()>500 ? "数据过大,不给予记录" : s);
    sysLog.setHttpMethod(request.getMethod());
    sysLog.setClassMethod(joinPoint.getSignature().getDeclaringTypeName()
            + "." + joinPoint.getSignature().getName()+"()");
    //判断身份是否为空
    if(spc!=null){
        JwtToken jwtToken = new JwtToken();
        BeanUtils.copyProperties(spc.getPrimaryPrincipal(),jwtToken);
        sysLog.setUsername(jwtToken.getUsername());
        sysLog.setUid(jwtToken.getUid());
    }else{
        sysLog.setUsername("游客");
        sysLog.setUid("0");
    }
    sysLog.setCreateDate(new Date());
    sysLogService.insert(sysLog);
}
 
Example 7
Source File: ShiroUtils.java    From LuckyFrameWeb with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void setSysUser(User 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 8
Source File: IndexController.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@RequiresPermissions(value = { "user:edit" })
    @GetMapping("/user/{id}")
    public Object user(@PathVariable(value = "id") String id,HttpServletRequest request) {
    	   Subject subject = SecurityUtils.getSubject();
    	   //gonson解析
    	   PrincipalCollection att = subject.getPrincipals();
    	   LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>> {}",att);
//    	   JSONArray ja = JSON.parseArray(subject.getPrincipals().toString());
//    	   LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>> {}",ja);
    	   

        return SecurityUtils.getSubject().getPrincipals();
    }
 
Example 9
Source File: ConanTokenManager.java    From nexus-repository-conan with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Verifies passed in principal/credentials combo, and creates (if not already exists) a npm token mapped to given
 * principal and returns the newly created token.
 */
public String login() {
  Subject subject = securityHelper.subject();
  boolean authenticated = subject.getPrincipal() != null && subject.isAuthenticated();
  if (authenticated || isAnonymous(subject)) {
    PrincipalCollection principals = subject.getPrincipals();
    return super.createToken(principals);
  }
  return null;
}
 
Example 10
Source File: IndexController.java    From jee-universal-bms with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "v1/api0/user/resource")
@ResponseBody
public JsonResult userResource() {
    Subject currentUser = SecurityUtils.getSubject();//获取当前用户
    if(currentUser != null && currentUser.getPrincipals() != null) {
        String username = currentUser.getPrincipals().toString();
        User user = userService.getByUsername(username);
        if(user != null) {
            List<Resource> resourceList = resourceService.getUserPermissions(user.getId());
            List<Tree> treeList = wrapTree(resourceList, 0);
            return new JsonResult(ResultCode.SUCCESS_CODE, ResultCode.SUCCESS_MSG, treeList);
        }
    }
    return new JsonResult(ResultCode.TOKEN_ERROR_CODE, ResultCode.TOKEN_ERROR_MSG);
}
 
Example 11
Source File: ShiroSecurityHelper.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
public String getCurrentUsername() {
	Subject subject = getSubject();
	PrincipalCollection collection = subject.getPrincipals();
	if (null != collection && !collection.isEmpty()) {
		return (String) collection.iterator().next();
	}
	
	return null;
}
 
Example 12
Source File: LoginExtension.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
@Override public void requestStart(cfSession session) {
	
	// the plugin may be disabled
	if ( userFormField == null )
		return;
	
	cfStructData formData = (cfStructData)session.getData("form");
	
	if ( formData.containsKey(userFormField) && formData.containsKey(passwordFormField) ){
		try {
			String username = formData.getData(userFormField).getString();
			String password = formData.getData(passwordFormField).getString();
			
			// Remove the fields from the form post
			formData.setData(passwordFormField, new cfStringData("******") );
			
			// Attempt to login them in
			Subject user = SecurityUtils.getSubject();
       UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			
       user.login(token);
       
       if ( user.isAuthenticated() ){
       	PrincipalCollection pc = user.getPrincipals();
       	formData.setData(returnFormField, new cfStringData( pc.asSet().toString() ) );
       	user.logout();
       }else{
       	formData.setData(returnFormField, new cfStringData("[failed]") );
       }
       
		} catch (Exception e) {
			formData.setData(returnFormField, new cfStringData("[exception]" + e.getMessage()) );
			PluginManager.getPlugInManager().log("[LoginExtension] " + e.getMessage() );
		}
		
	}
	
}
 
Example 13
Source File: SysLogAspect.java    From xmanager with Apache License 2.0 4 votes vote down vote up
@Around("cutController()")
public Object recordSysLog(ProceedingJoinPoint point) throws Throwable {
    String strMethodName = point.getSignature().getName();
    String strClassName = point.getTarget().getClass().getName();
    Object[] params = point.getArgs();
    StringBuffer bfParams = new StringBuffer();
    Enumeration<String> paraNames = null;
    HttpServletRequest request = null;
    if (params != null && params.length > 0) {
        request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        paraNames = request.getParameterNames();
        String key;
        String value;
        while (paraNames.hasMoreElements()) {
            key = paraNames.nextElement();
            value = request.getParameter(key);
            bfParams.append(key).append("=").append(value).append("&");
        }
        if (StringUtils.isBlank(bfParams)) {
            bfParams.append(request.getQueryString());
        }
    }

    String strMessage = String
            .format("[类名]:%s,[方法]:%s,[参数]:%s", strClassName, strMethodName, bfParams.toString());
    LOGGER.info(strMessage);
    if (isWriteLog(strMethodName)) {
        try {
            Subject currentUser = SecurityUtils.getSubject();
            PrincipalCollection collection = currentUser.getPrincipals();
            if (null != collection) {
                String loginName = collection.getPrimaryPrincipal().toString();
                SysLog sysLog = new SysLog();
                sysLog.setLoginName(loginName);
                sysLog.setRoleName(loginName);
                sysLog.setOptContent(strMessage);
                sysLog.setCreateTime(new Date());
                if (request != null) {
                    sysLog.setClientIp(request.getRemoteAddr());
                }
                LOGGER.info(sysLog.toString());
                sysLogService.insert(sysLog);
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    return point.proceed();
}
 
Example 14
Source File: AnonymousHelper.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Check given given subject is anonymous.
 */
public static boolean isAnonymous(@Nullable final Subject subject) {
  return subject != null && subject.getPrincipals() instanceof AnonymousPrincipalCollection;
}