org.apache.shiro.util.ThreadContext类的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(10.3k)|赞(0)|评价(0)|浏览(248)

本文整理了Java中org.apache.shiro.util.ThreadContext类的一些代码示例,展示了ThreadContext类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ThreadContext类的具体详情如下:
包路径:org.apache.shiro.util.ThreadContext
类名称:ThreadContext

ThreadContext介绍

[英]A ThreadContext provides a means of binding and unbinding objects to the current thread based on key/value pairs.

An internal java.util.HashMap is used to maintain the key/value pairs for each thread.

If the desired behavior is to ensure that bound data is not shared across threads in a pooled or reusable threaded environment, the application (or more likely a framework) must bind and remove any necessary values at the beginning and end of stack execution, respectively (i.e. individually explicitly or all via the clear method).
[中]ThreadContext提供了一种基于键/值对将对象绑定和解除绑定到当前线程的方法。
一个内部java。util。HashMap用于维护每个线程的键/值对。
如果所需的行为是确保绑定的数据不会在池或可重用线程环境中的线程之间共享,那么应用程序(或者更可能是框架)必须分别在堆栈执行的开始和结束时绑定并删除任何必要的值(即单独显式地或全部通过clear方法)。

代码示例

代码示例来源:origin: apache/shiro

protected SecurityManager createAndBindTestSecurityManager() {
  SecurityManager sm = createTestSecurityManager();
  ThreadContext.bind(sm);
  return sm;
}

代码示例来源:origin: Graylog2/graylog2-server

@Override
  public void configure(ResourceInfo resourceInfo, FeatureContext context) {
    final Class<?> resourceClass = resourceInfo.getResourceClass();
    final Method resourceMethod = resourceInfo.getResourceMethod();

    context.register(ShiroSecurityContextFilter.class);

    if (resourceMethod.isAnnotationPresent(RequiresAuthentication.class) || resourceClass.isAnnotationPresent(RequiresAuthentication.class)) {
      if (resourceMethod.isAnnotationPresent(RequiresGuest.class)) {
        LOG.debug("Resource method {}#{} is marked as unauthenticated, skipping setting filter.");
      } else {
        LOG.debug("Resource method {}#{} requires an authenticated user.", resourceClass.getCanonicalName(), resourceMethod.getName());
        context.register(new ShiroAuthenticationFilter());
      }
    }

    if (resourceMethod.isAnnotationPresent(RequiresPermissions.class) || resourceClass.isAnnotationPresent(RequiresPermissions.class)) {
      RequiresPermissions requiresPermissions = resourceClass.getAnnotation(RequiresPermissions.class);
      if (requiresPermissions == null) {
        requiresPermissions = resourceMethod.getAnnotation(RequiresPermissions.class);
      }

      LOG.debug("Resource method {}#{} requires an authorization checks.", resourceClass.getCanonicalName(), resourceMethod.getName());
      context.register(new ShiroAuthorizationFilter(requiresPermissions));
    }

    // TODO this is the wrong approach, we should have an Environment and proper request wrapping
    context.register((ContainerResponseFilter) (requestContext, responseContext) -> ThreadContext.unbindSubject());
  }
}

代码示例来源:origin: killbill/killbill

@AfterMethod(groups = "slow")
public void afterMethod() throws Exception {
  if (hasFailed()) {
    return;
  }
  super.afterMethod();
  ThreadContext.unbindSecurityManager();
}

代码示例来源:origin: apache/shiro

/**
 * Binds a {@link Subject} and {@link org.apache.shiro.mgt.SecurityManager SecurityManager} to the
 * {@link ThreadContext} so they can be retrieved later by any
 * {@code SecurityUtils.}{@link org.apache.shiro.SecurityUtils#getSubject() getSubject()} calls that might occur
 * during the thread's execution.
 * <p/>
 * Prior to binding, the {@code ThreadContext}'s existing {@link ThreadContext#getResources() resources} are
 * retained so they can be restored later via the {@link #restore restore} call.
 */
public void bind() {
  SecurityManager securityManager = this.securityManager;
  if ( securityManager == null ) {
    //try just in case the constructor didn't find one at the time:
    securityManager = ThreadContext.getSecurityManager();
  }
  this.originalResources = ThreadContext.getResources();
  ThreadContext.remove();
  ThreadContext.bind(this.subject);
  if (securityManager != null) {
    ThreadContext.bind(securityManager);
  }
}

代码示例来源:origin: apache/shiro

/**
 * {@link ThreadContext#remove Remove}s all thread-state that was bound by this instance.  If any previous
 * thread-bound resources existed prior to the {@link #bind bind} call, they are restored back to the
 * {@code ThreadContext} to ensure the thread state is exactly as it was before binding.
 */
public void restore() {
  ThreadContext.remove();
  if (!CollectionUtils.isEmpty(this.originalResources)) {
    ThreadContext.setResources(this.originalResources);
  }
}

代码示例来源:origin: apache/shiro

/**
 * Returns the currently accessible {@code Subject} available to the calling code depending on
 * runtime environment.
 * <p/>
 * This method is provided as a way of obtaining a {@code Subject} without having to resort to
 * implementation-specific methods.  It also allows the Shiro team to change the underlying implementation of
 * this method in the future depending on requirements/updates without affecting your code that uses it.
 *
 * @return the currently accessible {@code Subject} accessible to the calling code.
 * @throws IllegalStateException if no {@link Subject Subject} instance or
 *                               {@link SecurityManager SecurityManager} instance is available with which to obtain
 *                               a {@code Subject}, which which is considered an invalid application configuration
 *                               - a Subject should <em>always</em> be available to the caller.
 */
public static Subject getSubject() {
  Subject subject = ThreadContext.getSubject();
  if (subject == null) {
    subject = (new Subject.Builder()).buildSubject();
    ThreadContext.bind(subject);
  }
  return subject;
}

代码示例来源:origin: apache/shiro

@Test
public void testScope() throws Exception {
  Subject subject = createMock(Subject.class);
  try {
    ThreadContext.bind(subject);
    final Key<SomeClass> key = Key.get(SomeClass.class);
    Provider<SomeClass> mockProvider = createMock(Provider.class);
    Session session = createMock(Session.class);
    SomeClass retuned = new SomeClass();
    expect(subject.getSession()).andReturn(session);
    expect(session.getAttribute(key)).andReturn(null);
    expect(mockProvider.get()).andReturn(retuned);
    expect(subject.getSession()).andReturn(session);
    expect(session.getAttribute(key)).andReturn(retuned);
    replay(subject, mockProvider, session);
    ShiroSessionScope underTest = new ShiroSessionScope();
    // first time the session doesn't contain it, we expect the provider to be invoked
    assertSame(retuned, underTest.scope(key, mockProvider).get());
    // second time the session does contain it, we expect the provider to not be invoked
    assertSame(retuned, underTest.scope(key, mockProvider).get());
    verify(subject, mockProvider, session);
  } finally {
    ThreadContext.unbindSubject();
  }
}

代码示例来源:origin: org.seedstack.addons.ws/web-services-core

@Override
  public void close(MessageContext context) {
    ThreadContext.unbindSubject();
    ThreadContext.unbindSecurityManager();
  }
}

代码示例来源:origin: sonia.junit.shiro/shiro-unit

/**
  * Method description
  *
  */
 private void tearDownShiro()
 {
  try
  {
   SecurityManager securityManager = SecurityUtils.getSecurityManager();

   LifecycleUtils.destroy(securityManager);
   ThreadContext.unbindSecurityManager();
   ThreadContext.unbindSubject();
   ThreadContext.remove();
  }
  catch (UnavailableSecurityManagerException e)
  {

   // we don't care about this when cleaning up the test environment
   // (for example, maybe the subclass is a unit test and it didn't
   // need a SecurityManager instance because it was using only mock Subject instances)
  }

  SecurityUtils.setSecurityManager(null);
 }
}

代码示例来源:origin: Graylog2/graylog2-server

public void loginSubject() throws AuthenticationException {
  subject.login(token);
  // the subject instance will change to include the session
  final Subject newSubject = ThreadContext.getSubject();
  if (newSubject != null) {
    subject = newSubject;
  }
}

代码示例来源:origin: line/centraldogma

ThreadContext.bind(securityManager);
try {
  final Session session = securityManager.getSession(new DefaultSessionKey(sessionId));
  logger.warn("{} Failed to log out: {}", ctx, sessionId, t);
} finally {
  ThreadContext.unbindSecurityManager();

代码示例来源:origin: Graylog2/graylog2-server

final MultivaluedMap<String, String> requestHeaders = (MultivaluedMap<String, String>) ThreadContext.get(
    ShiroSecurityContextFilter.REQUEST_HEADERS);
  LOG.debug("Not extending session because the request indicated not to.");
ThreadContext.bind(subject);

代码示例来源:origin: apache/shiro

/**
   * Completely {@link ThreadContext#remove removes} the {@code ThreadContext} state.  Typically this method should
   * only be called in special cases - it is more 'correct' to {@link #restore restore} a thread to its previous
   * state than to clear it entirely.
   */
  public void clear() {
    ThreadContext.remove();
  }
}

代码示例来源:origin: bazaarvoice/emodb

@Override
public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
  Subject subject = ThreadContext.getSubject();
  if (subject != null) {
    if (subject.isAuthenticated()) {
      subject.logout();
    }
    ThreadContext.unbindSubject();
  }
  return response;
}

代码示例来源:origin: be.c4j.ee.security.octopus/octopus-core

@Override
public void onSuccess(AuthenticationToken token, AuthenticationInfo info) {
  if (!(token instanceof ProcessAuthenticationToken) && !(token instanceof SystemAccountAuthenticationToken)) {
    LogonEvent event = new LogonEvent(token, info);
    ThreadContext.put(IN_AUTHENTICATION_EVENT_FLAG, new InAuthenticationEvent());
    try {
      logonEvent.fire(event);
    } finally {
      // In any case (also in case of access denied) we need to remove this flag
      ThreadContext.remove(IN_AUTHENTICATION_EVENT_FLAG);
    }
  }
}

代码示例来源:origin: org.graylog2/graylog2-shared

public void loginSubject() throws AuthenticationException {
  // what a hack :(
  ThreadContext.put("REQUEST_HEADERS", headers);
  subject.login(token);
  // the subject instance will change to include the session
  final Subject newSubject = ThreadContext.getSubject();
  if (newSubject != null) {
    subject = newSubject;
  }
  ThreadContext.remove("REQUEST_HEADERS");
}

代码示例来源:origin: apache/shiro

@Test
public void testExecuteRunnable() {
  String username = "jsmith";
  SecurityManager securityManager = createNiceMock(SecurityManager.class);
  PrincipalCollection identity = new SimplePrincipalCollection(username, "testRealm");
  final Subject sourceSubject = new DelegatingSubject(identity, true, null, null, securityManager);
  assertNull(ThreadContext.getSubject());
  assertNull(ThreadContext.getSecurityManager());
  Runnable runnable = new Runnable() {
    public void run() {
      Subject callingSubject = SecurityUtils.getSubject();
      assertNotNull(callingSubject);
      assertNotNull(SecurityUtils.getSecurityManager());
      assertEquals(callingSubject, sourceSubject);
    }
  };
  sourceSubject.execute(runnable);
  assertNull(ThreadContext.getSubject());
  assertNull(ThreadContext.getSecurityManager());
}

代码示例来源:origin: Graylog2/graylog2-server

public static void requestSessionCreation(boolean createSessionRequest) {
    ThreadContext.put(AUTO_CREATE_SESSION_KEY, createSessionRequest);
  }
}

代码示例来源:origin: theonedev/onedev

@Override
public void run() {
  try {
    ThreadContext.bind(subject);
    check(load(requestId));
  } catch (Exception e) {
    logger.error("Error checking pull request status", e);
  } finally {
    ThreadContext.unbindSubject();
  }
}

代码示例来源:origin: org.apache.polygene.libraries/org.apache.polygene.library.shiro-core

@Override
public void passivateService()
    throws Exception
{
  ThreadContext.unbindSubject();
  ThreadContext.unbindSecurityManager();
}

相关文章