@Override public Authentication authenticate(Authentication authenticationRequest) throws AuthenticationException { GrantedAuthority[] authorities = new GrantedAuthorityImpl[authenticationRequest.getAuthorities().length + 1]; authorities[0] = new GrantedAuthorityImpl(AUTHENTICATED_AUTHORITY_NAME); int i = 1; for(GrantedAuthority originalAuth : authenticationRequest.getAuthorities()){ authorities[i] = new GrantedAuthorityImpl(originalAuth.getAuthority()); i += 1; } UsernamePasswordAuthenticationToken authenticationOutcome = new UsernamePasswordAuthenticationToken(authenticationRequest.getPrincipal(), authenticationRequest.getCredentials(), authorities); authenticationOutcome.setDetails(authenticationRequest.getDetails()); return authenticationOutcome; }
@Test public void shouldConvey_itsBasicProcessingFilter() throws IOException, ServletException { BasicAuthenticationFilter filter = new BasicAuthenticationFilter(localizer); final Boolean[] hadBasicMarkOnInsideAuthenticationManager = new Boolean[]{false}; filter.setAuthenticationManager(new AuthenticationManager() { public Authentication authenticate(Authentication authentication) throws AuthenticationException { hadBasicMarkOnInsideAuthenticationManager[0] = BasicAuthenticationFilter.isProcessingBasicAuth(); return new UsernamePasswordAuthenticationToken("school-principal", "u can be principal if you know this!"); } }); assertThat(BasicAuthenticationFilter.isProcessingBasicAuth(), is(false)); MockHttpServletRequest httpRequest = new MockHttpServletRequest(); httpRequest.addHeader("Authorization", "Basic " + Base64.getEncoder().encodeToString("loser:boozer".getBytes())); filter.doFilterHttp(httpRequest, new MockHttpServletResponse(), new FilterChain() { public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException { } }); assertThat(BasicAuthenticationFilter.isProcessingBasicAuth(), is(false)); assertThat(hadBasicMarkOnInsideAuthenticationManager[0], is(true)); }
@Before public void setUp() { request = new MockHttpServletRequest(); response = new MockHttpServletResponse(); filterChain = mock(FilterChain.class); authenticationException = mock(AuthenticationException.class); basicAuth = mock(BasicProcessingFilterEntryPoint.class); cruiseLoginFormAuth = mock(AuthenticationEntryPoint.class); securityService = mock(SecurityService.class); filter = new GoExceptionTranslationFilter(); filter.setUrlPatternsThatShouldNotBeRedirectedToAfterLogin("(\\.json)|(/images/)"); filter.setAuthenticationEntryPoint(cruiseLoginFormAuth); filter.setBasicAuthenticationEntryPoint(basicAuth); filter.setSecurityService(securityService); }
public void commence(ServletRequest request, ServletResponse response, AuthenticationException authException) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.addHeader("WWW-Authenticate", "Basic realm=\"GoCD\""); ArrayList<String> acceptHeader = getAcceptHeader(request); String contentType = getMatchingHeader(acceptHeader, "application/vnd\\.go\\.cd\\.v.\\+json"); if (contentType != null) { httpResponse.setContentType(contentType); httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); httpResponse.getOutputStream().print("{\n"); httpResponse.getOutputStream().print(" \"message\": \"You are not authorized to access this resource!\"\n"); httpResponse.getOutputStream().print("}\n"); return; } httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); }
protected void doFilterHttp(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String header = request.getHeader(AUTHORIZATION);//Token token="ACCESS_TOKEN" if (header != null) { logger.debug("Oauth authorization header: " + header); Matcher matcher = OAUTH_TOKEN_PATTERN.matcher(header); if (matcher.matches()) { String token = matcher.group(1); OauthAuthenticationToken authenticationToken = new OauthAuthenticationToken(token); try { Authentication authResult = authenticationManager.authenticate(authenticationToken); SecurityContextHolder.getContext().setAuthentication(authResult); } catch (AuthenticationException e) { logger.debug("Oauth authentication request for token: " + token, e); SecurityContextHolder.getContext().setAuthentication(null); } } } chain.doFilter(request, response); }
/** * Authenticate a token */ public Authentication authenticate(Authentication authentication) throws AuthenticationException { if( authentication == BAD_CREDENTIALS ) { throw new BadCredentialsException( "Bad credentials" ); } else if( authentication == LOCKED ) { throw new LockedException( "Account is locked" ); } return authentication; }
@Test public void shouldRaiseAuthenticationExceptionWhenNoMatchForTokenExists() { when(dataSource.findOauthTokenByAccessToken("token-string")).thenReturn(null); try { provider.authenticate(new OauthAuthenticationToken("token-string")); fail("should have thrown an AuthenticationException"); } catch (AuthenticationException e) { assertThat(e.getMessage(), is("No match for OAuth token: token-string")); } }
@Override public Authentication attemptAuthentication(HttpServletRequest request) throws AuthenticationException { PreAuthenticatedAuthenticationToken authRequest = new PreAuthenticatedAuthenticationToken(null, fetchAuthorizationServerAccessToken(request), pluginId(request)); Authentication authResult = this.getAuthenticationManager().authenticate(authRequest); return authResult; }
protected void sendStartAuthentication(ServletRequest request, ServletResponse response, FilterChain chain, AuthenticationException reason) throws ServletException, IOException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; //TODO: This is a hack for bug #3175, we should revisit this code in V2.0 if (isJson(httpRequest) || isJsonFormat(httpRequest)) { httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } final Logger logger = LoggerFactory.getLogger(GoExceptionTranslationFilter.class); SavedRequest savedRequest = new SavedRequest(httpRequest, getPortResolver()); logger.debug("Authentication entry point being called; SavedRequest added to Session: {}", savedRequest); if (isCreateSessionAllowed() && shouldRedirect(savedRequest.getRequestUrl())) { // Store the HTTP request itself. Used by AbstractProcessingFilter // for redirection after successful authentication (SEC-29) httpRequest.getSession().setAttribute(AbstractProcessingFilter.SPRING_SECURITY_SAVED_REQUEST_KEY, savedRequest); } // SEC-112: Clear the SecurityContextHolder's Authentication, as the // existing Authentication is no longer considered valid SecurityContextHolder.getContext().setAuthentication(null); determineAuthenticationPoint(httpRequest).commence(httpRequest, response, reason); }
@Override protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException { super.onUnsuccessfulAuthentication(request, response, failed); if (failed.getClass() == AuthenticationServiceException.class) { request.getSession().setAttribute(SPRING_SECURITY_LAST_EXCEPTION_KEY, new Exception(localizer.localize("AUTHENTICATION_SERVICE_EXCEPTION"))); LOGGER.error(failed.getMessage()); LOGGER.trace(failed.getMessage(), failed); } }
public UserDetails getUserDetails(X509Certificate clientCert) throws AuthenticationException { X500Principal principal = clientCert.getSubjectX500Principal(); Matcher cnMatcher = CN_PATTERN.matcher(principal.getName()); Matcher ouMatcher = OU_PATTERN.matcher(principal.getName()); if (cnMatcher.find() && ouMatcher.find()) { GrantedAuthorityImpl agentAuthority = new GrantedAuthorityImpl(role); return new User("_go_agent_" + cnMatcher.group(1), "", true, true, true, true, new GrantedAuthority[]{agentAuthority}); } throw new BadCredentialsException("Couldn't find CN and/or OU for the certificate"); }
public Authentication authenticate(Authentication authentication) throws AuthenticationException { Authentication auth = provider.authenticate(authentication); if (auth != null) { userService.addUserIfDoesNotExist(UserHelper.getUser(auth)); } return auth; }
@Override protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { assertPasswordNotBlank(authentication); User user = getUserDetailsFromAuthorizationPlugins(username, authentication); if (user == null) { removeAnyAssociatedPluginRolesFor(username); throw new UsernameNotFoundException("Unable to authenticate user: " + username); } userService.addUserIfDoesNotExist(toDomainUser(user)); GoUserPrinciple goUserPrinciple = new GoUserPrinciple(user.getUsername(), user.getDisplayName(), "", authorityGranter.authorities(user.getUsername()), loginName(username, authentication)); return goUserPrinciple; }
public OauthAuthenticationToken authenticate(Authentication authentication) throws AuthenticationException { OauthAuthenticationToken authenticationToken = (OauthAuthenticationToken) authentication; String token = authenticationToken.getCredentials(); OauthDataSource.OauthTokenDTO oauthToken = oauthDataSource.findOauthTokenByAccessToken(token); if (oauthToken == null) { throw new BadCredentialsException("No match for OAuth token: " + token); } String username = oauthToken.getUserId(); UserDetails user = new User(username, token, true, true, true, true, oauthAuthority()); return new OauthAuthenticationToken(user); }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (!supports(authentication.getClass())) { return null; } if (authentication.getCredentials() == null) { throw new BadCredentialsException("No pre-authenticated credentials found in request."); } PreAuthenticatedAuthenticationToken preAuthToken = (PreAuthenticatedAuthenticationToken) authentication; return doAuthenticate(preAuthToken); }
@When("user <username> authenticates with password <password>") @Alias("user $username authenticates with password $password") public void userAuthenticates(@Named(value="username") String username, @Named(value="password") String password) { try { auth = manager.authenticate(new UsernamePasswordAuthenticationToken(username, password)); authException = null; } catch (AuthenticationException e) { auth = null; authException = e; } }
/** {@inheritDoc} */ @Override protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken token) throws AuthenticationException { if (!userDetails.getPassword().equals(token.getCredentials().toString())) { throw new BadCredentialsException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"), userDetails); } }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { Authentication mockAuth = authentication; return mockAuth; }
@Override protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { }
@Override protected String determineUrlToUseForThisRequest(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) { Object hasSessionBeenDenied = request.getAttribute(SESSION_DENIED); return (hasSessionBeenDenied != null && (Boolean) hasSessionBeenDenied) ? deniedSessionLoginFormUrl : super.determineUrlToUseForThisRequest(request, response, exception); }
/** {@inheritDoc} */ public void commence(ServletRequest request, ServletResponse response, AuthenticationException authException) throws IOException, ServletException { String url = getUrl(request); AuthenticationEntryPoint entryPoint = getAppropriateEntryPoint(url); entryPoint.commence(request, response, authException); }