近期正在探索前端、后端、系统端各类常用组件与工具,对其一些常见的组件进行再次整理一下,形成标准化组件专题,后续该专题将包含各类语言中的一些常用组件。
本节我们分享一个在gin中有效使用go-oauth2的组件gin-server,在使用go-oauth2组件时内置的使用方式是golang原生的web服务,很多时候我们都使用到gin框架作为web开发框架,今天分享的这个组件就可以让我们更加丝滑的在gin中使用go-oauth2组件,注意这里gin-server中使用的v3版本,我看了下源码,可以直接将其几个实现的源码文件进行更改,直接在v4中使用。 下面是其提供的使用方式: 1、安装
go get -u github.com/go-oauth2/gin-server
2、使用案例
package main
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-oauth2/gin-server"
"gopkg.in/oauth2.v3/manage"
"gopkg.in/oauth2.v3/models"
"gopkg.in/oauth2.v3/server"
"gopkg.in/oauth2.v3/store"
)
func main() {
manager := manage.NewDefaultManager()
// token store
manager.MustTokenStorage(store.NewFileTokenStore("data.db"))
// client store
clientStore := store.NewClientStore()
clientStore.Set("000000", &models.Client{
ID: "000000",
Secret: "999999",
Domain: "http://localhost",
})
manager.MapClientStorage(clientStore)
// Initialize the oauth2 service
ginserver.InitServer(manager)
ginserver.SetAllowGetAccessRequest(true)
ginserver.SetClientInfoHandler(server.ClientFormHandler)
g := gin.Default()
auth := g.Group("/oauth2")
{
auth.GET("/token", ginserver.HandleTokenRequest)
}
api := g.Group("/api")
{
api.Use(ginserver.HandleTokenVerify())
api.GET("/test", func(c *gin.Context) {
ti, exists := c.Get(ginserver.DefaultConfig.TokenKey)
if exists {
c.JSON(http.StatusOK, ti)
return
}
c.String(http.StatusOK, "not found")
})
}
g.Run(":9096")
}
更多使用说明,可以参考其官方提供的中文README
本作品由 cn華少 采用 知识共享署名-非商业性使用 4.0 国际许可协议 进行许可。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有