Search in sources :

Example 1 with UserIdentityPair

use of io.cdap.cdap.security.auth.UserIdentityPair in project cdap by caskdata.

the class AuthenticationHandler method channelRead.

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof HttpRequest)) {
        ctx.fireChannelRead(msg);
        return;
    }
    HttpRequest request = (HttpRequest) msg;
    // Pass if security is bypassed or it has valid access token, process to the next handler
    if (isBypassed(request)) {
        ctx.fireChannelRead(msg);
        return;
    }
    UserIdentityExtractionResponse extractionResponse = userIdentityExtractor.extract(request);
    if (extractionResponse.success()) {
        UserIdentityPair userIdentityPair = extractionResponse.getIdentityPair();
        // User identity extraction succeeded, so set some header properties and allow the call through
        request.headers().remove(HttpHeaderNames.AUTHORIZATION);
        Credential credential = getUserCredential(userIdentityPair);
        // For backwards compatibility, we continue propagating credentials by default. This may change in the future.
        if (cConf.getBoolean(Constants.Security.Authentication.PROPAGATE_USER_CREDENTIAL, true) && credential != null) {
            request.headers().set(Constants.Security.Headers.RUNTIME_TOKEN, String.format("%s %s", credential.getType().getQualifiedName(), credential.getValue()));
        }
        request.headers().set(Constants.Security.Headers.USER_ID, userIdentityPair.getUserIdentity().getUsername());
        String clientIP = Networks.getIP(ctx.channel().remoteAddress());
        if (clientIP != null) {
            request.headers().set(Constants.Security.Headers.USER_IP, clientIP);
        }
        ctx.fireChannelRead(msg);
        return;
    }
    // Response with failure, plus optionally audit log
    try {
        HttpHeaders headers = new DefaultHttpHeaders();
        JsonObject jsonObject = new JsonObject();
        if (extractionResponse.getState().equals(UserIdentityExtractionState.ERROR_MISSING_CREDENTIAL)) {
            headers.add(HttpHeaderNames.WWW_AUTHENTICATE, String.format("Bearer realm=\"%s\"", realm));
            LOG.debug("Authentication failed due to missing credentials");
        } else {
            String shortError = extractionResponse.getState().toString();
            String errorDescription = extractionResponse.getErrorDescription();
            headers.add(HttpHeaderNames.WWW_AUTHENTICATE, String.format("Bearer realm=\"%s\" error=\"%s\" error_description=\"%s\"", realm, shortError, errorDescription));
            jsonObject.addProperty("error", shortError);
            jsonObject.addProperty("error_description", errorDescription);
            LOG.debug("Authentication failed due to error {}, reason={};", shortError, errorDescription);
        }
        jsonObject.add("auth_uri", getAuthenticationURLs());
        ByteBuf content = Unpooled.copiedBuffer(jsonObject.toString(), StandardCharsets.UTF_8);
        HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED, content);
        HttpUtil.setContentLength(response, content.readableBytes());
        HttpUtil.setKeepAlive(response, false);
        response.headers().setAll(headers);
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json;charset=UTF-8");
        auditLogIfNeeded(request, response, ctx.channel());
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    } finally {
        ReferenceCountUtil.release(msg);
    }
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) Credential(io.cdap.cdap.proto.security.Credential) UserIdentityExtractionResponse(io.cdap.cdap.security.auth.UserIdentityExtractionResponse) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) JsonObject(com.google.gson.JsonObject) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) UserIdentityPair(io.cdap.cdap.security.auth.UserIdentityPair) ByteBuf(io.netty.buffer.ByteBuf)

Example 2 with UserIdentityPair

use of io.cdap.cdap.security.auth.UserIdentityPair in project cdap by caskdata.

the class MockAccessTokenIdentityExtractor method extract.

@Override
public UserIdentityExtractionResponse extract(HttpRequest request) throws UserIdentityExtractionException {
    String auth = request.headers().get(HttpHeaderNames.AUTHORIZATION);
    String accessToken = null;
    if (auth != null) {
        int idx = auth.trim().indexOf(' ');
        if (idx < 0) {
            return new UserIdentityExtractionResponse(UserIdentityExtractionState.ERROR_MISSING_CREDENTIAL, "No access token found");
        }
        accessToken = auth.substring(idx + 1).trim();
    }
    if (accessToken == null || accessToken.length() == 0) {
        return new UserIdentityExtractionResponse(UserIdentityExtractionState.ERROR_MISSING_CREDENTIAL, "No access token found");
    }
    TokenState state = validator.validate(accessToken);
    if (!state.isValid()) {
        return new UserIdentityExtractionResponse(UserIdentityExtractionState.ERROR_INVALID_TOKEN, String.format("Failed to validate access token with reason: %s", state));
    }
    UserIdentityPair pair = new UserIdentityPair(accessToken, new UserIdentity("dummy", UserIdentity.IdentifierType.EXTERNAL, new LinkedHashSet<>(), System.currentTimeMillis(), System.currentTimeMillis() + 100000));
    return new UserIdentityExtractionResponse(pair);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) UserIdentityExtractionResponse(io.cdap.cdap.security.auth.UserIdentityExtractionResponse) UserIdentity(io.cdap.cdap.security.auth.UserIdentity) UserIdentityPair(io.cdap.cdap.security.auth.UserIdentityPair) TokenState(io.cdap.cdap.security.auth.TokenState)

Aggregations

UserIdentityExtractionResponse (io.cdap.cdap.security.auth.UserIdentityExtractionResponse)2 UserIdentityPair (io.cdap.cdap.security.auth.UserIdentityPair)2 JsonObject (com.google.gson.JsonObject)1 Credential (io.cdap.cdap.proto.security.Credential)1 TokenState (io.cdap.cdap.security.auth.TokenState)1 UserIdentity (io.cdap.cdap.security.auth.UserIdentity)1 ByteBuf (io.netty.buffer.ByteBuf)1 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)1 DefaultHttpHeaders (io.netty.handler.codec.http.DefaultHttpHeaders)1 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)1 HttpRequest (io.netty.handler.codec.http.HttpRequest)1 HttpResponse (io.netty.handler.codec.http.HttpResponse)1 LinkedHashSet (java.util.LinkedHashSet)1