Search in sources :

Example 66 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project midpoint by Evolveum.

the class HttpSecurityQuestionsAuthenticationEntryPoint method commence.

@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    try {
        if (authentication instanceof MidpointAuthentication) {
            if (request.getHeader(AUTHENTICATION_HEADER) != null && request.getHeader(AUTHENTICATION_HEADER).toLowerCase().startsWith(AuthenticationModuleNameConstants.SECURITY_QUESTIONS.toLowerCase())) {
                String header = request.getHeader(AUTHENTICATION_HEADER);
                if (header.equalsIgnoreCase(AuthenticationModuleNameConstants.SECURITY_QUESTIONS)) {
                    createSecurityQuestionAbortMessage(response, DEFAULT_JSON);
                } else {
                    byte[] jsonByte = Base64Utility.decode(header.substring(AuthenticationModuleNameConstants.SECURITY_QUESTIONS.length() + 1));
                    String json = new String(jsonByte);
                    JSONObject jsonObject = new JSONObject(json);
                    if (jsonObject.keySet().size() == 1 && jsonObject.keySet().contains(HttpSecurityQuestionsAuthenticationFilter.J_USER)) {
                        String username = jsonObject.getString(HttpSecurityQuestionsAuthenticationFilter.J_USER);
                        SearchResultList<PrismObject<UserType>> users = searchUser(username);
                        if (users == null || users.size() != 1) {
                            super.commence(request, response, authException);
                            return;
                        }
                        PrismObject<UserType> user = users.get(0);
                        JSONArray answers = generateAnswer(user);
                        if (answers == null) {
                            super.commence(request, response, authException);
                            return;
                        }
                        jsonObject.putOpt(HttpSecurityQuestionsAuthenticationFilter.J_ANSWER, answers);
                        createSecurityQuestionAbortMessage(response, jsonObject.toString());
                    } else {
                        super.commence(request, response, authException);
                        return;
                    }
                }
            } else {
                super.commence(request, response, authException);
                return;
            }
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        super.commence(request, response, authException);
        return;
    }
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}
Also used : PrismObject(com.evolveum.midpoint.prism.PrismObject) JSONObject(com.github.openjson.JSONObject) MidpointAuthentication(com.evolveum.midpoint.authentication.api.config.MidpointAuthentication) Authentication(org.springframework.security.core.Authentication) JSONArray(com.github.openjson.JSONArray) MidpointAuthentication(com.evolveum.midpoint.authentication.api.config.MidpointAuthentication) UserType(com.evolveum.midpoint.xml.ns._public.common.common_3.UserType) AuthenticationException(org.springframework.security.core.AuthenticationException) IOException(java.io.IOException)

Example 67 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project midpoint by Evolveum.

the class MidpointAuthFilter method resolveErrorWithMoreModules.

private void resolveErrorWithMoreModules(MidpointAuthentication mpAuthentication, HttpServletRequest httpRequest) {
    if (existMoreAsOneAuthModule(mpAuthentication)) {
        Exception actualException = (Exception) httpRequest.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
        String actualMessage;
        String restartFlowMessage = "web.security.flexAuth.restart.flow";
        if (actualException != null && StringUtils.isNotBlank(actualException.getMessage())) {
            actualMessage = actualException.getMessage() + ";" + restartFlowMessage;
        } else {
            actualMessage = restartFlowMessage;
        }
        AuthenticationException exception = new AuthenticationServiceException(actualMessage);
        AuthSequenceUtil.saveException(httpRequest, exception);
    }
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) AuthenticationException(org.springframework.security.core.AuthenticationException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) IOException(java.io.IOException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException)

Example 68 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project midpoint by Evolveum.

the class OidcResourceServerProvider method internalAuthentication.

@Override
protected Authentication internalAuthentication(Authentication authentication, List requireAssignment, AuthenticationChannel channel, Class focusType) throws AuthenticationException {
    Authentication token;
    if (authentication instanceof BearerTokenAuthenticationToken) {
        BearerTokenAuthenticationToken oidcAuthenticationToken = (BearerTokenAuthenticationToken) authentication;
        JwtAuthenticationToken jwtAuthentication;
        try {
            jwtAuthentication = (JwtAuthenticationToken) oidcProvider.authenticate(oidcAuthenticationToken);
        } catch (AuthenticationException e) {
            getAuditProvider().auditLoginFailure(null, null, createConnectEnvironment(getChannel()), e.getMessage());
            throw e;
        }
        HttpModuleAuthentication oidcModule = (HttpModuleAuthentication) AuthUtil.getProcessingModule();
        try {
            String username = jwtAuthentication.getName();
            if (StringUtils.isEmpty(username)) {
                LOGGER.error("Username from jwt token don't contains value");
                throw new AuthenticationServiceException("web.security.provider.invalid");
            }
            token = getPreAuthenticationToken(username, focusType, requireAssignment, channel);
        } catch (AuthenticationException e) {
            oidcModule.setAuthentication(oidcAuthenticationToken);
            LOGGER.info("Authentication with oidc module failed: {}", e.getMessage());
            throw e;
        }
    } else {
        LOGGER.error("Unsupported authentication {}", authentication);
        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;
}
Also used : JwtAuthenticationToken(org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken) AuthenticationException(org.springframework.security.core.AuthenticationException) HttpModuleAuthentication(com.evolveum.midpoint.authentication.impl.module.authentication.HttpModuleAuthentication) Authentication(org.springframework.security.core.Authentication) BearerTokenAuthenticationToken(org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) HttpModuleAuthentication(com.evolveum.midpoint.authentication.impl.module.authentication.HttpModuleAuthentication) MidPointPrincipal(com.evolveum.midpoint.security.api.MidPointPrincipal)

Example 69 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project gocd by gocd.

the class AuthenticationController method performLogin.

@RequestMapping(value = "/auth/security_check", method = RequestMethod.POST)
public RedirectView performLogin(@RequestParam("j_username") String username, @RequestParam("j_password") String password, HttpServletRequest request) {
    if (securityIsDisabledOrAlreadyLoggedIn(request)) {
        return new RedirectView("/pipelines", true);
    }
    LOGGER.debug("Requesting authentication for form auth.");
    try {
        SavedRequest savedRequest = SessionUtils.savedRequest(request);
        final AuthenticationToken<UsernamePassword> authenticationToken = passwordBasedPluginAuthenticationProvider.authenticate(new UsernamePassword(username, password), null);
        if (authenticationToken == null) {
            return badAuthentication(request, BAD_CREDENTIALS_MSG);
        } else {
            SessionUtils.setAuthenticationTokenAfterRecreatingSession(authenticationToken, request);
        }
        String redirectUrl = savedRequest == null ? "/go/pipelines" : savedRequest.getRedirectUrl();
        return new RedirectView(redirectUrl, false);
    } catch (AuthenticationException e) {
        LOGGER.error("Failed to authenticate user: {} ", username, e);
        return badAuthentication(request, e.getMessage());
    } catch (Exception e) {
        return unknownAuthenticationError(request);
    }
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) RedirectView(org.springframework.web.servlet.view.RedirectView) AuthenticationException(org.springframework.security.core.AuthenticationException) SavedRequest(org.springframework.security.web.savedrequest.SavedRequest) UsernamePassword(com.thoughtworks.go.server.newsecurity.models.UsernamePassword) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 70 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project gocd by gocd.

the class AuthenticationController method authenticateWithWebBasedPlugin.

@RequestMapping(value = "/plugin/{pluginId}/authenticate")
public RedirectView authenticateWithWebBasedPlugin(@PathVariable("pluginId") String pluginId, HttpServletRequest request) {
    if (securityIsDisabledOrAlreadyLoggedIn(request)) {
        return new RedirectView("/pipelines", true);
    }
    LOGGER.debug("Requesting authentication for form auth.");
    SavedRequest savedRequest = SessionUtils.savedRequest(request);
    try {
        final AccessToken accessToken = webBasedPluginAuthenticationProvider.fetchAccessToken(pluginId, getRequestHeaders(request), getParameterMap(request));
        AuthenticationToken<AccessToken> authenticationToken = webBasedPluginAuthenticationProvider.authenticate(accessToken, pluginId);
        if (authenticationToken == null) {
            return unknownAuthenticationError(request);
        }
        SessionUtils.setAuthenticationTokenAfterRecreatingSession(authenticationToken, request);
    } catch (AuthenticationException e) {
        LOGGER.error("Failed to authenticate user.", e);
        return badAuthentication(request, e.getMessage());
    } catch (Exception e) {
        return unknownAuthenticationError(request);
    }
    SessionUtils.removeAuthenticationError(request);
    String redirectUrl = savedRequest == null ? "/go/pipelines" : savedRequest.getRedirectUrl();
    return new RedirectView(redirectUrl, false);
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) AccessToken(com.thoughtworks.go.server.newsecurity.models.AccessToken) RedirectView(org.springframework.web.servlet.view.RedirectView) AuthenticationException(org.springframework.security.core.AuthenticationException) SavedRequest(org.springframework.security.web.savedrequest.SavedRequest) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

AuthenticationException (org.springframework.security.core.AuthenticationException)156 Authentication (org.springframework.security.core.Authentication)78 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)42 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)28 HttpServletRequest (javax.servlet.http.HttpServletRequest)27 HttpServletResponse (javax.servlet.http.HttpServletResponse)25 Test (org.junit.Test)24 Test (org.junit.jupiter.api.Test)19 AuthenticationServiceException (org.springframework.security.authentication.AuthenticationServiceException)15 IOException (java.io.IOException)13 ServletException (javax.servlet.ServletException)12 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)11 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)10 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)9 AuthenticationManager (org.springframework.security.authentication.AuthenticationManager)8 GrantedAuthority (org.springframework.security.core.GrantedAuthority)8 Map (java.util.Map)7 MidPointPrincipal (com.evolveum.midpoint.security.api.MidPointPrincipal)6 HashMap (java.util.HashMap)6 InternalAuthenticationServiceException (org.springframework.security.authentication.InternalAuthenticationServiceException)6