go-chi / go-chi/oauth

Documentation on how to use context on client. Why contextKey type?

Open
#7 2 comments 1 reaction 0 assignees View on GitHub
Dominant language
Go
Stars
35
Forks
7
PR merge metrics
No merged PRs in 30d

Description

After adding the middleware `router.Use(oauth.Authorize("mySecretKey-10101", nil))` and being able to authorize a user, I had some issues figuring out how to access the information of the access token using the Context.

The middleware.go file adds the token information to the Context using a new type that is basically a string. Code in question:
`type contextKey string

const (
CredentialContext contextKey = "oauth.credential"
ClaimsContext contextKey = "oauth.claims"
ScopeContext contextKey = "oauth.scope"
TokenTypeContext contextKey = "oauth.tokentype"
AccessTokenContext contextKey = "oauth.accesstoken"
)`

Given that the context is accessed using `r.Context().Value(key)` and that key is basically a string, I thought I had to access the claims just by using `r.Context().Value("oauth.claims")` but this approach returned nil.

To successfully access the token information in the context I had to import the oauth package and use the consts that I put above since their type is not a string but contextKey. Working Example:
`r.Context().Value(oauth.ClaimsContext)`

I was wondering why this contextKey type is used instead of using a string

Contributor guide

No contributing guide indexed for this repository

Research direction

Start with middleware.go and the contextKey, CredentialContext, ClaimsContext, ScopeContext, TokenTypeContext, and AccessTokenContext definitions mentioned in the issue. Document why the typed keys are used and show that callers should use the exported constants, with an example matching the reported context access; the documentation should answer why a plain string returns nil.

Written by the indexing model from the issue text.

Assessment

Tech stack
go
Domain
authentication
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.