Java Code Examples for org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken#setDetails()
The following examples show how to use
org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken#setDetails() .
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: HttpHeaderAuthenticationFilter.java From herd with Apache License 2.0 | 6 votes |
/** * Creates the user based on the given request, and puts the user into the security context. Throws if authentication fails. * * @param servletRequest {@link HttpServletRequest} containing the user's request. */ private void authenticateUser(HttpServletRequest servletRequest) { try { // Setup the authentication request and perform the authentication. Perform the authentication based on the fully built user. PreAuthenticatedAuthenticationToken preAuthenticatedAuthenticationToken = new PreAuthenticatedAuthenticationToken(applicationUserBuilder.build(servletRequest), "N/A"); preAuthenticatedAuthenticationToken.setDetails(authenticationDetailsSource.buildDetails(servletRequest)); Authentication authentication = authenticationManager.authenticate(preAuthenticatedAuthenticationToken); // The authentication returned so it was successful. successfulAuthentication(authentication); } catch (AuthenticationException e) { // An authentication exception was thrown so authentication failed. unsuccessfulAuthentication(servletRequest, e); // Throw an exception so we don't continue since there is some problem (e.g. user profile doesn't // exist for the logged in user or it couldn't be retrieved). throw e; } }
Example 2
Source File: TrustedUserAuthenticationFilter.java From herd with Apache License 2.0 | 6 votes |
/** * doFilter implementation for an HTTP request and response. * * @param request the HTTP servlet request. * @param response the HTTP servlet response. * @param chain the filter chain. * * @throws IOException if an I/O error occurs. * @throws ServletException if a servlet error occurs. */ public void doHttpFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { // Check if security is enabled // If security is not enabled, perform allow as trusted user. if (!securityHelper.isSecurityEnabled(request)) { // If authentication is not there or is not of trusted user type. PreAuthenticatedAuthenticationToken authRequest = new PreAuthenticatedAuthenticationToken(applicationUserBuilder.build(request), "N/A"); authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); Authentication authResult = authenticationManager.authenticate(authRequest); // The authentication returned so it was successful. SecurityContextHolder.getContext().setAuthentication(authResult); } chain.doFilter(request, response); }
Example 3
Source File: PreAuthTokenSourceTrustAuthenticationProviderTest.java From hawkbit with Eclipse Public License 1.0 | 6 votes |
@Test @Description("Testing in case the containing controllerId in the URI request path does not accord with the controllerId in the request header.") public void principalAndCredentialsNotTheSameThrowsAuthenticationException() { final String principal = "controllerIdURL"; final String credentials = "controllerIdHeader"; final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, Arrays.asList(credentials)); token.setDetails(webAuthenticationDetailsMock); // test, should throw authentication exception try { underTestWithoutSourceIpCheck.authenticate(token); fail("Should not work with wrong credentials"); } catch (final BadCredentialsException e) { } }
Example 4
Source File: PreAuthTokenSourceTrustAuthenticationProviderTest.java From hawkbit with Eclipse Public License 1.0 | 6 votes |
@Test @Description("Testing that the controllerId in the URI request match with the controllerId in the request header but the request are not coming from a trustful source.") public void priniciapAndCredentialsAreTheSameButSourceIpRequestNotMatching() { final String remoteAddress = "192.168.1.1"; final String principal = "controllerId"; final String credentials = "controllerId"; final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, Arrays.asList(credentials)); token.setDetails(webAuthenticationDetailsMock); when(webAuthenticationDetailsMock.getRemoteAddress()).thenReturn(remoteAddress); // test, should throw authentication exception try { underTestWithSourceIpCheck.authenticate(token); fail("as source is not trusted."); } catch (final InsufficientAuthenticationException e) { } }
Example 5
Source File: PreAuthTokenSourceTrustAuthenticationProviderTest.java From hawkbit with Eclipse Public License 1.0 | 6 votes |
@Test public void priniciapAndCredentialsAreTheSameAndSourceIpIsWithinList() { final String[] trustedIPAddresses = new String[] { "192.168.1.1", "192.168.1.2", REQUEST_SOURCE_IP, "192.168.1.3" }; final String principal = "controllerId"; final String credentials = "controllerId"; final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, Arrays.asList(credentials)); token.setDetails(webAuthenticationDetailsMock); when(webAuthenticationDetailsMock.getRemoteAddress()).thenReturn(REQUEST_SOURCE_IP); final PreAuthTokenSourceTrustAuthenticationProvider underTestWithList = new PreAuthTokenSourceTrustAuthenticationProvider( trustedIPAddresses); // test, should throw authentication exception final Authentication authenticate = underTestWithList.authenticate(token); assertThat(authenticate.isAuthenticated()).isTrue(); }
Example 6
Source File: PreAuthTokenSourceTrustAuthenticationProviderTest.java From hawkbit with Eclipse Public License 1.0 | 6 votes |
@Test(expected = InsufficientAuthenticationException.class) public void principalAndCredentialsAreTheSameSourceIpListNotMatches() { final String[] trustedIPAddresses = new String[] { "192.168.1.1", "192.168.1.2", "192.168.1.3" }; final String principal = "controllerId"; final String credentials = "controllerId"; final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, Arrays.asList(credentials)); token.setDetails(webAuthenticationDetailsMock); when(webAuthenticationDetailsMock.getRemoteAddress()).thenReturn(REQUEST_SOURCE_IP); final PreAuthTokenSourceTrustAuthenticationProvider underTestWithList = new PreAuthTokenSourceTrustAuthenticationProvider( trustedIPAddresses); // test, should throw authentication exception final Authentication authenticate = underTestWithList.authenticate(token); try { assertThat(authenticate.isAuthenticated()).isTrue(); fail("as source is not trusted."); } catch (final InsufficientAuthenticationException e) { } }
Example 7
Source File: SpringSecurityUtils.java From lemon with Apache License 2.0 | 5 votes |
public static void saveUserDetailsToContext(UserDetails userDetails, HttpServletRequest request, SecurityContext securityContext) { PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken( userDetails, userDetails.getPassword(), userDetails.getAuthorities()); if (request != null) { authentication.setDetails(new WebAuthenticationDetails(request)); } securityContext.setAuthentication(authentication); }
Example 8
Source File: SmsTokenGranter.java From spring-cloud-shop with MIT License | 5 votes |
@Override protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) { Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters()); String phone = parameters.get("phone"); String smsCode = parameters.get("smsCode"); Collection<? extends GrantedAuthority> grantedAuthorities = userService.loadUserBySMS(phone, smsCode); PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(phone, null, grantedAuthorities); authentication.setDetails(parameters); return new OAuth2Authentication(this.requestFactory.createOAuth2Request(client, tokenRequest), authentication); }
Example 9
Source File: SpringSecurityUtils.java From lemon with Apache License 2.0 | 5 votes |
/** * 将UserDetails保存到Security Context. * * @param userDetails * 已初始化好的用户信息. * @param request * 用于获取用户IP地址信息,可为Null. */ public static void saveUserDetailsToContext(UserDetails userDetails, HttpServletRequest request) { PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken( userDetails, userDetails.getPassword(), userDetails.getAuthorities()); if (request != null) { authentication.setDetails(new WebAuthenticationDetails(request)); } SecurityContextHolder.getContext().setAuthentication(authentication); }
Example 10
Source File: SpringSecurityUtils.java From spring-microservice-boilerplate with MIT License | 5 votes |
/** * Save user details to security context. * * @param userDetails user details * @param request request */ public static void saveUserDetailsToContext(UserDetails userDetails, HttpServletRequest request) { PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken( userDetails, userDetails.getPassword(), userDetails.getAuthorities()); if (request != null) { authentication.setDetails(new WebAuthenticationDetails(request)); } SecurityContextHolder.getContext().setAuthentication(authentication); }
Example 11
Source File: AmqpControllerAuthentication.java From hawkbit with Eclipse Public License 1.0 | 5 votes |
/** * Performs authentication with the security token. * * @param securityToken * the authentication request object * @return the authentication object */ public Authentication doAuthenticate(final DmfTenantSecurityToken securityToken) { resolveTenant(securityToken); PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(null, null); for (final PreAuthenticationFilter filter : filterChain) { final PreAuthenticatedAuthenticationToken authenticationRest = createAuthentication(filter, securityToken); if (authenticationRest != null) { authentication = authenticationRest; authentication.setDetails(new TenantAwareAuthenticationDetails(securityToken.getTenant(), true)); break; } } return preAuthenticatedAuthenticationProvider.authenticate(authentication); }
Example 12
Source File: PreAuthTokenSourceTrustAuthenticationProvider.java From hawkbit with Eclipse Public License 1.0 | 5 votes |
@Override public Authentication authenticate(final Authentication authentication) { if (!supports(authentication.getClass())) { return null; } final PreAuthenticatedAuthenticationToken token = (PreAuthenticatedAuthenticationToken) authentication; final Object credentials = token.getCredentials(); final Object principal = token.getPrincipal(); final Object tokenDetails = token.getDetails(); final Collection<GrantedAuthority> authorities = token.getAuthorities(); if (principal == null) { throw new BadCredentialsException("The provided principal and credentials are not match"); } final boolean successAuthentication = calculateAuthenticationSuccess(principal, credentials, tokenDetails); if (successAuthentication) { final PreAuthenticatedAuthenticationToken successToken = new PreAuthenticatedAuthenticationToken(principal, credentials, authorities); successToken.setDetails(tokenDetails); return successToken; } throw new BadCredentialsException("The provided principal and credentials are not match"); }
Example 13
Source File: PreAuthTokenSourceTrustAuthenticationProviderTest.java From hawkbit with Eclipse Public License 1.0 | 5 votes |
@Test @Description("Testing that the controllerId in the URI request match with the controllerId in the request header and the source Ip is matching the allowed remote IP address.") public void priniciapAndCredentialsAreTheSameAndSourceIpIsTrusted() { final String principal = "controllerId"; final String credentials = "controllerId"; final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, Arrays.asList(credentials)); token.setDetails(webAuthenticationDetailsMock); when(webAuthenticationDetailsMock.getRemoteAddress()).thenReturn(REQUEST_SOURCE_IP); // test, should throw authentication exception final Authentication authenticate = underTestWithSourceIpCheck.authenticate(token); assertThat(authenticate.isAuthenticated()).isTrue(); }
Example 14
Source File: PreAuthTokenSourceTrustAuthenticationProviderTest.java From hawkbit with Eclipse Public License 1.0 | 5 votes |
@Test @Description("Testing that the controllerId within the URI request path is the same with the controllerId within the request header and no source IP check is in place.") public void principalAndCredentialsAreTheSameWithNoSourceIpCheckIsSuccessful() { final String principal = "controllerId"; final String credentials = "controllerId"; final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, Arrays.asList(credentials)); token.setDetails(webAuthenticationDetailsMock); final Authentication authenticate = underTestWithoutSourceIpCheck.authenticate(token); assertThat(authenticate.isAuthenticated()).isTrue(); }
Example 15
Source File: AbstractHttpControllerAuthenticationFilter.java From hawkbit with Eclipse Public License 1.0 | 5 votes |
@Override protected void successfulAuthentication(final HttpServletRequest request, final HttpServletResponse response, final Authentication authResult) throws IOException, ServletException { final Collection<GrantedAuthority> authorities = new ArrayList<>(); authorities.addAll(authResult.getAuthorities()); authorities.addAll(abstractControllerAuthenticationFilter.getSuccessfulAuthenticationAuthorities()); final PreAuthenticatedAuthenticationToken authTokenWithGrantedAuthorities = new PreAuthenticatedAuthenticationToken( authResult.getPrincipal(), authResult.getCredentials(), authorities); authTokenWithGrantedAuthorities.setDetails(authResult.getDetails()); super.successfulAuthentication(request, response, authTokenWithGrantedAuthorities); }
Example 16
Source File: HmacAuthenticationFilter.java From spring-hmac-rest with MIT License | 4 votes |
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { final AuthHeader authHeader = HmacUtil.getAuthHeader(request); if (authHeader == null) { // invalid authorization token logger.warn("Authorization header is missing"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } final String username = authHeader.getApiKey(); UserDetails userDetails = userDetailsService.loadUserByUsername(username); assert (userDetails != null); CachingRequestWrapper requestWrapper = new CachingRequestWrapper(request); final byte[] contentAsByteArray = requestWrapper.getContentAsByteArray(); final HmacSignatureBuilder signatureBuilder = new HmacSignatureBuilder() .algorithm(authHeader.getAlgorithm()) .scheme(request.getScheme()) .host(request.getServerName() + ":" + request.getServerPort()) .method(request.getMethod()) .resource(request.getRequestURI()) .contentType(request.getContentType()) .date(request.getHeader(HttpHeaders.DATE)) .nonce(authHeader.getNonce()) .apiKey(username) .apiSecret(userDetails.getPassword()) .payload(contentAsByteArray); if (!signatureBuilder.isHashEquals(authHeader.getDigest())) { throw new BadCredentialsException("HmacAccessFilter.badSignature"); } final PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken( userDetails.getUsername(), null, userDetails.getAuthorities()); authentication.setDetails(userDetails); SecurityContextHolder.getContext().setAuthentication(authentication); try { filterChain.doFilter(requestWrapper, response); } finally { SecurityContextHolder.clearContext(); } }
Example 17
Source File: STSPreAuthAuthenticationProvider.java From cxf-fediz with Apache License 2.0 | 4 votes |
private Authentication handlePreAuthenticated( PreAuthenticatedAuthenticationToken preauthenticatedToken, IdpSTSClient sts ) { X509Certificate cert = (X509Certificate)preauthenticatedToken.getCredentials(); if (cert == null) { return null; } // Convert the received certificate to a DOM Element to write it out "OnBehalfOf" Document doc = DOMUtils.createDocument(); X509Data certElem = new X509Data(doc); try { certElem.addCertificate(cert); sts.setOnBehalfOf(certElem.getElement()); } catch (XMLSecurityException e) { LOG.debug("Error parsing a client certificate", e); return null; } try { // Line below may be uncommented for debugging // setTimeout(sts.getClient(), 3600000L); SecurityToken token = sts.requestSecurityToken(this.appliesTo); List<GrantedAuthority> authorities = createAuthorities(token); STSUserDetails details = new STSUserDetails(preauthenticatedToken.getName(), "", authorities, token); preauthenticatedToken.setDetails(details); LOG.debug("[IDP_TOKEN={}] provided for user '{}'", token.getId(), preauthenticatedToken.getName()); return preauthenticatedToken; } catch (Exception ex) { LOG.info("Failed to authenticate user '" + preauthenticatedToken.getName() + "'", ex); return null; } }
Example 18
Source File: AuthenticationTokenFilter.java From haven-platform with Apache License 2.0 | 4 votes |
private Authentication processTokenAuthentication(String token, Object details) { final PreAuthenticatedAuthenticationToken authenticationToken = new PreAuthenticatedAuthenticationToken(token, null); authenticationToken.setDetails(details); return authenticationProvider.authenticate(authenticationToken); }