Example usage for org.springframework.security.authentication AuthenticationServiceException AuthenticationServiceException

List of usage examples for org.springframework.security.authentication AuthenticationServiceException AuthenticationServiceException

Introduction

In this page you can find the example usage for org.springframework.security.authentication AuthenticationServiceException AuthenticationServiceException.

Prototype

public AuthenticationServiceException(String msg) 

Source Link

Document

Constructs an AuthenticationServiceException with the specified message.

Usage

From source file:org.thingsboard.server.service.security.auth.jwt.RefreshTokenProcessingFilter.java

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {
    if (!HttpMethod.POST.name().equals(request.getMethod())) {
        if (log.isDebugEnabled()) {
            log.debug("Authentication method not supported. Request method: " + request.getMethod());
        }//from  www .j ava 2  s.  c o m
        throw new AuthMethodNotSupportedException("Authentication method not supported");
    }

    RefreshTokenRequest refreshTokenRequest;
    try {
        refreshTokenRequest = objectMapper.readValue(request.getReader(), RefreshTokenRequest.class);
    } catch (Exception e) {
        throw new AuthenticationServiceException("Invalid refresh token request payload");
    }

    if (StringUtils.isBlank(refreshTokenRequest.getRefreshToken())) {
        throw new AuthenticationServiceException("Refresh token is not provided");
    }

    RawAccessJwtToken token = new RawAccessJwtToken(refreshTokenRequest.getRefreshToken());

    return this.getAuthenticationManager().authenticate(new RefreshAuthenticationToken(token));
}

From source file:org.thingsboard.server.service.security.auth.rest.RestLoginProcessingFilter.java

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {
    if (!HttpMethod.POST.name().equals(request.getMethod())) {
        if (log.isDebugEnabled()) {
            log.debug("Authentication method not supported. Request method: " + request.getMethod());
        }/*from   w ww. j a v a 2 s . c  om*/
        throw new AuthMethodNotSupportedException("Authentication method not supported");
    }

    LoginRequest loginRequest;
    try {
        loginRequest = objectMapper.readValue(request.getReader(), LoginRequest.class);
    } catch (Exception e) {
        throw new AuthenticationServiceException("Invalid login request payload");
    }

    if (StringUtils.isBlank(loginRequest.getUsername()) || StringUtils.isBlank(loginRequest.getPassword())) {
        throw new AuthenticationServiceException("Username or Password not provided");
    }

    UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, loginRequest.getUsername());

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal,
            loginRequest.getPassword());

    return this.getAuthenticationManager().authenticate(token);
}

From source file:org.thingsboard.server.service.security.auth.rest.RestPublicLoginProcessingFilter.java

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {
    if (!HttpMethod.POST.name().equals(request.getMethod())) {
        if (log.isDebugEnabled()) {
            log.debug("Authentication method not supported. Request method: " + request.getMethod());
        }//from   w w  w.  jav a 2 s .c  om
        throw new AuthMethodNotSupportedException("Authentication method not supported");
    }

    PublicLoginRequest loginRequest;
    try {
        loginRequest = objectMapper.readValue(request.getReader(), PublicLoginRequest.class);
    } catch (Exception e) {
        throw new AuthenticationServiceException("Invalid public login request payload");
    }

    if (StringUtils.isBlank(loginRequest.getPublicId())) {
        throw new AuthenticationServiceException("Public Id is not provided");
    }

    UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.PUBLIC_ID, loginRequest.getPublicId());

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, "");

    return this.getAuthenticationManager().authenticate(token);
}

From source file:pl.bcichecki.rms.customizations.org.springframework.security.web.authentication.www.EventPublisherAwareDigestAuthenticationFilter.java

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

    String header = request.getHeader("Authorization");

    if (header == null || !header.startsWith("Digest ")) {
        chain.doFilter(request, response);

        return;//w w w. j  av  a  2 s  .c o  m
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Digest Authorization header received from user agent: " + header);
    }

    DigestData digestAuth = new DigestData(header);

    try {
        digestAuth.validateAndDecode(authenticationEntryPoint.getKey(),
                authenticationEntryPoint.getRealmName());
    } catch (BadCredentialsException e) {
        fail(request, response, e);

        return;
    }

    // Lookup password for presented username
    // NB: DAO-provided password MUST be clear text - not encoded/salted
    // (unless this instance's passwordAlreadyEncoded property is 'false')
    boolean cacheWasUsed = true;
    UserDetails user = userCache.getUserFromCache(digestAuth.getUsername());
    String serverDigestMd5;

    try {
        if (user == null) {
            cacheWasUsed = false;
            user = userDetailsService.loadUserByUsername(digestAuth.getUsername());

            if (user == null) {
                throw new AuthenticationServiceException(
                        "AuthenticationDao returned null, which is an interface contract violation");
            }

            userCache.putUserInCache(user);
        }

        serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod());

        // If digest is incorrect, try refreshing from backend and
        // recomputing
        if (!serverDigestMd5.equals(digestAuth.getResponse()) && cacheWasUsed) {
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "Digest comparison failure; trying to refresh user from DAO in case password had changed");
            }

            user = userDetailsService.loadUserByUsername(digestAuth.getUsername());
            userCache.putUserInCache(user);
            serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod());
        }

    } catch (UsernameNotFoundException notFound) {
        // MODIFICATION

        boolean userWasNull = false;
        if (user == null) {
            userWasNull = true;
            user = new User(digestAuth.getUsername(), "fakePassSoSpringShutUp", false, false, false, false,
                    new ArrayList<GrantedAuthority>());
        }

        authenticationEventPublisher.publishAuthenticationFailure(notFound,
                createUnsuccessfulAuthentication(request, user));

        if (userWasNull) {
            user = null;
        }

        // END OF MODIFICATION

        fail(request, response,
                new BadCredentialsException(messages.getMessage("DigestAuthenticationFilter.usernameNotFound",
                        new Object[] { digestAuth.getUsername() }, "Username {0} not found")));

        return;
    }

    // If digest is still incorrect, definitely reject authentication
    // attempt
    if (!serverDigestMd5.equals(digestAuth.getResponse())) {
        if (logger.isDebugEnabled()) {
            logger.debug("Expected response: '" + serverDigestMd5 + "' but received: '"
                    + digestAuth.getResponse() + "'; is AuthenticationDao returning clear text passwords?");
        }

        // MODIFICATION

        authenticationEventPublisher.publishAuthenticationFailure(
                new BadCredentialsException("Bad credentials"),
                createUnsuccessfulAuthentication(request, user));

        // END OF MODIFICATION

        fail(request, response, new BadCredentialsException(
                messages.getMessage("DigestAuthenticationFilter.incorrectResponse", "Incorrect response")));
        return;
    }

    // To get this far, the digest must have been valid
    // Check the nonce has not expired
    // We do this last so we can direct the user agent its nonce is stale
    // but the request was otherwise appearing to be valid
    if (digestAuth.isNonceExpired()) {
        fail(request, response, new NonceExpiredException(
                messages.getMessage("DigestAuthenticationFilter.nonceExpired", "Nonce has expired/timed out")));

        return;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Authentication success for user: '" + digestAuth.getUsername() + "' with response: '"
                + digestAuth.getResponse() + "'");
    }

    SecurityContextHolder.getContext().setAuthentication(createSuccessfulAuthentication(request, user));

    chain.doFilter(request, response);
}

From source file:ro.nextreports.server.web.integration.IntegrationAuthenticationFilter.java

protected Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {

    if (postOnly && !request.getMethod().equals("POST")) {
        throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
    }//  w  w  w.  ja va 2s .c  o m

    String username = obtainUsername(request);
    //      System.out.println("username = " + username);
    String secret = obtainSecret(request);
    //      System.out.println("secret = " + secret);

    if (username == null) {
        username = "";
    }

    if (secret == null) {
        secret = "";
    }

    username = username.trim();
    secret = secret.trim();

    // is client behind something?
    String ipAddress = request.getHeader("X-FORWARDED-FOR");
    if (ipAddress == null) {
        ipAddress = request.getRemoteAddr();
    }
    //       System.out.println("ipAddress = " + ipAddress);
    //       System.out.println("whiteIp = " + whiteIp);
    if (!StringUtils.isEmpty(whiteIp) && !whiteIp.equals(ipAddress)) {
        throw new AuthenticationServiceException("Invalid remote address");
    }

    if (!StringUtils.isEmpty(secretKey) && !secretKey.equals(secret)) {
        throw new AuthenticationServiceException("Invalid secret key");
    }

    User user = (User) userDetailsService.loadUserByUsername(username);
    //      System.out.println("user = " + user);
    if (user == null) {
        throw new AuthenticationServiceException(
                "UserDetailsService returned null, which is an interface contract violation");
    }

    //      UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, secret);
    //      UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(authRequest.getPrincipal(),
    //            authRequest.getCredentials(), user.getAuthorities());
    //        result.setDetails(authentication.getDetails());
    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(user, secret,
            user.getAuthorities());

    // Allow subclasses to set the "details" property
    setDetails(request, authRequest);

    return authRequest;
}