Search in sources :

Example 26 with SecurityContext

use of org.neo4j.kernel.api.security.SecurityContext in project neo4j by neo4j.

the class AuthorizationEnabledFilter method doFilter.

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    validateRequestType(servletRequest);
    validateResponseType(servletResponse);
    final HttpServletRequest request = (HttpServletRequest) servletRequest;
    final HttpServletResponse response = (HttpServletResponse) servletResponse;
    final String path = request.getContextPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());
    if (request.getMethod().equals("OPTIONS") || whitelisted(path)) {
        // NOTE: If starting transactions with access mode on whitelisted uris should be possible we need to
        //       wrap servletRequest in an AuthorizedRequestWarpper here
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }
    final String header = request.getHeader(HttpHeaders.AUTHORIZATION);
    if (header == null) {
        requestAuthentication(request, noHeader).accept(response);
        return;
    }
    final String[] usernameAndPassword = extractCredential(header);
    if (usernameAndPassword == null) {
        badHeader.accept(response);
        return;
    }
    final String username = usernameAndPassword[0];
    final String password = usernameAndPassword[1];
    try {
        SecurityContext securityContext = authenticate(username, password);
        switch(securityContext.subject().getAuthenticationResult()) {
            case PASSWORD_CHANGE_REQUIRED:
                if (!PASSWORD_CHANGE_WHITELIST.matcher(path).matches()) {
                    passwordChangeRequired(username, baseURL(request)).accept(response);
                    return;
                }
            // fall through
            case SUCCESS:
                try {
                    filterChain.doFilter(new AuthorizedRequestWrapper(BASIC_AUTH, username, request, securityContext), servletResponse);
                } catch (AuthorizationViolationException e) {
                    unauthorizedAccess(e.getMessage()).accept(response);
                }
                return;
            case TOO_MANY_ATTEMPTS:
                tooManyAttempts.accept(response);
                return;
            default:
                log.warn("Failed authentication attempt for '%s' from %s", username, request.getRemoteAddr());
                requestAuthentication(request, invalidCredential).accept(response);
        }
    } catch (InvalidAuthTokenException e) {
        requestAuthentication(request, invalidAuthToken(e.getMessage())).accept(response);
    } catch (AuthProviderTimeoutException e) {
        authProviderTimeout.accept(response);
    } catch (AuthProviderFailedException e) {
        authProviderFailed.accept(response);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) SecurityContext(org.neo4j.kernel.api.security.SecurityContext) AuthProviderFailedException(org.neo4j.graphdb.security.AuthProviderFailedException) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthProviderTimeoutException(org.neo4j.graphdb.security.AuthProviderTimeoutException) AuthorizationViolationException(org.neo4j.graphdb.security.AuthorizationViolationException) InvalidAuthTokenException(org.neo4j.kernel.api.security.exception.InvalidAuthTokenException)

Example 27 with SecurityContext

use of org.neo4j.kernel.api.security.SecurityContext in project neo4j by neo4j.

the class UserService method setPassword.

@POST
@Path("/{username}/password")
public Response setPassword(@PathParam("username") String username, @Context HttpServletRequest req, String payload) {
    Principal principal = req.getUserPrincipal();
    if (principal == null || !principal.getName().equals(username)) {
        return output.notFound();
    }
    final Map<String, Object> deserialized;
    try {
        deserialized = input.readMap(payload);
    } catch (BadInputException e) {
        return output.response(BAD_REQUEST, new ExceptionRepresentation(new Neo4jError(Status.Request.InvalidFormat, e.getMessage())));
    }
    Object o = deserialized.get(PASSWORD);
    if (o == null) {
        return output.response(UNPROCESSABLE, new ExceptionRepresentation(new Neo4jError(Status.Request.InvalidFormat, String.format("Required parameter '%s' is missing.", PASSWORD))));
    }
    if (!(o instanceof String)) {
        return output.response(UNPROCESSABLE, new ExceptionRepresentation(new Neo4jError(Status.Request.InvalidFormat, String.format("Expected '%s' to be a string.", PASSWORD))));
    }
    String newPassword = (String) o;
    try {
        SecurityContext securityContext = getSecurityContextFromUserPrincipal(principal);
        if (securityContext == null) {
            return output.notFound();
        } else {
            UserManager userManager = userManagerSupplier.getUserManager(securityContext);
            userManager.setUserPassword(username, newPassword, false);
        }
    } catch (IOException e) {
        return output.serverErrorWithoutLegacyStacktrace(e);
    } catch (InvalidArgumentsException e) {
        return output.response(UNPROCESSABLE, new ExceptionRepresentation(new Neo4jError(e.status(), e.getMessage())));
    }
    return output.ok();
}
Also used : Neo4jError(org.neo4j.server.rest.transactional.error.Neo4jError) ExceptionRepresentation(org.neo4j.server.rest.repr.ExceptionRepresentation) BadInputException(org.neo4j.server.rest.repr.BadInputException) UserManager(org.neo4j.kernel.api.security.UserManager) SecurityContext(org.neo4j.kernel.api.security.SecurityContext) IOException(java.io.IOException) InvalidArgumentsException(org.neo4j.kernel.api.exceptions.InvalidArgumentsException) AuthorizedRequestWrapper.getSecurityContextFromUserPrincipal(org.neo4j.server.rest.dbms.AuthorizedRequestWrapper.getSecurityContextFromUserPrincipal) Principal(java.security.Principal) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 28 with SecurityContext

use of org.neo4j.kernel.api.security.SecurityContext in project neo4j by neo4j.

the class SecurityContextDescriptionTest method shouldMakeNiceDescriptionWithMode.

@Test
public void shouldMakeNiceDescriptionWithMode() throws Throwable {
    SecurityContext modified = context.withMode(AccessMode.Static.WRITE);
    assertThat(modified.description(), equalTo("user 'johan' with WRITE"));
}
Also used : SecurityContext(org.neo4j.kernel.api.security.SecurityContext) Test(org.junit.Test)

Example 29 with SecurityContext

use of org.neo4j.kernel.api.security.SecurityContext in project neo4j by neo4j.

the class SecurityContextDescriptionTest method shouldMakeNiceDescriptionRestricted.

@Test
public void shouldMakeNiceDescriptionRestricted() throws Throwable {
    SecurityContext restricted = context.withMode(new RestrictedAccessMode(context.mode(), AccessMode.Static.READ));
    assertThat(restricted.description(), equalTo("user 'johan' with FULL restricted to READ"));
}
Also used : RestrictedAccessMode(org.neo4j.kernel.impl.api.security.RestrictedAccessMode) SecurityContext(org.neo4j.kernel.api.security.SecurityContext) Test(org.junit.Test)

Example 30 with SecurityContext

use of org.neo4j.kernel.api.security.SecurityContext in project neo4j by neo4j.

the class BasicAuthManagerTest method assertLoginGivesResult.

private void assertLoginGivesResult(String username, String password, AuthenticationResult expectedResult) throws InvalidAuthTokenException {
    SecurityContext securityContext = manager.login(authToken(username, password));
    assertThat(securityContext.subject().getAuthenticationResult(), equalTo(expectedResult));
}
Also used : SecurityContext(org.neo4j.kernel.api.security.SecurityContext)

Aggregations

SecurityContext (org.neo4j.kernel.api.security.SecurityContext)33 Test (org.junit.Test)20 KernelTransaction (org.neo4j.kernel.api.KernelTransaction)6 ThreadToStatementContextBridge (org.neo4j.kernel.impl.core.ThreadToStatementContextBridge)4 POST (javax.ws.rs.POST)3 Path (javax.ws.rs.Path)3 IOException (java.io.IOException)2 Principal (java.security.Principal)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 Consumes (javax.ws.rs.Consumes)2 Produces (javax.ws.rs.Produces)2 InOrder (org.mockito.InOrder)2 ReturnsDeepStubs (org.mockito.internal.stubbing.defaultanswers.ReturnsDeepStubs)2 Transaction (org.neo4j.graphdb.Transaction)2 QueryRegistryOperations (org.neo4j.kernel.api.QueryRegistryOperations)2 Statement (org.neo4j.kernel.api.Statement)2 InvalidArgumentsException (org.neo4j.kernel.api.exceptions.InvalidArgumentsException)2 ExecutingQuery (org.neo4j.kernel.api.query.ExecutingQuery)2 KernelStatement (org.neo4j.kernel.impl.api.KernelStatement)2 InternalTransaction (org.neo4j.kernel.impl.coreapi.InternalTransaction)2