Categorygithub.com/Ashik80/oauth2jwtgen
modulepackage
0.0.0-20241208111954-a31dccbd36d2
Repository: https://github.com/ashik80/oauth2jwtgen.git
Documentation: pkg.go.dev

# README

oauth2jwtgen - An utility package for generating JWT tokens for OAuth2 authentication

This package can be used when developing an OAuth2 provider. Currently, the package can create tokens by properly signing them with HMAC or RSA signing methods. It provides built-in endpoint wrappers that returns OAuth2 tokens.

NOTE: Only the Resource Owner Password Credential grant has been implemented so far

Usage

  1. Initialize key manager

The following example is fo a HMAC signed key. The first step is to initialize a key manager and add a key

keyManager := manager.NewHSKeyManager()
keyManager.AddKey("key1", "thesecret")
  1. Set up token storage

Then define and create a token storage. The package includes memory storage as an example. Refer to the store/memory_store.go for the implementation and example.go file for an example of how to use it. The store directory also contains instructions on how to create a postgres store.

s := new(store.MemoryTokenStore)
s.CreateStore(ctx)

You can implement your own token storage but it must implement the TokenStorage interface. The TokenStore interface

type TokenStore interface {
	CreateStore(ctx context.Context) error
	StoreToken(ctx context.Context, tokenInfo *TokenInfo) error
	GetTokenInfo(ctx context.Context, resourceOwnerId string) (*TokenInfo, error)
	UpdateTokenInfo(ctx context.Context, resourceOwnerId string, accessToken string, idToken string) error
	CloseConnection() error
}
  1. Set the options for the auth server
serverOptions := &options.AuthOptions{
    Validity: v,
    Store:    s,
}
  1. Create the server obejct

And then we can initialize oauth server with the key manager

oauthServer := server.NewOAuthServer("key1", keyManager, serverOptions)
  1. Define the endpoint

Then we can call the password grant endpoint like this

http.HandleFunc(
    "POST /oauth2/token",
    oauthServer.ResourceOwnerPasswordCredential(
        func(r *http.Request, opt *options.AuthOptions) *server.CallbackError {
            username := r.FormValue("username")
            password := r.FormValue("password")
            fmt.Printf("do something with %s and %s\n", username, password)
            return nil
        }))

Default claims

By default, the username is used as sub. The application using this package will be the iss

Default validity

By default, the access token expires in 10 minutes and the refresh token in 1 hour. Refresh token is generated by default. If you want to disable the refresh token set the validity without refresh token expiry time like this

v := &accessor.Validity{
    AccessExpiresIn:  15 * 60, // 15 minutes
    // RefreshExpiresIn: 30 * 60, // commented out to show this is not being used
}

Id token

Since id token depends on a lot of data, it is left to be configured by the consumer in the endpoint's callback function

http.HandleFunc(
    "POST /oauth2/token",
    oauthServer.ResourceOwnerPasswordCredential(
        func(r *http.Request, opt *options.AuthOptions) *server.CallbackError {
            username := r.FormValue("username")
            password := r.FormValue("password")
            fmt.Printf("do something with %s and %s\n", username, password)

            // Added id token claims here
            givenName := "User"
            familyName := "One"
            idTokenClaims := &claims.JWTIdClaims{
                Name:       givenName + " " + familyName,
                GivenName:  givenName,
                FamilyName: familyName,
                Email:      username,
            }
            opt.AddIdTokenClaims(idTokenClaims)
            return nil
        }))

Example

Take a look at the example.go file for a detailed server setup with cookie based authentication

# Packages

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author