forked from labstack/echo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
90 lines (81 loc) · 2.27 KB
/
auth.go
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package middleware
import (
"encoding/base64"
"github.com/dgrijalva/jwt-go"
"github.com/labstack/echo"
"net/http"
)
type (
BasicValidateFunc func(string, string) bool
JWTValidateFunc func(string, jwt.SigningMethod) ([]byte, error)
)
const (
Basic = "Basic"
Bearer = "Bearer"
)
// BasicAuth returns an HTTP basic authentication middleware.
//
// For valid credentials it calls the next handler.
// For invalid Authorization header it sends "404 - Bad Request" response.
// For invalid credentials, it sends "401 - Unauthorized" response.
func BasicAuth(fn BasicValidateFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
// Skip WebSocket
if (c.Request().Header.Get(echo.Upgrade)) == echo.WebSocket {
return nil
}
auth := c.Request().Header.Get(echo.Authorization)
l := len(Basic)
he := echo.NewHTTPError(http.StatusBadRequest)
println(auth)
if len(auth) > l+1 && auth[:l] == Basic {
b, err := base64.StdEncoding.DecodeString(auth[l+1:])
if err == nil {
cred := string(b)
for i := 0; i < len(cred); i++ {
if cred[i] == ':' {
// Verify credentials
if fn(cred[:i], cred[i+1:]) {
return nil
}
he.SetCode(http.StatusUnauthorized)
}
}
}
}
return he
}
}
// JWTAuth returns a JWT authentication middleware.
//
// For valid token it sets JWT claims in the context with key `_claims` and calls
// the next handler.
// For invalid Authorization header it sends "404 - Bad Request" response.
// For invalid credentials, it sends "401 - Unauthorized" response.
func JWTAuth(fn JWTValidateFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
// Skip WebSocket
if (c.Request().Header.Get(echo.Upgrade)) == echo.WebSocket {
return nil
}
auth := c.Request().Header.Get("Authorization")
l := len(Bearer)
he := echo.NewHTTPError(http.StatusBadRequest)
if len(auth) > l+1 && auth[:l] == Bearer {
t, err := jwt.Parse(auth[l+1:], func(token *jwt.Token) (interface{}, error) {
// Lookup key and verify method
if kid := token.Header["kid"]; kid != nil {
return fn(kid.(string), token.Method)
}
return fn("", token.Method)
})
if err == nil && t.Valid {
c.Set("_claims", t.Claims)
return nil
} else {
he.SetCode(http.StatusUnauthorized)
}
}
return he
}
}