All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.sitewhere.grpc.client.JwtClientInterceptor Maven / Gradle / Ivy

There is a newer version: 3.0.13
Show newest version
/*
 * Copyright (c) SiteWhere, LLC. All rights reserved. http://www.sitewhere.com
 *
 * The software in this package is published under the terms of the CPAL v1.0
 * license, a copy of which has been included with this distribution in the
 * LICENSE.txt file.
 */
package com.sitewhere.grpc.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sitewhere.microservice.grpc.GrpcKeys;
import com.sitewhere.microservice.security.SiteWhereAuthentication;
import com.sitewhere.microservice.security.UserContext;

import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;

/**
 * GRPC interceptor that pushes JWT from Spring Security credentials into call
 * metadata.
 */
public class JwtClientInterceptor implements ClientInterceptor {

    /** Static logger instance */
    private static Logger LOGGER = LoggerFactory.getLogger(JwtClientInterceptor.class);

    /*
     * (non-Javadoc)
     * 
     * @see io.grpc.ClientInterceptor#interceptCall(io.grpc.MethodDescriptor,
     * io.grpc.CallOptions, io.grpc.Channel)
     */
    @Override
    public  ClientCall interceptCall(MethodDescriptor method,
	    CallOptions callOptions, Channel next) {
	LOGGER.trace("Intercepting client call...");
	return new SimpleForwardingClientCall(next.newCall(method, callOptions)) {

	    /*
	     * (non-Javadoc)
	     * 
	     * @see io.grpc.ForwardingClientCall#start(io.grpc.ClientCall.Listener,
	     * io.grpc.Metadata)
	     */
	    @Override
	    public void start(Listener responseListener, Metadata headers) {
		SiteWhereAuthentication authentication = UserContext.getCurrentUser();
		if (authentication == null) {
		    throw new RuntimeException("Attempting to make remote call with no user context.");
		}
		String jwt = authentication.getJwt();
		if (jwt == null) {
		    throw new RuntimeException("Attempting to make remote call with no JWT provided.");
		}
		LOGGER.trace("Adding JWT into gRPC headers: " + jwt);
		headers.put(GrpcKeys.JWT_KEY, jwt);
		super.start(responseListener, headers);
	    }
	};
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy