Search in sources :

Example 81 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project midpoint by Evolveum.

the class HttpBasicAuthenticationFilter method extractAndDecodeHeader.

@Override
protected AbstractMap.SimpleImmutableEntry<String, String> extractAndDecodeHeader(String header, HttpServletRequest request) {
    String token = createCredentialsFromHeader(header);
    int delim = token.indexOf(":");
    if (delim == -1) {
        throw new BadCredentialsException("Invalid authentication token");
    }
    return new AbstractMap.SimpleImmutableEntry<>(token.substring(0, delim), token.substring(delim + 1));
}
Also used : BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationEntryPoint(org.springframework.security.web.AuthenticationEntryPoint)

Example 82 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project midpoint by Evolveum.

the class MidPointLdapAuthenticationProvider method internalAuthentication.

@Override
protected Authentication internalAuthentication(Authentication authentication, List requireAssignment, AuthenticationChannel channel, Class focusType) throws AuthenticationException {
    if (authentication.isAuthenticated() && authentication.getPrincipal() instanceof GuiProfiledPrincipal) {
        return authentication;
    }
    String enteredUsername = (String) authentication.getPrincipal();
    LOGGER.trace("Authenticating username '{}'", enteredUsername);
    try {
        Authentication token;
        if (authentication instanceof LdapAuthenticationToken) {
            token = this.authenticatorProvider.authenticate(authentication);
        } else {
            LOGGER.error("Unsupported authentication {}", authentication);
            recordPasswordAuthenticationFailure(authentication.getName(), "unavailable provider");
            throw new AuthenticationServiceException("web.security.provider.unavailable");
        }
        MidPointPrincipal principal = (MidPointPrincipal) token.getPrincipal();
        LOGGER.debug("User '{}' authenticated ({}), authorities: {}", authentication.getPrincipal(), authentication.getClass().getSimpleName(), principal.getAuthorities());
        return token;
    } catch (InternalAuthenticationServiceException e) {
        // This sometimes happens ... for unknown reasons the underlying libraries cannot
        // figure out correct exception. Which results to wrong error message (MID-4518)
        // So, be smart here and try to figure out correct error.
        recordPasswordAuthenticationFailure(authentication.getName(), e.getMessage());
        throw processInternalAuthenticationException(e, e);
    } catch (IncorrectResultSizeDataAccessException e) {
        LOGGER.error("Failed to authenticate user {}. Error: {}", authentication.getName(), e.getMessage(), e);
        recordPasswordAuthenticationFailure(authentication.getName(), "bad user");
        throw new BadCredentialsException("LdapAuthentication.bad.user", e);
    } catch (RuntimeException e) {
        LOGGER.error("Failed to authenticate user {}. Error: {}", authentication.getName(), e.getMessage(), e);
        recordPasswordAuthenticationFailure(authentication.getName(), "bad credentials");
        throw e;
    }
}
Also used : LdapAuthenticationToken(com.evolveum.midpoint.authentication.impl.module.authentication.token.LdapAuthenticationToken) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException) LdapModuleAuthentication(com.evolveum.midpoint.authentication.impl.module.authentication.LdapModuleAuthentication) MidpointAuthentication(com.evolveum.midpoint.authentication.api.config.MidpointAuthentication) Authentication(org.springframework.security.core.Authentication) InternalAuthenticationServiceException(org.springframework.security.authentication.InternalAuthenticationServiceException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) InternalAuthenticationServiceException(org.springframework.security.authentication.InternalAuthenticationServiceException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException)

Example 83 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project midpoint by Evolveum.

the class MidPointLdapAuthenticationProvider method createSuccessfulAuthentication.

protected void createSuccessfulAuthentication(UsernamePasswordAuthenticationToken authentication, Authentication authNCtx) {
    Object principal = authNCtx.getPrincipal();
    if (!(principal instanceof MidPointPrincipal)) {
        recordPasswordAuthenticationFailure(authentication.getName(), "not contains required assignment");
        throw new BadCredentialsException("LdapAuthentication.incorrect.value");
    }
    MidPointPrincipal midPointPrincipal = (MidPointPrincipal) principal;
    FocusType focusType = midPointPrincipal.getFocus();
    Authentication actualAuthentication = SecurityContextHolder.getContext().getAuthentication();
    if (actualAuthentication instanceof MidpointAuthentication) {
        MidpointAuthentication mpAuthentication = (MidpointAuthentication) actualAuthentication;
        List<ObjectReferenceType> requireAssignment = mpAuthentication.getSequence().getRequireAssignmentTarget();
        if (!AuthenticationEvaluatorUtil.checkRequiredAssignment(focusType.getAssignment(), requireAssignment)) {
            recordPasswordAuthenticationFailure(midPointPrincipal.getUsername(), "not contains required assignment");
            throw new InternalAuthenticationServiceException("web.security.flexAuth.invalid.required.assignment");
        }
    }
    recordPasswordAuthenticationSuccess(midPointPrincipal);
}
Also used : LdapModuleAuthentication(com.evolveum.midpoint.authentication.impl.module.authentication.LdapModuleAuthentication) MidpointAuthentication(com.evolveum.midpoint.authentication.api.config.MidpointAuthentication) Authentication(org.springframework.security.core.Authentication) InternalAuthenticationServiceException(org.springframework.security.authentication.InternalAuthenticationServiceException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) MidpointAuthentication(com.evolveum.midpoint.authentication.api.config.MidpointAuthentication)

Example 84 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project new-cloud by xie-summer.

the class MobileLoginSuccessHandler method onAuthenticationSuccess.

/**
 * Called when a user has been successfully authenticated.
 * 调用spring security oauth API 生成 oAuth2AccessToken
 *
 * @param request        the request which caused the successful authentication
 * @param response       the response
 * @param authentication the <tt>Authentication</tt> object which was created during
 */
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    String header = request.getHeader("Authorization");
    if (header == null || !header.startsWith(BASIC_)) {
        throw new UnapprovedClientAuthenticationException("请求头中client信息为空");
    }
    try {
        String[] tokens = extractAndDecodeHeader(header);
        assert tokens.length == 2;
        String clientId = tokens[0];
        String clientSecret = tokens[1];
        JSONObject params = new JSONObject();
        params.put("clientId", clientId);
        params.put("clientSecret", clientSecret);
        params.put("authentication", authentication);
        ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
        TokenRequest tokenRequest = new TokenRequest(MapUtil.newHashMap(), clientId, clientDetails.getScope(), "mobile");
        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
        OAuth2AccessToken oAuth2AccessToken = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
        logger.info("获取token 成功:{}", oAuth2AccessToken.getValue());
        response.setCharacterEncoding(CommonConstant.UTF8);
        response.setContentType(CommonConstant.CONTENT_TYPE);
        PrintWriter printWriter = response.getWriter();
        printWriter.append(objectMapper.writeValueAsString(oAuth2AccessToken));
    } catch (IOException e) {
        throw new BadCredentialsException("Failed to decode basic authentication token");
    }
}
Also used : JSONObject(com.alibaba.fastjson.JSONObject) UnapprovedClientAuthenticationException(org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) IOException(java.io.IOException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) PrintWriter(java.io.PrintWriter)

Example 85 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project new-cloud by xie-summer.

the class SocialLoginSuccessHandler method onAuthenticationSuccess.

/**
 * Called when a user has been successfully authenticated.
 * 调用spring security oauth API 生成 oAuth2AccessToken
 *
 * @param request        the request which caused the successful authentication
 * @param response       the response
 * @param authentication the <tt>Authentication</tt> object which was created during
 */
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    try {
        String clientId = authServerConfig.getClientId();
        String clientSecret = authServerConfig.getClientSecret();
        JSONObject params = new JSONObject();
        params.put("clientId", clientId);
        params.put("clientSecret", clientSecret);
        params.put("authentication", authentication);
        ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
        TokenRequest tokenRequest = new TokenRequest(MapUtil.newHashMap(), clientId, clientDetails.getScope(), "social");
        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
        OAuth2AccessToken oAuth2AccessToken = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
        logger.info("获取token 成功:{}", oAuth2AccessToken.getValue());
        String url = String.format("http://localhost:9527/#/login?access_token=%s&refresh_token=%s", oAuth2AccessToken.getValue(), oAuth2AccessToken.getRefreshToken().getValue());
        logger.info("social登录,回调地址:{}", url);
        response.sendRedirect(url);
    } catch (IOException e) {
        throw new BadCredentialsException("Failed to decode basic authentication token");
    }
}
Also used : JSONObject(com.alibaba.fastjson.JSONObject) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) IOException(java.io.IOException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Aggregations

BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)174 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)63 Authentication (org.springframework.security.core.Authentication)57 Test (org.junit.jupiter.api.Test)32 Test (org.junit.Test)26 AuthenticationException (org.springframework.security.core.AuthenticationException)24 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)22 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)21 UserDetails (org.springframework.security.core.userdetails.UserDetails)20 GrantedAuthority (org.springframework.security.core.GrantedAuthority)15 AuthenticationManager (org.springframework.security.authentication.AuthenticationManager)14 HttpServletRequest (javax.servlet.http.HttpServletRequest)13 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)13 AuthenticationServiceException (org.springframework.security.authentication.AuthenticationServiceException)12 FilterChain (jakarta.servlet.FilterChain)10 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)10 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)10 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)9 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)7