private String getCurrentUsername() { Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof UserDetails) { return ((UserDetails) principal).getUsername(); } if (principal instanceof Principal) { return ((Principal) principal).getName(); } return String.valueOf(principal); }
@Test public void testContextHolderGetterSetterClearer() { SecurityContext sc = new SecurityContextImpl(); sc.setAuthentication(new UsernamePasswordAuthenticationToken("Foobar", "pass")); SecurityContextHolder.setContext(sc); assertThat(SecurityContextHolder.getContext()).isEqualTo(sc); SecurityContextHolder.clearContext(); assertThat(SecurityContextHolder.getContext()).isNotSameAs(sc); SecurityContextHolder.clearContext(); }
@Override public void run() { this.originalSecurityContext = SecurityContextHolder.getContext(); try { SecurityContextHolder.setContext(delegateSecurityContext); delegate.run(); } finally { SecurityContext emptyContext = SecurityContextHolder.createEmptyContext(); if (emptyContext.equals(originalSecurityContext)) { SecurityContextHolder.clearContext(); } else { SecurityContextHolder.setContext(originalSecurityContext); } this.originalSecurityContext = null; } }
private void setup(Message<?> message) { SecurityContext currentContext = SecurityContextHolder.getContext(); Stack<SecurityContext> contextStack = ORIGINAL_CONTEXT.get(); if (contextStack == null) { contextStack = new Stack<>(); ORIGINAL_CONTEXT.set(contextStack); } contextStack.push(currentContext); Object user = message.getHeaders().get(authenticationHeaderName); Authentication authentication; if ((user instanceof Authentication)) { authentication = (Authentication) user; } else { authentication = this.anonymous; } SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(authentication); SecurityContextHolder.setContext(context); }
@RequestMapping(value = "/query/{queryId}/stop", method = RequestMethod.PUT) @ResponseBody public void stopQuery(@PathVariable String queryId) { final String user = SecurityContextHolder.getContext().getAuthentication().getName(); logger.info("{} tries to stop the query: {}, but not guaranteed to succeed.", user, queryId); QueryContextFacade.stopQuery(queryId, "stopped by " + user); }
@RequestMapping(value = "{id}", method = DELETE) @Transactional public ResponseEntity<IdentityProvider> deleteIdentityProvider(@PathVariable String id, @RequestParam(required = false, defaultValue = "false") boolean rawConfig) throws MetadataProviderException { IdentityProvider existing = identityProviderProvisioning.retrieve(id, IdentityZoneHolder.get().getId()); if (publisher!=null && existing!=null) { existing.setSerializeConfigRaw(rawConfig); publisher.publishEvent(new EntityDeletedEvent<>(existing, SecurityContextHolder.getContext().getAuthentication())); return new ResponseEntity<>(existing, OK); } else { return new ResponseEntity<>(UNPROCESSABLE_ENTITY); } }
@RequestMapping(value = "/authenticate", method = RequestMethod.POST) public TokenTransfer authenticate(@RequestParam("username") String username, @RequestParam("password") String password) { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password); Authentication authentication = authManager.authenticate(authenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); UserDetails userDetails = userDetailsService.loadUserByUsername(username); return new TokenTransfer(TokenUtils.createToken(userDetails)); }
@Override public String signIn(String username, Connection<?> connection, NativeWebRequest request) { UserDetails principal = userDetailsService.loadUserByUsername(username); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, null, principal.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(token); return null; }
@Test public void targetShouldAllowProtectedMethodInvocationWithCorrectRole() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "Test", "Password", AuthorityUtils.createAuthorityList("ROLE_USER")); SecurityContextHolder.getContext().setAuthentication(token); target.someUserMethod1(); }
private void setAuthenticationPrincipal(Object principal) { this.expectedPrincipal = principal; SecurityContextHolder.getContext() .setAuthentication( new TestingAuthenticationToken(expectedPrincipal, "password", "ROLE_USER")); } }
Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth == null || !auth.isAuthenticated()) { throw new AuthenticationCredentialsNotFoundException("Authentication was null, not authenticated, or not logged in."); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), auth.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(token);
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { byte[] hashKey = hf.hashString(authentication.getName() + authentication.getCredentials()).asBytes(); String userKey = Arrays.toString(hashKey); SecurityContextHolder.getContext().setAuthentication(authed); } else { try { if (authed.getDetails() == null) { if (authed.getDetails() instanceof UserDetails) { UserDetails details = (UserDetails) authed.getDetails(); user = new ManagedUser(details.getUsername(), details.getPassword(), false, details.getAuthorities()); } else { user = new ManagedUser(authentication.getName(), "skippped-ldap", false, authed.getAuthorities());
@Override public UmsMember getCurrentMember() { SecurityContext ctx = SecurityContextHolder.getContext(); Authentication auth = ctx.getAuthentication(); MemberDetails memberDetails = (MemberDetails) auth.getPrincipal(); return memberDetails.getUmsMember(); }
@Test public void changePasswordSucceedsWithIfReAuthenticationSucceeds() { insertJoe(); Authentication currentAuth = authenticateJoe(); AuthenticationManager am = mock(AuthenticationManager.class); when(am.authenticate(currentAuth)).thenReturn(currentAuth); manager.setAuthenticationManager(am); manager.changePassword("password", "newPassword"); UserDetails newJoe = manager.loadUserByUsername("joe"); assertThat(newJoe.getPassword()).isEqualTo("newPassword"); // The password in the context should also be altered Authentication newAuth = SecurityContextHolder.getContext().getAuthentication(); assertThat(newAuth.getName()).isEqualTo("joe"); assertThat(newAuth.getDetails()).isEqualTo(currentAuth.getDetails()); assertThat(newAuth.getCredentials()).isNull(); assertThat(cache.getUserMap().containsKey("joe")).isFalse(); }
@Override public Set<GrantedAuthority> getAuthorities() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null) { return Collections.emptySet(); } return Collections.unmodifiableSet(new HashSet<GrantedAuthority>(authentication.getAuthorities())); }
/** * @see org.springframework.ldap.core.AuthenticationSource#getCredentials() */ public String getCredentials() { Authentication authentication = SecurityContextHolder.getContext() .getAuthentication(); if (authentication == null) { log.warn("No Authentication object set in SecurityContext - returning empty String as Credentials"); return ""; } return (String) authentication.getCredentials(); } }
private String principal() { if ( SecurityContextHolder.getContext().getAuthentication() != null ) { return SecurityContextHolder.getContext().getAuthentication().getName(); } return null; } }
/** * Determines if a user is already authenticated. * @return */ private boolean authenticated() { Authentication authentication = SecurityContextHolder.getContext() .getAuthentication(); return authentication != null && authentication.isAuthenticated() && !(authentication instanceof AnonymousAuthenticationToken); }
@Test public void changePasswordFailsIfReAuthenticationFails() { insertJoe(); authenticateJoe(); AuthenticationManager am = mock(AuthenticationManager.class); when(am.authenticate(any(Authentication.class))).thenThrow( new BadCredentialsException("")); manager.setAuthenticationManager(am); try { manager.changePassword("password", "newPassword"); fail("Expected BadCredentialsException"); } catch (BadCredentialsException expected) { } // Check password hasn't changed. UserDetails newJoe = manager.loadUserByUsername("joe"); assertThat(newJoe.getPassword()).isEqualTo("password"); assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("password"); assertThat(cache.getUserMap().containsKey("joe")).isTrue(); }
@Test(expected = AccessDeniedException.class) public void globalMethodSecurityIsEnabledWhenNotAllowedThenAccessDenied() { SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("test", null, "ROLE_USER")); this.userRepo.save(User.withUsernameAndPassword("denied", "password")); Authentication result = this.authenticationManager .authenticate(new UsernamePasswordAuthenticationToken("test", "password")); } }