jwt

command
v0.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 31, 2021 License: Apache-2.0 Imports: 8 Imported by: 0

README

JWT middleware

In this example, we will try to create echo server with JWT middleware enabled.

Table of Contents generated with DocToc

Quick start

Get rk-mux package from the remote repository.

go get -u github.com/rookie-ninja/rk-mux
Code

Add rkechojwt.Interceptor() jwt with option.

import     "github.com/rookie-ninja/rk-mux/interceptor/jwt"
    // ********************************************
    // ********** Enable interceptors *************
    // ********************************************
	interceptors := []mux.MiddlewareFunc{
		rkmuxjwt.Interceptor(
			// Required, provide signing key.
			rkmuxjwt.WithSigningKey([]byte("my-secret")),
		),
    }

Options

Name Description Default Values
rkmuxjwt.WithEntryNameAndType(entryName, entryType string) Optional. Provide entry name and type if there are multiple jwt interceptors needs to be used. echo, echo
rkmuxjwt.WithSkipper(skipper function) Optional. Provide skipper function function always returns false
rkmuxjwt.WithSigningKey(interface{}) Required. Provide signing key nil
rkmuxjwt.WithSigningKeys(string, interface{}) Optional. Provide signing key value pairs empty
rkmuxjwt.WithSigningAlgorithm(string) Optional, Provide signing algorithm. HS256
rkmuxjwt.WithClaims(jwt.Claims) Optional, provide jwt.Claims. jwt.MapClaims{}
rkmuxjwt.WithTokenLookup(string) Optional, provide jwt token lookup rules, please see code comments for details. "header:Authorization"
rkmuxjwt.WithAuthScheme(string) Optional, provide auth scheme. Bearer
rkmuxjwt.WithKeyFunc(jwt.Keyfunc) Optional, provide key function. default function will be assigned.
rkmuxjwt.WithParseTokenFunc(func) Optional, provide token parse function. default function will be assigned.
rkmuxjwt.WithIgnorePrefix([]string) Optional, provide ignoring path prefix. []
    // ********************************************
    // ********** Enable interceptors *************
    // ********************************************
	interceptors := []mux.MiddlewareFunc{
		rkmuxjwt.Interceptor(
			// Required, entry name and entry type will be used for distinguishing interceptors. Recommended.
			//rkmuxjwt.WithEntryNameAndType("greeter", "mux"),
			//
			// Required, provide signing key.
			rkmuxjwt.WithSigningKey([]byte("my-secret")),
			//
			// Optional, provide skipper function
			//rkmuxjwt.WithSkipper(func(*http.Request) bool {
			//	return true
			//}),
			//
			// Optional, provide token parse function, default one will be assigned.
			//rkmuxjwt.WithParseTokenFunc(func(auth string, req *http.Request) (*jwt.Token, error) {
			//	return nil, nil
			//}),
			//
			// Optional, provide key function, default one will be assigned.
			//rkmuxjwt.WithKeyFunc(func(token *jwt.Token) (interface{}, error) {
			//	return nil, nil
			//}),
			//
			// Optional, default is Bearer
			//rkmuxjwt.WithAuthScheme("Bearer"),
			//
			// Optional
			//rkmuxjwt.WithTokenLookup("header:my-jwt-header-key"),
			//
			// Optional, default is HS256
			//rkmuxjwt.WithSigningAlgorithm(rkmuxjwt.AlgorithmHS256),
		),
    }
Context Usage
Name Functionality
rkmuxctx.GetLogger(req, writer) Get logger generated by log interceptor. If there are X-Request-Id or X-Trace-Id as headers in incoming and outgoing metadata, then loggers will has requestId and traceId attached by default.
rkmuxctx.GetEvent(req) Get event generated by log interceptor. Event would be printed as soon as RPC finished.
rkmuxctx.GetIncomingHeaders(req) Get incoming header.
rkmuxctx.AddHeaderToClient(writer, "k", "v") Add k/v to headers which would be sent to client. This is append operation.
rkmuxctx.SetHeaderToClient(writer, "k", "v") Set k/v to headers which would be sent to client.
rkmuxctx.GetJwtToken(req) Get jwt token if exists
rkmuxctx.GetCsrfToken(req) Get csrf token if exists

Example

In this example, we will get jwt token from https://jwt.io/.

Start server
$ go run greeter-server.go
Send request
  • with valid jwt token
$ curl localhost:8080/v1/greeter -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.EpM5XBzTJZ4J8AfoJEcJrjth8pfH28LWdjLo90sYb9g"
{"Message":"Is token valid:true!"}
  • with invalid jwt token
$ curl localhost:8080/v1/greeter -H "Authorization: Bearer invalid-jwt-token"
{
    "error":{
        "code":401,
        "status":"Unauthorized",
        "message":"invalid or expired jwt",
        "details":[
            "token contains an invalid number of segments"
        ]
    }
}
Code

Documentation

The Go Gopher

There is no documentation for this package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL