File: restful-jwt-authentication.go

package info (click to toggle)
golang-github-emicklei-go-restful 3.10.2-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 792 kB
  • sloc: makefile: 9; sh: 6
file content (60 lines) | stat: -rw-r--r-- 1,277 bytes parent folder | download
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
56
57
58
59
60
package main

import (
	"io"
	"log"
	"net/http"
	"strings"

	restful "github.com/emicklei/go-restful/v3"
	"github.com/golang-jwt/jwt/v4"
)

// This example shows how to create a (Route) Filter that performs a JWT HS512 authentication.
//
// GET http://localhost:8080/secret
// and use shared-token as a shared secret.

var (
	sharedSecret = []byte("shared-token")
)

func main() {
	ws := new(restful.WebService)
	ws.Route(ws.GET("/secret").Filter(authJWT).To(secretJWT))
	restful.Add(ws)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

func secretJWT(req *restful.Request, resp *restful.Response) {
	io.WriteString(resp, "42")
}

func validJWT(authHeader string) bool {
	if !strings.HasPrefix(authHeader, "JWT ") {
		return false
	}

	jwtToken := strings.Split(authHeader, " ")
	if len(jwtToken) < 2 {
		return false
	}
	parts := strings.Split(jwtToken[1], ".")
	err := jwt.SigningMethodHS512.Verify(strings.Join(parts[0:2], "."), parts[2], sharedSecret)
	if err != nil {
		return false
	}

	return true
}

func authJWT(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
	authHeader := req.HeaderParameter("Authorization")

	if !validJWT(authHeader) {
		resp.WriteErrorString(401, "401: Not Authorized")
		return
	}

	chain.ProcessFilter(req, resp)
}