github.com/nats-io/jwt/v2@v2.5.6/header.go (about) 1 /* 2 * Copyright 2018-2019 The NATS Authors 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 package jwt 17 18 import ( 19 "encoding/json" 20 "fmt" 21 "strings" 22 ) 23 24 const ( 25 // Version is semantic version. 26 Version = "2.4.0" 27 28 // TokenTypeJwt is the JWT token type supported JWT tokens 29 // encoded and decoded by this library 30 // from RFC7519 5.1 "typ": 31 // it is RECOMMENDED that "JWT" always be spelled using uppercase characters for compatibility 32 TokenTypeJwt = "JWT" 33 34 // AlgorithmNkey is the algorithm supported by JWT tokens 35 // encoded and decoded by this library 36 AlgorithmNkeyOld = "ed25519" 37 AlgorithmNkey = AlgorithmNkeyOld + "-nkey" 38 ) 39 40 // Header is a JWT Jose Header 41 type Header struct { 42 Type string `json:"typ"` 43 Algorithm string `json:"alg"` 44 } 45 46 // Parses a header JWT token 47 func parseHeaders(s string) (*Header, error) { 48 h, err := decodeString(s) 49 if err != nil { 50 return nil, err 51 } 52 header := Header{} 53 if err := json.Unmarshal(h, &header); err != nil { 54 return nil, err 55 } 56 57 if err := header.Valid(); err != nil { 58 return nil, err 59 } 60 return &header, nil 61 } 62 63 // Valid validates the Header. It returns nil if the Header is 64 // a JWT header, and the algorithm used is the NKEY algorithm. 65 func (h *Header) Valid() error { 66 if TokenTypeJwt != strings.ToUpper(h.Type) { 67 return fmt.Errorf("not supported type %q", h.Type) 68 } 69 70 alg := strings.ToLower(h.Algorithm) 71 if !strings.HasPrefix(alg, AlgorithmNkeyOld) { 72 return fmt.Errorf("unexpected %q algorithm", h.Algorithm) 73 } 74 if AlgorithmNkeyOld != alg && AlgorithmNkey != alg { 75 return fmt.Errorf("unexpected %q algorithm", h.Algorithm) 76 } 77 return nil 78 }