MCPcopy
hub / github.com/golang-jwt/jwt / signToken

Function signToken

cmd/jwt/main.go:177–263  ·  view source on GitHub ↗

Create, sign, and output a token. This is a great, simple example of how to use this library to create and sign a token.

()

Source from the content-addressed store, hash-verified

175// Create, sign, and output a token. This is a great, simple example of
176// how to use this library to create and sign a token.
177func signToken() error {
178 // get the token data from command line arguments
179 tokData, err := loadData(*flagSign)
180 if err != nil {
181 return fmt.Errorf("couldn't read token: %w", err)
182 } else if *flagDebug {
183 fmt.Fprintf(os.Stderr, "Token: %v bytes", len(tokData))
184 }
185
186 // parse the JSON of the claims
187 var claims jwt.MapClaims
188 if err := json.Unmarshal(tokData, &claims); err != nil {
189 return fmt.Errorf("couldn't parse claims JSON: %w", err)
190 }
191
192 // add command line claims
193 if len(flagClaims) > 0 {
194 for k, v := range flagClaims {
195 claims[k] = v
196 }
197 }
198
199 // get the key
200 var key any
201 if isNone() {
202 key = jwt.UnsafeAllowNoneSignatureType
203 } else {
204 key, err = loadData(*flagKey)
205 if err != nil {
206 return fmt.Errorf("couldn't read key: %w", err)
207 }
208 }
209
210 // get the signing alg
211 alg := jwt.GetSigningMethod(*flagAlg)
212 if alg == nil {
213 return fmt.Errorf("couldn't find signing method: %v", *flagAlg)
214 }
215
216 // create a new token
217 token := jwt.NewWithClaims(alg, claims)
218
219 // add command line headers
220 if len(flagHead) > 0 {
221 for k, v := range flagHead {
222 token.Header[k] = v
223 }
224 }
225
226 switch {
227 case isEs():
228 k, ok := key.([]byte)
229 if !ok {
230 return fmt.Errorf("couldn't convert key data to key")
231 }
232 key, err = jwt.ParseECPrivateKeyFromPEM(k)
233 if err != nil {
234 return err

Callers 1

startFunction · 0.70

Calls 6

loadDataFunction · 0.85
isNoneFunction · 0.85
isEsFunction · 0.85
isRsFunction · 0.85
isEdFunction · 0.85
SignedStringMethod · 0.80

Tested by

no test coverage detected