Giter Club home page Giter Club logo

Comments (7)

simeng-li avatar simeng-li commented on June 19, 2024 1

@xiaoyijun do you mind taking a look at it?

from logto.

Gictorbit avatar Gictorbit commented on June 19, 2024

you might also check grpc-gateway
https://github.com/grpc-ecosystem/grpc-gateway

from logto.

xiaoyijun avatar xiaoyijun commented on June 19, 2024

Hi @Gictorbit ,
In web app frameworks, the user access token is passed by the HTTP request headers (Always Authorization header with Bearer <access_token> as its content).
In gRPC, you can retrieve the related header from the gRPC metadata (It's a supported feature, you can map HTTP headers to gRPC metadata, see Supported features).

image

from logto.

Gictorbit avatar Gictorbit commented on June 19, 2024

Hi @xiaoyijun xiaoyijun
Thank you for your response! I'm curious about Google OAuth. Does it utilize cookies or header tokens for authentication?
Could you please provide a code example using gRPC?

from logto.

xiaoyijun avatar xiaoyijun commented on June 19, 2024

@Gictorbit
Using OAuth only helps you obtain a token; how you use the obtained token depends on you (it can be in the cookie or the auth header).
If you want to protect your gRPC API, simply validate the token you obtained when the API receives a request (refer to https://docs.logto.io/docs/recipes/protect-your-api/).

This is a code example from ChatGPT (Note the 'Todo' comments):

  1. Client Code:
package main

import (
	"context"
	"log"

	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"

	pb "path/to/your/proto/package"
)

func main() {
	conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
	if err != nil {
		log.Fatalf("Failed to dial: %v", err)
	}
	defer conn.Close()

	client := pb.NewMyServiceClient(conn)

        // Todo: Get this token from OAuth service (Logto or Google OAuth)
	token := "your_token_here"
	ctx := metadata.AppendToOutgoingContext(context.Background(), "authorization", "Bearer "+token)

	response, err := client.MyRPCMethod(ctx, &pb.MyRequest{Message: "Hello!"})
	if err != nil {
		log.Fatalf("Failed to call MyRPCMethod: %v", err)
	}

	log.Printf("Response received: %s", response.Message)
}
  1. Server Code:
package main

import (
	"context"
	"log"
	"net"

	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"

	pb "path/to/your/proto/package"
)

type server struct{}

func (s *server) MyRPCMethod(ctx context.Context, req *pb.MyRequest) (*pb.MyResponse, error) {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		return nil, status.Errorf(codes.Unauthenticated, "missing metadata")
	}
	tokens := md.Get("authorization")
        // Todo: validate tokens before processing

	if len(tokens) == 0 {
		return nil, status.Errorf(codes.Unauthenticated, "missing token")
	}
	token := tokens[0]

	if token != "your_expected_token" {
		return nil, status.Errorf(codes.PermissionDenied, "invalid token")
	}

	return &pb.MyResponse{Message: "Hello back!"}, nil
}

func main() {
	lis, err := net.Listen("tcp", ":50051")
	if err != nil {
		log.Fatalf("Failed to listen: %v", err)
	}
	s := grpc.NewServer()
	pb.RegisterMyServiceServer(s, &server{})
	if err := s.Serve(lis); err != nil {
		log.Fatalf("Failed to serve: %v", err)
	}
}

Hope this helps!

from logto.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.