protected SecurityManager createAndBindTestSecurityManager() { SecurityManager sm = createTestSecurityManager(); ThreadContext.bind(sm); return sm; }
@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()); } }
@AfterMethod(groups = "slow") public void afterMethod() throws Exception { if (hasFailed()) { return; } super.afterMethod(); ThreadContext.unbindSecurityManager(); }
/** * 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); } }
/** * {@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); } }
/** * 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; }
@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(); } }
@Override public void close(MessageContext context) { ThreadContext.unbindSubject(); ThreadContext.unbindSecurityManager(); } }
/** * 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); } }
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; } }
ThreadContext.bind(securityManager); try { final Session session = securityManager.getSession(new DefaultSessionKey(sessionId)); logger.warn("{} Failed to log out: {}", ctx, sessionId, t); } finally { ThreadContext.unbindSecurityManager();
/** * 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(); } }
@Override public ContainerResponse filter(ContainerRequest request, ContainerResponse response) { Subject subject = ThreadContext.getSubject(); if (subject != null) { if (subject.isAuthenticated()) { subject.logout(); } ThreadContext.unbindSubject(); } return response; }
@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); } } }
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"); }
@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()); }
public static void requestSessionCreation(boolean createSessionRequest) { ThreadContext.put(AUTO_CREATE_SESSION_KEY, createSessionRequest); } }
@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(); } }
@Override public void passivateService() throws Exception { ThreadContext.unbindSubject(); ThreadContext.unbindSecurityManager(); }