Java Code Examples for org.apache.shiro.util.ThreadContext#bind()
The following examples show how to use
org.apache.shiro.util.ThreadContext#bind() .
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: ShiroJwtVerifyingFilterTest.java From cassandra-reaper with Apache License 2.0 | 6 votes |
@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 2
Source File: ShiroSecuritySupport.java From seed with Mozilla Public License 2.0 | 6 votes |
@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 3
Source File: UserIdMdcHelperTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Test public void setIfNeeded_notSet() { ThreadContext.bind(subject("test")); UserIdMdcHelper.setIfNeeded(); assertThat(UserIdMdcHelper.isSet(), is(true)); assertThat(MDC.get(KEY), is("test")); }
Example 4
Source File: UserIdMdcHelperTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Test public void set_notSet() { ThreadContext.bind(subject("test")); UserIdMdcHelper.set(); assertThat(UserIdMdcHelper.isSet(), is(true)); assertThat(MDC.get(KEY), is("test")); }
Example 5
Source File: AnonymousFilter.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@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 6
Source File: MaintenanceServiceImplTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@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 7
Source File: SecurityManagerAssociatingFilter.java From aries-jax-rs-whiteboard with Apache License 2.0 | 5 votes |
/** * Set up the incoming request context */ @Override public void filter(ContainerRequestContext requestContext) throws IOException { _LOG.debug("Establishing Shiro Security Context"); // Bind the security manager ThreadContext.bind(manager); Cookie cookie = requestContext.getCookies().get(SESSION_COOKIE_NAME); // If we have a session cookie then use it to prime the session value if(cookie != null) { _LOG.debug("Found a Shiro Security Context cookie: {}. Establishing user context", cookie); _LOG.debug("Establishing user context:"); Subject subject = new Subject.Builder(manager).sessionId(cookie.getValue()).buildSubject(); ThreadContext.bind(subject); if(_LOG.isDebugEnabled()) { _LOG.debug("Established user context for: {}", subject.getPrincipal()); } } UriInfo info = requestContext.getUriInfo(); if("security/authenticate".equals(info.getPath())) { requestContext.abortWith(authenticate(info, requestContext.getHeaderString("user"), requestContext.getHeaderString("password"))); } else if("security/logout".equals(info.getPath())) { logout(); } }
Example 8
Source File: IniSecurityManagerService.java From attic-polygene-java with Apache License 2.0 | 5 votes |
@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 9
Source File: WebSocketProcessor.java From onedev with MIT License | 5 votes |
private void run(Runnable runnable) { if (OneDev.getInstance().isReady()) { SessionManager sessionManager = AppLoader.getInstance(SessionManager.class); Subject subject = (Subject) request.getHttpServletRequest() .getAttribute(WebSocketFilter.SHIRO_SUBJECT); ThreadContext.bind(subject); sessionManager.run(runnable); } }
Example 10
Source File: UserIdMdcHelperTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@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 11
Source File: DefaultTaskScheduler.java From onedev with MIT License | 5 votes |
@Override public synchronized String schedule(SchedulableTask task) { Subject subject = SecurityUtils.getSubject(); SchedulableTask subjectAwareTask = new SchedulableTask() { @Override public ScheduleBuilder<?> getScheduleBuilder() { return task.getScheduleBuilder(); } @Override public void execute() { ThreadContext.bind(subject); task.execute(); } }; try { JobDetail job = JobBuilder.newJob(HelperTask.class) .withIdentity(UUID.randomUUID().toString()) .build(); Trigger trigger = TriggerBuilder.newTrigger() .withIdentity(UUID.randomUUID().toString()) .withSchedule(subjectAwareTask.getScheduleBuilder()) .forJob(job) .build(); trigger.getJobDataMap().put("task", subjectAwareTask); quartz.scheduleJob(job, trigger); return job.getKey().getName(); } catch (SchedulerException e) { throw new RuntimeException(e); } }
Example 12
Source File: SecurityUtils.java From onedev with MIT License | 5 votes |
public static <T> Callable<T> inheritSubject(Callable<T> callable) { Subject subject = SecurityUtils.getSubject(); return new Callable<T>() { @Override public T call() throws Exception { ThreadContext.bind(subject); return callable.call(); } }; }
Example 13
Source File: SecurityUtils.java From onedev with MIT License | 5 votes |
public static <T> PrioritizedCallable<T> inheritSubject(PrioritizedCallable<T> task) { Subject subject = SecurityUtils.getSubject(); return new PrioritizedCallable<T>(task.getPriority()) { @Override public T call() throws Exception { ThreadContext.bind(subject); return task.call(); } }; }
Example 14
Source File: SecurityUtils.java From onedev with MIT License | 5 votes |
public static PrioritizedRunnable inheritSubject(PrioritizedRunnable task) { Subject subject = SecurityUtils.getSubject(); return new PrioritizedRunnable(task.getPriority()) { @Override public void run() { ThreadContext.bind(subject); task.run(); } }; }
Example 15
Source File: UserIdMdcHelperTest.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@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 16
Source File: ShiroTest.java From utils with Apache License 2.0 | 4 votes |
@Before public void setup() { mvc = MockMvcBuilders.webAppContextSetup(wac).build(); org.apache.shiro.mgt.SecurityManager securityManger = mock(org.apache.shiro.mgt.SecurityManager.class, RETURNS_DEEP_STUBS); ThreadContext.bind(securityManger); }
Example 17
Source File: GitSshCommandCreator.java From onedev with MIT License | 4 votes |
@Override public void start(Environment env) throws IOException { ThreadContext.bind(SecurityUtils.asSubject(authenticator.getPublicKeyOwnerId(session))); File gitDir; Map<String, String> gitEnvs; sessionManager.openSession(); try { String projectName = StringUtils.stripEnd(StringUtils.substringAfterLast(command, "/"), "'"); Project project = projectManager.find(projectName); if (project == null) { onExit(-1, "Unable to find project " + projectName); return; } String errorMessage = checkPermission(project); if (errorMessage != null) { onExit(-1, errorMessage); return; } gitDir = project.getGitDir(); gitEnvs = buildGitEnvs(project); } finally { sessionManager.closeSession(); } commandFuture = workExecutor.submit(new PrioritizedRunnable(PRIORITY) { @Override public void run() { try { ExecuteResult result = execute(gitDir, gitEnvs); onExit(result.getReturnCode(), null); } catch (Exception e) { logger.error("Error executing git command", e); onExit(-1, e.getMessage()); } } }); }
Example 18
Source File: GitPostReceiveCallback.java From onedev with MIT License | 4 votes |
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String clientIp = request.getHeader("X-Forwarded-For"); if (clientIp == null) clientIp = request.getRemoteAddr(); if (!InetAddress.getByName(clientIp).isLoopbackAddress()) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Git hook callbacks can only be accessed from localhost."); return; } List<String> fields = StringUtils.splitAndTrim(request.getPathInfo(), "/"); Preconditions.checkState(fields.size() == 2); Long projectId = Long.valueOf(fields.get(0)); Long userId = Long.valueOf(fields.get(1)); ThreadContext.bind(SecurityUtils.asSubject(userId)); String refUpdateInfo = null; Enumeration<String> paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String paramName = paramNames.nextElement(); if (paramName.contains(" ")) { refUpdateInfo = paramName; } } Preconditions.checkState(refUpdateInfo != null, "Git ref update information is not available"); /* * If multiple refs are updated, the hook stdin will put each ref update info into * a separate line, however the line breaks is omitted when forward the hook stdin * to curl via "@-", below logic is used to parse these info correctly even * without line breaks. */ refUpdateInfo = StringUtils.reverse(StringUtils.remove(refUpdateInfo, '\n')); fields.clear(); fields.addAll(StringUtils.splitAndTrim(refUpdateInfo, " ")); sessionManager.runAsync(new Runnable() { @Override public void run() { try { Project project = projectManager.load(projectId); int pos = 0; while (true) { String refName = StringUtils.reverse(fields.get(pos)); pos++; ObjectId newObjectId = ObjectId.fromString(StringUtils.reverse(fields.get(pos))); pos++; String field = fields.get(pos); ObjectId oldObjectId = ObjectId.fromString(StringUtils.reverse(field.substring(0, 40))); if (!newObjectId.equals(ObjectId.zeroId())) { project.cacheObjectId(refName, newObjectId); } else { newObjectId = ObjectId.zeroId(); project.cacheObjectId(refName, null); } String branch = GitUtils.ref2branch(refName); if (branch != null && project.getDefaultBranch() == null) { RefUpdate refUpdate = GitUtils.getRefUpdate(project.getRepository(), "HEAD"); GitUtils.linkRef(refUpdate, refName); } listenerRegistry.post(new RefUpdated(project, refName, oldObjectId, newObjectId)); field = field.substring(40); if (field.length() == 0) break; else fields.set(pos, field); } } catch (Exception e) { logger.error("Error executing post-receive callback", e); } } }); }
Example 19
Source File: CleanupITSupport.java From nexus-public with Eclipse Public License 1.0 | 4 votes |
@Before public void setupSearchSecurity() { ThreadContext.bind(FakeAlmightySubject.forUserId("disabled-security")); }
Example 20
Source File: SecurityUtils.java From onedev with MIT License | 4 votes |
public static void bindAsSystem() { ThreadContext.bind(asSubject(User.SYSTEM_ID)); }