github.com/oam-dev/kubevela@v1.9.11/pkg/utils/jwt.go (about) 1 /* 2 Copyright 2022 The KubeVela Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package utils 18 19 import ( 20 "crypto/x509" 21 "crypto/x509/pkix" 22 "encoding/pem" 23 24 "github.com/form3tech-oss/jwt-go" 25 ) 26 27 // GetTokenSubject extract the subject field from the jwt token 28 func GetTokenSubject(token string) (string, error) { 29 claims, sub := jwt.MapClaims{}, "" 30 _, err := jwt.ParseWithClaims(token, claims, nil) 31 if len(claims) > 0 { 32 sub, _ = claims["sub"].(string) 33 } 34 return sub, err 35 } 36 37 // GetCertificateSubject extract Subject from Certificate 38 func GetCertificateSubject(certificate []byte) (*pkix.Name, error) { 39 if len(certificate) == 0 { 40 return nil, nil 41 } 42 blk, _ := pem.Decode(certificate) 43 if blk == nil { 44 return nil, nil 45 } 46 cert, err := x509.ParseCertificate(blk.Bytes) 47 if err != nil { 48 return nil, err 49 } 50 return &cert.Subject, nil 51 }