123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- package middleware
- import (
- "github.com/golang-jwt/jwt"
- "iot_manager_service/config"
- "time"
- )
- const (
- Authorization = "Authorization"
- Audience = "audience"
- Issuer = "issuser"
- )
- var EmptyKeyFunc = func(t *jwt.Token) (interface{}, error) { return []byte(config.Instance().Server.TokenSign), nil }
- type Claims struct {
- jwt.StandardClaims
- TenantId string `json:"tenant_id"`
- UserId int `json:"user_id"`
- RoleId int `json:"role_id"`
- UserName string `json:"user_name"`
- Random string `json:"random"`
- }
- func GetAccessToken(userId, roleId int, tenantId string, userName string, random string) (string, error) {
- jwtToken := Claims{StandardClaims: jwt.StandardClaims{
- Audience: Audience,
- Issuer: Issuer,
- ExpiresAt: time.Now().Add(2 * time.Hour).Unix(),
- NotBefore: time.Now().Unix(),
- },
- UserId: userId,
- TenantId: tenantId,
- RoleId: roleId,
- UserName: userName,
- Random: random,
- }
- claims := jwt.NewWithClaims(jwt.SigningMethodHS512, jwtToken)
- return claims.SignedString([]byte(config.Instance().Server.TokenSign))
- }
- func ParseAccessToken(authorization string) *Claims {
- token, err := jwt.ParseWithClaims(authorization, &Claims{}, EmptyKeyFunc)
- if err != nil {
- return nil
- }
- claims, ok := token.Claims.(*Claims)
- if !ok {
- return nil
- }
- return claims
- }
|