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);
}
}
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);
}
}
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();
}
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));
}
}
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));
}
Aggregations