2

I am making a web server with goa (Cannot create a stack overflow tag for it, not enough reputation).

I cannot find a way to get user context inside a controller method. I use JWT auth that is supported by basic auth. I have a JWT secure action that is secured via JWT middleware and it checks passwords and so on.

What I want is to get the username from JWT token to the secure method. Is there any way?

goa design file fragment:

var JWT = JWTSecurity("jwt", func() {
    Header("Authorization")
    Scope("api:access", "API access") // Define "api:access" scope
})

Security(JWT, func() {
    // Use JWT to auth requests to this endpoint
    Scope("api:access") // Enforce presence of "api" scope in JWT claims.
})

Action("secure", func() {
    Description("This action is secured with the jwt scheme")
    Routing(GET("/jwt"))
    Response(OK)
})

and this DSL gets generated into this method:

func (c *JWTSessionsController) Secure(ctx *app.SecureJWTContext) error {
    return ctx.OK(&app.Success{false})
}

The generated action is secured and works well (Middleware is mounted and all validation passes). But I want to get username inside in the action. Is is somehow possible?

I would like to get it in this way:

ctx.User.Username

For now I will have to parse the jwt twice. :(

I made a helper that parses base64 token claims.

Grokify
  • 15,092
  • 6
  • 60
  • 81
vvwccgz4lh
  • 86
  • 9

1 Answers1

1

The jwt package exposes a ContextJWT function which extracts the JWT token content from the request context. This makes it possible to retrieve the claims stored in the token:

token := jwt.ContextJWT(ctx)
claims := token.Claims.(jwtgo.MapClaims)
subject := claims["sub"] // "sub" claim contains security principal
// ... use subject to authenticate

Where jwtgo is the dgrijalva/jwt-go package.

raphael
  • 26
  • 2
  • It is quite nice, but it still needs some wrapping to isolate jwt-go framework from the generated controller. It looks like it should do the job – vvwccgz4lh Oct 16 '16 at 07:01