org.apache.shiro.util.ThreadContext.bind()方法的使用及代码示例

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

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

ThreadContext.bind介绍

[英]Convenience method that simplifies binding the application's SecurityManager instance to the ThreadContext.

The method's existence is to help reduce casting in code and to simplify remembering of ThreadContext key names. The implementation is simple in that, if the SecurityManager is not null, it binds it to the thread, i.e.:

if (securityManager != null) { 
put( SECURITY_MANAGER_KEY, securityManager); 
}

[中]简化将应用程序的SecurityManager实例绑定到ThreadContext的便捷方法。
该方法的存在有助于减少代码中的强制转换,并简化对ThreadContext键名称的记忆。实现很简单,如果SecurityManager不为null,它会将其绑定到线程,即:

if (securityManager != null) { 
put( SECURITY_MANAGER_KEY, securityManager); 
}

代码示例

代码示例来源: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

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

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

/**
 * It first looks the shiro subject in AccessControlContext since JMX will use multiple threads to
 * process operations from the same client, then it looks into Shiro's thead context.
 *
 * @return the shiro subject, null if security is not enabled
 */
@Override
public Subject getSubject() {
 Subject currentUser;
 // First try get the principal out of AccessControlContext instead of Shiro's Thread context
 // since threads can be shared between JMX clients.
 javax.security.auth.Subject jmxSubject =
   javax.security.auth.Subject.getSubject(AccessController.getContext());
 if (jmxSubject != null) {
  Set<ShiroPrincipal> principals = jmxSubject.getPrincipals(ShiroPrincipal.class);
  if (!principals.isEmpty()) {
   ShiroPrincipal principal = principals.iterator().next();
   currentUser = principal.getSubject();
   ThreadContext.bind(currentUser);
   return currentUser;
  }
 }
 // in other cases like rest call, client operations, we get it from the current thread
 currentUser = SecurityUtils.getSubject();
 if (currentUser == null || currentUser.getPrincipal() == null) {
  throw new AuthenticationRequiredException("Failed to find the authenticated user.");
 }
 return currentUser;
}

代码示例来源: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: Graylog2/graylog2-server

LOG.debug("Not extending session because the request indicated not to.");
ThreadContext.bind(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: Graylog2/graylog2-server

ThreadContext.bind(subject);
final Session s = subject.getSession();
try {

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

/**
 * 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: org.apache.shiro/shiro-core

/**
 * 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: com.github.sdorra/shiro-unit

/**
 * Set a subject manually for the current method execution.
 *
 *
 * @param subject subject to set
 */
public void setSubject(Subject subject)
{
 ThreadContext.bind(subject);
}

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

/**
 * Set a subject manually for the current method execution.
 *
 *
 * @param subject subject to set
 */
public void setSubject(Subject subject)
{
 ThreadContext.bind(subject);
}

代码示例来源:origin: org.sonatype.nexus/nexus-security

@Override
 public void afterCompletion(final ServletRequest request, final ServletResponse response, final Exception exception)
   throws Exception
 {
  Subject subject = (Subject) request.getAttribute(ORIGINAL_SUBJECT);
  if (subject != null) {
   log.trace("Binding original subject: {}", subject);
   ThreadContext.bind(subject);
  }
 }
}

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

private void supportForAsynchronousEJB(InvocationContext context, Method method) {
  Asynchronous asynchronous = method.getAnnotation(Asynchronous.class);
  if (asynchronous != null) {
    for (Object parameter : context.getParameters()) {
      if (parameter != null && OctopusSecurityContext.class.isAssignableFrom(parameter.getClass())) {
        Subject subject = ((OctopusSecurityContext) parameter).getSubject();
        ThreadContext.bind(subject);
      }
    }
  }
}

代码示例来源: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.seedstack.seed/seed-security-core

@Override
public void beforeTest(TestContext testContext) {
  getWithUser(testContext).ifPresent(withUser -> {
    LOGGER.info("Logging user {} before executing test {}", withUser.id(), testContext.testName());
    ThreadContext.bind(securityManager);
    subject = new Subject.Builder(securityManager).buildSubject();
    subject.login(new UsernamePasswordToken(withUser.id(), withUser.password()));
    ThreadContext.bind(subject);
  });
}

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

@Sessional
@Override
public void preStop() {
  ThreadContext.bind(userManager.getRoot().asSubject());
  listenerRegistry.post(new SystemStopping());
}

代码示例来源:origin: com.github.tianjing/tgtools.web.develop

protected void validLogin(WebSocketSession pWebSocketSession, ValidMessage pValidMessage) throws APPErrorException {
  //模拟登陆
  SimpleSession session = new SimpleSession();
  session.setHost(pWebSocketSession.getRemoteAddress().getHostName());
  WebDelegatingSubject subject = new WebDelegatingSubject(null, true, "", session, null, null, getSecurityManager());
  ThreadContext.bind(subject);
  getUserService().tokenLogin(pWebSocketSession.getRemoteAddress().getHostName(), pValidMessage.getUser(), pValidMessage.getToken());
  //登录成功后 添加客户端
  mClientFactory.addClient(pValidMessage.getUser(), pWebSocketSession);
}
@Override

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

@Override
public void run() {
  ThreadContext.bind(subject);
  try {
    PullRequest request = load(requestId);
    request.getTargetProject().cacheObjectId(request.getTargetRef(), newTargetHeadId);
    listenerRegistry.post(new RefUpdated(request.getTargetProject(), targetRef, 
          targetHeadId, newTargetHeadId));
  } finally {
    ThreadContext.unbindSubject();
  }
}

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

@Override
public void run() {
  ThreadContext.bind(subject);
  try {
    Project project = OneDev.getInstance(ProjectManager.class).load(projectId);
    project.cacheObjectId(branch, refUpdated.getNewCommitId());
    RefUpdated refUpdated = new RefUpdated(project, refName, oldCommitId, newCommitId);
    OneDev.getInstance(ListenerRegistry.class).post(refUpdated);
  } finally {
    ThreadContext.unbindSubject();
  }
}

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

@Override
public void run() {
  ThreadContext.bind(subject);
  try {
    Project project = OneDev.getInstance(ProjectManager.class).load(getId());
    OneDev.getInstance(ListenerRegistry.class).post(
        new RefUpdated(project, refName, commitId, ObjectId.zeroId()));
  } finally {
    ThreadContext.unbindSubject();
  }
}

相关文章