Search in sources :

Example 1 with AuthenticationResponse

use of org.apache.nifi.authentication.AuthenticationResponse in project nifi by apache.

the class LdapProvider method authenticate.

@Override
public final AuthenticationResponse authenticate(final LoginCredentials credentials) throws InvalidLoginCredentialsException, IdentityAccessException {
    if (provider == null) {
        throw new IdentityAccessException("The LDAP authentication provider is not initialized.");
    }
    try {
        // perform the authentication
        final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword());
        final Authentication authentication = provider.authenticate(token);
        // 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(), credentials.getUsername(), expiration, issuer);
            } else {
                logger.warn(String.format("Unable to determine user DN for %s, using username.", authentication.getName()));
                return new AuthenticationResponse(authentication.getName(), credentials.getUsername(), expiration, issuer);
            }
        } else {
            return new AuthenticationResponse(authentication.getName(), credentials.getUsername(), expiration, issuer);
        }
    } catch (final BadCredentialsException | UsernameNotFoundException | AuthenticationException e) {
        throw new InvalidLoginCredentialsException(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 InvalidLoginCredentialsException(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) Authentication(org.springframework.security.core.Authentication) InvalidLoginCredentialsException(org.apache.nifi.authentication.exception.InvalidLoginCredentialsException) LdapUserDetails(org.springframework.security.ldap.userdetails.LdapUserDetails) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) IdentityAccessException(org.apache.nifi.authentication.exception.IdentityAccessException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationResponse(org.apache.nifi.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.authentication.exception.IdentityAccessException) ProviderCreationException(org.apache.nifi.authentication.exception.ProviderCreationException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) ProviderDestructionException(org.apache.nifi.authentication.exception.ProviderDestructionException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) InvalidLoginCredentialsException(org.apache.nifi.authentication.exception.InvalidLoginCredentialsException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 2 with AuthenticationResponse

use of org.apache.nifi.authentication.AuthenticationResponse in project nifi by apache.

the class KerberosProvider method authenticate.

@Override
public final AuthenticationResponse authenticate(final LoginCredentials credentials) throws InvalidLoginCredentialsException, IdentityAccessException {
    if (provider == null) {
        throw new IdentityAccessException("The Kerberos authentication provider is not initialized.");
    }
    try {
        // Perform the authentication
        final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword());
        logger.debug("Created authentication token for principal {} with name {} and is authenticated {}", token.getPrincipal(), token.getName(), token.isAuthenticated());
        final Authentication authentication = provider.authenticate(token);
        logger.debug("Ran provider.authenticate() and returned authentication for " + "principal {} with name {} and is authenticated {}", authentication.getPrincipal(), authentication.getName(), authentication.isAuthenticated());
        return new AuthenticationResponse(authentication.getName(), credentials.getUsername(), expiration, issuer);
    } catch (final AuthenticationException e) {
        throw new InvalidLoginCredentialsException(e.getMessage(), e);
    }
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) InvalidLoginCredentialsException(org.apache.nifi.authentication.exception.InvalidLoginCredentialsException) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) IdentityAccessException(org.apache.nifi.authentication.exception.IdentityAccessException) AuthenticationResponse(org.apache.nifi.authentication.AuthenticationResponse)

Example 3 with AuthenticationResponse

use of org.apache.nifi.authentication.AuthenticationResponse in project nifi by apache.

the class AccessResource method createAccessToken.

/**
 * Creates a token for accessing the REST API via username/password.
 *
 * @param httpServletRequest the servlet request
 * @param username           the username
 * @param password           the password
 * @return A JWT (string)
 */
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_PLAIN)
@Path("/token")
@ApiOperation(value = "Creates a token for accessing the REST API via username/password", 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(value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 403, message = "Client is not authorized to make this request."), @ApiResponse(code = 409, message = "Unable to create access token because NiFi is not in the appropriate state. (i.e. may not be configured to support username/password login."), @ApiResponse(code = 500, message = "Unable to create access token because an unexpected error occurred.") })
public Response createAccessToken(@Context HttpServletRequest httpServletRequest, @FormParam("username") String username, @FormParam("password") String password) {
    // only support access tokens when communicating over HTTPS
    if (!httpServletRequest.isSecure()) {
        throw new IllegalStateException("Access tokens are only issued over HTTPS.");
    }
    // if not configuration for login, don't consider credentials
    if (loginIdentityProvider == null) {
        throw new IllegalStateException("Username/Password login not supported by this NiFi.");
    }
    final LoginAuthenticationToken loginAuthenticationToken;
    // ensure we have login credentials
    if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
        throw new IllegalArgumentException("The username and password must be specified.");
    }
    try {
        // attempt to authenticate
        final AuthenticationResponse authenticationResponse = loginIdentityProvider.authenticate(new LoginCredentials(username, password));
        long expiration = validateTokenExpiration(authenticationResponse.getExpiration(), authenticationResponse.getIdentity());
        // create the authentication token
        loginAuthenticationToken = new LoginAuthenticationToken(authenticationResponse.getIdentity(), expiration, authenticationResponse.getIssuer());
    } catch (final InvalidLoginCredentialsException ilce) {
        throw new IllegalArgumentException("The supplied username and password are not valid.", ilce);
    } catch (final IdentityAccessException iae) {
        throw new AdministrationException(iae.getMessage(), iae);
    }
    // generate JWT for response
    final String token = jwtService.generateSignedToken(loginAuthenticationToken);
    // build the response
    final URI uri = URI.create(generateResourceUri("access", "token"));
    return generateCreatedResponse(uri, token).build();
}
Also used : LoginCredentials(org.apache.nifi.authentication.LoginCredentials) InvalidLoginCredentialsException(org.apache.nifi.authentication.exception.InvalidLoginCredentialsException) LoginAuthenticationToken(org.apache.nifi.web.security.token.LoginAuthenticationToken) IdentityAccessException(org.apache.nifi.authentication.exception.IdentityAccessException) AdministrationException(org.apache.nifi.admin.service.AdministrationException) AuthenticationResponse(org.apache.nifi.authentication.AuthenticationResponse) 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 4 with AuthenticationResponse

use of org.apache.nifi.authentication.AuthenticationResponse in project nifi by apache.

the class X509AuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    final X509AuthenticationRequestToken request = (X509AuthenticationRequestToken) authentication;
    // attempt to authenticate if certificates were found
    final AuthenticationResponse authenticationResponse;
    try {
        authenticationResponse = certificateIdentityProvider.authenticate(request.getCertificates());
    } catch (final IllegalArgumentException iae) {
        throw new InvalidAuthenticationException(iae.getMessage(), iae);
    }
    if (StringUtils.isBlank(request.getProxiedEntitiesChain())) {
        final String mappedIdentity = mapIdentity(authenticationResponse.getIdentity());
        return new NiFiAuthenticationToken(new NiFiUserDetails(new Builder().identity(mappedIdentity).groups(getUserGroups(mappedIdentity)).clientAddress(request.getClientAddress()).build()));
    } else {
        // build the entire proxy chain if applicable - <end-user><proxy1><proxy2>
        final List<String> proxyChain = new ArrayList<>(ProxiedEntitiesUtils.tokenizeProxiedEntitiesChain(request.getProxiedEntitiesChain()));
        proxyChain.add(authenticationResponse.getIdentity());
        // add the chain as appropriate to each proxy
        NiFiUser proxy = null;
        for (final ListIterator<String> chainIter = proxyChain.listIterator(proxyChain.size()); chainIter.hasPrevious(); ) {
            String identity = chainIter.previous();
            // determine if the user is anonymous
            final boolean isAnonymous = StringUtils.isBlank(identity);
            if (isAnonymous) {
                identity = StandardNiFiUser.ANONYMOUS_IDENTITY;
            } else {
                identity = mapIdentity(identity);
            }
            final Set<String> groups = getUserGroups(identity);
            // Only set the client address for client making the request because we don't know the clientAddress of the proxied entities
            String clientAddress = (proxy == null) ? request.getClientAddress() : null;
            proxy = createUser(identity, groups, proxy, clientAddress, isAnonymous);
            if (chainIter.hasPrevious()) {
                try {
                    PROXY_AUTHORIZABLE.authorize(authorizer, RequestAction.WRITE, proxy);
                } catch (final AccessDeniedException e) {
                    throw new UntrustedProxyException(String.format("Untrusted proxy %s", identity));
                }
            }
        }
        return new NiFiAuthenticationToken(new NiFiUserDetails(proxy));
    }
}
Also used : AccessDeniedException(org.apache.nifi.authorization.AccessDeniedException) StandardNiFiUser(org.apache.nifi.authorization.user.StandardNiFiUser) NiFiUser(org.apache.nifi.authorization.user.NiFiUser) Builder(org.apache.nifi.authorization.user.StandardNiFiUser.Builder) ArrayList(java.util.ArrayList) AuthenticationResponse(org.apache.nifi.authentication.AuthenticationResponse) InvalidAuthenticationException(org.apache.nifi.web.security.InvalidAuthenticationException) NiFiAuthenticationToken(org.apache.nifi.web.security.token.NiFiAuthenticationToken) UntrustedProxyException(org.apache.nifi.web.security.UntrustedProxyException) NiFiUserDetails(org.apache.nifi.authorization.user.NiFiUserDetails)

Example 5 with AuthenticationResponse

use of org.apache.nifi.authentication.AuthenticationResponse in project nifi by apache.

the class X509AuthenticationProviderTest method setup.

@Before
public void setup() {
    extractor = new SubjectDnX509PrincipalExtractor();
    certificateIdentityProvider = mock(X509IdentityProvider.class);
    when(certificateIdentityProvider.authenticate(any(X509Certificate[].class))).then(invocation -> {
        final X509Certificate[] certChain = invocation.getArgumentAt(0, X509Certificate[].class);
        final String identity = extractor.extractPrincipal(certChain[0]).toString();
        if (INVALID_CERTIFICATE.equals(identity)) {
            throw new IllegalArgumentException();
        }
        return new AuthenticationResponse(identity, identity, TimeUnit.MILLISECONDS.convert(12, TimeUnit.HOURS), "");
    });
    authorizer = mock(Authorizer.class);
    when(authorizer.authorize(any(AuthorizationRequest.class))).then(invocation -> {
        final AuthorizationRequest request = invocation.getArgumentAt(0, AuthorizationRequest.class);
        if (UNTRUSTED_PROXY.equals(request.getIdentity())) {
            return AuthorizationResult.denied();
        }
        return AuthorizationResult.approved();
    });
    x509AuthenticationProvider = new X509AuthenticationProvider(certificateIdentityProvider, authorizer, NiFiProperties.createBasicNiFiProperties(null, null));
}
Also used : AuthorizationRequest(org.apache.nifi.authorization.AuthorizationRequest) Authorizer(org.apache.nifi.authorization.Authorizer) AuthenticationResponse(org.apache.nifi.authentication.AuthenticationResponse) X509Certificate(java.security.cert.X509Certificate) Before(org.junit.Before)

Aggregations

AuthenticationResponse (org.apache.nifi.authentication.AuthenticationResponse)5 IdentityAccessException (org.apache.nifi.authentication.exception.IdentityAccessException)3 InvalidLoginCredentialsException (org.apache.nifi.authentication.exception.InvalidLoginCredentialsException)3 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)2 Authentication (org.springframework.security.core.Authentication)2 ApiOperation (io.swagger.annotations.ApiOperation)1 ApiResponses (io.swagger.annotations.ApiResponses)1 IOException (java.io.IOException)1 URI (java.net.URI)1 KeyManagementException (java.security.KeyManagementException)1 KeyStoreException (java.security.KeyStoreException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 UnrecoverableKeyException (java.security.UnrecoverableKeyException)1 CertificateException (java.security.cert.CertificateException)1 X509Certificate (java.security.cert.X509Certificate)1 ArrayList (java.util.ArrayList)1 Consumes (javax.ws.rs.Consumes)1 POST (javax.ws.rs.POST)1 Path (javax.ws.rs.Path)1 Produces (javax.ws.rs.Produces)1