Java 类org.springframework.security.AuthenticationException 实例源码

项目:pentaho-authentication-ext    文件:ExtensionAuthenticationProvider.java   
@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;
}
项目:pentaho-transparent-authentication    文件:ExtensionAuthenticationProvider.java   
@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;
}
项目:gocd    文件:BasicAuthenticationFilterTest.java   
@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));
}
项目:gocd    文件:GoExceptionTranslationFilterTest.java   
@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);
}
项目:gocd    文件:BasicProcessingFilterEntryPoint.java   
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());
}
项目:gocd    文件:OauthAuthenticationFilter.java   
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);
}
项目:spring-rich-client    文件:TestAuthenticationManager.java   
/**
 * 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;
}
项目:gocd    文件:OauthAuthenticationProviderTest.java   
@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"));
    }
}
项目:gocd    文件:PreAuthenticatedRequestsProcessingFilter.java   
@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;
}
项目:gocd    文件:GoExceptionTranslationFilter.java   
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);
}
项目:gocd    文件:AuthenticationProcessingFilter.java   
@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);
    }
}
项目:gocd    文件:X509AuthoritiesPopulator.java   
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");
}
项目:gocd    文件:GoAuthenticationProvider.java   
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Authentication auth = provider.authenticate(authentication);
    if (auth != null) {
        userService.addUserIfDoesNotExist(UserHelper.getUser(auth));
    }
    return auth;
}
项目:gocd    文件:PluginAuthenticationProvider.java   
@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;
}
项目:gocd    文件:OauthAuthenticationProvider.java   
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);
}
项目:gocd    文件:PreAuthenticatedAuthenticationProvider.java   
@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);
}
项目:jbehave-core    文件:AuthenticationSteps.java   
@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;
  }
}
项目:spring-richclient    文件:TestAuthenticationManager.java   
/**
 * 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;
}
项目:OpenNMS    文件:RadiusAuthenticationProvider.java   
/** {@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);
    }
}
项目:pentaho-authentication-ext    文件:MockAuthenticationManager.java   
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Authentication mockAuth = authentication;
    return mockAuth;
}
项目:pentaho-transparent-authentication    文件:MockAuthenticationManager.java   
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Authentication mockAuth = authentication;
    return mockAuth;
}
项目:gocd    文件:PluginAuthenticationProvider.java   
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
}
项目:gocd    文件:SessionDenialAwareAuthenticationProcessingFilterEntryPoint.java   
@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);
}
项目:OpenNMS    文件:AntPatternBasedAuthenticationEntryPointChain.java   
/** {@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);

}