@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 protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { String authHeader = request.getHeader(this.tokenHeader); if (authHeader != null && authHeader.startsWith(this.tokenHead)) { String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer " String username = jwtTokenUtil.getUserNameFromToken(authToken); LOGGER.info("checking username:{}", username); if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails userDetails = this.userDetailsService.loadUserByUsername(username); if (jwtTokenUtil.validateToken(authToken, userDetails)) { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); LOGGER.info("authenticated user:{}", username); SecurityContextHolder.getContext().setAuthentication(authentication); } } } chain.doFilter(request, response); } }
@Override public Authentication authenticate(Authentication authentication, HttpServletRequest request) throws AuthenticationException { UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; // check if name is root if (GeoServerUser.ROOT_USERNAME.equals(token.getPrincipal()) == false) return null; // check password if (token.getCredentials() != null) { if (getSecurityManager().checkMasterPassword(token.getCredentials().toString())) { Collection<GrantedAuthority> roles = new ArrayList<GrantedAuthority>(); roles.add(GeoServerRole.ADMIN_ROLE); UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken( GeoServerUser.ROOT_USERNAME, null, roles); result.setDetails(token.getDetails()); return result; } } // not BadCredentialException is thrown, maybe there is another user with // the same name log(new BadCredentialsException("Bad credentials for: " + token.getPrincipal())); return null; } }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication; String username = String.valueOf(auth.getPrincipal()); String password = String.valueOf(auth.getCredentials()); logger.info("username:" + username); logger.info("password:" + password); // Don't log passwords in real app // 1. Use the username to load the data for the user, including authorities and password. YourUser user = .... // 2. Check the passwords match. if (!user.getPassword().equals(password)) { throw new BadCredentialsException("Bad Credentials"); } // 3. Preferably clear the password in the user object before storing in authentication object user.clearPassword(); // 4. Return an authenticated token, containing user data and authorities return UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()) ; }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (authentication == null) { return authentication; } UsernamePasswordAuthenticationToken output = null; if (authentication instanceof UsernamePasswordAuthenticationToken) { output = (UsernamePasswordAuthenticationToken) authentication; } else { output = new UsernamePasswordAuthenticationToken(authentication, authentication.getCredentials(), authentication.getAuthorities()); output.setAuthenticated(authentication.isAuthenticated()); output.setDetails(authentication.getDetails()); } return delegate.authenticate(output); }
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; }
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { if (allowOnlyPost && !"POST".equalsIgnoreCase(request.getMethod())) { throw new HttpRequestMethodNotSupportedException(request.getMethod(), new String[] { "POST" }); } String clientId = request.getParameter("client_id"); String clientSecret = request.getParameter("client_secret"); // If the request is already authenticated we can assume that this // filter is not needed Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null && authentication.isAuthenticated()) { return authentication; } if (clientId == null) { throw new BadCredentialsException("No client credentials presented"); } if (clientSecret == null) { clientSecret = ""; } clientId = clientId.trim(); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(clientId, clientSecret); return this.getAuthenticationManager().authenticate(authRequest); }
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"); DefaultSavedRequest defaultSavedRequest = ((DefaultSavedRequest) request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST")); sessionRepository.saveContext(SecurityContextHolder.getContext(), responseHolder.getRequest(), responseHolder.getResponse()); model.addAttribute("authorizationRequest", authRequest);
throws IOException { String usHeader = request.getHeader(userNameHeaderName); String pwHeader = request.getHeader(passwordHeaderName); new UsernamePasswordAuthenticationToken(us, pw, new ArrayList<GrantedAuthority>()); Authentication auth = null; try { auth = getSecurityManager().authenticationManager().authenticate(result); } catch (ProviderNotFoundException e) { LOGGER.log(Level.WARNING, "couldn't to authenticate user:" + us); for (GrantedAuthority grauth : auth.getAuthorities()) { roles.add((GeoServerRole) grauth); new UsernamePasswordAuthenticationToken( auth.getPrincipal(), auth.getCredentials(), roles); newResult.setDetails(auth.getDetails()); SecurityContextHolder.getContext().setAuthentication(newResult);
public void changePassword(String oldPassword, String newPassword) { Authentication currentUser = SecurityContextHolder.getContext() .getAuthentication(); if (currentUser == null) { // This would indicate bad coding somewhere throw new AccessDeniedException( "Can't change password as no Authentication object found in context " + "for current user."); } String username = currentUser.getName(); logger.debug("Changing password for user '" + username + "'"); // If an authentication manager has been set, re-authenticate the user with the // supplied password. if (authenticationManager != null) { logger.debug("Reauthenticating user '" + username + "' for password change request."); authenticationManager.authenticate(new UsernamePasswordAuthenticationToken( username, oldPassword)); } else { logger.debug("No authentication manager set. Password won't be re-checked."); } MutableUserDetails user = users.get(username); if (user == null) { throw new IllegalStateException("Current user doesn't exist in database."); } user.setPassword(newPassword); }
private Authentication authenticateJoe() { UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken( "joe", "password", joe.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(auth); return auth; }
/** * If the incoming request contains user credentials in headers or parameters then extract them here into an * Authentication token that can be validated later. This implementation only recognises password grant requests and * extracts the username and password. * * @param request the incoming request, possibly with user credentials * @return an authentication for validation (or null if there is no further authentication) */ protected Authentication extractCredentials(HttpServletRequest request) { String grantType = request.getParameter("grant_type"); if (grantType != null && grantType.equals("password")) { UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken( request.getParameter("username"), request.getParameter("password")); result.setDetails(authenticationDetailsSource.buildDetails(request)); return result; } return null; }
private void authenticateUser(String username, String password, HttpServletRequest request) { UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username, password); HttpSession session = request.getSession(); authToken.setDetails(new WebAuthenticationDetails(request)); Authentication authentication = authenticationManager.authenticate(authToken); SecurityContextHolder.getContext().setAuthentication(authentication); // creates context for that session. session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext()); //set necessary details in session session.setAttribute("username", username); session.setAttribute("authorities", authentication.getAuthorities()); }
public void login(HttpServletRequest request, String userName, String password) { UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(userName, password); // Authenticate the user Authentication authentication = authenticationManager.authenticate(authRequest); SecurityContext securityContext = SecurityContextHolder.getContext(); securityContext.setAuthentication(authentication); // Create a new session and add the security context. HttpSession session = request.getSession(true); session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext); }
@Override @Transactional("blTransactionManager") public AdminUser changePassword(PasswordChange passwordChange) { AdminUser user = readAdminUserByUserName(passwordChange.getUsername()); user.setUnencodedPassword(passwordChange.getNewPassword()); user = saveAdminUser(user); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(passwordChange.getUsername(), passwordChange.getNewPassword(), auth.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authRequest); auth.setAuthenticated(false); return user; }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (!(authentication instanceof PasscodeAuthenticationFilter.ExpiringCodeAuthentication)) { return parent.authenticate(authentication); } else { PasscodeAuthenticationFilter.ExpiringCodeAuthentication expiringCodeAuthentication = (PasscodeAuthenticationFilter.ExpiringCodeAuthentication) authentication; if (methods != null && !methods.contains(expiringCodeAuthentication.getRequest().getMethod().toUpperCase())) { throw new BadCredentialsException("Credentials must be sent by (one of methods): " + methods); authorities = user.getAuthorities(); } catch (UsernameNotFoundException x) { throw new BadCredentialsException("Invalid user."); Authentication result = new UsernamePasswordAuthenticationToken( principal, null,
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 auth) throws AuthenticationException { if (auth.getName() != null && auth.getCredentials() != null) { User user = getUserInfo(auth.getName(), (String) (auth.getCredentials())); return new UsernamePasswordAuthenticationToken(user, null, AUTHORITIES); } throw new BadCredentialsException("Bad Credentials"); }
@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 doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpServletRequest = getAsHttpRequest(request); String authToken = extractAuthTokenFromRequest(httpServletRequest); String username = TokenUtils.getUserNameFromToken(authToken); if (username != null) { UserDetails userDetails = userDetailsService.loadUserByUsername(username); if (TokenUtils.validateToken(authToken, userDetails)) { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest)); SecurityContextHolder.getContext().setAuthentication(authenticationToken); } } chain.doFilter(request, response); }