Add simple Authorization middleware for Echo-framework in Go

Mohammed Hewedy
1 min readAug 15, 2019

--

Photo by Markus Spiske on Unsplash

In the last post, I’ve written about an echo-framework middleware for gorm/audited.

This post, I’ll talk about a simple Authorization middleware for echo-framework.

Here’s how to use it:

import "github.com/mhewedy/echox/middlewarex"// then use it:
e.POST("/url", myHandlerFunc, middlewarex.HasRole("role1", "role2))

The package middlewarex is introduced athttps://github.com/mhewedy/echox and its usage comes into two flavors:

middlewarex.HasRole(<role names>)

Or

middlewarex.HasRoleWithConfig(HasRoleConfig, <role names>)

Where HasRoleConfig is the following struct:

type HasRoleConfig struct {
JWTContextKey string
RolesClaim string
}

With the following defaults:

var DefaultHasRoleConfig = HasRoleConfig{
JWTContextKey: middleware.DefaultJWTConfig.ContextKey,
RolesClaim: "roles",
}

It depends on the JWT middleware, so it got user information from user context key.

So if it is not found in the echo context or if the user doesn’t have the requested permission then a 403 Forbidden error is returned with a message: role(s) [%s] required to access the resource.

That’s all folks.

To use it: go get github.com/mhewedy/echox

Resources:

https://github.com/mhewedy/echox

--

--

Mohammed Hewedy
Mohammed Hewedy

No responses yet