Search in sources :

Example 11 with AdministrationException

use of org.apache.nifi.admin.service.AdministrationException 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 12 with AdministrationException

use of org.apache.nifi.admin.service.AdministrationException in project nifi by apache.

the class JwtService method parseTokenFromBase64EncodedString.

private Jws<Claims> parseTokenFromBase64EncodedString(final String base64EncodedToken) throws JwtException {
    try {
        return Jwts.parser().setSigningKeyResolver(new SigningKeyResolverAdapter() {

            @Override
            public byte[] resolveSigningKeyBytes(JwsHeader header, Claims claims) {
                final String identity = claims.getSubject();
                // Get the key based on the key id in the claims
                final Integer keyId = claims.get(KEY_ID_CLAIM, Integer.class);
                final Key key = keyService.getKey(keyId);
                // Ensure we were able to find a key that was previously issued by this key service for this user
                if (key == null || key.getKey() == null) {
                    throw new UnsupportedJwtException("Unable to determine signing key for " + identity + " [kid: " + keyId + "]");
                }
                return key.getKey().getBytes(StandardCharsets.UTF_8);
            }
        }).parseClaimsJws(base64EncodedToken);
    } catch (final MalformedJwtException | UnsupportedJwtException | SignatureException | ExpiredJwtException | IllegalArgumentException | AdministrationException e) {
        // TODO: Exercise all exceptions to ensure none leak key material to logs
        final String errorMessage = "Unable to validate the access token.";
        throw new JwtException(errorMessage, e);
    }
}
Also used : Claims(io.jsonwebtoken.Claims) SigningKeyResolverAdapter(io.jsonwebtoken.SigningKeyResolverAdapter) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) JwsHeader(io.jsonwebtoken.JwsHeader) SignatureException(io.jsonwebtoken.SignatureException) AdministrationException(org.apache.nifi.admin.service.AdministrationException) UnsupportedJwtException(io.jsonwebtoken.UnsupportedJwtException) MalformedJwtException(io.jsonwebtoken.MalformedJwtException) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) JwtException(io.jsonwebtoken.JwtException) MalformedJwtException(io.jsonwebtoken.MalformedJwtException) Key(org.apache.nifi.key.Key) UnsupportedJwtException(io.jsonwebtoken.UnsupportedJwtException)

Example 13 with AdministrationException

use of org.apache.nifi.admin.service.AdministrationException in project nifi by apache.

the class JwtServiceTest method testShouldNotGenerateTokenWithMissingKey.

@Test(expected = JwtException.class)
public void testShouldNotGenerateTokenWithMissingKey() throws Exception {
    // Arrange
    final int EXPIRATION_MILLIS = 60000;
    LoginAuthenticationToken loginAuthenticationToken = new LoginAuthenticationToken("alopresto", EXPIRATION_MILLIS, "MockIdentityProvider");
    logger.debug("Generating token for " + loginAuthenticationToken);
    // Set up the bad key service
    KeyService missingKeyService = Mockito.mock(KeyService.class);
    when(missingKeyService.getOrCreateKey(anyString())).thenThrow(new AdministrationException("Could not find a " + "key for that user"));
    jwtService = new JwtService(missingKeyService);
    // Act
    jwtService.generateSignedToken(loginAuthenticationToken);
// Assert
// Should throw exception
}
Also used : LoginAuthenticationToken(org.apache.nifi.web.security.token.LoginAuthenticationToken) KeyService(org.apache.nifi.admin.service.KeyService) AdministrationException(org.apache.nifi.admin.service.AdministrationException) Test(org.junit.Test)

Aggregations

AdministrationException (org.apache.nifi.admin.service.AdministrationException)13 DataAccessException (org.apache.nifi.admin.dao.DataAccessException)8 Transaction (org.apache.nifi.admin.service.transaction.Transaction)8 TransactionException (org.apache.nifi.admin.service.transaction.TransactionException)8 Key (org.apache.nifi.key.Key)4 JwtException (io.jsonwebtoken.JwtException)3 ExpiredJwtException (io.jsonwebtoken.ExpiredJwtException)2 MalformedJwtException (io.jsonwebtoken.MalformedJwtException)2 UnsupportedJwtException (io.jsonwebtoken.UnsupportedJwtException)2 ApiOperation (io.swagger.annotations.ApiOperation)2 ApiResponses (io.swagger.annotations.ApiResponses)2 Consumes (javax.ws.rs.Consumes)2 Path (javax.ws.rs.Path)2 Produces (javax.ws.rs.Produces)2 AddActionsAction (org.apache.nifi.admin.service.action.AddActionsAction)2 GetActionsAction (org.apache.nifi.admin.service.action.GetActionsAction)2 PurgeActionsAction (org.apache.nifi.admin.service.action.PurgeActionsAction)2 LoginAuthenticationToken (org.apache.nifi.web.security.token.LoginAuthenticationToken)2 Claims (io.jsonwebtoken.Claims)1 JwsHeader (io.jsonwebtoken.JwsHeader)1