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); }
@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); }
private List<String> getGroupsFromCurrentUser() { List<String> groups = new ArrayList<>(); Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication() .getAuthorities(); for (GrantedAuthority auth : authorities) { groups.add(auth.getAuthority()); } return groups; }
public Map<String, ?> convertUserAuthentication(Authentication authentication) { Map<String, Object> response = new LinkedHashMap<String, Object>(); response.put(USERNAME, authentication.getName()); if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) { response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities())); } return response; }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = (String) authentication.getPrincipal(); String password = (String) authentication.getCredentials(); UserDetails userDetails = userDetailsService.loadUserByUsername(username); if (!password.equals(userDetails.getPassword())) { return new UsernamePasswordAuthenticationToken(username, null, null); } return null; }
protected Authentication createNewAuthentication(Authentication currentAuth, String newPassword) { UserDetails user = loadUserByUsername(currentAuth.getName()); UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken( user, null, user.getAuthorities()); newAuthentication.setDetails(currentAuth.getDetails()); return newAuthentication; }
/** * Get the indicated resource set * @param rsid * @param m * @param auth * @return */ @RequestMapping(value = "/{rsid}", method = RequestMethod.GET, produces = MimeTypeUtils.APPLICATION_JSON_VALUE) public String getResourceSet(@PathVariable (value = "rsid") Long rsid, Model m, Authentication auth) { ResourceSet rs = resourceSetService.getById(rsid); if (rs == null) { m.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND); return HttpCodeView.VIEWNAME; } if (!rs.getOwner().equals(auth.getName())) { logger.warn("Unauthorized resource set request from bad user; expected " + rs.getOwner() + " got " + auth.getName()); // authenticated user didn't match the owner of the resource set m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN); return HttpCodeView.VIEWNAME; } m.addAttribute(JsonEntityView.ENTITY, rs); return JsonEntityView.VIEWNAME; }
@Secured("IS_AUTHENTICATED_FULLY") @RequestMapping(path = "/whoami/roles", method = RequestMethod.GET) public List<String> user() { UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext(). getAuthentication().getPrincipal(); return userDetails.getAuthorities().stream().map(ga -> ga.getAuthority()).collect(Collectors.toList()); } }
@RequestMapping(value = "/login", method = RequestMethod.POST) public String login(HttpServletRequest request, HttpServletResponse response, Model model) { new UsernamePasswordAuthenticationToken(request.getParameter("username"), request.getParameter("password"), authorities); SecurityContextHolder.getContext() .setAuthentication(authenticationManager.authenticate(auth)); if(!authenticationManager.authenticate(auth).isAuthenticated()) throw new CredentialException("User could not be authenticated"); sessionRepository.saveContext(SecurityContextHolder.getContext(), responseHolder.getRequest(), responseHolder.getResponse()); model.addAttribute("authorizationRequest", authRequest);
/** * List all resource sets for the current user * @param m * @param auth * @return */ @RequestMapping(value = "", method = RequestMethod.GET, produces = MimeTypeUtils.APPLICATION_JSON_VALUE) public String getResourceSetsForCurrentUser(Model m, Authentication auth) { Collection<ResourceSet> resourceSets = resourceSetService.getAllForOwner(auth.getName()); m.addAttribute(JsonEntityView.ENTITY, resourceSets); return JsonEntityView.VIEWNAME; }
@RequestMapping(value = "/oauth/token/list", method = GET) public ResponseEntity<List<RevocableToken>> listUserTokens(OAuth2Authentication authentication) { UaaPrincipal principal = (UaaPrincipal) authentication.getUserAuthentication().getPrincipal(); String userId = principal.getId(); String clientId = authentication.getOAuth2Request().getClientId(); logger.debug("Listing revocable tokens access token userId:"+ userId +" clientId:"+ clientId); List<RevocableToken> result = tokenProvisioning.getUserTokens(userId, clientId, IdentityZoneHolder.get().getId()); removeTokenValues(result); return new ResponseEntity<>(result, OK); }
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()); logger.error("Failed to auth user: " + authentication.getName(), e); throw e;
@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 UmsMember getCurrentMember() { SecurityContext ctx = SecurityContextHolder.getContext(); Authentication auth = ctx.getAuthentication(); MemberDetails memberDetails = (MemberDetails) auth.getPrincipal(); return memberDetails.getUmsMember(); }
/** * Determines if a user is already authenticated. * @return */ private boolean authenticated() { Authentication authentication = SecurityContextHolder.getContext() .getAuthentication(); return authentication != null && authentication.isAuthenticated() && !(authentication instanceof AnonymousAuthenticationToken); }
@Override public Set<GrantedAuthority> getAuthorities() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null) { return Collections.emptySet(); } return Collections.unmodifiableSet(new HashSet<GrantedAuthority>(authentication.getAuthorities())); }
private String principal() { if ( SecurityContextHolder.getContext().getAuthentication() != null ) { return SecurityContextHolder.getContext().getAuthentication().getName(); } return null; } }
/** * @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(); } }
@Test public void securityContextDeserializeTest() throws IOException { SecurityContext context = mapper.readValue(SECURITY_CONTEXT_JSON, SecurityContextImpl.class); assertThat(context).isNotNull(); assertThat(context.getAuthentication()).isNotNull().isInstanceOf(UsernamePasswordAuthenticationToken.class); assertThat(context.getAuthentication().getPrincipal()).isEqualTo("admin"); assertThat(context.getAuthentication().getCredentials()).isEqualTo("1234"); assertThat(context.getAuthentication().isAuthenticated()).isTrue(); Collection authorities = context.getAuthentication().getAuthorities(); assertThat(authorities).hasSize(1); assertThat(authorities).contains(new SimpleGrantedAuthority("ROLE_USER")); } }