Version: v1.19.0
Adding Bearer authentication with Gin
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/rafaelsouzaribeiro/jwt-auth/pkg/middleware"
)
router := gin.Default()
cre, err := middleware.NewCredential(3600, "secretkey", nil)
if err != nil {
panic(err)
}
router.POST("/publish", cre.AuthMiddlewareGin(), func(c *gin.Context) {
var json struct {
Message string `json:"message"`
}
if err := c.ShouldBindJSON(&json); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{
"status": "success",
"message": json.Message,
})
})
router.Run(":8080")
Version: v1.15.0 or latest
Updating folder: pkg/middleware
import jwtauth "github.com/rafaelsouzaribeiro/jwt-auth/pkg/middleware"
Version: v1.14.0 or latest
ExtractClaims method
cre, err := jwtauth.NewCredential(3600, "secretkey", nil)
if err != nil {
panic(err)
}
claims, err = cre.ExtractClaims(token)
if err != nil {
panic(err)
}
println(fmt.Sprint(claims["lastname"]), fmt.Sprint(claims["firstname"]))
CreateToken
// pass multiple data
claims := map[string]interface{}{
"username": username,
// ... other claims
}
token, err := cre.CreateToken(claims)
Methods for http getting the bearer token and validating
package main
import (
"fmt"
"net/http"
jwtauth "github.com/rafaelsouzaribeiro/jwt-auth"
)
func main() {
mx := http.NewServeMux()
cre, err := jwtauth.NewCredential(3600, "secretkey", nil)
if err != nil {
panic(err)
}
// Protected routes
mx.HandleFunc("/route1", cre.AuthMiddleware(rota1Handler))
mx.HandleFunc("/route2", cre.AuthMiddleware(rota2Handler))
// Public route
mx.HandleFunc("/public-route", rotaPublicaHandler)
http.ListenAndServe(":8080", mx)
}
func rota1Handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Token-protected Route 1")
}
func rota2Handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Token-protected Route 2")
}
func rotaPublicaHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Public route accessible without token")
}
How to add an interceptor in grpc?
This example takes Bearer Token Authentication and skips token validation for functions login,loginAdm
c, errs := jwtauth.NewCredential(3600, secretkey, []string{"login", "loginAdm"})
if err != nil {
panic(errs)
}
grpcServer := grpc.NewServer(
grpc.UnaryInterceptor(c.UnaryInterceptorBearer),
grpc.StreamInterceptor(c.StreamInterceptorBearer),
)
How to add an interceptor in grpc? passing the token as a parameter
cre, err := jwtauth.NewCredential(3600, secretkey, nil)
if err != nil {
return "", err
}
claims := map[string]interface{}{
"username": username,
// ... other claims
}
token, err := cre.CreateToken(claims)
if err != nil {
return "", err
}
grpcServer := grpc.NewServer(
grpc.UnaryInterceptor(c.JwtUnaryInterceptor(token)),
grpc.StreamInterceptor(c.JwtStreamInterceptor(token)),
)