// @APIVersion 1.0.0// @Title 认证中心、用户中心// @Description token、用户、角色、权限package routersimport ( "zhsq_go/code" "zhsq_go/user_center/controllers" "zhsq_go/user_center/models" "github.com/astaxie/beego" "github.com/astaxie/beego/context")func init() { // 所有接口访问之前的过滤器 beego.InsertFilter("/*", beego.BeforeRouter, func(ctx *context.Context) { // 校验Token是否有效 result, userId := models.FilterValidateToken(ctx) if !result { //Token无效 message := code.ApiResult{Code: code.UNAUTHORIZED, Message: "Token 无效!"} ctx.Output.JSON(message, false, false) return } else { ctx.Input.SetData("userId", userId) } }) ns := beego.NewNamespace("/api/user-center", beego.NSNamespace("/token", beego.NSInclude( &controllers.TokenController{}, ), ), ) beego.AddNamespace(ns)}
package modelsimport ( "fmt" "net/http" "strings" "github.com/astaxie/beego" "github.com/astaxie/beego/context" "github.com/dgrijalva/jwt-go" "github.com/dgrijalva/jwt-go/request")const ( // TokenSecretKey 令牌密钥 TokenSecretKey = "TokenSecretKey" // TokenPeriod 令牌有效期,24个小时 TokenPeriod = 24)// Token 令牌信息type Token struct { Token string `json:"token"` //令牌 ExpiresIn int64 `json:"expiresIn"` //过期时间,秒级}// 过滤器校验Token有效性func FilterValidateToken(ctx *context.Context) (bool, string) { ignoredUrls := beego.AppConfig.Strings("ignored::url") url := ctx.Request.RequestURI // 判断用户请求地址是否在忽略列表中;默认不在列表中。 isExist := false if url == "/" { isExist = true } else { for i := 0; i < len(ignoredUrls); i++ { isExist = strings.Contains(url, ignoredUrls[i]) if isExist { break } } } if !isExist { //不在忽略列表中,需要校验Token是否有效 return ValidateToken(ctx) } else { // 放行 return true, "" }}// 校验Token有效性func ValidateToken(ctx *context.Context) (bool, string) { var r *http.Request = ctx.Request // 从请求头信息中获取Token token, err := request.ParseFromRequest(r, request.AuthorizationHeaderExtractor, func(token *jwt.Token) (interface{}, error) { return []byte(TokenSecretKey), nil }) if err == nil { //TODO先到数据库中判断Token是否存在 //如果Token在数据库中存在,判断Token是否有效 // fmt.Println("Claims", fmt.Sprintf("%+v", token.Claims)) if token.Valid { // token有效 // fmt.Println("Token is valid") claims := token.Claims.(jwt.MapClaims) return true, fmt.Sprintf("%+v", claims["userId"]) } else { // token无效 // fmt.Println("Token is not valid") return false, "" } } else { // fmt.Println("Unauthorized access to this resource") return false, "" }}