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:fi.helsinki.opintoni.security.AuthFailureHandler.java

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException exception) throws IOException, ServletException {
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

    PrintWriter writer = response.getWriter();
    writer.write(exception.getMessage());
    writer.flush();//from  w  ww.j  a  v a 2s  .  c o m
}

From source file:com.erudika.para.security.SimpleAuthenticationFailureHandler.java

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException exception) throws IOException, ServletException {
    if (isRestRequest(request)) {
        RestUtils.returnStatusResponse(response, HttpServletResponse.SC_UNAUTHORIZED, exception.getMessage());
    } else {//from  ww  w  .j  av  a  2s. c  o m
        super.onAuthenticationFailure(request, response, exception);
    }
}

From source file:it.smartcommunitylab.aac.controller.ResourceAccessController.java

/**
 * Check the access to the specified resource using the client app token header
 * @param token//  w w w .  ja v a  2  s  . com
 * @param resourceUri
 * @param request
 * @return
 */
@ApiOperation(value = "Check scope access for token")
@RequestMapping(method = RequestMethod.GET, value = "/resources/access")
@Deprecated
public @ResponseBody Boolean canAccessResource(@RequestParam String scope, HttpServletRequest request) {
    try {
        String parsedToken = it.smartcommunitylab.aac.common.Utils.parseHeaderToken(request);
        OAuth2Authentication auth = resourceServerTokenServices.loadAuthentication(parsedToken);
        Collection<String> actualScope = auth.getOAuth2Request().getScope();
        Collection<String> scopeSet = StringUtils.commaDelimitedListToSet(scope);
        if (actualScope != null && !actualScope.isEmpty() && actualScope.containsAll(scopeSet)) {
            return true;
        }
    } catch (AuthenticationException e) {
        logger.error("Error validating token: " + e.getMessage());
    }
    return false;
}

From source file:de.knightsoftnet.validators.server.security.AuthFailureHandler.java

@Override
public void onAuthenticationFailure(final HttpServletRequest prequest, final HttpServletResponse presponse,
        final AuthenticationException pexception) throws IOException, ServletException {
    presponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

    final PrintWriter writer = presponse.getWriter();
    writer.write(pexception.getMessage());
    writer.flush();//from www  . j a  v  a2 s  .  c  o  m
}

From source file:fr.treeptik.cloudunit.config.Http401EntryPoint.java

public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg)
        throws IOException, ServletException {

    // Maybe change the log level...
    log.warn("Access Denied [ " + request.getRequestURL().toString() + "] : " + arg.getMessage());

    // Trace message to ban intruders with fail2ban
    //generateLogTraceForFail2ban();

    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access unauthorized");
}

From source file:com.econcept.init.AppAuthenticationEntryPoint.java

@Override
public void commence(HttpServletRequest request, HttpServletResponse pResponse,
        AuthenticationException authException) throws IOException, ServletException {
    pResponse.addHeader("WWW-Authenticate", "xBasic realm=\"" + getRealmName() + "\"");
    pResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());
}

From source file:com.iservport.auth.SecurityWebConfig.java

/**
 * Intercepta erros de autenticao./* w  w w  .  j a  va  2 s .  c  o m*/
 */
@Bean
public AuthenticationFailureHandler authenticationFailureHandler() {
    return new AuthenticationFailureHandler() {

        @Override
        public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                AuthenticationException exception) throws IOException, ServletException {
            String exceptionToken = exception.getMessage().trim().toLowerCase().replace(" ", "");
            int type = 0;
            if (exceptionToken.contains("badcredentials")) {
                type = 1;
            } else if (exceptionToken.contains("unabletoextractvaliduser")) {
                type = 2;
            }
            response.sendRedirect(request.getContextPath() + "/login/error?type=" + type);
        }
    };
}

From source file:org.apache.coheigea.cxf.spring.security.authentication.SpringSecurityUTValidator.java

public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    if (credential == null || credential.getUsernametoken() == null) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noCredential");
    }/* ww w.j  ava  2 s .c  om*/

    // Validate the UsernameToken
    UsernameToken usernameToken = credential.getUsernametoken();
    String pwType = usernameToken.getPasswordType();
    if (log.isDebugEnabled()) {
        log.debug("UsernameToken user " + usernameToken.getName());
        log.debug("UsernameToken password type " + pwType);
    }
    if (!WSConstants.PASSWORD_TEXT.equals(pwType)) {
        if (log.isDebugEnabled()) {
            log.debug("Authentication failed - digest passwords are not accepted");
        }
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    }
    if (usernameToken.getPassword() == null) {
        if (log.isDebugEnabled()) {
            log.debug("Authentication failed - no password was provided");
        }
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    }

    // Validate it via Spring Security

    // Set a Subject up
    UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
            usernameToken.getName(), usernameToken.getPassword());
    Subject subject = new Subject();
    subject.getPrincipals().add(authToken);

    Set<Authentication> authentications = subject.getPrincipals(Authentication.class);
    Authentication authenticated = null;
    try {
        authenticated = authenticationManager.authenticate(authentications.iterator().next());
    } catch (AuthenticationException ex) {
        if (log.isDebugEnabled()) {
            log.debug(ex.getMessage(), ex);
        }
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    }

    if (!authenticated.isAuthenticated()) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    }

    for (GrantedAuthority authz : authenticated.getAuthorities()) {
        System.out.println("Granted: " + authz.getAuthority());
    }

    // Authorize request
    if (accessDecisionManager != null && !requiredRoles.isEmpty()) {
        List<ConfigAttribute> attributes = SecurityConfig
                .createList(requiredRoles.toArray(new String[requiredRoles.size()]));
        for (ConfigAttribute attr : attributes) {
            System.out.println("Attr: " + attr.getAttribute());
        }
        accessDecisionManager.decide(authenticated, this, attributes);
    }

    credential.setSubject(subject);
    return credential;
}

From source file:com.qpark.eip.core.spring.security.EipDaoAuthenticationProvider.java

/**
 * @see org.springframework.security.authentication.dao.DaoAuthenticationProvider#additionalAuthenticationChecks(org.springframework.security.core.userdetails.UserDetails,
 *      org.springframework.security.authentication.UsernamePasswordAuthenticationToken)
 */// ww  w .  j a v a  2  s  .com
@Override
protected void additionalAuthenticationChecks(final UserDetails userDetails,
        final UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    this.logger.debug("+additionalAuthenticationChecks {}", authentication.getName());
    try {
        super.additionalAuthenticationChecks(userDetails, authentication);
    } catch (AuthenticationException e) {
        this.logger.warn(" additionalAuthenticationChecks {}/{} failed: {}", authentication.getName(),
                (userDetails == null ? "NoUserDetailsFound" : userDetails.getUsername()), e.getMessage());
        throw e;
    } finally {
        this.logger.debug("-additionalAuthenticationChecks {}", authentication.getName());
    }
}

From source file:com.bitium.confluence.servlet.SsoLoginServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {/*  w  ww  . j a va  2 s .com*/
        SAMLContext context = new SAMLContext(request, saml2Config);
        SAMLMessageContext messageContext = context.createSamlMessageContext(request, response);

        // Process response
        context.getSamlProcessor().retrieveMessage(messageContext);

        messageContext.setLocalEntityEndpoint(
                SAMLUtil.getEndpoint(messageContext.getLocalEntityRoleMetadata().getEndpoints(),
                        messageContext.getInboundSAMLBinding(), request.getRequestURL().toString()));
        messageContext.getPeerEntityMetadata().setEntityID(saml2Config.getIdpEntityId());

        WebSSOProfileConsumer consumer = new WebSSOProfileConsumerImpl(context.getSamlProcessor(),
                context.getMetadataManager());
        SAMLCredential credential = consumer.processAuthenticationResponse(messageContext);

        request.getSession().setAttribute("SAMLCredential", credential);

        //           String userName = ((XSAny)credential.getAttributes().get(0).getAttributeValues().get(0)).getTextContent();
        String userName = credential.getNameID().getValue();

        authenticateUserAndLogin(request, response, userName);
    } catch (AuthenticationException e) {
        try {
            log.error("saml plugin error + " + e.getMessage());
            response.sendRedirect("/confluence/login.action?samlerror=plugin_exception");
        } catch (IOException e1) {
            throw new ServletException();
        }
    } catch (Exception e) {
        try {
            log.error("saml plugin error + " + e.getMessage());
            response.sendRedirect("/confluence/login.action?samlerror=plugin_exception");
        } catch (IOException e1) {
            throw new ServletException();
        }
    }
}