This repository has been archived by the owner on Oct 23, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
oauth2_token.go
208 lines (167 loc) · 5.55 KB
/
oauth2_token.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
// SPDX-License-Identifier: Apache-2.0
// Copyright © 2019 Intel Corporation
package oauth2
import (
"encoding/json"
"errors"
"io/ioutil"
"path/filepath"
"time"
"github.com/dgrijalva/jwt-go/v4"
logger "github.com/open-ness/common/log"
)
var log = logger.DefaultLogger.WithField("oauth2", nil)
// Path for OAuth2 Configuration file
const cfgPath string = "configs/oauth2.json"
//TokenVerificationResult Result of the token verification
type TokenVerificationResult string
// Error results of token verification
const (
StatusBadRequest = "StatusBadRequest"
StatusInvalidToken = "StatusInvalidToken"
StatusSuccess = "StatusSuccess"
StatusConfigErr = "StatusConfigErr"
)
//Config OAuth2 config struct
type Config struct {
SigningKey string `json:"signingkey"`
Expiration int64 `json:"expiration"`
}
//PlmnID PLMN ID struct
type PlmnID struct {
Mcc string `json:"mcc" yaml:"mcc" bson:"mcc" mapstructure:"Mcc"`
Mnc string `json:"mnc" yaml:"mnc" bson:"mnc" mapstructure:"Mnc"`
}
//NfType Network Function type
type NfType string
//AccessTokenReq NRF access token request
type AccessTokenReq struct {
GrantType string `json:"grant_type"`
NfInstanceID string `json:"nfInstanceId"`
NfType NfType `json:"nfType,omitempty"`
TargetNfType NfType `json:"targetNfType,omitempty"`
Scope string `json:"scope"`
TargetNfInstanceID string `json:"targetNfInstanceId,omitempty"`
RequesterPlmn *PlmnID `json:"requesterPlmn,omitempty"`
TargetPlmn *PlmnID `json:"targetPlmn,omitempty"`
}
//AccessTokenClaims struct
type AccessTokenClaims struct {
Issuer string `json:"issuer"`
Subject string `json:"subject"`
Audience interface{} `json:"audience"`
Scope string `json:"scope"`
Expiration int64 `json:"expiration"`
jwt.StandardClaims
}
// LoadJSONConfig reads a file located at configPath and unmarshals it to
// config structure
func loadJSONConfig(configPath string, config interface{}) error {
cfgData, err := ioutil.ReadFile(filepath.Clean(configPath))
if err != nil {
log.Infoln(err)
return err
}
return json.Unmarshal(cfgData, config)
}
// GetNEFAccessTokenFromNRF Generates the token. This is the functionality of
// NRF component of 5GC
func GetNEFAccessTokenFromNRF(accessTokenReq AccessTokenReq) (
NefAccessToken string, err error) {
var oAuth2Cfg = Config{}
//Read Json config
err = loadJSONConfig(cfgPath, &oAuth2Cfg)
if err != nil {
log.Errln("Failed to load OAuth2 configuration")
return NefAccessToken, err
}
expiration := time.Now().Add(
time.Second * time.Duration(oAuth2Cfg.Expiration)).Unix()
jwtexp,e:= jwt.ParseTime(expiration)
if e!=nil{
log.Errln("Failed to parse time",e.Error())
}
log.Infoln("Token expires in : ", oAuth2Cfg.Expiration, " seconds")
var mySigningKey = []byte(oAuth2Cfg.SigningKey)
//log.Infoln("Expiration Set to ", expiration)
// Create AccessToken
var accessTokenClaims = AccessTokenClaims{
"OpenNESS", //Issuer:
"NEF Validation token", //Subject:
"AF-NEF", //Audience:
accessTokenReq.Scope, //Scope:
oAuth2Cfg.Expiration, //Expiration:
jwt.StandardClaims{ExpiresAt: jwtexp},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, accessTokenClaims)
accessToken, SignedStringErr := token.SignedString(mySigningKey)
if SignedStringErr != nil {
log.Info(SignedStringErr)
}
return accessToken, nil
}
func fetchNEFAccessTokenFromNRF() (token string, err error) {
var accessTokenReq AccessTokenReq
//In case we construct and send it to NRF
accessTokenReq.GrantType = "client_credentials"
//Dont have it right now added static UUID
accessTokenReq.NfInstanceID = "0"
accessTokenReq.NfType = "AF"
accessTokenReq.TargetNfType = "NEF"
accessTokenReq.Scope = "nnrf-nfm"
accessTokenReq.TargetNfInstanceID = "0" //Instance of NEF
//POST AccessTokenRequest to NRF /oauth2/token
return GetNEFAccessTokenFromNRF(accessTokenReq)
}
//GetAccessToken Get the access token to access NEF NF component. This API can
// be ported to operator provided token access mechanism
// i/p : None
// o/p token : The access token
// err : error code in case of failure or nil in success
func GetAccessToken() (token string, err error) {
token, err = fetchNEFAccessTokenFromNRF()
if err != nil {
log.Info("Failed to get NEF access token ")
}
return token, err
}
//ValidateAccessToken Validate the access token
// i/p reqToken : token to be validated
// o/p status : Success/Failure result of the operation
// err : error info of the token validation process.
func ValidateAccessToken(reqToken string) (status TokenVerificationResult,
err error) {
var oAuth2Cfg = Config{}
//Read Json config
err = loadJSONConfig(cfgPath, &oAuth2Cfg)
if err != nil {
log.Errln("Failed to load OAuth2 configuration")
return StatusConfigErr, err
}
var mySigningKey = []byte(oAuth2Cfg.SigningKey)
claims := &AccessTokenClaims{}
tkn, err := jwt.ParseWithClaims(reqToken, claims, func(token *jwt.Token) (
interface{}, error) {
return mySigningKey, nil
})
if err != nil {
log.Info(err)
if err == jwt.ErrSignatureInvalid {
log.Info("Token is invalid, ErrSignatureInvalid")
return StatusInvalidToken, err
}
//Check for Validation error
validationErr, ok := err.(*jwt.MalformedTokenError)
if !ok {
log.Info(validationErr.Message)
return StatusInvalidToken, err
}
return StatusBadRequest, err
}
if !tkn.Valid {
log.Info("Token is invalid")
return StatusInvalidToken, errors.New("Token is Invalid")
}
log.Info("OAuth2 Token Validation successful")
return StatusSuccess, nil
}