2019-02-21 16:58:25 +00:00
|
|
|
// Copyright 2019 Sorint.lab
|
|
|
|
//
|
|
|
|
// 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 common
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rsa"
|
|
|
|
"encoding/json"
|
|
|
|
"time"
|
|
|
|
|
2021-09-10 10:33:59 +00:00
|
|
|
"github.com/golang-jwt/jwt/v4"
|
2019-05-23 09:23:14 +00:00
|
|
|
errors "golang.org/x/xerrors"
|
2019-02-21 16:58:25 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type TokenSigningData struct {
|
|
|
|
Duration time.Duration
|
|
|
|
Method jwt.SigningMethod
|
|
|
|
PrivateKey *rsa.PrivateKey
|
|
|
|
PublicKey *rsa.PublicKey
|
|
|
|
Key []byte
|
|
|
|
}
|
|
|
|
|
2019-05-07 16:30:20 +00:00
|
|
|
func GenerateGenericJWTToken(sd *TokenSigningData, claims jwt.Claims) (string, error) {
|
|
|
|
token := jwt.NewWithClaims(sd.Method, claims)
|
2019-02-21 16:58:25 +00:00
|
|
|
|
|
|
|
var key interface{}
|
|
|
|
switch sd.Method {
|
|
|
|
case jwt.SigningMethodRS256:
|
|
|
|
key = sd.PrivateKey
|
|
|
|
case jwt.SigningMethodHS256:
|
|
|
|
key = sd.Key
|
|
|
|
default:
|
2019-05-07 16:30:20 +00:00
|
|
|
return "", errors.Errorf("unsupported signing method %q", sd.Method.Alg())
|
2019-02-21 16:58:25 +00:00
|
|
|
}
|
|
|
|
// Sign and get the complete encoded token as a string
|
|
|
|
return token.SignedString(key)
|
|
|
|
}
|
|
|
|
|
2019-05-07 16:30:20 +00:00
|
|
|
func GenerateOauth2JWTToken(sd *TokenSigningData, remoteSourceName, requestType string, request interface{}) (string, error) {
|
|
|
|
requestj, err := json.Marshal(request)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
return GenerateGenericJWTToken(sd, jwt.MapClaims{
|
|
|
|
"exp": time.Now().Add(sd.Duration).Unix(),
|
|
|
|
"remote_source_name": remoteSourceName,
|
|
|
|
"request_type": requestType,
|
|
|
|
"request": string(requestj),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2019-02-21 16:58:25 +00:00
|
|
|
func GenerateLoginJWTToken(sd *TokenSigningData, userID string) (string, error) {
|
2019-05-07 16:30:20 +00:00
|
|
|
return GenerateGenericJWTToken(sd, jwt.MapClaims{
|
2019-02-21 16:58:25 +00:00
|
|
|
"sub": userID,
|
|
|
|
"exp": time.Now().Add(sd.Duration).Unix(),
|
|
|
|
})
|
|
|
|
}
|