org.apache.shiro.util.ThreadContext Java Examples

The following examples show how to use org.apache.shiro.util.ThreadContext. 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: UserUtil.java    From scaffold-cloud with MIT License 6 votes vote down vote up
public static Session getSession(){
    try{
        SecurityManager securityManager = ThreadContext.getSecurityManager();
        if(securityManager == null){
            return null;
        }

        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession(false);
        if (session == null){
            session = subject.getSession();
        }
        if (session != null){
            return session;
        }
    }catch (InvalidSessionException e){

    }
    return null;
}
 
Example #2
Source File: ShiroJwtVerifyingFilterTest.java    From cassandra-reaper with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthorizationValid() throws Exception {
  try {
    SecurityUtils.setSecurityManager(new DefaultSecurityManager());
    HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
    Principal principal = Mockito.mock(Principal.class);
    Mockito.when(principal.getName()).thenReturn("test-user");
    Mockito.when(req.getUserPrincipal()).thenReturn(principal);
    String jwt = new ShiroJwtProvider(Mockito.mock(AppContext.class)).getJwt(req);
    Mockito.when(req.getHeader("Authorization")).thenReturn("Bearer " + jwt);
    ShiroJwtVerifyingFilter filter = new ShiroJwtVerifyingFilter();

    Assertions.assertThat(
        filter.isAccessAllowed(
            req,
            Mockito.mock(ServletResponse.class),
            Mockito.mock(Object.class)))
        .isTrue();
  } finally {
    ThreadContext.unbindSubject();
    ThreadContext.unbindSecurityManager();
  }
}
 
Example #3
Source File: ShiroJwtVerifyingFilterTest.java    From cassandra-reaper with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthorization3() throws Exception {
  try {
    SecurityUtils.setSecurityManager(new DefaultSecurityManager());
    new ShiroJwtProvider(Mockito.mock(AppContext.class));
    HttpServletRequest req = Mockito.mock(HttpServletRequest.class);

    Mockito
        .when(req.getHeader("Authorization"))
        .thenReturn(
            "Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0LXVzZXIifQ.neIA5mbTFZsZokqG5CFwK7gIxMiBoGOU0anDZmD7kkU");

    ShiroJwtVerifyingFilter filter = new ShiroJwtVerifyingFilter();

    Assertions.assertThat(
        filter.isAccessAllowed(
            req,
            Mockito.mock(ServletResponse.class),
            Mockito.mock(Object.class)))
        .isFalse();
  } finally {
    ThreadContext.unbindSubject();
    ThreadContext.unbindSecurityManager();
  }
}
 
Example #4
Source File: ShiroJwtVerifyingFilterTest.java    From cassandra-reaper with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthorization2() throws Exception {
  try {
    SecurityUtils.setSecurityManager(new DefaultSecurityManager());
    new ShiroJwtProvider(Mockito.mock(AppContext.class));
    HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
    Mockito.when(req.getHeader("Authorization")).thenReturn("Bearer eyJhbGciOiJIUzI1NiJ9");
    ShiroJwtVerifyingFilter filter = new ShiroJwtVerifyingFilter();

    Assertions.assertThat(
        filter.isAccessAllowed(
            req,
            Mockito.mock(ServletResponse.class),
            Mockito.mock(Object.class)))
        .isFalse();
  } finally {
    ThreadContext.unbindSubject();
    ThreadContext.unbindSecurityManager();
  }
}
 
Example #5
Source File: ShiroJwtVerifyingFilterTest.java    From cassandra-reaper with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthorization1() throws Exception {
  try {
    SecurityUtils.setSecurityManager(new DefaultSecurityManager());
    new ShiroJwtProvider(Mockito.mock(AppContext.class));
    HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
    Mockito.when(req.getHeader("Authorization")).thenReturn("Bearer ");
    ShiroJwtVerifyingFilter filter = new ShiroJwtVerifyingFilter();

    Assertions.assertThat(
        filter.isAccessAllowed(
            req,
            Mockito.mock(ServletResponse.class),
            Mockito.mock(Object.class)))
        .isFalse();
  } finally {
    ThreadContext.unbindSubject();
    ThreadContext.unbindSecurityManager();
  }
}
 
Example #6
Source File: ShiroJwtVerifyingFilterTest.java    From cassandra-reaper with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthorization0() throws Exception {
  try {
    SecurityUtils.setSecurityManager(new DefaultSecurityManager());
    new ShiroJwtProvider(Mockito.mock(AppContext.class));
    HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
    Mockito.when(req.getHeader("Authorization")).thenReturn("junk");
    ShiroJwtVerifyingFilter filter = new ShiroJwtVerifyingFilter();

    Assertions.assertThat(
        filter.isAccessAllowed(
            req,
            Mockito.mock(ServletResponse.class),
            Mockito.mock(Object.class)))
        .isFalse();
  } finally {
    ThreadContext.unbindSubject();
    ThreadContext.unbindSecurityManager();
  }
}
 
Example #7
Source File: ShiroJwtVerifyingFilterTest.java    From cassandra-reaper with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsAuthenticated() throws Exception {
  try {
    Subject subject = Mockito.mock(Subject.class);
    Mockito.when(subject.getPrincipal()).thenReturn(Mockito.mock(Object.class));
    Mockito.when(subject.isAuthenticated()).thenReturn(true);
    ThreadContext.bind(subject);
    ShiroJwtVerifyingFilter filter = new ShiroJwtVerifyingFilter();

    Assertions.assertThat(
        filter.isAccessAllowed(
            Mockito.mock(HttpServletRequest.class),
            Mockito.mock(ServletResponse.class),
            Mockito.mock(Object.class)))
        .isTrue();
  } finally {
    ThreadContext.unbindSubject();
  }
}
 
Example #8
Source File: ShiroJwtVerifyingFilterTest.java    From cassandra-reaper with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsRemembered() throws Exception {
  try {
    Subject subject = Mockito.mock(Subject.class);
    Mockito.when(subject.getPrincipal()).thenReturn(Mockito.mock(Object.class));
    Mockito.when(subject.isRemembered()).thenReturn(true);
    ThreadContext.bind(subject);
    ShiroJwtVerifyingFilter filter = new ShiroJwtVerifyingFilter();

    Assertions.assertThat(
        filter.isAccessAllowed(
            Mockito.mock(HttpServletRequest.class),
            Mockito.mock(ServletResponse.class),
            Mockito.mock(Object.class)))
        .isTrue();
  } finally {
    ThreadContext.unbindSubject();
  }
}
 
Example #9
Source File: SecurityManagerAssociatingFilter.java    From aries-jax-rs-whiteboard with Apache License 2.0 6 votes vote down vote up
/**
 * Clean up after the request
 */
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
        throws IOException {
    _LOG.debug("Cleaning up the Shiro Security Context");
    Subject subject = ThreadContext.getSubject();
    ThreadContext.unbindSecurityManager();
    ThreadContext.unbindSubject();
    
    if(subject != null && !subject.isAuthenticated()) {
        // Not authenticated. Check for incoming session cookie
        Cookie cookie = requestContext.getCookies().get(SESSION_COOKIE_NAME);
        
        // If we have a session cookie then it should be deleted
        if(cookie != null) {
            _LOG.debug("The subject associated with this request is not authenticated, removing the session cookie");
            responseContext.getHeaders().add(SET_COOKIE, getDeletionCookie(requestContext));
        }
    }
    
}
 
Example #10
Source File: AuthenticationResourceFilter.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Override
public ContainerRequest filter(ContainerRequest request) {
    Subject subject = new Subject.Builder(_securityManager).buildSubject();
    ThreadContext.bind(subject);

    AuthenticationToken token = _tokenGenerator.createToken(request);
    if (token == null) {
        token = AnonymousToken.getInstance();
    }
    subject.login(token);

    // The user has been successfully logged in.  Update the container authentication.
    setJettyAuthentication(subject);

    return request;
}
 
Example #11
Source File: CreateTestData.java    From ElementVueSpringbootCodeTemplate with Apache License 2.0 6 votes vote down vote up
public void createConfigs() {
    log.error("---addTestData---");

    // 登陆
    userSevice.login("xwjie", "123456");

    //
    ThreadContext.bind(securityManager);

    for (int i = 1; i <= 20; i++) {

        Config config = new Config();

        config.setName("测试数据:" + i);
        System.out.println("测试数据:" + i);
        config.setValue("https://github.com/xwjie");
        config.setDescription("晓风轻:" + i);

        // 创建记录的用户
        config.setCreator(UserUtil.getUser());

        configService.add(config);
    }
}
 
Example #12
Source File: RGroupIT.java    From nexus-repository-r with Eclipse Public License 1.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  ThreadContext.bind(FakeAlmightySubject.forUserId("disabled-security"));
  remote = Server.withPort(0)
      .serve("/*").withBehaviours(error(NOT_FOUND))
      .serve("/" + AGRICOLAE_121_TARGZ.fullPath)
      .withBehaviours(file(testData.resolveFile(AGRICOLAE_121_TARGZ.filename)))
      .start();

  repoProxy = repos.createRProxy(testName.getMethodName() + "-proxy", remote.getUrl().toExternalForm());
  repoHosted = repos.createRHosted(testName.getMethodName() + "-hosted");
  repoGroup = repos.createRGroup(testName.getMethodName() + "-group", repoHosted.getName(), repoProxy.getName());

  hostedClient = createRClient(repoHosted);
  groupClient = createRClient(repoGroup);

  assertThat(status(hostedClient.putAndClose(AGRICOLAE_131_TARGZ.fullPath,
      fileToHttpEntity(AGRICOLAE_131_TARGZ.filename))), is(OK));
}
 
Example #13
Source File: ShiroSecuritySupport.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void login(AuthenticationToken authenticationToken) {
    SecurityManager alreadyBoundSecurityManager = ThreadContext.getSecurityManager();
    try {
        if (alreadyBoundSecurityManager == null) {
            ThreadContext.bind(securityManager);
        }
        Subject currentSubject = SecurityUtils.getSubject();
        currentSubject.login(new AuthenticationTokenWrapper(authenticationToken));
    } catch (org.apache.shiro.authc.AuthenticationException e) {
        throw new AuthenticationException("Unable to login subject with provided credentials " + authenticationToken
                .getPrincipal(), e);
    } finally {
        if (alreadyBoundSecurityManager == null) {
            ThreadContext.unbindSecurityManager();
        }
    }
}
 
Example #14
Source File: KnoxCLI.java    From knox with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param config - the shiro.ini config file created in topology deployment.
 * @return returns the Subject given by the shiro config's settings.
 */
protected Subject getSubject(Ini config) throws BadSubjectException {
  try {
    ThreadContext.unbindSubject();
    @SuppressWarnings("deprecation")
    Factory factory = new IniSecurityManagerFactory(config);
    org.apache.shiro.mgt.SecurityManager securityManager = (org.apache.shiro.mgt.SecurityManager) factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);
    Subject subject = SecurityUtils.getSubject();
    if( subject != null) {
      return subject;
    } else {
      out.println("Error Creating Subject from config at: " + config);
    }
  } catch (Exception e){
    out.println(e.toString());
  }
  throw new BadSubjectException("Subject could not be created with Shiro Config at " + config);
}
 
Example #15
Source File: SecurityUtils.java    From onedev with MIT License 6 votes vote down vote up
public static <T> Collection<Callable<T>> inheritSubject(Collection<? extends Callable<T>> callables) {
	Subject subject = SecurityUtils.getSubject();
	Collection<Callable<T>> wrappedTasks = new ArrayList<>();
	for (Callable<T> task: callables) {
		wrappedTasks.add(new Callable<T>() {

			@Override
			public T call() throws Exception {
				ThreadContext.bind(subject);
				return task.call();
			}
			
		});
	}
	return wrappedTasks;
}
 
Example #16
Source File: AnonymousFilter.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected boolean preHandle(final ServletRequest request, final ServletResponse response) throws Exception {
  Subject subject = SecurityUtils.getSubject();
  AnonymousManager manager = anonymousManager.get();
 
  if (subject.getPrincipal() == null && manager.isEnabled()) {
    request.setAttribute(ORIGINAL_SUBJECT, subject);
    subject = manager.buildSubject();
    ThreadContext.bind(subject);
    log.trace("Bound anonymous subject: {}", subject);
    
    // fire an event if we haven't already seen this ClientInfo since the server started
    if (request instanceof HttpServletRequest) {
      String userId = manager.getConfiguration().getUserId();
      ClientInfo clientInfo = ClientInfo
          .builder()
          .userId(userId)
          .remoteIP(request.getRemoteAddr())
          .userAgent(((HttpServletRequest) request).getHeader(HttpHeaders.USER_AGENT))
          .path(((HttpServletRequest) request).getServletPath())
          .build();
      if (cache.add(clientInfo)) {
        log.trace("Tracking new anonymous access from: {}", clientInfo);
        eventManager.get().post(new AnonymousAccessEvent(clientInfo, new Date()));
      }
    }
  }

  return true;
}
 
Example #17
Source File: MaintenanceServiceImplTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testDeleteFolder() {
  ThreadContext.bind(FakeAlmightySubject.forUserId("disabled-security"));
  when(repositoryPermissionChecker.userCanDeleteInRepository(mavenReleases)).thenReturn(true);

  underTest.deleteFolder(mavenReleases, "someFolder");

  verify(deleteFolderService, timeout(500)).deleteFolder(eq(mavenReleases), eq("someFolder"), any(DateTime.class), any());
}
 
Example #18
Source File: WithUserTestDecorator.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void afterTest(TestContext testContext) {
    if (subject != null) {
        LOGGER.info("Logging user out", testContext.testMethod());
        subject.logout();
        ThreadContext.unbindSecurityManager();
        ThreadContext.unbindSubject();
    }
}
 
Example #19
Source File: WithUserTestDecorator.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
@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);
    });
}
 
Example #20
Source File: SecurityModule.java    From tapestry-security with Apache License 2.0 5 votes vote down vote up
/**
 * Secure all service methods that are marked with authorization annotations.
 * <p>
 * <b>Restriction:</b> Only service interfaces can be annotated.
 */
@Match("*")
@Order("before:*")
public static void adviseSecurityAssert(MethodAdviceReceiver receiver,
										final @Core Environment environment) {
	Class<?> serviceInterface = receiver.getInterface();

	for (Method method : serviceInterface.getMethods()) {

		List<SecurityInterceptor> interceptors =
				AopHelper.createSecurityInterceptorsSeeingInterfaces(method, serviceInterface);

		for (final SecurityInterceptor interceptor : interceptors) {
			MethodAdvice advice = new MethodAdvice() {
				@Override
				public void advise(MethodInvocation invocation) {
					// Only (try to) intercept if subject is bound.
					// This is useful in case background or initializing operations
					// call service operations that are secure
					if (ThreadContext.getSubject() != null) {
						environment.push(MethodInvocation.class, invocation);
						try {
							interceptor.intercept();
						}
						finally {
							environment.pop(MethodInvocation.class);
						}
					}
					invocation.proceed();

				}
			};
			receiver.adviseMethod(method, advice);
		}

	}
}
 
Example #21
Source File: SecurityServiceImpl.java    From tapestry-security with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T invokeWithSecurityDisabled(Callable<T> callable) throws Exception {
	org.apache.shiro.mgt.SecurityManager securityManager = ThreadContext.getSecurityManager();
	ThreadContext.unbindSecurityManager();
	try {
		return callable.call();
	}
	finally {
		if (securityManager != null) ThreadContext.bind(securityManager);
	}
}
 
Example #22
Source File: SecurityConfiguration.java    From tapestry-security with Apache License 2.0 5 votes vote down vote up
public boolean service(final HttpServletRequest originalRequest, final HttpServletResponse response, final HttpServletRequestHandler handler)
		throws IOException {
	// TODO consider whether this guard is necessary at all? I think possibly if container forwards the request internally
	// or, more generically, if the same thread/container-level filter mapping handles the request twice
	if (originalRequest instanceof ShiroHttpServletRequest) return handler.service(originalRequest, response);

	final HttpServletRequest request = new ShiroHttpServletRequest(originalRequest, servletContext, true);

	final String requestURI = loginContextService.getLocalelessPathWithinApplication();

	runChainListeners();

	final SecurityFilterChain chain = getMatchingChain(requestURI);

	requestGlobals.storeServletRequestResponse(request, response);

	ThreadContext.bind(securityManager);
	WebSubject subject = new WebSubject.Builder(securityManager, request, response).buildWebSubject();
	ThreadContext.bind(subject);

	try {
		// return subject.execute(new Callable<Boolean>() {
		// public Boolean call() throws Exception {
		if (chain == null) return handler.service(request, response);
		else {
			boolean handled = chain.getHandler().service(request, response);
			return handled || handler.service(request, response);
		}
		// }
		// });
	}
	finally {
		/**
		 * final 'clean up' operation that removes the underlying {@link ThreadLocal ThreadLocal} from the thread
		 * at the end of execution to prevent leaks in pooled thread environments.
		 */
		ThreadContext.remove(subject);
		ThreadContext.remove();
	}
}
 
Example #23
Source File: UserIdMdcHelperTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void setIfNeeded_alreadySet() {
  MDC.put(KEY, "foo");

  ThreadContext.bind(subject("test"));

  UserIdMdcHelper.setIfNeeded();

  assertThat(UserIdMdcHelper.isSet(), is(true));
  assertThat(MDC.get(KEY), is("foo"));
}
 
Example #24
Source File: AnonymousFilter.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@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);
  }
}
 
Example #25
Source File: IniSecurityManagerService.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public void passivateService()
        throws Exception
{
    ThreadContext.unbindSubject();
    ThreadContext.unbindSecurityManager();
}
 
Example #26
Source File: UserIdMdcHelperTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void set_notSet() {
  ThreadContext.bind(subject("test"));

  UserIdMdcHelper.set();

  assertThat(UserIdMdcHelper.isSet(), is(true));
  assertThat(MDC.get(KEY), is("test"));
}
 
Example #27
Source File: UserIdMdcHelperTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void set_notSet_withoutSubject() {
  ThreadContext.bind(mock(SecurityManager.class));

  UserIdMdcHelper.set();

  assertThat(UserIdMdcHelper.isSet(), is(false));
  assertThat(MDC.get(KEY), is(UNKNOWN));
}
 
Example #28
Source File: UserIdMdcHelperTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void set_alreadySet() {
  MDC.put(KEY, "foo");

  ThreadContext.bind(subject("test"));

  UserIdMdcHelper.set();

  assertThat(UserIdMdcHelper.isSet(), is(true));
  assertThat(MDC.get(KEY), is("test"));
}
 
Example #29
Source File: IniSecurityManagerService.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public void activateService()
        throws Exception
{
    configuration.refresh();
    ShiroIniConfiguration config = configuration.get();

    String iniResourcePath = config.iniResourcePath().get() == null
                             ? Shiro.DEFAULT_INI_RESOURCE_PATH
                             : config.iniResourcePath().get();

    setIni( Ini.fromResourcePath( iniResourcePath ) );
    securityManager = getInstance();

    if ( realmsRefs != null && realmsRefs.iterator().hasNext() ) {

        // Register Realms Services
        RealmSecurityManager realmSecurityManager = ( RealmSecurityManager ) securityManager;
        Collection<Realm> iniRealms = new ArrayList<>( realmSecurityManager.getRealms() );
        for ( ServiceReference<Realm> realmRef : realmsRefs ) {
            iniRealms.add( realmRef.get() );
            LOG.debug( "Realm Service '{}' registered!", realmRef.identity() );
        }
        realmSecurityManager.setRealms( iniRealms );

    }

    ThreadContext.bind( securityManager );
}
 
Example #30
Source File: UserIdMdcHelperTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void setIfNeeded_notSet() {
  ThreadContext.bind(subject("test"));

  UserIdMdcHelper.setIfNeeded();

  assertThat(UserIdMdcHelper.isSet(), is(true));
  assertThat(MDC.get(KEY), is("test"));
}