Search in sources :

Example 61 with Subject

use of javax.security.auth.Subject in project camel by apache.

the class JAASSecurityAuthenticator method login.

@Override
public Subject login(HttpPrincipal principal) throws LoginException {
    if (ObjectHelper.isEmpty(getName())) {
        throw new IllegalArgumentException("Realm has not been configured on this SecurityAuthenticator: " + this);
    }
    LOG.trace("Login username: {} using realm: {}", principal.getName(), getName());
    LoginContext context = new LoginContext(getName(), new HttpPrincipalCallbackHandler(principal));
    context.login();
    Subject subject = context.getSubject();
    LOG.debug("Login username: {} successful returning Subject: {}", principal.getName(), subject);
    if (LOG.isTraceEnabled()) {
        for (Principal p : subject.getPrincipals()) {
            LOG.trace("Principal on subject {} -> {}", p.getClass().getName(), p.getName());
        }
    }
    return subject;
}
Also used : LoginContext(javax.security.auth.login.LoginContext) Subject(javax.security.auth.Subject) Principal(java.security.Principal)

Example 62 with Subject

use of javax.security.auth.Subject in project camel by apache.

the class HttpServerChannelHandler method channelRead0.

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    HttpRequest request = (HttpRequest) msg;
    LOG.debug("Message received: {}", request);
    if (consumer.isSuspended()) {
        // are we suspended?
        LOG.debug("Consumer suspended, cannot service request {}", request);
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, SERVICE_UNAVAILABLE);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        ctx.writeAndFlush(response);
        ctx.channel().close();
        return;
    }
    // if its an OPTIONS request then return which methods is allowed
    boolean isRestrictedToOptions = consumer.getEndpoint().getHttpMethodRestrict() != null && consumer.getEndpoint().getHttpMethodRestrict().contains("OPTIONS");
    if ("OPTIONS".equals(request.method().name()) && !isRestrictedToOptions) {
        String s;
        if (consumer.getEndpoint().getHttpMethodRestrict() != null) {
            s = "OPTIONS," + consumer.getEndpoint().getHttpMethodRestrict();
        } else {
            // allow them all
            s = "GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,CONNECT,PATCH";
        }
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
        response.headers().set("Allow", s);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        ctx.writeAndFlush(response);
        return;
    }
    if (consumer.getEndpoint().getHttpMethodRestrict() != null && !consumer.getEndpoint().getHttpMethodRestrict().contains(request.method().name())) {
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        ctx.writeAndFlush(response);
        ctx.channel().close();
        return;
    }
    if ("TRACE".equals(request.method().name()) && !consumer.getEndpoint().isTraceEnabled()) {
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        ctx.writeAndFlush(response);
        ctx.channel().close();
        return;
    }
    // must include HOST header as required by HTTP 1.1
    if (!request.headers().contains(HttpHeaderNames.HOST.toString())) {
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, BAD_REQUEST);
        //response.setChunked(false);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        ctx.writeAndFlush(response);
        ctx.channel().close();
        return;
    }
    // is basic auth configured
    NettyHttpSecurityConfiguration security = consumer.getEndpoint().getSecurityConfiguration();
    if (security != null && security.isAuthenticate() && "Basic".equalsIgnoreCase(security.getConstraint())) {
        String url = request.uri();
        // drop parameters from url
        if (url.contains("?")) {
            url = ObjectHelper.before(url, "?");
        }
        // we need the relative path without the hostname and port
        URI uri = new URI(request.uri());
        String target = uri.getPath();
        // strip the starting endpoint path so the target is relative to the endpoint uri
        String path = consumer.getConfiguration().getPath();
        if (path != null && target.startsWith(path)) {
            // need to match by lower case as we want to ignore case on context-path
            path = path.toLowerCase(Locale.US);
            String match = target.toLowerCase(Locale.US);
            if (match.startsWith(path)) {
                target = target.substring(path.length());
            }
        }
        // is it a restricted resource?
        String roles;
        if (security.getSecurityConstraint() != null) {
            // if restricted returns null, then the resource is not restricted and we should not authenticate the user
            roles = security.getSecurityConstraint().restricted(target);
        } else {
            // assume any roles is valid if no security constraint has been configured
            roles = "*";
        }
        if (roles != null) {
            // basic auth subject
            HttpPrincipal principal = extractBasicAuthSubject(request);
            // authenticate principal and check if the user is in role
            Subject subject = null;
            boolean inRole = true;
            if (principal != null) {
                subject = authenticate(security.getSecurityAuthenticator(), security.getLoginDeniedLoggingLevel(), principal);
                if (subject != null) {
                    String userRoles = security.getSecurityAuthenticator().getUserRoles(subject);
                    inRole = matchesRoles(roles, userRoles);
                }
            }
            if (principal == null || subject == null || !inRole) {
                if (principal == null) {
                    LOG.debug("Http Basic Auth required for resource: {}", url);
                } else if (subject == null) {
                    LOG.debug("Http Basic Auth not authorized for username: {}", principal.getUsername());
                } else {
                    LOG.debug("Http Basic Auth not in role for username: {}", principal.getUsername());
                }
                // restricted resource, so send back 401 to require valid username/password
                HttpResponse response = new DefaultHttpResponse(HTTP_1_1, UNAUTHORIZED);
                response.headers().set("WWW-Authenticate", "Basic realm=\"" + security.getRealm() + "\"");
                response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
                response.headers().set(Exchange.CONTENT_LENGTH, 0);
                ctx.writeAndFlush(response);
                // close the channel
                ctx.channel().close();
                return;
            } else {
                LOG.debug("Http Basic Auth authorized for username: {}", principal.getUsername());
            }
        }
    }
    // let Camel process this message
    super.channelRead0(ctx, msg);
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) NettyHttpSecurityConfiguration(org.apache.camel.component.netty4.http.NettyHttpSecurityConfiguration) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) URI(java.net.URI) HttpPrincipal(org.apache.camel.component.netty4.http.HttpPrincipal) Subject(javax.security.auth.Subject)

Example 63 with Subject

use of javax.security.auth.Subject in project cassandra by apache.

the class AuthorizationProxyTest method rejectWhenSubjectNotAuthenticated.

@Test
public void rejectWhenSubjectNotAuthenticated() throws Throwable {
    // Access is denied to a Subject without any associated Principals
    // Verify that the superuser status is never tested as the request is rejected early
    // due to the Subject
    final AtomicBoolean suStatusChecked = new AtomicBoolean(false);
    AuthorizationProxy proxy = new ProxyBuilder().isAuthzRequired(() -> true).isSuperuser((role) -> {
        suStatusChecked.set(true);
        return true;
    }).build();
    assertFalse(proxy.authorize(new Subject(), "getAttribute", new Object[] { objectName(osBean), "arch" }));
    assertFalse(suStatusChecked.get());
}
Also used : java.util(java.util) ImmutableSet(com.google.common.collect.ImmutableSet) BeforeClass(org.junit.BeforeClass) ImmutableMap(com.google.common.collect.ImmutableMap) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) ObjectName(javax.management.ObjectName) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Collectors(java.util.stream.Collectors) Subject(javax.security.auth.Subject) MalformedObjectNameException(javax.management.MalformedObjectNameException) Assert.assertFalse(org.junit.Assert.assertFalse) org.apache.cassandra.auth(org.apache.cassandra.auth) Assert.fail(org.junit.Assert.fail) DatabaseDescriptor(org.apache.cassandra.config.DatabaseDescriptor) Assert.assertEquals(org.junit.Assert.assertEquals) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Subject(javax.security.auth.Subject) Test(org.junit.Test)

Example 64 with Subject

use of javax.security.auth.Subject in project cassandra by apache.

the class AuthorizationProxyTest method authorizeWhenSubjectIsNull.

@Test
public void authorizeWhenSubjectIsNull() throws Throwable {
    // a null subject indicates that the action is being performed by the
    // connector itself, so we always authorize it
    // Verify that the superuser status is never tested as the request returns early
    // due to the null Subject
    // Also, hardcode the permissions provider to return an empty set, so we know that
    // can be doubly sure that it's the null Subject which causes the authz to succeed
    final AtomicBoolean suStatusChecked = new AtomicBoolean(false);
    AuthorizationProxy proxy = new ProxyBuilder().getPermissions((role) -> Collections.emptySet()).isAuthzRequired(() -> true).isSuperuser((role) -> {
        suStatusChecked.set(true);
        return false;
    }).build();
    assertTrue(proxy.authorize(null, "getAttribute", new Object[] { objectName(osBean), "arch" }));
    assertFalse(suStatusChecked.get());
}
Also used : java.util(java.util) ImmutableSet(com.google.common.collect.ImmutableSet) BeforeClass(org.junit.BeforeClass) ImmutableMap(com.google.common.collect.ImmutableMap) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) ObjectName(javax.management.ObjectName) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Collectors(java.util.stream.Collectors) Subject(javax.security.auth.Subject) MalformedObjectNameException(javax.management.MalformedObjectNameException) Assert.assertFalse(org.junit.Assert.assertFalse) org.apache.cassandra.auth(org.apache.cassandra.auth) Assert.fail(org.junit.Assert.fail) DatabaseDescriptor(org.apache.cassandra.config.DatabaseDescriptor) Assert.assertEquals(org.junit.Assert.assertEquals) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test)

Example 65 with Subject

use of javax.security.auth.Subject in project spring-security by spring-projects.

the class JaasApiIntegrationFilterTests method doFilterAuthenticationNull.

@Test
public void doFilterAuthenticationNull() throws Exception {
    assertJaasSubjectEquals(null);
    filter.setCreateEmptySubject(true);
    assertJaasSubjectEquals(new Subject());
}
Also used : Subject(javax.security.auth.Subject) Test(org.junit.Test)

Aggregations

Subject (javax.security.auth.Subject)669 Test (org.testng.annotations.Test)131 Test (org.junit.Test)122 HashMap (java.util.HashMap)120 Principal (java.security.Principal)114 HashSet (java.util.HashSet)109 Set (java.util.Set)82 EntitlementException (com.sun.identity.entitlement.EntitlementException)64 LoginContext (javax.security.auth.login.LoginContext)62 LoginException (javax.security.auth.login.LoginException)49 ConditionDecision (com.sun.identity.entitlement.ConditionDecision)47 ResourceResponse (org.forgerock.json.resource.ResourceResponse)47 RealmContext (org.forgerock.openam.rest.RealmContext)46 Context (org.forgerock.services.context.Context)41 SSOToken (com.iplanet.sso.SSOToken)40 IOException (java.io.IOException)40 ClientContext (org.forgerock.services.context.ClientContext)40 Map (java.util.Map)38 SSOTokenContext (org.forgerock.openam.rest.resource.SSOTokenContext)38 ResourceException (org.forgerock.json.resource.ResourceException)37