org.apache.shiro.session.Session Java Examples

The following examples show how to use org.apache.shiro.session.Session. 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: MyShiroRealm.java    From scaffold-cloud with MIT License 6 votes vote down vote up
/**认证*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    //获取用户的输入的账号.
    String username = (String) token.getPrincipal();
    SysOperateBO operator = sysOperateFeign.findByUserName(username).getData();

    // 帐号锁定
    if (operator.getStatus() == null || operator.getStatus() == 1) {
        throw new LockedAccountException();
    }
    SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
            username,
            operator.getPwd(),
            ByteSource.Util.bytes(username),
            getName()
    );
    //当验证都通过后,把用户信息放在session里
    Session session = SecurityUtils.getSubject().getSession();
    session.setAttribute(SESSION_ATTRIBUTE_KEY_OPERATOR, operator);
    session.setAttribute(SESSION_ATTRIBUTE_KEY_OPERATOR_ID, operator.getId());
    return authenticationInfo;

}
 
Example #2
Source File: MyShiroRealm.java    From JavaQuarkBBS with Apache License 2.0 6 votes vote down vote up
/**
 * 认证
 * @param token
 * @return
 * @throws AuthenticationException
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    //获取用户的输入的账号.
    String username = (String)token.getPrincipal();
    AdminUser user = adminUserService.findByUserName(username);
    if(user==null) throw new UnknownAccountException();
    if (0==user.getEnable()) {
        throw new LockedAccountException(); // 帐号锁定
    }
    SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
            user.getId(), //用户
            user.getPassword(), //密码
            ByteSource.Util.bytes(username),
            getName() //realm name
    );
    // 把用户信息放在session里
    Session session = SecurityUtils.getSubject().getSession();
    session.setAttribute("AdminSession", user);
    session.setAttribute("AdminSessionId", user.getId());
    return authenticationInfo;
}
 
Example #3
Source File: ValidateUserFilter.java    From civism-sso with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
    boolean existSession = SecurityUtils.getSubject().isAuthenticated();
    if (!existSession) {
        return false;
    } else {
        Session session = SecurityUtils.getSubject().getSession(false);
        if (session != null) {
            Serializable id = session.getId();
            if (id != null) {
                if (redisClient.get((String) id) != null) {
                    return true;
                }
            }
        }
        return false;
    }
}
 
Example #4
Source File: GuicedCassandraSessionDAO.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Inject
public GuicedCassandraSessionDAO(com.datastax.driver.core.Session cassandraSession) {
   GsonFactory gsonFactory = new GsonFactory(
         ImmutableSet.of(),
         ImmutableSet.of(),
         ImmutableSet.of(new DefaultPrincipalTypeAdapter(), new PrincipalCollectionTypeAdapter()),
         ImmutableSet.of(new DefaultPrincipalTypeAdapter(), 	new PrincipalCollectionTypeAdapter())
   );
   this.gson = gsonFactory.get();
   this.setSessionIdGenerator(new TimeUuidSessionIdGenerator());
   this.serializer = new DefaultSerializer<SimpleSession>();
   this.cassandraSession = cassandraSession;
   this.sessionCache = 
         CacheBuilder
            .newBuilder()
            .concurrencyLevel(32)
            .expireAfterWrite(sessionCacheTimeoutMs, TimeUnit.MILLISECONDS)
            .build();
   this.readPreparedStatement = prepareReadStatement();
   this.savePreparedStatement = prepareSaveStatement();
   this.deletePreparedStatement = prepareDeleteStatement();
}
 
Example #5
Source File: AbstractIamSessionManager.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
@Override
protected void onStart(Session session, SessionContext context) {
	if (!WebUtils.isHttp(context)) {
		throw new IllegalStateException(String.format("IAM currently only supports HTTP protocol family!"));
	}

	HttpServletRequest request = WebUtils.getHttpRequest(context);
	HttpServletResponse response = WebUtils.getHttpResponse(context);
	if (isSessionIdCookieEnabled()) {
		if (StringUtils2.isEmpty(session.getId())) {
			throw new IllegalArgumentException("sessionId cannot be null when persisting for subsequent requests.");
		}
		// Storage session token
		saveSessionIdCookieIfNecessary(request, response, session.getId().toString());
	} else {
		log.debug("Session ID cookie is disabled.  No cookie has been set for new session with id {}", session.getId());
	}
	request.removeAttribute(REFERENCED_SESSION_ID_SOURCE);
	request.setAttribute(REFERENCED_SESSION_IS_NEW, TRUE);
}
 
Example #6
Source File: AuthenticationInterceptor.java    From EasyEE with MIT License 6 votes vote down vote up
/**
 * 设置当前用户的菜单
 * 
 * @param session
 * @param token
 */
public void initMenu(Session session, UsernamePasswordEncodeToken token) {
	// Set<SysMenuPermission> menus = new HashSet<SysMenuPermission>();
	// Set<SysRole> roles = sysUser.getSysRoles(); // Roles
	// // 菜单权限
	// for (SysRole role : roles) {
	// Set<SysMenuPermission> menuPermissions =
	// role.getSysMenuPermissions();
	// for (SysMenuPermission menuPermission : menuPermissions) {
	// menus.add(menuPermission);
	// }
	// }

	List<SysMenuPermission> menus = sysMenuPermissionService.listByUserId(token.getUserId());

	// 将菜单权限集合转为EasyUI菜单Tree
	List<EasyUITreeEntity> list = EasyUIUtil.getEasyUITreeFromUserMenuPermission(menus);
	Gson gson = new GsonBuilder().create();
	String menuTreeJson = gson.toJson(list);
	// session.setAttribute("menus", menus); //菜单权限集合 info
	session.setAttribute("menuTreeJson", menuTreeJson); // 菜单权限集合 info
}
 
Example #7
Source File: OnlineSessionFactory.java    From ruoyiplus with MIT License 6 votes vote down vote up
@Override
public Session createSession(SessionContext initData)
{
    OnlineSession session = new OnlineSession();
    if (initData != null && initData instanceof WebSessionContext)
    {
        WebSessionContext sessionContext = (WebSessionContext) initData;
        HttpServletRequest request = (HttpServletRequest) sessionContext.getServletRequest();
        if (request != null)
        {
            UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
            // 获取客户端操作系统
            String os = userAgent.getOperatingSystem().getName();
            // 获取客户端浏览器
            String browser = userAgent.getBrowser().getName();
            session.setHost(IpUtils.getIpAddr(request));
            session.setBrowser(browser);
            session.setOs(os);
        }
    }
    return session;
}
 
Example #8
Source File: JedisSessionDAO.java    From easyweb with Apache License 2.0 6 votes vote down vote up
@Override
public void delete(Session session) {
	if (session == null || session.getId() == null) {
		return;
	}
	
	Jedis jedis = null;
	try {
		jedis = JedisUtils.getResource();
		
		jedis.hdel(JedisUtils.getBytesKey(sessionKeyPrefix), JedisUtils.getBytesKey(session.getId().toString()));
		jedis.del(JedisUtils.getBytesKey(sessionKeyPrefix + session.getId()));

		logger.debug("delete {} ", session.getId());
	} catch (Exception e) {
		logger.error("delete {} ", session.getId(), e);
	} finally {
		JedisUtils.returnResource(jedis);
	}
}
 
Example #9
Source File: RedisSessionDAO.java    From mumu with Apache License 2.0 6 votes vote down vote up
/**
 * save session
 * @param session
 * @throws UnknownSessionException
 */
private void saveSession(Session session) throws UnknownSessionException{
    if(session == null || session.getId() == null){
        logger.error("session or session id is null");
        return;
    }
    
    byte[] key = getByteKey(session.getId());
    byte[] value = JavaSerializeUtil.serialize(session);
    session.setTimeout(expire*1000);
    try {
        this.jedisClient.set(key, value, expire);
    }catch (Exception e){
        e.printStackTrace();
    }
}
 
Example #10
Source File: RedisSessionDAO.java    From mumu with Apache License 2.0 5 votes vote down vote up
@Override
protected Serializable doCreate(Session session) {
	logger.info("save session "+session.toString());
	
    Serializable sessionId = this.generateSessionId(session);
    this.assignSessionId(session, sessionId);
    this.saveSession(session);
    return sessionId;
}
 
Example #11
Source File: AllOpenController.java    From JavaWeb with Apache License 2.0 5 votes vote down vote up
@GetMapping(value="/checkSessionExist")
@ResponseBody
public String checkSessionExist(HttpServletRequest request, 
 			             	        HttpServletResponse response){
	Session session = ShiroUtil.getSession();
	Object object = session.getAttribute(Constant.SESSION_USER);
	JSONObject jsonObject = new JSONObject();
	if(object==null){
		jsonObject.put(Constant.STATUS, Constant.STATUS_FAIL);
	}else{
		jsonObject.put(Constant.STATUS, Constant.STATUS_SUCCESS);
	}
	return jsonObject.toString();
}
 
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 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 #14
Source File: JedisSessionDAO.java    From Shop-for-JavaWeb with MIT License 5 votes vote down vote up
@Override
  public Session readSession(Serializable sessionId) throws UnknownSessionException {
  	try{
      	return super.readSession(sessionId);
  	}catch (UnknownSessionException e) {
	return null;
}
  }
 
Example #15
Source File: SubjectUtils.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public static BiMap<UUID, String> getOrganizations() {
    Subject currentUser = getSubject();
    if ( !isOrganizationAdmin() ) {
        return null;
    }
    Session session = currentUser.getSession();
    BiMap<UUID, String> organizations = HashBiMap.create();
    Map map = (Map)session.getAttribute( "organizations" );
    organizations.putAll(map);
    return organizations;
}
 
Example #16
Source File: CacheSessionDAO.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
@Override
protected void doDelete(Session session) {
	if (session == null || session.getId() == null) {  
        return;
    }
	
	super.doDelete(session);
	logger.debug("delete {} ", session.getId());
}
 
Example #17
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 #18
Source File: CacheSessionDAO.java    From easyweb with Apache License 2.0 5 votes vote down vote up
@Override
  protected Serializable doCreate(Session session) {
HttpServletRequest request = Servlets.getRequest();
if (request != null){
	String uri = request.getServletPath();
	// 如果是静态文件,则不创建SESSION
	if (Servlets.isStaticFile(uri)){
        return null;
	}
}
super.doCreate(session);
logger.debug("doCreate {} {}", session, request != null ? request.getRequestURI() : "");
  	return session.getId();
  }
 
Example #19
Source File: RelationAttributesIamSessionDAO.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
/**
 * Aware sets relation cache
 * 
 * @param session
 * @return
 */
protected Session awareRelationCache(final Session session) {
	// Sets relation cache.
	if (!isNull(session) && (session instanceof IamSession)) {
		((IamSession) session).setRelationAttrsCache(getRelationAttrsCache(session.getId()));
	}
	return session;
}
 
Example #20
Source File: UpmsAuthenticationFilter.java    From zheng with MIT License 5 votes vote down vote up
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
    Subject subject = getSubject(request, response);
    Session session = subject.getSession();
    // 判断请求类型
    String upmsType = PropertiesFileUtil.getInstance("zheng-upms-client").get("zheng.upms.type");
    session.setAttribute(UpmsConstant.UPMS_TYPE, upmsType);
    if ("client".equals(upmsType)) {
        return validateClient(request, response);
    }
    if ("server".equals(upmsType)) {
        return subject.isAuthenticated();
    }
    return false;
}
 
Example #21
Source File: OnlineSessionFilter.java    From es with Apache License 2.0 5 votes vote down vote up
@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 id设置进去
        boolean isGuest = onlineSession.getUserId() == null || onlineSession.getUserId() == 0L;
        if (isGuest == true) {
            User user = (User) request.getAttribute(Constants.CURRENT_USER);
            if (user != null) {
                onlineSession.setUserId(user.getId());
                onlineSession.setUsername(user.getUsername());
                onlineSession.markAttributeChanged();
            }
        }

        if (onlineSession.getStatus() == OnlineSession.OnlineStatus.force_logout) {
            return false;
        }
    }
    return true;
}
 
Example #22
Source File: RelationAttributesIamSessionDAO.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public Serializable create(Session session) {
	try {
		return super.create(session);
	} finally {
		// Sets relation cache.
		((IamSession) session).setRelationAttrsCache(getRelationAttrsCache(session.getId()));
	}
}
 
Example #23
Source File: CacheSessionDAO.java    From Shop-for-JavaWeb with MIT License 5 votes vote down vote up
/**
 * 获取活动会话
 * @param includeLeave 是否包括离线(最后访问时间大于3分钟为离线会话)
 * @param principal 根据登录者对象获取活动会话
 * @param filterSession 不为空,则过滤掉(不包含)这个会话。
 * @return
 */
@Override
public Collection<Session> getActiveSessions(boolean includeLeave, Object principal, Session filterSession) {
	// 如果包括离线,并无登录者条件。
	if (includeLeave && principal == null){
		return getActiveSessions();
	}
	Set<Session> sessions = Sets.newHashSet();
	for (Session session : getActiveSessions()){
		boolean isActiveSession = false;
		// 不包括离线并符合最后访问时间小于等于3分钟条件。
		if (includeLeave || DateUtils.pastMinutes(session.getLastAccessTime()) <= 3){
			isActiveSession = true;
		}
		// 符合登陆者条件。
		if (principal != null){
			PrincipalCollection pc = (PrincipalCollection)session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
			if (principal.toString().equals(pc != null ? pc.getPrimaryPrincipal().toString() : StringUtils.EMPTY)){
				isActiveSession = true;
			}
		}
		// 过滤掉的SESSION
		if (filterSession != null && filterSession.getId().equals(session.getId())){
			isActiveSession = false;
		}
		if (isActiveSession){
			sessions.add(session);
		}
	}
	return sessions;
}
 
Example #24
Source File: AuthzLoginController.java    From spring-boot-starter-samples with Apache License 2.0 5 votes vote down vote up
@ApiOperation(value = "switchRole", notes = "切换角色")
@ApiImplicitParams({ @ApiImplicitParam(name = "roleid", value = "角色ID", dataType = "String") })
//@BusinessLog(module = Constants.Module.LOGIN, business = "切换角色", opt = BusinessType.LOGIN)
@RequestMapping(value = "switchRole", method = {RequestMethod.POST, RequestMethod.GET})
public String switchRole(String roleid) {
	try {

		AuthzLoginModel principal = SubjectUtils.getPrincipal(AuthzLoginModel.class);
		Session session = SubjectUtils.getSession();
		
		
		//SubjectUtils.getSubject().runAs(principals);
		
		if (StringUtils.isNotBlank(roleid) && (!StringUtils.equals(roleid, principal.getRoleid()))) {
			/*// 切换当前的角色信息
			getUser().setJsdm(jsdm);

			// 刷新shiro缓存
			AccountRealm shiroRealm = ServiceFactory.getService(DefaultAccountRealm.class);
			shiroRealm.clearAuthorizationCache();*/
			// 刷新shiro缓存
			// 删除用户数据范围标识
			session.removeAttribute("");
		}
	} catch (Exception e) {
		logException(this, e);
	}
	return "redirect:/index";
}
 
Example #25
Source File: SessionServletTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void setup() {
  underTest = new SessionServlet();
  when(subject.isAuthenticated()).thenReturn(true);
  when(subject.getSession(false)).thenReturn(mock(Session.class));
  ThreadContext.bind(subject);
}
 
Example #26
Source File: LimitedMemorySessionDAO.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Override
public Serializable create(Session session) {
    final SimpleSession simpleSession = ensureSimpleSession(session);
    final String id = sessionIdGenerator.get();
    simpleSession.setId(id);
    cache.put(id, simpleSession);
    return session.getId();
}
 
Example #27
Source File: ShiroSessionDao.java    From Spring-Shiro-Spark with Apache License 2.0 5 votes vote down vote up
/**
 * 如果session中没有登录信息就调用doReadSession方法从Redis中重读
 * session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) == null 代表没有登录,登录后Shiro会放入该值
 * @param sessionId
 * @return
 * @throws UnknownSessionException
 */
@Override
public Session readSession(Serializable sessionId) throws UnknownSessionException{
    Session session = getCachedSession(sessionId);
    if(session == null || session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) == null) {
        session =  this.doReadSession(sessionId);
        if(session == null){
            throw new UnknownSessionException("There is no session with id [" + sessionId + "]");
        }else {
            cache(session,session.getId());
        }
    }
    return session;
}
 
Example #28
Source File: JedisIamSessionDAO.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public Session readSession(Serializable sessionId) throws UnknownSessionException {
	log.debug("readSession {}", sessionId);
	try {
		return super.readSession(sessionId);
	} catch (UnknownSessionException e) {
		return null;
	}
}
 
Example #29
Source File: JedisSessionDAO.java    From easyweb with Apache License 2.0 5 votes vote down vote up
@Override
  public Session readSession(Serializable sessionId) throws UnknownSessionException {
  	try{
      	return super.readSession(sessionId);
  	}catch (UnknownSessionException e) {
	return null;
}
  }
 
Example #30
Source File: RedisSessionDAO.java    From mysiteforme with Apache License 2.0 5 votes vote down vote up
@Override
protected Serializable doCreate(Session session) {
    Serializable sessionId = super.doCreate(session);
    logger.debug("创建session:{}", session.getId());
    redisTemplate.opsForValue().set(prefix + sessionId.toString(), session);
    return sessionId;
}