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

The following examples show how to use org.apache.shiro.subject.Subject#getSession() . 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: Realm.java    From usergrid with Apache License 2.0 6 votes vote down vote up
@Override
protected AuthorizationInfo getAuthorizationInfo(PrincipalCollection principals) {
    UsergridAuthorizationInfo info = (UsergridAuthorizationInfo)super.getAuthorizationInfo(principals);

    Subject currentUser = SecurityUtils.getSubject();
    Session session = currentUser.getSession();
    session.setAttribute( "applications", info.getApplicationSet());
    session.setAttribute("organizations", info.getOrganizationSet());
    if ( info.getOrganization() != null ) {
        session.setAttribute( "organization", info.getOrganization() );
    }
    if ( info.getApplication() != null ) {
        session.setAttribute( "application", info.getApplication() );
    }

    return info;
}
 
Example 2
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 3
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 4
Source File: UserController.java    From songjhh_blog with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/login",method = RequestMethod.POST)
public String login(UserCustom userCustom, Model model) {
    Subject subject = SecurityUtils.getSubject();
    if(!subject.isAuthenticated()) {
        UsernamePasswordToken token = new UsernamePasswordToken(userCustom.getUsername(), userCustom.getPassword());
        token.setRememberMe(true);
        try {
            subject.login(token);
            Session session = subject.getSession();
            userService.updateLoginLastTime(userService.getByUserName(userCustom.getUsername()),session);
            return "redirect:/";
        } catch (UnknownAccountException uae) {
            model.addAttribute("errorMsg", "username wasn't in the system.");
        } catch (IncorrectCredentialsException ice){
            model.addAttribute("errorMsg", "password didn't match.");
        } catch (LockedAccountException lae) {
            model.addAttribute("errorMsg", "account for that username is locked - can't login.");
        } catch (ExcessiveAttemptsException  eae) {
            model.addAttribute("errorMsg", "password lost miss too much,please try again later.");
        } catch (AuthenticationException ae) {
            model.addAttribute("errorMsg", "unexpected condition.");
        }
        model.addAttribute("userCustom", userCustom);
        return "user/login";
    }
    return "redirect:/";
}
 
Example 5
Source File: OnlineSessionFilter.java    From LuckyFrameWeb with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 表示是否允许访问;mappedValue就是[urls]配置中拦截器参数部分,如果允许访问返回true,否则false;
 */
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
    Subject subject = getSubject(request, response);
    if (subject == null || subject.getSession() == null)
    {
        return true;
    }
    Session session = onlineSessionDAO.readSession(subject.getSession().getId());
    if (session instanceof OnlineSession)
    {
        OnlineSession onlineSession = (OnlineSession) session;
        request.setAttribute(ShiroConstants.ONLINE_SESSION, onlineSession);
        // 把user对象设置进去
        boolean isGuest = onlineSession.getUserId() == null || onlineSession.getUserId() == 0L;
        if (isGuest)
        {
            User user = ShiroUtils.getSysUser();
            if (user != null)
            {
                onlineSession.setUserId(user.getUserId());
                onlineSession.setLoginName(user.getLoginName());
                onlineSession.setDeptName(user.getDept().getDeptName());
                onlineSession.markAttributeChanged();
            }
        }

        return onlineSession.getStatus() != OnlineSession.OnlineStatus.off_line;
    }
    return true;
}
 
Example 6
Source File: OnlineSessionFilter.java    From RuoYi with Apache License 2.0 5 votes vote down vote up
/**
 * 表示是否允许访问;mappedValue就是[urls]配置中拦截器参数部分,如果允许访问返回true,否则false;
 */
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue){
    Subject subject = getSubject(request, response);
    if (subject == null || subject.getSession() == null) {
        return true;
    }
    Session session = onlineSessionDAO.readSession(subject.getSession().getId());
    if (session instanceof OnlineSession) {
        OnlineSession onlineSession = (OnlineSession) session;
        request.setAttribute(ShiroConstants.ONLINE_SESSION, onlineSession);
        // 把user对象设置进去
        boolean isGuest = onlineSession.getUserId() == null || onlineSession.getUserId() == 0L;
        if (isGuest) {
            SysUser user = ShiroUtils.getSysUser();
            if (user != null) {
                onlineSession.setUserId(user.getUserId());
                onlineSession.setLoginName(user.getLoginName());
                onlineSession.setAvatar(user.getAvatar());
                onlineSession.setDeptName(user.getDept().getDeptName());
                onlineSession.markAttributeChanged();
            }
        }

        return onlineSession.getStatus() != OnlineStatus.OFF_LINE;
    }
    return true;
}
 
Example 7
Source File: UserFrontController.java    From cjs_ssms with GNU General Public License v2.0 5 votes vote down vote up
@RequestMapping("/logoutUser")
public String logout(UUser user, Model model) throws IOException {
  Subject subject = SecurityUtils.getSubject();
  Session session = subject.getSession();
  //session.removeAttribute("userName");
  session.removeAttribute("sysbUserName");
  return "redirect:/index.jsp";
}
 
Example 8
Source File: BaseController.java    From cms with Apache License 2.0 5 votes vote down vote up
public Session getSession() {
    try {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession(false);
        if (session == null) {
            session = subject.getSession();
        }
        if (session != null) {
            return session;
        }
    } catch (InvalidSessionException e) {

    }
    return null;
}
 
Example 9
Source File: AdminRealm.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
/**
 * 将一些数据放到ShiroSession中,以便于其它地方使用
 * 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到
 *
 * @param key
 * @param value
 */
private void setSession(Object key, Object value) {
    Subject currentUser = SecurityUtils.getSubject();
    if (null != currentUser) {
        Session session = currentUser.getSession();
        session.setTimeout(1800000L);
        log.info("Session默认超时时间为[" + session.getTimeout() + "]毫秒");
        if (null != session) {
            session.setAttribute(key, value);
        }
    }
}
 
Example 10
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 11
Source File: LoginRestApi.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private JsonResponse<Map<String, String>> proceedToLogin(Subject currentUser, AuthenticationToken token) {
  JsonResponse<Map<String, String>> response = null;
  try {
    logoutCurrentUser();
    currentUser.getSession(true);
    currentUser.login(token);

    Set<String> roles = authenticationService.getAssociatedRoles();
    String principal = authenticationService.getPrincipal();
    String ticket = "anonymous".equals(principal) ? "anonymous" : TicketContainer.instance.getTicket(principal);

    Map<String, String> data = new HashMap<>();
    data.put("principal", principal);
    data.put("roles", GSON.toJson(roles));
    data.put("ticket", ticket);

    response = new JsonResponse<>(Status.OK, "", data);
    // if no exception, that's it, we're done!

    // set roles for user in NotebookAuthorization module
    authorizationService.setRoles(principal, roles);
  } catch (AuthenticationException uae) {
    // username wasn't in the system, show them an error message?
    // password didn't match, try again?
    // account for that username is locked - can't login.  Show them a message?
    // unexpected condition - error?
    LOG.error("Exception in login: ", uae);
  }
  return response;
}
 
Example 12
Source File: SessionCacheManager.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
public Session getSession(){
    Session session = null;
    try{
        Subject subject = SecurityUtils.getSubject();
        session = subject.getSession(false);
        if (session == null){
            session = subject.getSession();
        }
    }catch (InvalidSessionException e){
        logger.error("Invalid session error", e);
    }catch (UnavailableSecurityManagerException e2){
        logger.error("Unavailable SecurityManager error", e2);
    }
    return session;
}
 
Example 13
Source File: OnlineSessionFilter.java    From ruoyiplus with MIT License 5 votes vote down vote up
/**
 * 表示是否允许访问;mappedValue就是[urls]配置中拦截器参数部分,如果允许访问返回true,否则false;
 */
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
        throws Exception
{
    Subject subject = getSubject(request, response);
    if (subject == null || subject.getSession() == null)
    {
        return true;
    }
    Session session = onlineSessionDAO.readSession(subject.getSession().getId());
    if (session != null && session instanceof OnlineSession)
    {
        OnlineSession onlineSession = (OnlineSession) session;
        request.setAttribute(ShiroConstants.ONLINE_SESSION, onlineSession);
        // 把user对象设置进去
        boolean isGuest = onlineSession.getUserId() == null || onlineSession.getUserId() == 0L;
        if (isGuest == true)
        {
            SysUser user = ShiroUtils.getSysUser();
            if (user != null)
            {
                onlineSession.setUserId(user.getUserId());
                onlineSession.setLoginName(user.getLoginName());
                onlineSession.setDeptName(user.getDept().getDeptName());
                onlineSession.markAttributeChanged();
            }
        }

        if (onlineSession.getStatus() == OnlineStatus.off_line)
        {
            return false;
        }
    }
    return true;
}
 
Example 14
Source File: UserManagerController.java    From cjs_ssms with GNU General Public License v2.0 5 votes vote down vote up
@RequestMapping("/mlogoutUser")
public String logout(UUser user, Model model) throws IOException {
  Subject subject = SecurityUtils.getSubject();
  Session session = subject.getSession();
  session.removeAttribute("UserName");
  return "redirect:../login.jsp";
}
 
Example 15
Source File: LoginController.java    From dpCms with Apache License 2.0 5 votes vote down vote up
/**
 * 获取登录的图片验证码
 */
@RequestMapping(value = "/imgcode", method = RequestMethod.GET)
public void captcha(HttpServletRequest request, HttpServletResponse response )
		throws ServletException, IOException {
	Subject currentUser = SecurityUtils.getSubject();
	Session session = currentUser.getSession();
	Producer captchaProducer = KaptchaProducerAgency.getKaptchaProducerExample();
	response.setDateHeader("Expires", 0);
	// Set standard HTTP/1.1 no-cache headers.
	response.setHeader("Cache-Control",
			"no-store, no-cache, must-revalidate");
	// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
	response.addHeader("Cache-Control", "post-check=0, pre-check=0");
	// Set standard HTTP/1.0 no-cache header.
	response.setHeader("Pragma", "no-cache");
	// return a jpeg
	response.setContentType("image/jpeg");
	// create the text for the image
	String capText = captchaProducer.createText();
	log.debug("******************验证码是: " + capText + "******************");
	// store the text in the session
	session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText	);
	// create the image with the text
	BufferedImage bi = captchaProducer.createImage(capText);
	ServletOutputStream out = response.getOutputStream();
	// write the data out
	ImageIO.write(bi, "jpg", out);
	try {
		out.flush();
	} finally {
		out.close();
	}
}
 
Example 16
Source File: SSORealm.java    From kafka-eagle with Apache License 2.0 4 votes vote down vote up
private Session getSession() {
	Subject subject = SecurityUtils.getSubject();
	Session sesison = subject.getSession();
	return sesison;
}
 
Example 17
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 18
Source File: LoginController.java    From taoshop with Apache License 2.0 4 votes vote down vote up
/**
 * 基于Shiro框架的登录验证,页面发送JSON请求数据,
 * 服务端进行登录验证之后,返回Json响应数据,"success"表示验证成功
 * @param request
 * @return
 * @throws Exception
 */
@RequestMapping(value="/loginCheck", produces="application/json;charset=UTF-8")
@ResponseBody
public String loginCheck(HttpServletRequest request)throws AuthenticationException {
    JSONObject obj = new JSONObject();
    String errInfo = "";//错误信息
    String logindata[] = request.getParameter("LOGINDATA").split(",");
    if(logindata != null && logindata.length == 3){
        //获取Shiro管理的Session
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        String codeSession = (String)session.getAttribute(Constants.SESSION_SECURITY_CODE);
        String code = logindata[2];
        /**检测页面验证码是否为空,调用工具类检测**/
        if(StringUtils.isEmpty(code)){
            errInfo = "nullcode";
        }else{
            String username = logindata[0];
            String password = logindata[1];
            if(StringUtils.isNotEmpty(codeSession)/*&&code.equalsIgnoreCase(codeSession)*/){
                //Shiro框架SHA加密
                String passwordsha = new SimpleHash("SHA-1",username,password).toString();
                System.out.println(passwordsha);
                //检测用户名和密码是否正确
                SysUser user = iSysUserService.getSysUser(username,passwordsha);
                if(user != null){
                    if(Boolean.TRUE.equals(user.getLocked())){
                        errInfo = "locked";
                    }else{
                        //Shiro添加会话
                        session.setAttribute("username", username);
                        session.setAttribute(Constants.SESSION_USER, user);
                        //删除验证码Session
                        session.removeAttribute(Constants.SESSION_SECURITY_CODE);
                        //保存登录IP
                        //getRemortIP(username);
                        /**Shiro加入身份验证**/
                        Subject sub = SecurityUtils.getSubject();
                        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
                        sub.login(token);
                        log.info("登录成功!");
                    }
                }else{
                    //账号或者密码错误
                    errInfo = "uerror";
                }
                if(StringUtils.isEmpty(errInfo)){
                    errInfo = "success";
                }
            }else{
                //缺少参数
                errInfo="codeerror";
            }
        }
    }
    obj.put("result", errInfo);
    return obj.toString();
}
 
Example 19
Source File: SSOFilter.java    From kafka-eagle with Apache License 2.0 4 votes vote down vote up
private Session getSession() {
	Subject subject = SecurityUtils.getSubject();
	return subject.getSession();
}
 
Example 20
Source File: LoginController.java    From dpCms with Apache License 2.0 4 votes vote down vote up
/**
 * 
 * @Title: loginDo 
 * @Description: 平台登录
 * @param @param username
 * @param @param password
 * @return Response 返回类型,如果成功返回跳转的URL
 * @throws
 */
@RequestMapping(value = "/login")
@ResponseBody
public Response login(String username, String password, String logincode , Response response ) {
	String msg = "";
	Subject currentUser = SecurityUtils.getSubject();
	Session session = currentUser.getSession();
	String codeSession = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
	if (StringUtils.isBlank(logincode) || StringUtils.isBlank(codeSession)
			|| !logincode.equals(codeSession)) {
		response.setStateCode(StateCode.LOGIN_FAIL);
		msg = "验证码不正确,朋友!";
	} else {
		AuthenticationToken token = new UsernamePasswordToken(username,password);
		Account account = accountService.findByLoginName(username);
		try {
			currentUser.login(token);
			account.setPassword("");
			// 获取当前登录用户的岗位信息。
			CurrentInfo currentInfo = currentUserInfoService.findCurrentUserInfo(account);
			Employee emplpyee = currentInfo.getEmployee();
			if (emplpyee == null || emplpyee.getDefaultPostId() == null) {
				throw new AccountNoActiceException();
			}
			long defaultPostId = emplpyee.getDefaultPostId();

			// 遍历岗位信息,如果有一个岗位不需要过滤权限,那么这个人不需要过滤权限
			Set<Post> postSet = currentInfo.getPostList();
			Iterator<Post> it = postSet.iterator();
			if (it.hasNext()) {
				Post post = it.next();
				if (post.getNeedFilter() == null) {// 当前登录的员工不需要过滤任何权限
					currentInfo.setNeedFilter(false);
				}
				if (post.getId() == defaultPostId) {// 该人的默认岗位
					currentInfo.setDefaultPostId(defaultPostId);// 保存到SESSION里,快速获取
					currentInfo.setIndexPage(post.getIndexPage());// 保存到SESSION里,快速获取
					currentUser.getSession().setAttribute("currentInfo", currentInfo);
					response.setStateCode(StateCode.OK);
					response.setData("index.html");// 把该人应该跳转的页面返回到客户端
				}
			}

			msg = "登录成功";
		} catch (UnknownAccountException uae) {
			response.setStateCode(StateCode.LOGIN_FAIL);
			msg = "用户不存在!";
		} catch (IncorrectCredentialsException ice) {
			response.setStateCode(StateCode.LOGIN_FAIL);
			msg = "用户名或密码错误!";
		} catch (LockedAccountException lae) {
			response.setStateCode(StateCode.LOGIN_FAIL);
			msg = "用户为锁定状态!";
		} catch (AuthenticationException ae) {
			response.setStateCode(StateCode.LOGIN_FAIL);
			ae.printStackTrace();
			msg = "登录失败!";
		} catch (AccountNoActiceException ana) {
			response.setStateCode(StateCode.LOGIN_FAIL);
			msg = "该帐号未激活!";
		} catch (Exception e) {
			response.setStateCode(StateCode.LOGIN_FAIL);
			e.printStackTrace();
			msg = "平台繁忙!";
		}
	}
	response.setMessage(msg);
	currentUser.getSession().removeAttribute(Constants.KAPTCHA_SESSION_KEY);
	return response;
}