Search in sources :

Example 6 with InvalidCredentialsException

use of org.apache.nifi.registry.security.authentication.exception.InvalidCredentialsException in project nifi-registry by apache.

the class LdapIdentityProvider method authenticate.

@Override
public AuthenticationResponse authenticate(AuthenticationRequest authenticationRequest) throws InvalidCredentialsException, IdentityAccessException {
    if (authenticationRequest == null || StringUtils.isEmpty(authenticationRequest.getUsername())) {
        logger.debug("Call to authenticate method with null or empty authenticationRequest, returning null without attempting to authenticate");
        return null;
    }
    if (ldapAuthenticationProvider == null) {
        throw new IdentityAccessException("The LDAP authentication provider is not initialized.");
    }
    try {
        final String username = authenticationRequest.getUsername();
        final Object credentials = authenticationRequest.getCredentials();
        final String password = credentials != null && credentials instanceof String ? (String) credentials : null;
        // perform the authentication
        final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, credentials);
        final Authentication authentication = ldapAuthenticationProvider.authenticate(token);
        logger.debug("Created authentication token: {}", token.toString());
        // use dn if configured
        if (IdentityStrategy.USE_DN.equals(identityStrategy)) {
            // attempt to get the ldap user details to get the DN
            if (authentication.getPrincipal() instanceof LdapUserDetails) {
                final LdapUserDetails userDetails = (LdapUserDetails) authentication.getPrincipal();
                return new AuthenticationResponse(userDetails.getDn(), username, expiration, issuer);
            } else {
                logger.warn(String.format("Unable to determine user DN for %s, using username.", authentication.getName()));
                return new AuthenticationResponse(authentication.getName(), username, expiration, issuer);
            }
        } else {
            return new AuthenticationResponse(authentication.getName(), username, expiration, issuer);
        }
    } catch (final BadCredentialsException | UsernameNotFoundException | AuthenticationException e) {
        throw new InvalidCredentialsException(e.getMessage(), e);
    } catch (final Exception e) {
        // there appears to be a bug that generates a InternalAuthenticationServiceException wrapped around an AuthenticationException. this
        // shouldn't be the case as they the service exception suggestions that something was wrong with the service. while the authentication
        // exception suggests that username and/or credentials were incorrect. checking the cause seems to address this scenario.
        final Throwable cause = e.getCause();
        if (cause instanceof AuthenticationException) {
            throw new InvalidCredentialsException(e.getMessage(), e);
        }
        logger.error(e.getMessage());
        if (logger.isDebugEnabled()) {
            logger.debug(StringUtils.EMPTY, e);
        }
        throw new IdentityAccessException("Unable to validate the supplied credentials. Please contact the system administrator.", e);
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) AuthenticationException(org.springframework.ldap.AuthenticationException) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationResponse(org.apache.nifi.registry.security.authentication.AuthenticationResponse) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationException(org.springframework.ldap.AuthenticationException) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) KeyStoreException(java.security.KeyStoreException) IdentityAccessException(org.apache.nifi.registry.security.authentication.exception.IdentityAccessException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) SecurityProviderDestructionException(org.apache.nifi.registry.security.exception.SecurityProviderDestructionException) InvalidCredentialsException(org.apache.nifi.registry.security.authentication.exception.InvalidCredentialsException) SecurityProviderCreationException(org.apache.nifi.registry.security.exception.SecurityProviderCreationException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidCredentialsException(org.apache.nifi.registry.security.authentication.exception.InvalidCredentialsException) Authentication(org.springframework.security.core.Authentication) LdapUserDetails(org.springframework.security.ldap.userdetails.LdapUserDetails) IdentityAccessException(org.apache.nifi.registry.security.authentication.exception.IdentityAccessException)

Example 7 with InvalidCredentialsException

use of org.apache.nifi.registry.security.authentication.exception.InvalidCredentialsException in project nifi-registry by apache.

the class AccessResource method createAccessTokenUsingBasicAuthCredentials.

/**
 * Creates a token for accessing the REST API.
 *
 * @param httpServletRequest the servlet request
 * @return A JWT (string)
 */
@POST
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.TEXT_PLAIN)
@Path("/token/login")
@ApiOperation(value = "Creates a token for accessing the REST API via username/password", notes = "The user credentials must be passed in standard HTTP Basic Auth format. " + "That is: 'Authorization: Basic <credentials>', where <credentials> is the base64 encoded value of '<username>:<password>'. " + "The token returned is formatted as a JSON Web Token (JWT). The token is base64 encoded and comprised of three parts. The header, " + "the body, and the signature. The expiration of the token is a contained within the body. The token can be used in the Authorization header " + "in the format 'Authorization: Bearer <token>'.", response = String.class, authorizations = { @Authorization("BasicAuth") })
@ApiResponses({ @ApiResponse(code = 400, message = HttpStatusMessages.MESSAGE_400), @ApiResponse(code = 401, message = HttpStatusMessages.MESSAGE_401), @ApiResponse(code = 409, message = HttpStatusMessages.MESSAGE_409 + " The NiFi Registry may not be configured to support login with username/password."), @ApiResponse(code = 500, message = HttpStatusMessages.MESSAGE_500) })
public Response createAccessTokenUsingBasicAuthCredentials(@Context HttpServletRequest httpServletRequest) {
    // only support access tokens when communicating over HTTPS
    if (!httpServletRequest.isSecure()) {
        throw new IllegalStateException("Access tokens are only issued over HTTPS");
    }
    // if not configured with custom identity provider, or if provider doesn't support HTTP Basic Auth, don't consider credentials
    if (identityProvider == null) {
        logger.debug("An Identity Provider must be configured to use this endpoint. Please consult the administration guide.");
        throw new IllegalStateException("Username/Password login not supported by this NiFi. Contact System Administrator.");
    }
    if (!(identityProvider instanceof BasicAuthIdentityProvider)) {
        logger.debug("An Identity Provider is configured, but it does not support HTTP Basic Auth authentication. " + "The configured Identity Provider must extend {}", BasicAuthIdentityProvider.class);
        throw new IllegalStateException("Username/Password login not supported by this NiFi. Contact System Administrator.");
    }
    // generate JWT for response
    AuthenticationRequest authenticationRequest = identityProvider.extractCredentials(httpServletRequest);
    if (authenticationRequest == null) {
        throw new UnauthorizedException("The client credentials are missing from the request.").withAuthenticateChallenge(IdentityProviderUsage.AuthType.OTHER);
    }
    final String token;
    try {
        token = createAccessToken(identityProvider, authenticationRequest);
    } catch (final InvalidCredentialsException ice) {
        throw new UnauthorizedException("The supplied client credentials are not valid.", ice).withAuthenticateChallenge(IdentityProviderUsage.AuthType.OTHER);
    }
    // form the response
    final URI uri = URI.create(generateResourceUri("access", "token"));
    return generateCreatedResponse(uri, token).build();
}
Also used : InvalidCredentialsException(org.apache.nifi.registry.security.authentication.exception.InvalidCredentialsException) UnauthorizedException(org.apache.nifi.registry.web.exception.UnauthorizedException) AuthenticationRequest(org.apache.nifi.registry.security.authentication.AuthenticationRequest) URI(java.net.URI) BasicAuthIdentityProvider(org.apache.nifi.registry.security.authentication.BasicAuthIdentityProvider) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 8 with InvalidCredentialsException

use of org.apache.nifi.registry.security.authentication.exception.InvalidCredentialsException in project nifi-registry by apache.

the class AccessResource method createAccessTokenByTryingAllProviders.

/**
 * Creates a token for accessing the REST API.
 *
 * @param httpServletRequest the servlet request
 * @return A JWT (string)
 */
@POST
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.TEXT_PLAIN)
@Path("/token")
@ApiOperation(value = "Creates a token for accessing the REST API via auto-detected method of verifying client identity claim credentials", notes = "The token returned is formatted as a JSON Web Token (JWT). The token is base64 encoded and comprised of three parts. The header, " + "the body, and the signature. The expiration of the token is a contained within the body. The token can be used in the Authorization header " + "in the format 'Authorization: Bearer <token>'.", response = String.class)
@ApiResponses({ @ApiResponse(code = 400, message = HttpStatusMessages.MESSAGE_400), @ApiResponse(code = 401, message = HttpStatusMessages.MESSAGE_401), @ApiResponse(code = 409, message = HttpStatusMessages.MESSAGE_409 + " The NiFi Registry may not be configured to support login with username/password."), @ApiResponse(code = 500, message = HttpStatusMessages.MESSAGE_500) })
public Response createAccessTokenByTryingAllProviders(@Context HttpServletRequest httpServletRequest) {
    // only support access tokens when communicating over HTTPS
    if (!httpServletRequest.isSecure()) {
        throw new IllegalStateException("Access tokens are only issued over HTTPS");
    }
    List<IdentityProvider> identityProviderWaterfall = generateIdentityProviderWaterfall();
    String token = null;
    for (IdentityProvider provider : identityProviderWaterfall) {
        AuthenticationRequest authenticationRequest = identityProvider.extractCredentials(httpServletRequest);
        if (authenticationRequest == null) {
            continue;
        }
        try {
            token = createAccessToken(identityProvider, authenticationRequest);
            break;
        } catch (final InvalidCredentialsException ice) {
            logger.debug("{}: the supplied client credentials are invalid.", identityProvider.getClass().getSimpleName());
            logger.debug("", ice);
        }
    }
    if (StringUtils.isEmpty(token)) {
        List<IdentityProviderUsage.AuthType> acceptableAuthTypes = identityProviderWaterfall.stream().map(IdentityProvider::getUsageInstructions).map(IdentityProviderUsage::getAuthType).filter(Objects::nonNull).distinct().collect(Collectors.toList());
        throw new UnauthorizedException("Client credentials are missing or invalid according to all configured identity providers.").withAuthenticateChallenge(acceptableAuthTypes);
    }
    // build the response
    final URI uri = URI.create(generateResourceUri("access", "token"));
    return generateCreatedResponse(uri, token).build();
}
Also used : InvalidCredentialsException(org.apache.nifi.registry.security.authentication.exception.InvalidCredentialsException) Objects(java.util.Objects) UnauthorizedException(org.apache.nifi.registry.web.exception.UnauthorizedException) KerberosSpnegoIdentityProvider(org.apache.nifi.registry.web.security.authentication.kerberos.KerberosSpnegoIdentityProvider) BasicAuthIdentityProvider(org.apache.nifi.registry.security.authentication.BasicAuthIdentityProvider) X509IdentityProvider(org.apache.nifi.registry.web.security.authentication.x509.X509IdentityProvider) IdentityProvider(org.apache.nifi.registry.security.authentication.IdentityProvider) AuthenticationRequest(org.apache.nifi.registry.security.authentication.AuthenticationRequest) URI(java.net.URI) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 9 with InvalidCredentialsException

use of org.apache.nifi.registry.security.authentication.exception.InvalidCredentialsException in project nifi-registry by apache.

the class IdentityAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    // Determine if this AuthenticationProvider's identityProvider should be able to support this AuthenticationRequest
    boolean tokenOriginatedFromThisIdentityProvider = checkTokenOriginatedFromThisIdentityProvider(authentication);
    if (!tokenOriginatedFromThisIdentityProvider) {
        // cannot authenticate this token and another provider should be tried.
        return null;
    }
    AuthenticationRequestToken authenticationRequestToken = ((AuthenticationRequestToken) authentication);
    AuthenticationRequest authenticationRequest = authenticationRequestToken.getAuthenticationRequest();
    try {
        AuthenticationResponse authenticationResponse = identityProvider.authenticate(authenticationRequest);
        if (authenticationResponse == null) {
            return null;
        }
        return buildAuthenticatedToken(authenticationRequestToken, authenticationResponse);
    } catch (InvalidCredentialsException e) {
        throw new BadCredentialsException("Identity Provider authentication failed.", e);
    }
}
Also used : InvalidCredentialsException(org.apache.nifi.registry.security.authentication.exception.InvalidCredentialsException) AuthenticationRequest(org.apache.nifi.registry.security.authentication.AuthenticationRequest) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationResponse(org.apache.nifi.registry.security.authentication.AuthenticationResponse)

Aggregations

InvalidCredentialsException (org.apache.nifi.registry.security.authentication.exception.InvalidCredentialsException)9 AuthenticationRequest (org.apache.nifi.registry.security.authentication.AuthenticationRequest)5 AuthenticationResponse (org.apache.nifi.registry.security.authentication.AuthenticationResponse)5 ApiOperation (io.swagger.annotations.ApiOperation)4 ApiResponses (io.swagger.annotations.ApiResponses)4 URI (java.net.URI)4 Consumes (javax.ws.rs.Consumes)4 POST (javax.ws.rs.POST)4 Path (javax.ws.rs.Path)4 Produces (javax.ws.rs.Produces)4 UnauthorizedException (org.apache.nifi.registry.web.exception.UnauthorizedException)4 IdentityAccessException (org.apache.nifi.registry.security.authentication.exception.IdentityAccessException)3 Authentication (org.springframework.security.core.Authentication)3 BasicAuthIdentityProvider (org.apache.nifi.registry.security.authentication.BasicAuthIdentityProvider)2 SecurityProviderCreationException (org.apache.nifi.registry.security.exception.SecurityProviderCreationException)2 SecurityProviderDestructionException (org.apache.nifi.registry.security.exception.SecurityProviderDestructionException)2 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)2 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)2 AuthenticationException (org.springframework.security.core.AuthenticationException)2 IOException (java.io.IOException)1