Skip to content

Latest commit

 

History

History
55 lines (39 loc) · 1.86 KB

README.md

File metadata and controls

55 lines (39 loc) · 1.86 KB

Auth

Simple auth using JWT tokens

Coverage Status Build Status GoDoc Go Report Card

Example - the login handler

secret := make([]byte, 20)
rand.Read(secret)
// Signing method is used to sign tokens
signingMethod := auth.SigningMethodHMAC(secret, auth.Size256)

// TokenGenerator is used to create/verify tokens
tokenGenerator := auth.NewTokenGenerator(signingMethod)

// Authenticator authenticates logins and creates a token
authenticator := auth.NewAuthenticator(tokenGenerator, storage, time.Hour)

// Handler implements http.Handler and handles logins
handler := auth.NewHandler(authenticator)

http.Handle("/auth", handler)
http.ListenAndServe(:8080, nil)

OR

secret := make([]byte, 20)
rand.Read(secret)
// Signing method is used to sign tokens
signingMethod := auth.SigningMethodHMAC(secret, auth.Size256)

// Handler implements http.Handler and handles logins
handler, authenticator := auth.NewHandlerAndAuthenticator(signingMethod, storage, time.Hour))

http.Handle("/auth", handler)
http.ListenAndServe(:8080, nil)

Example - getting the users information

func SomeHandlerOrMiddleware(w http.ResponseWriter, r *http.Request) {
    user, _ := handler.UserFromRequest(r);

    // You can also store and retrieve from a context
    ctx := context.Background()
    ctx = auth.NewUserContext(ctx, user)

    userFromContext := auth.UserFromContext(ctx)
}