Last active
April 24, 2019 15:24
-
-
Save zacksleo/0607c81ff5a427ed16683c479e2d97e3 to your computer and use it in GitHub Desktop.
create oauth2 server by gin & go-oauth2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package controllers | |
import ( | |
"fmt" | |
"log" | |
"os" | |
"github.com/project/db" | |
model "github.com/project/models" | |
"github.com/gin-gonic/gin" | |
mysql "gopkg.in/go-oauth2/mysql.v3" | |
"gopkg.in/oauth2.v3/manage" | |
"gopkg.in/oauth2.v3/models" | |
"gopkg.in/oauth2.v3/server" | |
"gopkg.in/oauth2.v3/store" | |
// mysql | |
_ "github.com/go-sql-driver/mysql" | |
) | |
// CreateToken get tokens | |
func CreateToken(c *gin.Context) { | |
manager := manage.NewDefaultManager() | |
// use mysql token store | |
tStore := mysql.NewDefaultStore( | |
mysql.NewConfig(os.Getenv("DATABASE_URL")), | |
) | |
defer tStore.Close() | |
manager.MapTokenStorage(tStore) | |
clientStore := store.NewClientStore() | |
clientID := os.Getenv("CLIENT_ID") | |
clientSecret := os.Getenv("CLIENT_SECRET") | |
clientStore.Set(clientID, &models.Client{ | |
ID: clientID, | |
Secret: clientSecret, | |
Domain: "http://localhost", | |
}) | |
manager.MapClientStorage(clientStore) | |
// Initialize the oauth2 service | |
srv := server.NewDefaultServer(manager) | |
srv.SetClientInfoHandler(server.ClientFormHandler) | |
srv.SetPasswordAuthorizationHandler(func(username string, password string) (userID string, err error) { | |
admin := model.Admin{} | |
db := db.DBInstance(c) | |
if err := db.Where("username = ?", username).First(&admin).Error; err != nil { | |
err = fmt.Errorf("user not found") | |
} | |
if admin.ValidatePassword(password) { | |
log.Println(username) | |
userID = username | |
return | |
} | |
err = fmt.Errorf("密码不正确") | |
return | |
}) | |
//ginserver.InitServer(manager) | |
//srv.SetAllowedGrantType(oauth2.PasswordCredentials) | |
srv.HandleTokenRequest(c.Writer, c.Request) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment