jwtauth

module
v3.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 1, 2021 License: MIT

README

Package jwtauth provides middlewares for the Goa framework that perform "auth" (authentication and authorization) using JSON WEB Tokens.

When you install the authentication middleware, it populates the context of every request with a Claims object, representing all of the JWT claims associated with the request. Unauthenticated requests have a present-but-empty Claims object.

The authorization middleware makes use of JWT claims, comparing them against goa's ContextRequiredScopes to decide whether the request may proceed.

Authentication and authorization behaviors can be customized by passing an optional callback when the middlewares are instantiated.

Usage

This is a trivial example; for thorough information, please consult the godoc.

First install jwtauth and its dependency:

go get -u github.com/rightscale/jwtauth

In your service's design DSL, declare a JWT security scheme and protect some of your actions with required scopes:

var JWT = JWTSecurity("JWT", func() {
        Header("Authorization")
})

var _ = Resource("Bottle", func() {  
   Security(JWT)

   Action("drink", func() {
     Security(JWT, func() {
       Scope("bottle:drink")
     })
   })      
})

When you create your goa.Service at startup, determine which keys to trust, then install a pair of jwtauth middlewares: one for authentication, one for authorization.

  secret := []byte("super secret HMAC key")
  store := &jwtauth.SimpleKeystore{Key: secret}

  // Authentication is not a security scheme in goa's terminology; it is
  // merely a prerequisite to authorization that handles parsing and validating
  // the JWT.
  service.Use(jwtauth.Authenticate(app.NewJWTSecurity(), store))

  // The authorization middleware should be mounted through goa's UseXxx
  // functions, so that goa knows which middleware is associated with which
  // security scheme.
  app.UseJWTMiddleware(service, jwtauth.Authorize())

Create a token and hand it out to your user:

  claims := jwtauth.NewClaims("iss", "example.com", "sub", "Bob", "scopes", []string{"bottle:drink"})
  token := jwtauth.NewToken("super secret HMAC key", claims)
  fmt.Println("the magic password is", token)

Now, sit back and enjoy the security! Your user won't be able to drink your bottles unless she includes the token as a header:

curl -X POST http://localhost:8080/bottles/drink -H "Authorization: Bearer $myjwt"

(The "bearer" is unimportant; it can be any word, or be absent, and jwtauth will still parse the token.)

You can also make use of authentication claims in your controllers:

func (c *BottleController) Drink(ctx app.DrinkBottleContext) {
  claims := jwtauth.ContextClaims(ctx)
  return fmt.Printf("Hello, %s", claims.Subject())
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL