Merge branch 'update/jwt-package' of https://github.com/hyperyuri/go-base into hyperyuri-update/jwt-package
This commit is contained in:
commit
d8d770478f
7 changed files with 70 additions and 49 deletions
|
|
@ -4,6 +4,8 @@ import (
|
|||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/lestrrat-go/jwx/jwt"
|
||||
|
||||
"github.com/go-chi/jwtauth/v5"
|
||||
"github.com/go-chi/render"
|
||||
|
||||
|
|
@ -32,7 +34,7 @@ func RefreshTokenFromCtx(ctx context.Context) string {
|
|||
// response for any unverified tokens and passes the good ones through.
|
||||
func Authenticator(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, claims, err := jwtauth.FromContext(r.Context())
|
||||
token, claims, err := jwtauth.FromContext(r.Context())
|
||||
|
||||
if err != nil {
|
||||
logging.GetLogEntry(r).Warn(err)
|
||||
|
|
@ -40,6 +42,11 @@ func Authenticator(next http.Handler) http.Handler {
|
|||
return
|
||||
}
|
||||
|
||||
if err := jwt.Validate(token); err != nil {
|
||||
render.Render(w, r, ErrUnauthorized(ErrTokenExpired))
|
||||
return
|
||||
}
|
||||
|
||||
// Token is authenticated, parse claims
|
||||
var c AppClaims
|
||||
err = c.ParseClaims(claims)
|
||||
|
|
@ -58,13 +65,18 @@ func Authenticator(next http.Handler) http.Handler {
|
|||
// AuthenticateRefreshJWT checks validity of refresh tokens and is only used for access token refresh and logout requests. It responds with 401 Unauthorized for invalid or expired refresh tokens.
|
||||
func AuthenticateRefreshJWT(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, claims, err := jwtauth.FromContext(r.Context())
|
||||
token, claims, err := jwtauth.FromContext(r.Context())
|
||||
if err != nil {
|
||||
logging.GetLogEntry(r).Warn(err)
|
||||
render.Render(w, r, ErrUnauthorized(ErrTokenUnauthorized))
|
||||
return
|
||||
}
|
||||
|
||||
if err := jwt.Validate(token); err != nil {
|
||||
render.Render(w, r, ErrUnauthorized(ErrTokenExpired))
|
||||
return
|
||||
}
|
||||
|
||||
// Token is authenticated, parse refresh token string
|
||||
var c RefreshClaims
|
||||
err = c.ParseClaims(claims)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue