forked from jfrog/jfrog-client-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
authutils.go
55 lines (47 loc) · 1.62 KB
/
authutils.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
package auth
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"github.com/jfrog/jfrog-client-go/utils/errorutils"
"strings"
)
func ExtractUsernameFromAccessToken(token string) (string, error) {
// Separate token parts.
tokenParts := strings.Split(token, ".")
// Decode the payload.
if len(tokenParts) != 3 {
return "", errorutils.CheckError(errors.New("Received invalid access-token."))
}
payload, err := base64.RawStdEncoding.DecodeString(tokenParts[1])
if err != nil {
return "", errorutils.CheckError(err)
}
// Unmarshal json.
var tokenPayload tokenPayload
err = json.Unmarshal(payload, &tokenPayload)
if err != nil {
return "", errorutils.CheckError(errors.New("Failed extracting payload from the provided access-token." + err.Error()))
}
// Extract subject.
if tokenPayload.Subject == "" {
return "", errorutils.CheckError(errors.New("Could not extract subject from the provided access-token."))
}
// Extract username from subject.
usernameStartIndex := strings.LastIndex(tokenPayload.Subject, "/")
if usernameStartIndex < 0 {
return "", errorutils.CheckError(errors.New(fmt.Sprintf("Could not extract username from access-token's subject: %s", tokenPayload.Subject)))
}
username := tokenPayload.Subject[usernameStartIndex+1:]
return username, nil
}
type tokenPayload struct {
Subject string `json:"sub,omitempty"`
Scope string `json:"scp,omitempty"`
Audience string `json:"aud,omitempty"`
Issuer string `json:"iss,omitempty"`
ExpirationTime int `json:"exp,omitempty"`
IssuedAt int `json:"iat,omitempty"`
JwtId string `json:"jti,omitempty"`
}