mirror of
https://github.com/casdoor/casdoor.git
synced 2025-05-23 18:54:03 +08:00
fix: support using bearer token to access protected resources (#364)
* fix: require signed in by bearer token. Signed-off-by: 0x2a <stevesough@gmail.com> * fix: utilize existing code refactoring functions Signed-off-by: 0x2a <stevesough@gmail.com> * fix: improve the bearer parese function Signed-off-by: 0x2a <stevesough@gmail.com>
This commit is contained in:
parent
589c0404d2
commit
00ab156453
@ -62,4 +62,12 @@ func AutoSigninFilter(ctx *context.Context) {
|
|||||||
setSessionUser(ctx, userId)
|
setSessionUser(ctx, userId)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//Bearer token
|
||||||
|
//headers: {"Authorization":accessToken}
|
||||||
|
if claims, ok := parseBearer(ctx); ok {
|
||||||
|
setSessionUser(ctx, fmt.Sprintf("%s/%s", claims.Owner, claims.Name))
|
||||||
|
setSessionExpire(ctx, claims.ExpiresAt.Unix())
|
||||||
|
return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -16,9 +16,11 @@ package routers
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/astaxie/beego/context"
|
"github.com/astaxie/beego/context"
|
||||||
"github.com/casbin/casdoor/object"
|
"github.com/casbin/casdoor/object"
|
||||||
|
"github.com/casbin/casdoor/util"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Response struct {
|
type Response struct {
|
||||||
@ -85,3 +87,29 @@ func setSessionUser(ctx *context.Context, user string) {
|
|||||||
// https://github.com/beego/beego/issues/3445#issuecomment-455411915
|
// https://github.com/beego/beego/issues/3445#issuecomment-455411915
|
||||||
ctx.Input.CruSession.SessionRelease(ctx.ResponseWriter)
|
ctx.Input.CruSession.SessionRelease(ctx.ResponseWriter)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func setSessionExpire(ctx *context.Context, ExpireTime int64) {
|
||||||
|
SessionData := struct{ ExpireTime int64 }{ExpireTime: ExpireTime}
|
||||||
|
err := ctx.Input.CruSession.Set("SessionData", util.StructToJson(SessionData))
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
ctx.Input.CruSession.SessionRelease(ctx.ResponseWriter)
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseBearer(ctx *context.Context) (*object.Claims, bool) {
|
||||||
|
bearer := ctx.Request.Header.Get("Authorization")
|
||||||
|
bearerList := strings.Split(bearer, " ")
|
||||||
|
if len(bearerList) != 2 {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
prefix := bearerList[0]
|
||||||
|
if prefix != "Bearer" {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
claims, err := object.ParseJwtToken(bearerList[1])
|
||||||
|
if err != nil {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
return claims, true
|
||||||
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user