Codota Logo
Session
Code IndexAdd Codota to your IDE (free)

How to use
Session
in
org.apache.shiro.session

Best Java code snippets using org.apache.shiro.session.Session (Showing top 20 results out of 918)

Refine searchRefine arrow

  • Subject
  • SecurityUtils
  • Common ways to obtain Session
private void myMethod () {
Session s =
  • Codota IconSecurityUtils.getSubject().getSession()
  • Codota IconSubject subject;subject.getSession(false)
  • Codota IconSubject subject;subject.getSession()
  • Smart code suggestions by Codota
}
origin: apache/shiro

Session session = subject.getSession(false);
  if (subject.isAuthenticated()) {
    session = subject.getSession();
    session.setAttribute(DefaultSubjectContext.AUTHENTICATED_SESSION_KEY, Boolean.TRUE);
  Boolean existingAuthc = (Boolean) session.getAttribute(DefaultSubjectContext.AUTHENTICATED_SESSION_KEY);
  if (subject.isAuthenticated()) {
    if (existingAuthc == null || !existingAuthc) {
      session.setAttribute(DefaultSubjectContext.AUTHENTICATED_SESSION_KEY, Boolean.TRUE);
    if (existingAuthc != null) {
      session.removeAttribute(DefaultSubjectContext.AUTHENTICATED_SESSION_KEY);
origin: killbill/killbill

public SessionModelDao(final Session session) {
  this.id = session.getId() == null ? null : session.getId().toString();
  this.startTimestamp = new DateTime(session.getStartTimestamp(), DateTimeZone.UTC);
  this.lastAccessTime = new DateTime(session.getLastAccessTime(), DateTimeZone.UTC);
  this.timeout = session.getTimeout();
  this.host = session.getHost();
  try {
    this.sessionData = serializeSessionData(session);
  } catch (final IOException e) {
    this.sessionData = new byte[]{};
  }
}
origin: killbill/killbill

  private byte[] serializeSessionData(final Session session) throws IOException {
    final Map<Object, Object> sessionAttributes = new HashMap<Object, Object>();
    for (final Object key : session.getAttributeKeys()) {
      sessionAttributes.put(key, session.getAttribute(key));
    }

    return serializer.serialize(sessionAttributes);
  }
}
origin: apache/shiro

SecurityUtils.setSecurityManager(securityManager);
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
  log.info("Retrieved the correct value! [" + value + "]");
if (!currentUser.isAuthenticated()) {
  UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
  token.setRememberMe(true);
  try {
    currentUser.login(token);
  } catch (UnknownAccountException uae) {
    log.info("There is no user with username of " + token.getPrincipal());
origin: apache/shiro

@Test
public void testDefaultConfig() {
  Subject subject = SecurityUtils.getSubject();
  AuthenticationToken token = new UsernamePasswordToken("guest", "guest");
  subject.login(token);
  assertTrue(subject.isAuthenticated());
  assertTrue("guest".equals(subject.getPrincipal()));
  assertTrue(subject.hasRole("guest"));
  Session session = subject.getSession();
  session.setAttribute("key", "value");
  assertEquals(session.getAttribute("key"), "value");
  subject.logout();
  assertNull(subject.getSession(false));
  assertNull(subject.getPrincipal());
  assertNull(subject.getPrincipals());
}
origin: org.copper-engine/copper-monitoring-server

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (SecurityUtils.getSubject().isAuthenticated()) {
      return method.invoke(copperMonitoringService, args);
    } else {
      final String text = "user not authenticated: " + SecurityUtils.getSubject().getPrincipal() + " session:" + SecurityUtils.getSubject().getSession().getHost();
      logger.warn(text);
      throw new RemoteAccessException(text);
    }
  }
}
origin: apache/shiro

  @Test
  public void testVMSingleton() {
    DefaultSecurityManager sm = new DefaultSecurityManager();
    Ini ini = new Ini();
    Ini.Section section = ini.addSection(IniRealm.USERS_SECTION_NAME);
    section.put("guest", "guest");
    sm.setRealm(new IniRealm(ini));
    SecurityUtils.setSecurityManager(sm);

    try {
      Subject subject = SecurityUtils.getSubject();

      AuthenticationToken token = new UsernamePasswordToken("guest", "guest");
      subject.login(token);
      subject.getSession().setAttribute("key", "value");
      assertTrue(subject.getSession().getAttribute("key").equals("value"));

      subject = SecurityUtils.getSubject();

      assertTrue(subject.isAuthenticated());
      assertTrue(subject.getSession().getAttribute("key").equals("value"));
    } finally {
      sm.destroy();
      //SHIRO-270:
      SecurityUtils.setSecurityManager(null);
    }
  }
}
origin: Graylog2/graylog2-server

final Subject subject = new Subject.Builder().sessionId(id).host(remoteAddrFromRequest).buildSubject();
ThreadContext.bind(subject);
final Session s = subject.getSession();
try {
  subject.login(new UsernamePasswordToken(createRequest.username(), createRequest.password()));
  final User user = userService.load(createRequest.username());
  if (user != null) {
    long timeoutInMillis = user.getSessionTimeoutMs();
    s.setTimeout(timeoutInMillis);
  } else {
    s.setTimeout(TimeUnit.HOURS.toMillis(8));
  s.touch();
  ((DefaultSecurityManager) SecurityUtils.getSecurityManager()).getSubjectDAO().save(subject);
  subject.logout();
if (subject.isAuthenticated()) {
  id = s.getId();
  return SessionResponse.create(new DateTime(s.getLastAccessTime(), DateTimeZone.UTC).plus(s.getTimeout()).toDate(),
      id.toString());
} else {
origin: apache/shiro

public static void saveRequest(ServletRequest request) {
  Subject subject = SecurityUtils.getSubject();
  Session session = subject.getSession();
  HttpServletRequest httpRequest = toHttp(request);
  SavedRequest savedRequest = new SavedRequest(httpRequest);
  session.setAttribute(SAVED_REQUEST_KEY, savedRequest);
}
origin: apache/shiro

/**
 * Test that validates functionality for issue
 * <a href="https://issues.apache.org/jira/browse/JSEC-46">JSEC-46</a>
 */
@Test
public void testAutoCreateSessionAfterInvalidation() {
  Subject subject = SecurityUtils.getSubject();
  Session session = subject.getSession();
  Serializable origSessionId = session.getId();
  String key = "foo";
  String value1 = "bar";
  session.setAttribute(key, value1);
  assertEquals(value1, session.getAttribute(key));
  //now test auto creation:
  session.setTimeout(50);
  try {
    Thread.sleep(150);
  } catch (InterruptedException e) {
    //ignored
  }
  try {
    session.setTimeout(AbstractValidatingSessionManager.DEFAULT_GLOBAL_SESSION_TIMEOUT);
    fail("Session should have expired.");
  } catch (ExpiredSessionException expected) {
  }
}
origin: apache/geode

/**
 * @return return a shiro subject
 */
@Override
public Subject login(final Properties credentials) {
 if (credentials == null) {
  throw new AuthenticationRequiredException("credentials are null");
 }
 // this makes sure it starts with a clean user object
 ThreadContext.remove();
 Subject currentUser = SecurityUtils.getSubject();
 GeodeAuthenticationToken token = new GeodeAuthenticationToken(credentials);
 try {
  logger.debug("Logging in " + token.getPrincipal());
  currentUser.login(token);
 } catch (ShiroException e) {
  logger.info("error logging in: " + token.getPrincipal());
  throw new AuthenticationFailedException(
    "Authentication error. Please check your credentials.", e);
 }
 Session currentSession = currentUser.getSession();
 currentSession.setAttribute(CREDENTIALS_SESSION_ATTRIBUTE, credentials);
 return currentUser;
}
origin: linlinjava/litemall

@PostMapping("/login")
public Object login(@RequestBody String body) {
  String username = JacksonUtil.parseString(body, "username");
  String password = JacksonUtil.parseString(body, "password");
  if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
    return ResponseUtil.badArgument();
  }
  Subject currentUser = SecurityUtils.getSubject();
  try {
    currentUser.login(new UsernamePasswordToken(username, password));
  } catch (UnknownAccountException uae) {
    return ResponseUtil.fail(ADMIN_INVALID_ACCOUNT, "用户帐号或密码不正确");
  } catch (LockedAccountException lae) {
    return ResponseUtil.fail(ADMIN_INVALID_ACCOUNT, "用户帐号已锁定不可用");
  } catch (AuthenticationException ae) {
    return ResponseUtil.fail(ADMIN_INVALID_ACCOUNT, ae.getMessage());
  }
  return ResponseUtil.ok(currentUser.getSession().getId());
}
origin: Graylog2/graylog2-server

@GET
@ApiOperation(value = "Validate an existing session",
  notes = "Checks the session with the given ID: returns http status 204 (No Content) if session is valid.",
  code = 204
)
public SessionValidationResponse validateSession(@Context ContainerRequestContext requestContext) {
  try {
    this.authenticationFilter.filter(requestContext);
  } catch (NotAuthorizedException | LockedAccountException | IOException e) {
    return SessionValidationResponse.invalid();
  }
  final Subject subject = getSubject();
  if (!subject.isAuthenticated()) {
    return SessionValidationResponse.invalid();
  }
  // there's no valid session, but the authenticator would like us to create one
  if (subject.getSession(false) == null && ShiroSecurityContext.isSessionCreationRequested()) {
    final Session session = subject.getSession();
    LOG.debug("Session created {}", session.getId());
    session.touch();
    // save subject in session, otherwise we can't get the username back in subsequent requests.
    ((DefaultSecurityManager) SecurityUtils.getSecurityManager()).getSubjectDAO().save(subject);
    return SessionValidationResponse.validWithNewSession(String.valueOf(session.getId()),
                               String.valueOf(subject.getPrincipal()));
  }
  return SessionValidationResponse.valid();
}
origin: apache/shiro

public static SavedRequest getSavedRequest(ServletRequest request) {
  SavedRequest savedRequest = null;
  Subject subject = SecurityUtils.getSubject();
  Session session = subject.getSession(false);
  if (session != null) {
    savedRequest = (SavedRequest) session.getAttribute(SAVED_REQUEST_KEY);
  }
  return savedRequest;
}
origin: apache/usergrid

public static OrganizationInfo getOrganization() {
  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" );
  return organization;
}
origin: 527515025/springBoot

  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    logger.info("doGetAuthorizationInfo+"+principalCollection.toString());
    User user = userService.getByUserName((String) principalCollection.getPrimaryPrincipal());


    //把principals放session中 key=userId value=principals
    SecurityUtils.getSubject().getSession().setAttribute(String.valueOf(user.getId()),SecurityUtils.getSubject().getPrincipals());

    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    //赋予角色
    for(Role userRole:user.getRoles()){
      info.addRole(userRole.getName());
    }
    //赋予权限
    for(Permission permission:permissionService.getByUserId(user.getId())){
//            if(StringUtils.isNotBlank(permission.getPermCode()))
        info.addStringPermission(permission.getName());
    }

    //设置登录次数、时间
//        userService.updateUserLogin(user);
    return info;
  }

origin: apache/shiro

if (subject.isRunAs() && subject instanceof DelegatingSubject) {
  try {
    Field field = DelegatingSubject.class.getDeclaredField("principals");
  currentPrincipals = subject.getPrincipals();
Session session = subject.getSession(false);
    session = subject.getSession();
    session.setAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY, currentPrincipals);
      (PrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
      session.removeAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
      session.setAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY, currentPrincipals);
origin: apache/shiro

try {
  SecurityUtils.getSecurityManager();
  if (!sessionManagerMethodInvocation) {
    Subject subject = SecurityUtils.getSubject();
    Session session = subject.getSession(false);
    if (session != null) {
      sessionId = session.getId();
      host = session.getHost();
origin: apache/shiro

public static SavedRequest getAndClearSavedRequest(ServletRequest request) {
  SavedRequest savedRequest = getSavedRequest(request);
  if (savedRequest != null) {
    Subject subject = SecurityUtils.getSubject();
    Session session = subject.getSession();
    session.removeAttribute(SAVED_REQUEST_KEY);
  }
  return savedRequest;
}
origin: com.gitee.zhaohuihua/bdp-general-web

  /** Session已修改, 触发Shiro框架保存到缓存, 如果不这样做分布式Session的属性不会更新 **/
  public static void sessionChanged() {
    Session session = SecurityUtils.getSubject().getSession();
    // 随机修改一个属性, 触发NativeSessionManager的onChange(session)
    session.setAttribute("<<NULL>>", RandomTools.generateNumber(6));
    session.removeAttribute("<<NULL>>");
  }
}
org.apache.shiro.sessionSession

Javadoc

A Session is a stateful data context associated with a single Subject (user, daemon process, etc) who interacts with a software system over a period of time.

A Session is intended to be managed by the business tier and accessible via other tiers without being tied to any given client technology. This is a great benefit to Java systems, since until now, the only viable session mechanisms were the javax.servlet.http.HttpSession or Stateful Session EJB's, which many times unnecessarily coupled applications to web or ejb technologies.

Most used methods

  • getAttribute
    Returns the object bound to this session identified by the specified key. If there is no object boun
  • setAttribute
    Binds the specified value to this session, uniquely identified by the specifed key name. If there is
  • getId
    Returns the unique identifier assigned by the system upon session creation. All return values from t
  • removeAttribute
    Removes (unbinds) the object bound to this session under the specified key name.
  • getHost
    Returns the host name or IP string of the host that originated this session, or nullif the host is u
  • getTimeout
    Returns the time in milliseconds that the session session may remain idle before expiring. * A negat
  • getLastAccessTime
    Returns the last time the application received a request or method invocation from the user associat
  • getStartTimestamp
    Returns the time the session was started; that is, the time the system created the instance.
  • setTimeout
    Sets the time in milliseconds that the session may remain idle before expiring. * A negative val
  • getAttributeKeys
    Returns the keys of all the attributes stored under this session. If there are no attributes, this r
  • stop
    Explicitly stops (invalidates) this session and releases all associated resources. If this session h
  • touch
    Explicitly updates the #getLastAccessTime() of this session to the current time when this method is
  • stop,
  • touch

Popular in Java

  • Updating database using SQL prepared statement
  • getSystemService (Context)
  • getSupportFragmentManager (FragmentActivity)
  • scheduleAtFixedRate (ScheduledExecutorService)
    Creates and executes a periodic action that becomes enabled first after the given initial delay, and
  • Point (java.awt)
    A point representing a location in (x, y) coordinate space, specified in integer precision.
  • FileWriter (java.io)
    Convenience class for writing character files. The constructors of this class assume that the defaul
  • Collection (java.util)
    Collection is the root of the collection hierarchy. It defines operations on data collections and t
  • Iterator (java.util)
    An iterator over a collection. Iterator takes the place of Enumeration in the Java Collections Frame
  • Handler (java.util.logging)
    A Handler object accepts a logging request and exports the desired messages to a target, for example
  • Base64 (org.apache.commons.codec.binary)
    Provides Base64 encoding and decoding as defined by RFC 2045.This class implements section 6.8. Base
Codota Logo
  • Products

    Search for Java codeSearch for JavaScript codeEnterprise
  • IDE Plugins

    IntelliJ IDEAWebStormAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimAtomGoLandRubyMineEmacsJupyter
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogCodota Academy Plugin user guide Terms of usePrivacy policyJava Code IndexJavascript Code Index
Get Codota for your IDE now