Skip to content

Feature Request: Customizable onError Handling in Auth Middleware #264

@fbuedding

Description

@fbuedding

It would be great to change the behavior when a user is not authorized, such as rendering an HTML page or redirecting.

In the onError function, maybe it is possible to make error handling a parameter. If keeping the current API unchanged is essential, we could alter the private function signature while maintaining the public signatures as they are. Additionally, introducing a new public function would allow users to provide their own onError function.

onError := func(h http.Handler, w http.ResponseWriter, r *http.Request, err error) {
if !reqAuth { // if no auth required allow to proceeded on error
h.ServeHTTP(w, r)
return
}
a.Logf("[DEBUG] auth failed, %v", err)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
}

The same could apply to the RBAC function:

auth/v2/middleware/auth.go

Lines 247 to 273 in fe8d691

func (a *Authenticator) RBAC(roles ...string) func(http.Handler) http.Handler {
f := func(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
user, err := token.GetUserInfo(r)
if err != nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
var matched bool
for _, role := range roles {
if strings.EqualFold(role, user.Role) {
matched = true
break
}
}
if !matched {
http.Error(w, "Access denied", http.StatusForbidden)
return
}
h.ServeHTTP(w, r)
}
return a.auth(true)(http.HandlerFunc(fn)) // enforce auth
}
return f
}

If you're open to it, I could try to implement these changes myself and create a pull request.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions