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

The following examples show how to use org.apache.shiro.subject.Subject#getPrincipal() . 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: AdminAuthController.java    From dts-shop with GNU Lesser General Public License v3.0 8 votes vote down vote up
@RequiresAuthentication
@GetMapping("/info")
public Object info() {
	Subject currentUser = SecurityUtils.getSubject();
	DtsAdmin admin = (DtsAdmin) currentUser.getPrincipal();

	Map<String, Object> data = new HashMap<>();
	data.put("name", admin.getUsername());
	data.put("avatar", admin.getAvatar());

	Integer[] roleIds = admin.getRoleIds();
	Set<String> roles = roleService.queryByIds(roleIds);
	Set<String> permissions = permissionService.queryByRoleIds(roleIds);
	data.put("roles", roles);
	// NOTE
	// 这里需要转换perms结构,因为对于前端而已API形式的权限更容易理解
	data.put("perms", toAPI(permissions));

	logger.info("【请求结束】系统管理->用户信息获取,响应结果:{}", JSONObject.toJSONString(data));
	return ResponseUtil.ok(data);
}
 
Example 2
Source File: PermissionUtils.java    From supplierShop with MIT License 6 votes vote down vote up
/**
 * 返回用户属性值
 *
 * @param property 属性名称
 * @return 用户属性值
 */
public static Object getPrincipalProperty(String property)
{
    Subject subject = SecurityUtils.getSubject();
    if (subject != null)
    {
        Object principal = subject.getPrincipal();
        try
        {
            BeanInfo bi = Introspector.getBeanInfo(principal.getClass());
            for (PropertyDescriptor pd : bi.getPropertyDescriptors())
            {
                if (pd.getName().equals(property) == true)
                {
                    return pd.getReadMethod().invoke(principal, (Object[]) null);
                }
            }
        }
        catch (Exception e)
        {
            log.error("Error reading property [{}] from principal of type [{}]", property,
                    principal.getClass().getName());
        }
    }
    return null;
}
 
Example 3
Source File: AdminAdminController.java    From litemall with MIT License 6 votes vote down vote up
@RequiresPermissions("admin:admin:delete")
@RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "删除")
@PostMapping("/delete")
public Object delete(@RequestBody LitemallAdmin admin) {
    Integer anotherAdminId = admin.getId();
    if (anotherAdminId == null) {
        return ResponseUtil.badArgument();
    }

    // 管理员不能删除自身账号
    Subject currentUser = SecurityUtils.getSubject();
    LitemallAdmin currentAdmin = (LitemallAdmin) currentUser.getPrincipal();
    if (currentAdmin.getId().equals(anotherAdminId)) {
        return ResponseUtil.fail(ADMIN_DELETE_NOT_ALLOWED, "管理员不能删除自己账号");
    }

    adminService.deleteById(anotherAdminId);
    logHelper.logAuthSucceed("删除管理员", admin.getUsername());
    return ResponseUtil.ok();
}
 
Example 4
Source File: SysUserFilter.java    From es with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
    Subject subject = getSubject(request, response);
    if (subject == null) {
        return true;
    }

    String username = (String) subject.getPrincipal();
    //此处注意缓存 防止大量的查询db
    User user = userService.findByUsername(username);
    //把当前用户放到session中
    request.setAttribute(Constants.CURRENT_USER, user);
    //druid监控需要
    ((HttpServletRequest)request).getSession().setAttribute(Constants.CURRENT_USERNAME, username);

    return true;
}
 
Example 5
Source File: SecurityConcern.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private void handleRequiresUser( Subject subject )
{
    if ( requiresUser != null ) {
        LOGGER.debug( "SecurityConcern::RequiresUser" );
        if ( subject.getPrincipal() == null ) {
            throw new UnauthenticatedException(
                    "Attempting to perform a user-only operation. The current Subject is "
                    + "not a user (they haven't been authenticated or remembered from a previous login).  "
                    + "Access denied." );
        }
    } else {
        LOGGER.debug( "SecurityConcern::RequiresUser: not concerned" );
    }
}
 
Example 6
Source File: ShiroSecuritySupport.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public PrincipalProvider<?> getIdentityPrincipal() {
    Subject subject = SecurityUtils.getSubject();
    if (subject.getPrincipal() instanceof PrincipalProvider) {
        return (PrincipalProvider<?>) subject.getPrincipal();
    }
    return Principals.identityPrincipal("");
}
 
Example 7
Source File: ForceLogoutFilter.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
	Subject subject = getSubject(request, response);
	if (!subject.isAuthenticated() && !subject.isRemembered()) {
		return this.respondLogin(request, response);
	}
	Session currentSession = subject.getSession();
       if (null!=currentSession.getAttribute(ShiroProperties.ATTRIBUTE_SESSION_FORCE_LOGOUT)) {
       	String account = (String) subject.getPrincipal();
           subject.logout();
           this.authListenerManager.onForceLogout(request, account);
		return this.respondRedirect(request, response,this.properties.getForceLogoutUrl());
       }
       return true;
}
 
Example 8
Source File: JsetsAuthorizationFilter.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
    Subject subject = getSubject(request, response);
    //未认证
    if (null == subject.getPrincipal()) {
		if (CommonUtils.isAjax(WebUtils.toHttp(request))) {
			CommonUtils.ajaxFailed(WebUtils.toHttp(response) 
					,HttpServletResponse.SC_UNAUTHORIZED
					,ShiroProperties.REST_CODE_AUTH_UNAUTHORIZED
					,ShiroProperties.REST_MESSAGE_AUTH_UNAUTHORIZED);
		}
        saveRequestAndRedirectToLogin(request, response);
    //未授权
    } else {
		if (CommonUtils.isAjax(WebUtils.toHttp(request))) {
			CommonUtils.ajaxFailed(WebUtils.toHttp(response) 
					,HttpServletResponse.SC_FORBIDDEN
					,ShiroProperties.REST_CODE_AUTH_FORBIDDEN
					,ShiroProperties.REST_MESSAGE_AUTH_FORBIDDEN);
		}else{
            String unauthorizedUrl = getUnauthorizedUrl();
            if (StringUtils.hasText(unauthorizedUrl)) {
                WebUtils.issueRedirect(request, response, unauthorizedUrl);
            } else {
                WebUtils.toHttp(response).sendError(HttpServletResponse.SC_FORBIDDEN);
            }
		}
    }
    return false;
}
 
Example 9
Source File: AccountManager.java    From DWSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 取出当前登陆用户
 */
public User getCurUser(){
	Subject subject=SecurityUtils.getSubject();
	
	if(subject!=null){
		Object principal=subject.getPrincipal();
		if(principal!=null){
			User user = findUserByLoginName(principal.toString());
			return user;
		}
	}
	return null;
}
 
Example 10
Source File: UserIdHelper.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Get the user-id from the given subject or {@link #UNKNOWN}.
 */
public static String get(@Nullable final Subject subject) {
  if (subject != null) {
    Object principal = subject.getPrincipal();
    if (principal != null) {
      return principal.toString();
    }
  }
  return UNKNOWN;
}
 
Example 11
Source File: AccountSubjectFactory.java    From mblog with GNU General Public License v3.0 5 votes vote down vote up
private void handlerSession(Subject subject) {
    Session session = subject.getSession(true);
    if ((subject.isAuthenticated() || subject.isRemembered()) && session.getAttribute("profile") == null) {
        AccountProfile profile = (AccountProfile) subject.getPrincipal();
        log.debug("reload session - " + profile.getUsername());
        session.setAttribute("profile", userService.findProfile(profile.getId()));
    }
}
 
Example 12
Source File: LogoutFilter.java    From frpMgr with MIT License 5 votes vote down vote up
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
	try{
		Subject subject = getSubject(request, response);
        String redirectUrl = getRedirectUrl(request, response, subject);
        //try/catch added for SHIRO-298:
        try {
        	Object principal = subject.getPrincipal();
        	if (principal != null){
        		// 记录用户退出日志(@Deprecated v4.0.5支持setAuthorizingRealm,之后版本可删除此if子句)
	        	if (authorizingRealm == null){
		    		LogUtils.saveLog(UserUtils.getUser(), ServletUtils.getRequest(),
		    				"系统退出", Log.TYPE_LOGIN_LOGOUT);
	        	}
	        	// 退出成功之前初始化授权信息并处理登录后的操作
	        	else{
	        		authorizingRealm.onLogoutSuccess((LoginInfo)subject.getPrincipal(),
	        				(HttpServletRequest)request);
	        	}
        	}
    		// 退出登录	
    		subject.logout();
        } catch (SessionException ise) {
            log.debug("Encountered session exception during logout.  This can generally safely be ignored.", ise);
        }
        
        // 如果是Ajax请求,返回Json字符串。
 		if (ServletUtils.isAjaxRequest((HttpServletRequest)request)){
 			ServletUtils.renderResult((HttpServletResponse)response,
 					Global.TRUE, Global.getText("sys.logout.success"));
 			return false;
 		}
     	
        issueRedirect(request, response, redirectUrl);
	}catch(Exception e){
		log.debug("Encountered session exception during logout.  This can generally safely be ignored.", e);
	}
	return false;
}
 
Example 13
Source File: RoleController.java    From Mario with Apache License 2.0 5 votes vote down vote up
/**
 * 重置User的Menu信息
 */
private void resetUserMenu() {
    Subject currentUser = SecurityUtils.getSubject();
    ShiroUser user = (ShiroUser) currentUser.getPrincipal();

    Session session = currentUser.getSession();
    List<Menu> menus = accountService.findMenuByUserID(user.getId());
    session.setAttribute("menuList", menus);
}
 
Example 14
Source File: RestAuthorizationFilter.java    From Shiro-Action with MIT License 4 votes vote down vote up
/**
 * 当没有权限被拦截时:
 *          如果是 AJAX 请求, 则返回 JSON 数据.
 *          如果是普通请求, 则跳转到配置 UnauthorizedUrl 页面.
 */
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
    Subject subject = getSubject(request, response);
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    // 如果未登录
    if (subject.getPrincipal() == null) {
        // AJAX 请求返回 JSON
        if (WebHelper.isAjaxRequest(WebUtils.toHttp(request))) {
            if (log.isDebugEnabled()) {
                log.debug("sessionId: [{}], ip: [{}] 请求 restful url : {}, 未登录被拦截.",
                        httpServletRequest.getRequestedSessionId(),
                        IPUtils.getIpAddr(),
                        this.getPathWithinApplication(request));
            }
            WebHelper.writeJson(ResultBean.error("未登录"), response);
        } else {
            // 其他请求跳转到登陆页面
            saveRequestAndRedirectToLogin(request, response);
        }
    } else {
        // 如果已登陆, 但没有权限
        // 对于 AJAX 请求返回 JSON
        if (WebHelper.isAjaxRequest(WebUtils.toHttp(request))) {
            if (log.isDebugEnabled()) {
                log.debug("用户: [{}] 请求 restful url : {}, 无权限被拦截.", subject.getPrincipal(), this.getPathWithinApplication(request));
            }

            WebHelper.writeJson(ResultBean.error("无权限"), response);
        } else {
            // 对于普通请求, 跳转到配置的 UnauthorizedUrl 页面.
            // 如果未设置 UnauthorizedUrl, 则返回 401 状态码
            String unauthorizedUrl = getUnauthorizedUrl();
            if (StringUtils.hasText(unauthorizedUrl)) {
                WebUtils.issueRedirect(request, response, unauthorizedUrl);
            } else {
                WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
            }
        }

    }
    return false;
}
 
Example 15
Source File: TeacherController.java    From Online_Study_System with Apache License 2.0 4 votes vote down vote up
/**
 * 获取当前用户名
 * @return 用户名
 */
private String getUserName() {
    Subject subject = SecurityUtils.getSubject();
    String userName = (String) subject.getPrincipal();
    return userName;
}
 
Example 16
Source File: KeepOneUserFilter.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
	Subject subject = getSubject(request, response);
	if (!subject.isAuthenticated() && !subject.isRemembered()) {
		return this.respondLogin(request, response);
	}
	String account = (String) subject.getPrincipal();
	String loginedSessionId = this.cacheDelegator.getKeepUser(account);
	Session loginedSession = null;
	Session currentSession = subject.getSession();
	String currentSessionId = (String) currentSession.getId();
	
	if(currentSessionId.equals(loginedSessionId)) {
		return true;
	} else if (Strings.isNullOrEmpty(loginedSessionId)){
		this.cacheDelegator.putKeepUser(account, currentSessionId);
       	return true;
	} else if (null==currentSession.getAttribute(ShiroProperties.ATTRIBUTE_SESSION_KICKOUT)) {
		this.cacheDelegator.putKeepUser(account, currentSessionId);
		try{
			loginedSession = this.sessionManager.getSession(new DefaultSessionKey(loginedSessionId));
			if(null != loginedSession){
				loginedSession.setAttribute(ShiroProperties.ATTRIBUTE_SESSION_KICKOUT,Boolean.TRUE);
			}
		} catch(SessionException e){
			LOGGER.warn(e.getMessage());
		}
	}
       if (null!=currentSession.getAttribute(ShiroProperties.ATTRIBUTE_SESSION_KICKOUT)) {
       	subject.logout();
       	String loginedHost = "";
       	Date loginedTime = null;
		if(null != loginedSession){
			loginedHost = loginedSession.getHost();
			loginedTime = loginedSession.getStartTimestamp();
		}
		this.authListenerManager.onKeepOneKickout(request, account, loginedHost, loginedTime);
		return this.respondRedirect(request, response,this.properties.getKickoutUrl());
       }

	return true;
}
 
Example 17
Source File: LoginRegisterController.java    From DouBiNovel with Apache License 2.0 4 votes vote down vote up
@RequestMapping(method = RequestMethod.POST, value = "/doLogin")
@ResponseBody
public MvcResult doLogin(String username, String password, String captcha, boolean rememberMe, HttpSession session, HttpServletRequest request) {
    MvcResult result = MvcResult.create(false);
    if (captcha == null || !Objects.equals(captcha, session.getAttribute(Const.session.VERIFICATION_CODE).toString())) {
        result.setMessage("验证码错误");
    } else if (StringUtils.isEmpty(username)) {
        result.setMessage("账号不能为空");
    } else if (StringUtils.isEmpty(password)) {
        result.setMessage("密码不能为空");
    } else {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        try {
            subject.login(token);
            if (subject.isAuthenticated()) {
                result.setSuccess(true);
                result.setMessage("登录成功");
                User user = (User) subject.getPrincipal();
                session.setAttribute(Const.session.LOGIN_USER,user);
                LoginLog loginLog = new LoginLog();
                loginLog.setUserId(user.getId());
                loginLog.setName(user.getName());
                loginLog.setLoginType(1);
                String ip = IpUtil.getIpAddr(request);
                loginLog.setLoginIp(ip);
                loginLogService.add(loginLog);
            } else {
                result.setSuccess(false);
                result.setMessage("登录失败");
                token.clear();
            }
        } catch (UnknownAccountException uae) {
            result.setMessage("未知账户");
        } catch (IncorrectCredentialsException ice) {
            result.setMessage("密码不正确");
        } catch (LockedAccountException lae) {
            result.setMessage("账户已锁定");
        } catch (ExcessiveAttemptsException eae) {
            result.setMessage("用户名或密码错误次数过多");
        } catch (AuthenticationException ae) {
            result.setMessage("用户名或密码不正确");
        } finally {
            if (!result.isSuccess()) {
                token.clear();
                subject.logout();
            }
        }
    }
    return result;
}
 
Example 18
Source File: UserController.java    From springboot-shiro-cas-mybatis with MIT License 4 votes vote down vote up
@RequestMapping("/userGet")
@ResponseBody
public String userGet(HttpServletRequest req,HttpServletResponse respon)throws Exception{
	Subject currentUser = SecurityUtils.getSubject();		
	return (String) currentUser.getPrincipal();
}
 
Example 19
Source File: GunsUserFilter.java    From WebStack-Guns with MIT License 3 votes vote down vote up
/**
 * Returns <code>true</code> if the request is a
 * {@link #isLoginRequest(javax.servlet.ServletRequest, javax.servlet.ServletResponse) loginRequest} or
 * if the current {@link #getSubject(javax.servlet.ServletRequest, javax.servlet.ServletResponse) subject}
 * is not <code>null</code>, <code>false</code> otherwise.
 *
 * @return <code>true</code> if the request is a
 * {@link #isLoginRequest(javax.servlet.ServletRequest, javax.servlet.ServletResponse) loginRequest} or
 * if the current {@link #getSubject(javax.servlet.ServletRequest, javax.servlet.ServletResponse) subject}
 * is not <code>null</code>, <code>false</code> otherwise.
 */
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
    if (isLoginRequest(request, response)) {
        return true;
    } else {
        Subject subject = getSubject(request, response);
        // If principal is not null, then the user is known and should be allowed access.
        return subject.getPrincipal() != null;
    }
}
 
Example 20
Source File: UserFilter.java    From tapestry-security with Apache License 2.0 3 votes vote down vote up
/**
 * Returns <code>true</code> if the request is a
 * {@link #isLoginRequest(javax.servlet.ServletRequest, javax.servlet.ServletResponse) loginRequest} or
 * if the current {@link #getSubject(javax.servlet.ServletRequest, javax.servlet.ServletResponse) subject}
 * is not <code>null</code>, <code>false</code> otherwise.
 *
 * @return <code>true</code> if the request is a
 * {@link #isLoginRequest(javax.servlet.ServletRequest, javax.servlet.ServletResponse) loginRequest} or
 * if the current {@link #getSubject(javax.servlet.ServletRequest, javax.servlet.ServletResponse) subject}
 * is not <code>null</code>, <code>false</code> otherwise.
 */
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
    if (isLoginRequest(request, response)) {
        return true;
    } else {
        Subject subject = getSubject(request, response);
        // If principal is not null, then the user is known and should be allowed access.
        return subject.getPrincipal() != null;
    }
}