Example usage for org.springframework.security.core AuthenticationException getMessage

List of usage examples for org.springframework.security.core AuthenticationException getMessage

Introduction

In this page you can find the example usage for org.springframework.security.core AuthenticationException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:authentication.DefaultAuthenticationFailureHandler.java

/** {@inheritDoc} */
@Override/*from  ww  w  . jav  a  2s.c  o m*/
public void onAuthenticationFailure(final HttpServletRequest request, final HttpServletResponse response,
        final AuthenticationException exception) throws IOException {
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    response.setStatus(HttpStatus.UNAUTHORIZED.value());
    response.getOutputStream()
            .print(String.format(JSON, HttpStatus.UNAUTHORIZED.value(), exception.getMessage()));
}

From source file:com.cruz.sec.config.ItemBasedAuthenticationFailureHandler.java

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException exception) throws IOException, ServletException {
    UsernamePasswordAuthenticationToken user = (UsernamePasswordAuthenticationToken) exception
            .getAuthentication();/*from  w w w  . j av  a 2  s .  c o  m*/
    System.out.println("Mensaje del error: " + exception.getMessage());
    //        PrincipalsessionInformaction user = request.getUserPrincipal();
    System.out.println("-----------------------------INTENTO FALLIDO-----------------------------");

    //Causas de la autenticacin fallida
    if (exception.getClass().isAssignableFrom(UsernameNotFoundException.class)) {
        System.out.println("INTENTO FALLIDO: El usuario no est registrado en la base de datos ");
        request.setAttribute("ERRORSESSION", "Usuario no registrado, verifique con el administrador");
        request.getRequestDispatcher("/login").forward(request, response);
        //response.sendRedirect("login?err=1");
    } else if (exception.getClass().isAssignableFrom(BadCredentialsException.class)) {
        System.out.println("INTENTO FALLIDO: Creedenciales erroneas");
        request.setAttribute("ERRORSESSION", "Contrasea incorrecta, intente nuevamente");
        request.getRequestDispatcher("/login").forward(request, response);
    } else if (exception.getClass().isAssignableFrom(DisabledException.class)) {
        System.out.println("INTENTO FALLIDO: Usuario desabilitado");
        request.setAttribute("ERRORSESSION", "Usuario deshabilitado, verifique con el administrador");
        request.getRequestDispatcher("/login").forward(request, response);
    } else if (exception.getClass().isAssignableFrom(SessionAuthenticationException.class)) {
        System.out.println("INTENTO FALLIDO: Usuario ya logeado");
        request.setAttribute("ERRORSESSION", "Ya existe una sesión abierta con este usuario");
        request.getRequestDispatcher("/login").forward(request, response);
    } else {
        System.out.println("INTENTO FALLIDO: NO SE QUE PASO");
        request.setAttribute("ERRORSESSION", "No ha sido posible iniciar sesión");
        request.getRequestDispatcher("/login").forward(request, response);
    }
}

From source file:org.mitre.openid.connect.assertion.JWTBearerClientAssertionTokenEndpointFilter.java

@Override
public void afterPropertiesSet() {
    super.afterPropertiesSet();
    setAuthenticationFailureHandler(new AuthenticationFailureHandler() {
        @Override/*w w w.ja  v  a 2 s.  c o m*/
        public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                AuthenticationException exception) throws IOException, ServletException {
            if (exception instanceof BadCredentialsException) {
                exception = new BadCredentialsException(exception.getMessage(),
                        new BadClientCredentialsException());
            }
            authenticationEntryPoint.commence(request, response, exception);
        }
    });
    setAuthenticationSuccessHandler(new AuthenticationSuccessHandler() {
        @Override
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                Authentication authentication) throws IOException, ServletException {
            // no-op - just allow filter chain to continue to token endpoint
        }
    });
}

From source file:com.thoughtworks.go.server.newsecurity.filters.AccessTokenAuthenticationFilter.java

private void filterWhenSecurityEnabled(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain, AccessTokenCredential accessTokenCredential)
        throws IOException, ServletException {
    if (accessTokenCredential == null) {
        LOGGER.debug("Bearer auth credentials are not provided in request.");
        filterChain.doFilter(request, response);
    } else {//  www  .  j  a  v  a  2  s  .  c  o  m
        accessTokenService.updateLastUsedCacheWith(accessTokenCredential.getAccessToken());
        ACCESS_TOKEN_LOGGER.debug(
                "[Bearer Token Authentication] Authenticating bearer token for: " + "GoCD User: '{}'. "
                        + "GoCD API endpoint: '{}', " + "API Client: '{}', " + "Is Admin Scoped Token: '{}', "
                        + "Current Time: '{}'.",
                accessTokenCredential.getAccessToken().getUsername(), request.getRequestURI(),
                request.getHeader("User-Agent"),
                securityService.isUserAdmin(new Username(accessTokenCredential.getAccessToken().getUsername())),
                new Timestamp(System.currentTimeMillis()));

        try {
            SecurityAuthConfig authConfig = securityAuthConfigService
                    .findProfile(accessTokenCredential.getAccessToken().getAuthConfigId());
            final AuthenticationToken<AccessTokenCredential> authenticationToken = authenticationProvider
                    .authenticateUser(accessTokenCredential, authConfig);
            if (authenticationToken == null) {
                onAuthenticationFailure(request, response, BAD_CREDENTIALS_MSG);
            } else {
                SessionUtils.setAuthenticationTokenAfterRecreatingSession(authenticationToken, request);
                filterChain.doFilter(request, response);
            }
        } catch (AuthenticationException e) {
            LOGGER.debug("Failed to authenticate user.", e);
            onAuthenticationFailure(request, response, e.getMessage());
        }
    }
}

From source file:com.counter.counter.api.AuthenticationEntryPoint.java

@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx)
        throws IOException, ServletException {
    response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName());
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    PrintWriter writer = response.getWriter();
    writer.println("HTTP Status 401 - " + authEx.getMessage());
}

From source file:org.cloudfoundry.identity.uaa.home.HomeController.java

@RequestMapping("/saml_error")
public String error401(Model model, HttpServletRequest request) {
    AuthenticationException exception = (AuthenticationException) request.getSession()
            .getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
    model.addAttribute("saml_error", exception.getMessage());
    return "external_auth_error";
}

From source file:org.osiam.security.helper.FBClientCredentialsTokenEndpointFilter.java

@Override
/**//  w  w w.j av  a 2 s.  c o m
 * Sets the handler, failed -> BadCredentialsException, success -> just continue.
 */
public void afterPropertiesSet() {
    super.afterPropertiesSet();
    setAuthenticationFailureHandler(new AuthenticationFailureHandler() {
        public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                AuthenticationException exception) throws IOException, ServletException {
            if (exception instanceof BadCredentialsException) {
                exception = // NOSONAR
                        new BadCredentialsException(exception.getMessage(),
                                new BadClientCredentialsException());
            }
            authenticationEntryPoint.commence(request, response, exception);
        }
    });
    setAuthenticationSuccessHandler(new MyAuthenticationSuccessHandler());
}

From source file:com.gmail.volodymyrdotsenko.cms.fe.vaadin.LoginUI.java

private void login() {
    try {/*  www  . j a va2 s  .com*/
        vaadinSecurity.login(userName.getValue(), passwordField.getValue(), rememberMe.getValue());

        VaadinSession.getCurrent().setLocale(new Locale((String) lang.getValue()));
    } catch (AuthenticationException ex) {
        userName.focus();
        userName.selectAll();
        passwordField.setValue("");
        loginFailedLabel.setValue(String.format("Login failed: %s", ex.getMessage()));
        loginFailedLabel.setVisible(true);
        if (loggedOutLabel != null) {
            loggedOutLabel.setVisible(false);
        }
    } catch (Exception ex) {
        Notification.show("An unexpected error occurred", ex.getMessage(), Notification.Type.ERROR_MESSAGE);
        LoggerFactory.getLogger(getClass()).error("Unexpected error while logging in", ex);
    } finally {
        login.setEnabled(true);
    }
}

From source file:eu.freme.broker.security.AuthenticationFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = asHttp(request);
    HttpServletResponse httpResponse = asHttp(response);

    Optional<String> username = Optional.fromNullable(httpRequest.getHeader("X-Auth-Username"));
    Optional<String> password = Optional.fromNullable(httpRequest.getHeader("X-Auth-Password"));
    Optional<String> token = Optional.fromNullable(httpRequest.getHeader("X-Auth-Token"));

    if (httpRequest.getParameter("token") != null) {
        token = Optional.fromNullable(httpRequest.getParameter("token"));
    }/*  ww  w. j a  v a  2 s  . c o  m*/

    String resourcePath = new UrlPathHelper().getPathWithinApplication(httpRequest);

    try {
        if (postToAuthenticate(httpRequest, resourcePath)) {
            logger.debug("Trying to authenticate user {} by X-Auth-Username method", username);
            processUsernamePasswordAuthentication(httpResponse, username, password);
            return;
        }

        if (token.isPresent()) {
            logger.debug("Trying to authenticate user by X-Auth-Token method. Token: {}", token);
            processTokenAuthentication(token);
        }

        logger.debug("AuthenticationFilter is passing request down the filter chain");
        addSessionContextToLogging();
        chain.doFilter(request, response);
    } catch (InternalAuthenticationServiceException internalAuthenticationServiceException) {
        SecurityContextHolder.clearContext();
        logger.error("Internal authentication service exception", internalAuthenticationServiceException);
        httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (AuthenticationException authenticationException) {
        SecurityContextHolder.clearContext();
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage());
    } finally {
        MDC.remove(TOKEN_SESSION_KEY);
        MDC.remove(USER_SESSION_KEY);
    }
}

From source file:eu.freme.common.security.AuthenticationFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = asHttp(request);
    HttpServletResponse httpResponse = asHttp(response);

    Optional<String> username = Optional.fromNullable(httpRequest.getHeader("X-Auth-Username"));
    Optional<String> password = Optional.fromNullable(httpRequest.getHeader("X-Auth-Password"));
    Optional<String> token = Optional.fromNullable(httpRequest.getHeader("X-Auth-Token"));

    if (httpRequest.getParameter("token") != null) {
        token = Optional.fromNullable(httpRequest.getParameter("token"));
    }//from   ww  w  . j  a  v a 2s  .  c o m

    String resourcePath = new UrlPathHelper().getPathWithinApplication(httpRequest);

    try {
        //            if (postToAuthenticate(httpRequest, resourcePath)) {
        //                logger.debug("Trying to authenticate user {} by X-Auth-Username method", username);
        //                processUsernamePasswordAuthentication(httpResponse, username, password);
        //                return;
        //            }

        if (token.isPresent()) {
            logger.debug("Trying to authenticate user by X-Auth-Token method. Token: {}", token);
            processTokenAuthentication(token);
        }

        logger.debug("AuthenticationFilter is passing request down the filter chain");
        addSessionContextToLogging();
        chain.doFilter(request, response);
    } catch (InternalAuthenticationServiceException internalAuthenticationServiceException) {
        SecurityContextHolder.clearContext();
        logger.error("Internal authentication service exception", internalAuthenticationServiceException);
        httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (AuthenticationException authenticationException) {
        SecurityContextHolder.clearContext();
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage());
    } finally {
        MDC.remove(TOKEN_SESSION_KEY);
        MDC.remove(USER_SESSION_KEY);
    }
}