golang OAuth2服务端及客户端编写示例

服务端实现

  1. 从OAuth2库导入相关的包:
import (
    "golang.org/x/oauth2"
    "golang.org/x/oauth2/google"
)
  1. 定义OAuth2认证的配置:
var (
    googleOauthConfig *oauth2.Config
    oauthStateString = "random_string"
)

func init() {
    googleOauthConfig = &oauth2.Config{
        RedirectURL: "http://localhost:8080/oauth2callback",
        ClientID: "<client_id>",
        ClientSecret: "<client_secret>",
        Scopes: []string{"https://www.googleapis.com/auth/userinfo.profile"},
        Endpoint: google.Endpoint,
    }
}
  1. 编写HTTP处理程序:
func HandleHome(w http.ResponseWriter, r *http.Request) {
    var html = `
        <html>
            <body>
                <a href="%s">Google Login</a>
            </body>
        </html>
    `
    fmt.Fprintf(w, html, GetLoginURL(oauthStateString))
}

func GetLoginURL(state string) string {
    return googleOauthConfig.AuthCodeURL(state)
}

func HandleOAuth2Callback(w http.ResponseWriter, r *http.Request) {
    state := r.FormValue("state")
    if state != oauthStateString {
        fmt.Printf("invalid OAuth state, expected '%s', got '%s'\n", oauthStateString, state)
        http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
        return
    }

    code := r.FormValue("code")
    token, err := googleOauthConfig.Exchange(oauth2.NoContext, code)
    if err != nil {
        fmt.Printf("oauth2: %s", err.Error())
        http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
        return
    }

    client := googleOauthConfig.Client(oauth2.NoContext, token)
    resp, err := client.Get("https://www.googleapis.com/oauth2/v2/userinfo")
    if err != nil {
        fmt.Printf("Get: %s", err.Error())
        http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
        return
    }

    defer resp.Body.Close()

    contents, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Printf("ReadAll: %s", err.Error())
        http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
        return
    }

    fmt.Fprintf(w, "Content: %s\n", contents)
}
  1. 启动服务端监听:
http.HandleFunc("/", HandleHome)
http.HandleFunc("/oauth2callback", HandleOAuth2Callback)
http.ListenAndServe(":8080", nil)

客户端实现

  1. 创建OAuth2配置:
var (
    googleOauthConfig *oauth2.Config
)

func init() {
    googleOauthConfig = &oauth2.Config{
        ClientID: "<client_id>",
        ClientSecret: "<client_secret>",
        RedirectURL: "http://localhost:9000/oauth2callback",
        Scopes: []string{
            "https://www.googleapis.com/auth/userinfo.email",
            "https://www.googleapis.com/auth/userinfo.profile",
        },
        Endpoint: google.Endpoint,
    }
}
  1. 发起OAuth2授权请求:
func HandleGoogleLogin(w http.ResponseWriter, r *http.Request) {
    url := googleOauthConfig.AuthCodeURL("state")
    http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
  1. 处理OAuth2回调:
func HandleGoogleCallback(w http.ResponseWriter, r *http.Request) {
    code := r.FormValue("code")
    token, err := googleOauthConfig.Exchange(oauth2.NoContext, code)
    if err != nil {
        fmt.Fprintln(w, err)
        return
    }
    client := googleOauthConfig.Client(oauth2.NoContext, token)
    resp, err := client.Get("https://www.googleapis.com/oauth2/v2/userinfo")
    if err != nil {
        fmt.Fprintln(w, err)
        return
    }
    defer resp.Body.Close()
    contents, err := ioutil.ReadAll(resp.Body)
    fmt.Fprintf(w, "Content: %s\n", contents)
}

启动客户端:

http.HandleFunc("/login/google", HandleGoogleLogin)
http.HandleFunc("/oauth2callback", HandleGoogleCallback)
log.Fatal(http.ListenAndServe(":9000", nil))
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
首先,需要安装gRPC和protobuf。可以使用以下命令: ``` go get -u google.golang.org/grpc go get -u github.com/golang/protobuf/proto go get -u github.com/golang/protobuf/protoc-gen-go ``` 接下来,我们需要定义protobuf文件,其中包含服务的RPC方法和消息格式,例如: ``` syntax = "proto3"; package myservice; message Request { string message = 1; } message Response { string message = 1; } service MyService { rpc SayHello(Request) returns (Response) {} } ``` 然后,使用以下命令将protobuf文件编译为Go代码: ``` protoc --go_out=plugins=grpc:. myservice.proto ``` 这将生成myservice.pb.go文件。 接下来,我们需要实现gRPC服务端客户端。以下是一个简单的示例服务端: ``` package main import ( "log" "net" "google.golang.org/grpc" pb "path/to/myservice" ) type myServiceServer struct{} func (s *myServiceServer) SayHello(ctx context.Context, req *pb.Request) (*pb.Response, error) { log.Printf("Received message: %v", req.Message) return &pb.Response{Message: "Hello " + req.Message}, 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, &myServiceServer{}) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } } ``` 客户端: ``` package main import ( "log" "golang.org/x/net/context" "google.golang.org/grpc" pb "path/to/myservice" ) func main() { conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure()) if err != nil { log.Fatalf("failed to connect: %v", err) } defer conn.Close() c := pb.NewMyServiceClient(conn) res, err := c.SayHello(context.Background(), &pb.Request{Message: "World"}) if err != nil { log.Fatalf("failed to call SayHello: %v", err) } log.Printf("Response message: %v", res.Message) } ``` 运行服务端客户端,即可进行gRPC通信。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值