68 lines
1.9 KiB
Go
68 lines
1.9 KiB
Go
package ginoidc
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"git.icod.de/dalu/ginoidc/ginerror"
|
|
"git.icod.de/dalu/oidc"
|
|
"git.icod.de/dalu/oidc/options"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// New returns an OpenID Connect (OIDC) discovery handler (middleware)
|
|
// to be used with `gin`.
|
|
func New(setters ...options.Option) gin.HandlerFunc {
|
|
oidcHandler, err := oidc.NewHandler(setters...)
|
|
if err != nil {
|
|
panic(fmt.Sprintf("oidc discovery: %v", err))
|
|
}
|
|
return toGinHandler(oidcHandler.ParseToken, setters...)
|
|
}
|
|
|
|
// onError is called when there's an error.
|
|
func onError(c *gin.Context, errorHandler options.ErrorHandler, statusCode int, description options.ErrorDescription, err error) {
|
|
c.AbortWithStatusJSON(statusCode, gin.H{"error": err.Error()})
|
|
}
|
|
|
|
// toGinHandler creates a gin.HandlerFunc so the stdlib handler can be used as a gin middleware.
|
|
func toGinHandler(parseToken oidc.ParseTokenFunc, setters ...options.Option) gin.HandlerFunc {
|
|
opts := options.New(setters...)
|
|
|
|
var errs []ginerror.Error
|
|
|
|
return func(c *gin.Context) {
|
|
tokenString, err := oidc.GetTokenString(c.Request.Header.Get, opts.TokenString)
|
|
if err != nil {
|
|
if !opts.Permissive {
|
|
onError(c, opts.ErrorHandler, http.StatusBadRequest, options.GetTokenErrorDescription, err)
|
|
return
|
|
} else {
|
|
errs = append(errs, ginerror.Error{
|
|
Description: string(options.GetTokenErrorDescription),
|
|
Error: err,
|
|
})
|
|
c.Set(string(opts.ErrorsContextKeyName), errs)
|
|
c.Next()
|
|
return
|
|
}
|
|
}
|
|
|
|
token, err := parseToken(c, tokenString)
|
|
if err != nil {
|
|
onError(c, opts.ErrorHandler, http.StatusUnauthorized, options.ParseTokenErrorDescription, err)
|
|
return
|
|
}
|
|
|
|
tokenClaims, err := token.AsMap(c)
|
|
if err != nil {
|
|
onError(c, opts.ErrorHandler, http.StatusUnauthorized, options.ConvertTokenErrorDescription, err)
|
|
return
|
|
}
|
|
|
|
c.Set(string(opts.ClaimsContextKeyName), tokenClaims)
|
|
|
|
c.Next()
|
|
}
|
|
}
|