gin-server/examples/server.go

58 lines
1.2 KiB
Go
Raw Normal View History

2016-09-25 20:08:45 +08:00
package main
import (
2021-08-22 01:00:58 +08:00
ginserver "gin-server"
2016-09-25 20:08:45 +08:00
"net/http"
2021-08-22 01:00:58 +08:00
"gitee.ltd/go-oauth2/gin-server"
2016-09-25 20:08:45 +08:00
"github.com/gin-gonic/gin"
2021-08-22 01:00:58 +08:00
"github.com/go-oauth2/oauth2/v4/manage"
"github.com/go-oauth2/oauth2/v4/models"
"github.com/go-oauth2/oauth2/v4/server"
"github.com/go-oauth2/oauth2/v4/store"
2016-09-25 20:08:45 +08:00
)
func main() {
manager := manage.NewDefaultManager()
2016-11-29 09:08:31 +08:00
2016-09-25 20:08:45 +08:00
// token store
2019-01-19 13:29:36 +08:00
manager.MustTokenStorage(store.NewFileTokenStore("data.db"))
2016-11-29 09:08:31 +08:00
2016-09-25 20:08:45 +08:00
// client store
2016-11-29 09:08:31 +08:00
clientStore := store.NewClientStore()
clientStore.Set("000000", &models.Client{
ID: "000000",
2016-09-25 20:08:45 +08:00
Secret: "999999",
2016-11-29 09:08:31 +08:00
Domain: "http://localhost",
})
manager.MapClientStorage(clientStore)
2016-09-25 20:08:45 +08:00
// Initialize the oauth2 service
2019-01-19 13:29:36 +08:00
ginserver.InitServer(manager)
ginserver.SetAllowGetAccessRequest(true)
ginserver.SetClientInfoHandler(server.ClientFormHandler)
2016-09-25 20:08:45 +08:00
2016-11-29 09:08:31 +08:00
g := gin.Default()
auth := g.Group("/oauth2")
{
2019-01-19 13:29:36 +08:00
auth.GET("/token", ginserver.HandleTokenRequest)
2016-11-29 09:08:31 +08:00
}
2016-09-25 20:08:45 +08:00
2016-11-29 09:08:31 +08:00
api := g.Group("/api")
{
2019-01-19 13:29:36 +08:00
api.Use(ginserver.HandleTokenVerify())
2016-11-29 09:08:31 +08:00
api.GET("/test", func(c *gin.Context) {
2019-01-19 13:29:36 +08:00
ti, exists := c.Get(ginserver.DefaultConfig.TokenKey)
2016-11-29 09:08:31 +08:00
if exists {
c.JSON(http.StatusOK, ti)
return
}
c.String(http.StatusOK, "not found")
})
}
g.Run(":9096")
2016-09-25 20:08:45 +08:00
}