Java Code Examples for org.springframework.security.core.context.SecurityContextHolder#setContext()
The following examples show how to use
org.springframework.security.core.context.SecurityContextHolder#setContext() .
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: PermissionCheckingDecoratorTest.java From molgenis with GNU Lesser General Public License v3.0 | 6 votes |
@Test void testAggregateSystemUser() { SecurityContext originalSecurityContext = SecurityContextHolder.getContext(); try { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication( new UsernamePasswordAuthenticationToken( "principal", "credentials", singleton(new SimpleGrantedAuthority("ROLE_SYSTEM")))); SecurityContextHolder.setContext(securityContext); AggregateQuery aggregateQuery = mock(AggregateQuery.class); permissionCheckingDecorator.aggregate(aggregateQuery); verify(delegateRepository).aggregate(aggregateQuery); } finally { SecurityContextHolder.setContext(originalSecurityContext); } }
Example 2
Source File: PageListControllerTest.java From Asqatasun with GNU Affero General Public License v3.0 | 6 votes |
/** * */ private void setUpMockAuthenticationContext(){ // initialise the context with the user identified by the email // "[email protected]" seen as authenticated Collection<GrantedAuthority> gac = new ArrayList(); TgolUserDetails tud = new TgolUserDetails("[email protected]", "", true, false, true, true, gac, mockUser); mockAuthentication = createMock(Authentication.class); SecurityContextImpl securityContextImpl = new SecurityContextImpl(); securityContextImpl.setAuthentication(mockAuthentication); SecurityContextHolder.setContext(securityContextImpl); expect(mockAuthentication.getName()).andReturn("[email protected]").anyTimes(); expect(mockAuthentication.getPrincipal()).andReturn(tud).anyTimes(); expect(mockAuthentication.getAuthorities()).andReturn(null).anyTimes(); replay(mockAuthentication); mockAuthenticationDetails = createMock(AuthenticationDetails.class); expect(mockAuthenticationDetails.getContext()).andReturn("[email protected]").anyTimes(); replay(mockAuthenticationDetails); }
Example 3
Source File: SystemSecurityContext.java From hawkbit with Eclipse Public License 1.0 | 6 votes |
/** * Runs a given {@link Callable} within a system security context, which has * the provided {@link GrantedAuthority}s to successfully run the * {@link Callable}. * * The security context will be switched to the a new * {@link SecurityContext} and back after the callable is called. * * @param tenant * under which the {@link Callable#call()} must be executed. * @param callable * to call within the security context * @return the return value of the {@link Callable#call()} method. */ // The callable API throws a Exception and not a specific one @SuppressWarnings({ "squid:S2221", "squid:S00112" }) public <T> T runAsControllerAsTenant(@NotEmpty final String tenant, @NotNull final Callable<T> callable) { final SecurityContext oldContext = SecurityContextHolder.getContext(); List<SimpleGrantedAuthority> authorities = Collections .singletonList(new SimpleGrantedAuthority(SpringEvalExpressions.CONTROLLER_ROLE_ANONYMOUS)); try { return tenantAware.runAsTenant(tenant, () -> { try { setCustomSecurityContext(tenant, oldContext.getAuthentication().getPrincipal(), authorities); return callable.call(); } catch (final Exception e) { throw new RuntimeException(e); } }); } finally { SecurityContextHolder.setContext(oldContext); } }
Example 4
Source File: LoginTicketInterceptor.java From MyCommunity with Apache License 2.0 | 6 votes |
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // loginTicket.getTicket() String ticket = CookieUtil.getValue(request, Const.ticket.TICKET); if (ticket != null) { // ticket:UUID LoginTicket loginTicket = userService.findLoginTicket(ticket); if (loginTicket != null && loginTicket.getStatus() == Const.loginStatus.VALID && loginTicket.getExpired().after(new Date())) { // 对 userId 加密,只分装必要的信息,密码不泄漏 UserVo userVo = userService.findUserById(XORUtil.encryptId(loginTicket.getUserId(), Const.getIdEncodeKeys.userIdKeys)); // 在本次请求中持有的用户 hostHolder.setUser(userVo); // 构建用户认证的结果,并存入SecurityContext,以便于Security进行授权. // authentication 认证结果 User user = userMapper.selectByPrimaryKey(XORUtil.encryptId(userVo.getId(), Const.getIdEncodeKeys.userIdKeys)); Authentication authentication = new UsernamePasswordAuthenticationToken( userVo.getId(), user.getPassword(), userService.getAuthorities(user.getId()) ); SecurityContextHolder.setContext(new SecurityContextImpl(authentication)); } } return true; }
Example 5
Source File: JwtTokenAuthenticationProcessingFilter.java From springboot-security-jwt with MIT License | 5 votes |
@Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(authResult); SecurityContextHolder.setContext(context); chain.doFilter(request, response); }
Example 6
Source File: RunAsSystemAspect.java From molgenis with GNU Lesser General Public License v3.0 | 5 votes |
public static <T, X extends Throwable> T runAsSystem(RunnableAsSystem<T, X> runnable) throws X { // Remember the original context SecurityContext origCtx = SecurityContextHolder.getContext(); try { // Set a SystemSecurityToken SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext()); SecurityContextHolder.getContext().setAuthentication(SystemSecurityToken.getInstance()); return runnable.run(); } finally { // Set the original context back when method is finished SecurityContextHolder.setContext(origCtx); } }
Example 7
Source File: SecurityUtilsUnitTest.java From java-microservices-examples with Apache License 2.0 | 5 votes |
@Test public void testGetCurrentUserLogin() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin")); SecurityContextHolder.setContext(securityContext); Optional<String> login = SecurityUtils.getCurrentUserLogin(); assertThat(login).contains("admin"); }
Example 8
Source File: SecurityUtilsUnitTest.java From java-microservices-examples with Apache License 2.0 | 5 votes |
@Test public void testGetCurrentUserLogin() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin")); SecurityContextHolder.setContext(securityContext); Optional<String> login = SecurityUtils.getCurrentUserLogin(); assertThat(login).contains("admin"); }
Example 9
Source File: FiatAuthenticationFilter.java From fiat with Apache License 2.0 | 5 votes |
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!fiatStatus.isEnabled()) { chain.doFilter(request, response); return; } Authentication auth = AuthenticatedRequest.getSpinnakerUser() .map( username -> (Authentication) new PreAuthenticatedAuthenticationToken(username, null, new ArrayList<>())) .orElseGet( () -> new AnonymousAuthenticationToken( "anonymous", "anonymous", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"))); val ctx = SecurityContextHolder.createEmptyContext(); ctx.setAuthentication(auth); SecurityContextHolder.setContext(ctx); log.debug("Set SecurityContext to user: {}", auth.getPrincipal().toString()); chain.doFilter(request, response); }
Example 10
Source File: SecurityUtilsUnitTest.java From e-commerce-microservice with Apache License 2.0 | 5 votes |
@Test public void testgetCurrentUserLogin() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin")); SecurityContextHolder.setContext(securityContext); Optional<String> login = SecurityUtils.getCurrentUserLogin(); assertThat(login).contains("admin"); }
Example 11
Source File: SpringSafeSessionFilter.java From Android_Code_Arbiter with GNU Lesser General Public License v3.0 | 5 votes |
@Override protected void doFilterInternal( HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException { ServletRequestAttributes attributes = new ServletRequestAttributes(req, res); try { if(1 + 1 == 2) { SecurityContext oldCtx = SecurityContextHolder.getContext(); SecurityContextHolder.setContext(null); // try { super.doFilter(req, res, chain); } finally { SecurityContextHolder.setContext(oldCtx); } } else { super.doFilter(req, res, chain); } } finally { attributes.requestCompleted(); } }
Example 12
Source File: SecurityUtilsUnitTest.java From expper with GNU General Public License v3.0 | 5 votes |
@Test public void testAnonymousIsNotAuthenticated() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); Collection<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS)); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities)); SecurityContextHolder.setContext(securityContext); boolean isAuthenticated = SecurityUtils.isAuthenticated(); assertThat(isAuthenticated).isFalse(); }
Example 13
Source File: SecurityUtilsUnitTest.java From TeamDojo with Apache License 2.0 | 5 votes |
@Test public void testgetCurrentUserLogin() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin")); SecurityContextHolder.setContext(securityContext); Optional<String> login = SecurityUtils.getCurrentUserLogin(); assertThat(login).contains("admin"); }
Example 14
Source File: SecurityUtilsUnitTest.java From flair-engine with Apache License 2.0 | 5 votes |
@Test public void testgetCurrentUserLogin() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin")); SecurityContextHolder.setContext(securityContext); String login = SecurityUtils.getCurrentUserLogin(); assertThat(login).isEqualTo("admin"); }
Example 15
Source File: SecurityUtilsUnitTest.java From gpmr with Apache License 2.0 | 5 votes |
@Test public void testIsAuthenticated() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin")); SecurityContextHolder.setContext(securityContext); boolean isAuthenticated = SecurityUtils.isAuthenticated(); assertThat(isAuthenticated).isTrue(); }
Example 16
Source File: SecurityUtilsUnitTest.java From Spring-5.0-Projects with MIT License | 5 votes |
@Test public void testIsCurrentUserInRole() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); Collection<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER)); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("user", "user", authorities)); SecurityContextHolder.setContext(securityContext); assertThat(SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.USER)).isTrue(); assertThat(SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.ADMIN)).isFalse(); }
Example 17
Source File: SecurityUtilsTest.java From expper with GNU General Public License v3.0 | 5 votes |
@Test public void testIsAuthenticated() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin")); SecurityContextHolder.setContext(securityContext); boolean isAuthenticated = SecurityUtils.isAuthenticated(); assertThat(isAuthenticated).isTrue(); }
Example 18
Source File: SecurityUtilsUnitTest.java From TeamDojo with Apache License 2.0 | 5 votes |
@Test public void testAnonymousIsNotAuthenticated() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); Collection<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS)); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities)); SecurityContextHolder.setContext(securityContext); boolean isAuthenticated = SecurityUtils.isAuthenticated(); assertThat(isAuthenticated).isFalse(); }
Example 19
Source File: UserServiceImplTest.java From molgenis with GNU Lesser General Public License v3.0 | 4 votes |
@AfterAll static void tearDownAfterClass() { SecurityContextHolder.setContext(previousContext); }
Example 20
Source File: SystemSecurityContext.java From hawkbit with Eclipse Public License 1.0 | 4 votes |
private static void setSystemContext(final SecurityContext oldContext) { final Authentication oldAuthentication = oldContext.getAuthentication(); final SecurityContextImpl securityContextImpl = new SecurityContextImpl(); securityContextImpl.setAuthentication(new SystemCodeAuthentication(oldAuthentication)); SecurityContextHolder.setContext(securityContextImpl); }