All Projects → majusko → grpc-jwt-spring-boot-starter

majusko / grpc-jwt-spring-boot-starter

Licence: other
Spring boot starter for gRPC framework with JWT authorization

Programming Languages

java
68154 projects - #9 most used programming language

Projects that are alternatives of or similar to grpc-jwt-spring-boot-starter

grpc-apm-spring-boot-starter
Spring boot starter for gRPC framework with Elastic APM
Stars: ✭ 18 (-25%)
Mutual labels:  interceptor, grpc-framework, grpc-java, grpc-library, springboot-starter
Grpc Spring Boot Starter
Spring Boot starter module for gRPC framework.
Stars: ✭ 2,190 (+9025%)
Mutual labels:  grpc, grpc-framework, grpc-java
xrgrpc
gRPC library for Cisco IOS XR
Stars: ✭ 40 (+66.67%)
Mutual labels:  protobuf, grpc, grpc-library
grpc-spring-security-demo
Spring Boot-based gRPC server with gRPC endpoints secured by Spring Security
Stars: ✭ 50 (+108.33%)
Mutual labels:  protobuf, grpc, grpc-java
Rules protobuf
Bazel rules for building protocol buffers and gRPC services (java, c++, go, ...)
Stars: ✭ 206 (+758.33%)
Mutual labels:  protobuf, grpc
protoc-plugin
A protoc compiler plugin for Clojure applications
Stars: ✭ 28 (+16.67%)
Mutual labels:  protobuf, grpc
qtprotobuf
Protobuf generator and bindings for Qt framework
Stars: ✭ 138 (+475%)
Mutual labels:  protobuf, grpc
compatip
A simple tool to ensure compatibility between microservices
Stars: ✭ 13 (-45.83%)
Mutual labels:  protobuf, grpc
Go Grpc Examples
This repo contains examples and implementations of different types of GRPC services and APIs using Golang.
Stars: ✭ 180 (+650%)
Mutual labels:  protobuf, grpc
go2gql
graphql-go schema generator by proto files
Stars: ✭ 33 (+37.5%)
Mutual labels:  protobuf, proto
zf-dependency-injection
Advanced dependency injection for laminas framework
Stars: ✭ 17 (-29.17%)
Mutual labels:  annotations, autowire
Istio Micro
istio 微服务示例代码 grpc+protobuf+echo+websocket+mysql+redis+kafka+docker-compose
Stars: ✭ 194 (+708.33%)
Mutual labels:  protobuf, grpc
Grpc Kotlin
gRPC with Kotlin Coroutines
Stars: ✭ 190 (+691.67%)
Mutual labels:  protobuf, grpc
Clay
Proto-first minimal server platform for gRPС+REST+Swagger APIs
Stars: ✭ 212 (+783.33%)
Mutual labels:  protobuf, grpc
Buildbuddy
BuildBuddy is an open source Bazel build event viewer, result store, and remote cache.
Stars: ✭ 182 (+658.33%)
Mutual labels:  protobuf, grpc
go-grpcmw
A Go package and protobuf generator for managing grpc interceptors.
Stars: ✭ 19 (-20.83%)
Mutual labels:  protobuf, interceptor
karate-grpc
gRPC Testing Made Simple by Karate
Stars: ✭ 43 (+79.17%)
Mutual labels:  protobuf, grpc-java
FSharp.GrpcCodeGenerator
A protoc plugin to enable generation of F# code
Stars: ✭ 61 (+154.17%)
Mutual labels:  protobuf, grpc
grphp
PHP gRPC Framework
Stars: ✭ 19 (-20.83%)
Mutual labels:  protobuf, grpc
Makeaplan public
【制定一个计划】是一个目标规划应用,通过最直接,最清晰的方式帮助你记录和追踪自己的计划,辅助你达成自己的目标。
Stars: ✭ 174 (+625%)
Mutual labels:  protobuf, grpc

Spring boot starter for gRPC framework with JWT authorization - gRPC Java JWT

Maven Central Release Build Status Test Coverage License: MIT Join the chat at https://gitter.im/grpc-jwt-spring-boot-starter/community

Extending great gRPC library with Auth module. Easy implementation using a simple annotations similar to ones used in Spring Security module.

Quick Start

(Try example project: gRPC example project in Kotlin.)

Simple start consist only from 3 simple steps.

(If you never used gRPC library before, have a look on this basic setup first.)

1. Add Maven dependency

<dependency>
  <groupId>io.github.majusko</groupId>
  <artifactId>grpc-jwt-spring-boot-starter</artifactId>
  <version>${version}</version>
</dependency>

2. Add @Allow annotation to your service method

All you need to do is to annotate your method in the service implementation.

@GRpcService
public class ExampleServiceImpl extends ExampleServiceGrpc.ExampleServiceImplBase {

    @Allow(roles = GrpcRole.INTERNAL)
    public void getExample(GetExample request, StreamObserver<Empty> response) {
        //...
    }
}

3. Add interceptor to client

Just autowire already prepared AuthClientInterceptor bean and intercept your client. It will inject the internal token to every request by default.

@Service
public class ExampleClient {

    @Autowired
    private AuthClientInterceptor authClientInterceptor;

    public void exampleRequest() {
        final ManagedChannel channel = ManagedChannelBuilder.forTarget(target).usePlaintext().build();
        final Channel interceptedChannel = ClientInterceptors.intercept(channel,authClientInterceptor);
        final ExampleServiceBlockingStub stub = ExampleServiceGrpc.newBlockingStub(interceptedChannel);
        
        stub.getExample(GetExample.newBuilder().build());
    }
}

Documentation

0. Basic setup of gRPC

Useful only in case you never heard about gRPC library from LogNet. You can find there a nice show case too.

0.1 Service implementation

The service definition from .proto file looks like this

service ExampleService {
    rpc GetExample (GetExample) returns (Empty) {};
}

message Empty {}
message GetExample {
    string ownerField = 1;
}

0.2 Service implementation

All you need to do is to annotate your service implementation with GRpcService

@GRpcService
public class ExampleServiceImpl extends ExampleServiceGrpc.ExampleServiceImplBase {

    public void getExample(GetExample request, StreamObserver<Empty> response) {
        response.onNext(Empty.newBuilder().build());
        response.onCompleted();
    }
}

1. Configuration

You can use application.properties to override the default configuration.

  • grpc.jwt.algorithm -> Algorithm used for signing the JWT token. Default: HmacSHA256
  • grpc.jwt.secret -> String used as a secret to sign the JWT token. Default: default
  • grpc.jwt.expirationSec -> Number of seconds needed to token becoming expired. Default: 3600
grpc.jwt.algorithm=HmacSHA256
grpc.jwt.secret=secret
grpc.jwt.expirationSec=3600

2. Annotations

We know 2 types of annotation: @Allow and @Expose

@Allow

  • roles -> Algorithm used for signing the JWT token. Default: HmacSHA256
  • ownerField -> Example: ownerField. Optional field. Your request will be parsed and if the mentioned field is found, it will compare equality with JWT token subject(e.g.: ownerField). By this comparison, you can be sure that any operation with that field is made by the owner of the token. If the fields don't match and data are owned by another user, specified roles will be checked after.

Example use case of ownerField: Imagine, you want to list purchased orders of some user. You might want to reuse the exact same API for back-office and also for that particular user who created the orders. With ownerField you can check for the owner and also for some role if owner ownerField in JWT token is different.

@Exposed

  • environments List of environments (Spring Profiles) where you can access the gRPC without checking for owner or roles. Use case: Debug endpoint for the client/front-end development team.
@GRpcService
public class ExampleServiceImpl extends ExampleServiceGrpc.ExampleServiceImplBase {

    @Allow(ownerField="ownerField", roles = GrpcRole.INTERNAL)
    @Exposed(environments={"dev","qa"})
    public void getExample(GetExample request, StreamObserver<Empty> response) {
        //...
    }
}

Token generation

You will need to generate tokens for your users or clients. You might want to specify special roles for each user and also service method. You can use the JwtService for simple and performing usage.

@Service
public class SomeClass {

    private final static String ADMIN = "admin";

    @Autowired
    private JwtService jwtService;

    public void someMethod() {
        final JwtData data = new JwtData("user-id-12345", new HashSet<>(ADMIN));

        final String token = jwtService.generate(data);
    }
}

Making requests

We have two types of usages for client.

  1. Inter-service communication.
  2. User communication.

1. Client for inter-service communication only.

  • Autowire AuthClientInterceptor to your service.
  • Register your interceptor with native ClientInterceptors class.
  • Call request from gRPC generated stub.
@Service
public class SomeClass {

    @Autowired
    private AuthClientInterceptor authClientInterceptor;

    public void customTokenRequest() {

        final ManagedChannel channel = ManagedChannelBuilder.forTarget(target).usePlaintext().build();
        final Channel interceptedChannel = ClientInterceptors.intercept(channel,authClientInterceptor);
        final ExampleServiceBlockingStub stub = ExampleServiceGrpc.newBlockingStub(interceptedChannel);

        final Empty response = stub.getExample(GetExample.newBuilder().setUserId("user-id-jr834fh").build());
    }
}

2. Client for custom token communication.

  • Add your token generated with JwtService to gRPC header with GrpcHeader.AUTHORIZATION
  • Call request from gRPC generated stub.
@Service
public class SomeClass {

    public void customTokenRequest() {

        final Metadata header = new Metadata();
        header.put(GrpcHeader.AUTHORIZATION, "jwt-token-r348hf34hf43f93");

        final ManagedChannel channel = ManagedChannelBuilder.forTarget(target).usePlaintext().build();
        final ExampleServiceBlockingStub stub = ExampleServiceGrpc.newBlockingStub(channel);
        final ExampleServiceBlockingStub stubWithHeaders = MetadataUtils.attachHeaders(stub, header);

        final Empty response = stub.getExample(GetExample.newBuilder().setUserId("user-id-jr834fh").build());
    }
}

Tests

The library is fully covered with integration tests which are also very useful as a usage example.

GrpcJwtSpringBootStarterApplicationTest

Contributing

All contributors are welcome. If you never contributed to the open-source, start with reading the Github Flow.

  1. Create an issue
  2. Create a pull request with reference to the issue
  3. Rest and enjoy the great feeling of being a contributor.
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].