/** * 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; }
/** * 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 username = request.getParameter("username"); String password = request.getParameter("password"); UsernamePasswordAuthenticationToken credentials = new UsernamePasswordAuthenticationToken(username, password); credentials.setDetails(authenticationDetailsSource.buildDetails(request)); return credentials; }
private Authentication getAuthentication() { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( "Principal", "Credentials"); authentication.setDetails("127.0.0.1"); return authentication; }
private Authentication getAuthentication() { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( "Principal", "Credentials"); authentication.setDetails("127.0.0.1"); return authentication; }
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 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); } }
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; }
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest) request));
private OAuth2Authentication extractAuthentication(Map<String, Object> map) { Object principal = getPrincipal(map); OAuth2Request request = getRequest(map); List<GrantedAuthority> authorities = this.authoritiesExtractor .extractAuthorities(map); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( principal, "N/A", authorities); token.setDetails(map); return new OAuth2Authentication(request, token); }
private OAuth2Authentication extractAuthentication(Map<String, Object> map) { Object principal = getPrincipal(map); OAuth2Request request = getRequest(map); List<GrantedAuthority> authorities = this.authoritiesExtractor .extractAuthorities(map); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( principal, "N/A", authorities); token.setDetails(map); return new OAuth2Authentication(request, token); }
private boolean authenticateClient(String clientId, String clientSecret) { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(clientId,clientSecret); try { HttpServletRequest curRequest = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); if (curRequest != null) { authentication.setDetails(new UaaAuthenticationDetails(curRequest, clientId)); } }catch (IllegalStateException x) { //ignore - means no thread bound request found } try { Authentication auth = authenticationManager.authenticate(authentication); return auth.isAuthenticated(); } catch (AuthenticationException e) { return false; } catch (Exception e) { logger.debug("Unable to authenticate/validate "+clientId, e); return false; } }
@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); }
@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); }
@Override public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response) throws AuthenticationException, IOException { // if the request is a proxy request process it and return null to indicate the // request has been processed if (proxyReceptorRequest(request)) { logger.debug("Responding to proxy receptor request"); CommonUtils.readAndRespondToProxyReceptorRequest(request, response, this.proxyGrantingTicketStorage); return null; } final boolean serviceTicketRequest = serviceTicketRequest(request, response); final String username = serviceTicketRequest ? CAS_STATEFUL_IDENTIFIER : CAS_STATELESS_IDENTIFIER; String password = obtainArtifact(request); if (password == null) { logger.debug("Failed to obtain an artifact (cas ticket)"); password = ""; } final UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken( username, password); authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); return this.getAuthenticationManager().authenticate(authRequest); }
/** * Creates the final {@code Authentication} object which will be returned from the * {@code authenticate} method. * * @param authentication the original authentication request token * @param user the <tt>UserDetails</tt> instance returned by the configured * <tt>UserDetailsContextMapper</tt>. * @return the Authentication object for the fully authenticated user. */ protected Authentication createSuccessfulAuthentication( UsernamePasswordAuthenticationToken authentication, UserDetails user) { Object password = this.useAuthenticationRequestCredentials ? authentication.getCredentials() : user.getPassword(); UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken( user, password, this.authoritiesMapper.mapAuthorities(user.getAuthorities())); result.setDetails(authentication.getDetails()); return result; }
/** * Creates a successful {@link Authentication} object. * <p> * Protected so subclasses can override. * </p> * <p> * Subclasses will usually store the original credentials the user supplied (not * salted or encoded passwords) in the returned <code>Authentication</code> object. * </p> * * @param principal that should be the principal in the returned object (defined by * the {@link #isForcePrincipalAsString()} method) * @param authentication that was presented to the provider for validation * @param user that was loaded by the implementation * * @return the successful authentication token */ protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) { // Ensure we return the original credentials the user supplied, // so subsequent attempts are successful even with encoded passwords. // Also ensure we return the original getDetails(), so that future // authentication events after cache expiry contain the details UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken( principal, authentication.getCredentials(), authoritiesMapper.mapAuthorities(user.getAuthorities())); result.setDetails(authentication.getDetails()); return result; }
@Test public void testAuthenticates() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "rod", "koala"); token.setDetails("192.168.0.1"); DaoAuthenticationProvider provider = createProvider(); provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserCache(new MockUserCache()); Authentication result = provider.authenticate(token); if (!(result instanceof UsernamePasswordAuthenticationToken)) { fail("Should have returned instance of UsernamePasswordAuthenticationToken"); } UsernamePasswordAuthenticationToken castResult = (UsernamePasswordAuthenticationToken) result; assertThat(castResult.getPrincipal().getClass()).isEqualTo(User.class); assertThat(castResult.getCredentials()).isEqualTo("koala"); assertThat( AuthorityUtils.authorityListToSet(castResult.getAuthorities())).contains( "ROLE_ONE", "ROLE_TWO"); assertThat(castResult.getDetails()).isEqualTo("192.168.0.1"); }
@Test public void normalUsage() { MockAuthoritiesPopulator populator = new MockAuthoritiesPopulator(); LdapAuthenticationProvider ldapProvider = new LdapAuthenticationProvider( new MockAuthenticator(), populator); LdapUserDetailsMapper userMapper = new LdapUserDetailsMapper(); userMapper.setRoleAttributes(new String[] { "ou" }); ldapProvider.setUserDetailsContextMapper(userMapper); assertThat(ldapProvider.getAuthoritiesPopulator()).isNotNull(); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken( "ben", "benspassword"); Object authDetails = new Object(); authRequest.setDetails(authDetails); Authentication authResult = ldapProvider.authenticate(authRequest); assertThat(authResult.getCredentials()).isEqualTo("benspassword"); assertThat(authResult.getDetails()).isSameAs(authDetails); UserDetails user = (UserDetails) authResult.getPrincipal(); assertThat(user.getAuthorities()).hasSize(2); assertThat(user.getPassword()).isEqualTo("{SHA}nFCebWjxfaLbHHG1Qk5UU4trbvQ="); assertThat(user.getUsername()).isEqualTo("ben"); assertThat(populator.getRequestedUsername()).isEqualTo("ben"); assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities())) .contains("ROLE_FROM_ENTRY"); assertThat(AuthorityUtils.authorityListToSet(user.getAuthorities())) .contains("ROLE_FROM_POPULATOR"); }
@Test public void statelessAuthenticationIsSuccessful() throws Exception { CasAuthenticationProvider cap = new CasAuthenticationProvider(); cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); cap.setKey("qwerty"); StatelessTicketCache cache = new MockStatelessTicketCache(); cap.setStatelessTicketCache(cache); cap.setTicketValidator(new MockTicketValidator(true)); cap.setServiceProperties(makeServiceProperties()); cap.afterPropertiesSet(); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER, "ST-456"); token.setDetails("details"); Authentication result = cap.authenticate(token); // Confirm ST-456 was added to the cache assertThat(cache.getByTicketId("ST-456") != null).isTrue(); if (!(result instanceof CasAuthenticationToken)) { fail("Should have returned a CasAuthenticationToken"); } assertThat(result.getPrincipal()).isEqualTo(makeUserDetailsFromAuthoritiesPopulator()); assertThat(result.getCredentials()).isEqualTo("ST-456"); assertThat(result.getDetails()).isEqualTo("details"); // Now try to authenticate again. To ensure TicketValidator not // called again, set it to deliver an exception... cap.setTicketValidator(new MockTicketValidator(false)); // Previously created UsernamePasswordAuthenticationToken is OK Authentication newResult = cap.authenticate(token); assertThat(newResult.getPrincipal()).isEqualTo(makeUserDetailsFromAuthoritiesPopulator()); assertThat(newResult.getCredentials()).isEqualTo("ST-456"); }
token.setDetails("details");