Generate real access token.

This commit is contained in:
Yang Luo 2021-03-14 22:48:09 +08:00
parent 1fd6ee388c
commit f014554415
8 changed files with 115 additions and 10 deletions

View File

@ -70,13 +70,14 @@ func (c *ApiController) DeleteToken() {
}
func (c *ApiController) GetOAuthCode() {
userId := c.GetSessionUser()
clientId := c.Input().Get("client_id")
responseType := c.Input().Get("response_type")
redirectUri := c.Input().Get("redirect_uri")
scope := c.Input().Get("scope")
state := c.Input().Get("state")
c.Data["json"] = object.GetOAuthCode(clientId, responseType, redirectUri, scope, state)
c.Data["json"] = object.GetOAuthCode(userId, clientId, responseType, redirectUri, scope, state)
c.ServeJSON()
}

1
go.mod
View File

@ -6,6 +6,7 @@ require (
github.com/astaxie/beego v1.12.3
github.com/casbin/casbin/v2 v2.23.4
github.com/casbin/xorm-adapter/v2 v2.2.0
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/go-sql-driver/mysql v1.5.0
github.com/google/uuid v1.2.0
github.com/qiangmzsx/string-adapter/v2 v2.1.0

2
go.sum
View File

@ -41,6 +41,8 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/denisenkom/go-mssqldb v0.0.0-20200428022330-06a60b6afbbc/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M=
github.com/elastic/go-elasticsearch/v6 v6.8.5/go.mod h1:UwaDJsD3rWLM5rKNFzv9hgox93HoX8utj1kxD9aFUcI=
github.com/elazarl/go-bindata-assetfs v1.0.0 h1:G/bYguwHIzWq9ZoyUQqrjTmJbbYn3j3CKKpKinvZLFk=

View File

@ -33,9 +33,10 @@ type Application struct {
Providers []string `xorm:"varchar(100)" json:"providers"`
ProviderObjs []*Provider `xorm:"-" json:"providerObjs"`
ClientId string `xorm:"varchar(100)" json:"clientId"`
ClientSecret string `xorm:"varchar(100)" json:"clientSecret"`
RedirectUrls []string `xorm:"varchar(1000)" json:"redirectUrls"`
ClientId string `xorm:"varchar(100)" json:"clientId"`
ClientSecret string `xorm:"varchar(100)" json:"clientSecret"`
RedirectUrls []string `xorm:"varchar(1000)" json:"redirectUrls"`
ExpireInHours int `json:"expireInHours"`
}
func GetApplications(owner string) []*Application {

View File

@ -123,7 +123,22 @@ func DeleteToken(token *Token) bool {
return affected != 0
}
func GetOAuthCode(clientId string, responseType string, redirectUri string, scope string, state string) *Code {
func GetOAuthCode(userId string, clientId string, responseType string, redirectUri string, scope string, state string) *Code {
if userId == "" {
return &Code{
Message: "please sign in first",
Code: "",
}
}
user := GetUser(userId)
if user == nil {
return &Code{
Message: "invalid user_id",
Code: "",
}
}
application := getApplicationByClientId(clientId)
if application == nil {
return &Code{
@ -153,14 +168,19 @@ func GetOAuthCode(clientId string, responseType string, redirectUri string, scop
}
}
accessToken, err := generateJwtToken(application, user)
if err != nil {
panic(err)
}
token := &Token{
Owner: application.Owner,
Name: util.GenerateId(),
CreatedTime: util.GetCurrentTime(),
Application: application.Name,
Code: util.GenerateClientId(),
AccessToken: "",
ExpiresIn: 7200,
AccessToken: accessToken,
ExpiresIn: application.ExpireInHours * 60,
Scope: scope,
TokenType: "Bearer",
}

69
object/token_jwt.go Normal file
View File

@ -0,0 +1,69 @@
// Copyright 2021 The casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package object
import (
"time"
"github.com/dgrijalva/jwt-go"
)
var jwtSecret = []byte("aaa")
type Claims struct {
Username string `json:"username"`
Name string `json:"name"`
Email string `json:"email"`
jwt.StandardClaims
}
func generateJwtToken(application *Application, user *User) (string, error) {
nowTime := time.Now()
expireTime := nowTime.Add(time.Duration(application.ExpireInHours) * time.Hour)
claims := Claims{
Username: user.Name,
Name: user.DisplayName,
Email: user.Email,
StandardClaims: jwt.StandardClaims{
Audience: application.ClientId,
ExpiresAt: expireTime.Unix(),
Id: "",
IssuedAt: nowTime.Unix(),
Issuer: "casdoor",
NotBefore: nowTime.Unix(),
Subject: user.Id,
},
}
tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
token, err := tokenClaims.SignedString(jwtSecret)
return token, err
}
func parseJwtToken(token string) (*Claims, error) {
tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
return jwtSecret, nil
})
if tokenClaims != nil {
if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
return claims, nil
}
}
return nil, err
}

View File

@ -71,9 +71,9 @@ class ApplicationEditPage extends React.Component {
}
parseApplicationField(key, value) {
// if ([].includes(key)) {
// value = Setting.myParseInt(value);
// }
if (["expireInHours"].includes(key)) {
value = Setting.myParseInt(value);
}
return value;
}
@ -206,6 +206,16 @@ class ApplicationEditPage extends React.Component {
/>
</Col>
</Row>
<Row style={{marginTop: '20px'}} >
<Col style={{marginTop: '5px'}} span={2}>
{i18next.t("general:Expire In Hours")}:
</Col>
<Col span={22} >
<Input value={this.state.application.expireInHours} onChange={e => {
this.updateApplicationField('expireInHours', e.target.value);
}} />
</Col>
</Row>
<Row style={{marginTop: '20px'}} >
<Col style={{marginTop: '5px'}} span={2}>
{i18next.t("application:Enable Password")}:

View File

@ -52,6 +52,7 @@ class ApplicationListPage extends React.Component {
EnablePassword: true,
providers: [],
redirectUrls: [],
expireInHours: 24 * 7,
}
}