Go-Guardian is a golang library that provides a simple, clean, and idiomatic way to create powerful modern API and web authentication.

GoDoc Go Report Card Coverage Status CircleCI

Cache package has been moved to libcache repository

Go-Guardian

Go-Guardian is a golang library that provides a simple, clean, and idiomatic way to create powerful modern API and web authentication.

Overview

Go-Guardian sole purpose is to authenticate requests, which it does through an extensible set of authentication methods known as strategies.
Go-Guardian does not mount routes or assume any particular database schema, which maximizes flexibility and allows decisions to be made by the developer.
The API is simple: you provide go-guardian a request to authenticate, and go-guardian invoke strategies to authenticate end-user request.
Strategies provide callbacks for controlling what occurs when authentication should succeeds or fails.

Installing

Using go-guardian is easy. First, use go get to install the latest version of the library.

go get github.com/shaj13/go-guardian/v2

Next, include go-guardian in your application:

import "github.com/shaj13/go-guardian/v2"

Why Go-Guardian?

When building a modern application, you don't want to implement authentication module from scratch;
you want to focus on building awesome software. go-guardian is here to help with that.

Here are a few bullet point reasons you might like to try it out:

  • provides simple, clean, and idiomatic API.
  • provides top trends and traditional authentication methods.
  • provides two-factor authentication and one-time password as defined in RFC-4226 and RFC-6238
  • provides a mechanism to customize strategies, even enables writing a custom strategy

Strategies

Examples

Examples are available on GoDoc or Examples Folder.

Documentation

API docs are available on GoDoc.

Contributing

  1. Fork it
  2. Download your fork to your PC (git clone https://github.com/your_username/go-guardian && cd go-guardian)
  3. Create your feature branch (git checkout -b my-new-feature)
  4. Make changes and add them (git add .)
  5. Commit your changes (git commit -m 'Add some feature')
  6. Push to the branch (git push origin my-new-feature)
  7. Create new pull request

License

Go-Guardian is released under the MIT license. See LICENSE

Comments
  • Feature: Access token, Refresh token, OAuth2

    Feature: Access token, Refresh token, OAuth2

    Hi,

    I am currently using the jwt strategy for development process. This works good so far, however, I can see there is some caveats:

    • lifespan must be huge or user experience will be bad (have to relog each x minutes)
    • jwt could be intercepted by a malicious third party and this jwt will be usage for probably a long time (lifespan config value)

    I think creating a new strategy like refreshTokenStrategy will resolve these issues.

    There is a full specification of the OAuth2 here: https://datatracker.ietf.org/doc/html/rfc6749

    Protocol Flow: https://datatracker.ietf.org/doc/html/rfc6749#section-1.2

    What is a refresh token: https://datatracker.ietf.org/doc/html/rfc6749#section-1.5 What is an access token: https://datatracker.ietf.org/doc/html/rfc6749#section-1.4

    Authorization code grant: https://datatracker.ietf.org/doc/html/rfc6749#section-4.1 Resource owner Password credentials grant: https://datatracker.ietf.org/doc/html/rfc6749#section-4.3 (case we want to auth a microservice for example)

    I could keep linking all the docs, but I think this isn't necessary as someone made a great OAuth server implementation here: https://github.com/go-oauth2/oauth2

    My point is: could we create an oauth strategy based on the OAuth server implementation that go-oauth2 made?

  • LDAPS Schema does not work with 389 + Start TLS Server

    LDAPS Schema does not work with 389 + Start TLS Server

    What version of Go are you using (go version)?

    $ go version 1.17
    
    

    Does this issue reproduce with the latest release?

    yes

    What version of Go-Guardian are you using ?

    Go-Guardian Version: 2.11.4
    

    What did you do?

    I configured ldap against a server that has port 636 "ldaps" disabled, and only uses StartTLS on port 389.

    What did you expect to see?

    I expected to connect and authenticate with ldap credentials

    What did you see instead?

    "Network Error": read tcp x.x.x.x:60677->x.x.x.x:389: read: connection reset by peer

    I believe this should still be scheme ldap, and ldaps should be used against an LDAP server with SSL enabled on port 636.

    This would remediate the issue:

    diff --git a/auth/strategies/ldap/ldap.go b/auth/strategies/ldap/ldap.go
    index ec9b920..cc00906 100644
    --- a/auth/strategies/ldap/ldap.go
    +++ b/auth/strategies/ldap/ldap.go
    @@ -56,10 +56,13 @@ func dial(cfg *Config) (conn, error) {
     	opts := []ldap.DialOpt{}
     
     	if cfg.TLS != nil {
    -		scheme = "ldaps"
     		opts = append(opts, ldap.DialWithTLSConfig(cfg.TLS))
     	}
     
    +  if cfg.Port == "636" {
    +    scheme = "ldaps"
    +  }
    +
     	addr := fmt.Sprintf("%s://%s:%s", scheme, cfg.Host, cfg.Port)
     	return ldap.DialURL(addr, opts...)
     }
    
    
  • starttls on 389 requires ldap scheme

    starttls on 389 requires ldap scheme

    Hello!

    Using the ldaps scheme against an LDAP server running on port 389, with StartTLS, will result is a "Network Error": read tcp x.x.x.x:60677->x.x.x.x:389: read: connection reset by peer error

    I believe this should still be scheme ldap, and ldaps should be used against an LDAP server with SSL enabled on port 636.

  • Rotated secrets always triggers a new secret to be generated

    Rotated secrets always triggers a new secret to be generated

    What version of Go are you using (go version)?

    $ go version
    1.16
    

    Does this issue reproduce with the latest release?

    Yes

    What version of Go-Guardian are you using ?

    Go-Guardian Version: 
    v2.11.3
    

    What did you do?

    Trying to get rotated secrets working and have been looking at https://play.golang.org/p/5N-5fWa0mfN (posted by @shaj13) for some help. This is also found somewhere in the examples but can't find it right now.

    The issue is that jwt.SecretsKeeper's methods Get and KID doesn't use pointers in it's signature definitions so changes to r.LastRotation in KID is not saved to the keeper struct.

    For example this func (r RotatedSecrets) KID() string should be this func (r *RotatedSecrets) KID() string?

    What did you expect to see?

    That time.Now().After(r.LastRotation) would be false if within specified rotation duration.

    What did you see instead?

    That time.Now().After(r.LastRotation) is always true as r.LastRotation is always 0.

  • organize basic and token examples

    organize basic and token examples

    What did you expect to see?

    token and basic example

    What did you see instead?

    https://github.com/shaj13/go-guardian/tree/master/_examples/basic_bearer

    TODO

    split the basic_bearer to basic and token. the token example can use the basic similar to jwt example

  • Password included in token from jwt strategy example

    Password included in token from jwt strategy example

    What version of Go are you using (go version)?

    $ go version
    1.16
    

    Does this issue reproduce with the latest release?

    Yes

    What version of Go-Guardian are you using ?

    Go-Guardian Version: 
    v2.11.2
    

    What did you do?

    Run the jwt token example in the repo with basic login.

    What did you expect to see?

    A token without password.

    What did you see instead?

    The password included in plain text in the payload of the token:

    {
      "Extensions": {
        "x-go-guardian-basic-password": [
          "admin"
        ]
      },
      "Groups": null,
      "ID": "1",
      "Name": "admin",
      "aud": [
        ""
      ],
      "exp": 1615318474,
      "iat": 1615318174,
      "nbf": 1615318174,
      "sub": "1"
    }
    
  • jwt Example doens't return a token

    jwt Example doens't return a token

    What version of Go are you using (go version)?

    1.13

    Does this issue reproduce with the latest release?

    yes

    What version of Go-Guardian are you using?

    latest

    What did you do?

    https://play.golang.org/p/NlbR34g1GRM I just ran the jwt example

    What did you expect to see?

    I expect to get a token in the response

    What did you see instead?

    token:  
    ➜  ~ curl  -k http://127.0.0.1:8080/v1/book/1449311601 -u admin:admin
    Author: Ryan Boyd 
    ➜  ~ curl  -k http://127.0.0.1:8080/v1/auth/token -u admin:admin
    token:  
    ➜  ~ 
    

    Token is empty

  • Question: How to achieve digest auth that survives after service restarts.

    Question: How to achieve digest auth that survives after service restarts.

    I'm using Digest strategy and works fine until I restart my service. Chrome re-challenges user to give creds again. Strategy returns: userInfo = nil, err = Invalid Response to all web requests. I'm using FIFO lib cache FWIW.

    Do I need to implement my own cache implementation that stores values on disk to survive restarts?

    I'm trying to replace nginx reverse proxy and this doesn't happen w/nginx so this is a loss in functionality as well and user issue.

  • Congratulations and question

    Congratulations and question

    If someone asks you how this project differs from https://github.com/volatiletech/authboss, what would you answer?

    Thanks for your amazing commitment! ❤️

  • Consider changing ID() method in auth.Info interface to UserID()?

    Consider changing ID() method in auth.Info interface to UserID()?

    I was trying to use this library in my project and ran into a naming collision of sorts. I have a few GORM models including a base Model and a User model. Model includes a few fields that get used in all of my other models, such as ID, created at, updated at, etc. My other models then have something like this.

    type User struct {
        Model
    
        Email string
        HashedPassword []byte
    }
    

    What seemed appropriate to do at the time was add the functions from your auth.Info interface to my User model so that I could just pass my User into functions like Append, for example, or return my User model instead of a DefaultUser instance from my validateLogin function. That part works perfectly, but it came with other compromises.

    One of the functions in the auth.Info interface is ID(). One of my fields in my base Model (and by extension my User model and indeed all my models) is also ID. Obviously I can change the name of the field, and that's what I've done for now, but I either name it Id which works but causes go-lint to yell at me, or name it something like ModelID which just feels... weird. I could also not use the base Model in my User model and manually add the necessary fields from the base Model, naming the id field UserID in the process, but that creates code duplication and means if I have to add to or edit the base Model I also most likely have to edit the User model. Not too big of a deal but a bit of a code smell.

    What I would like to propose is renaming the ID() method on the auth.Info interface to UserID(), as it not only avoids this issue but also makes it match better with the UserName() method. Of course if you're privy to information that I'm not on why that wouldn't work I absolutely understand, and I can work around the issue with either one of the methods I described above or writing some functions to convert my User models to DefaultUser instances, but I figured it was worth having the discussion.

  • Is cache implementation thread-safe?

    Is cache implementation thread-safe?

    I noticed that shaj13/libcache's documentation says that lru.New() initializes a non-thread safe cache (https://github.com/shaj13/libcache/blob/master/lru/lru.go#L15) and I couldn't find any code to handle thread safety in go-guardian so I'm wondering, is go-guardian thread-safe? Can it be used in the request path of a go web server safely?

  • Feature: implement opaque token revocation

    Feature: implement opaque token revocation

    What version of Go are you using (go version)?

    $ go version
    
    

    Does this issue reproduce with the latest release?

    What version of Go-Guardian are you using ?

    Go-Guardian Version: 
    

    What did you do?

    What did you expect to see?

    What did you see instead?

  • Issue with example directory

    Issue with example directory

    What version of Go are you using (go version)?

    $ go version
    go version go1.18.3 linux/amd64
    

    Does this issue reproduce with the latest release?

    Yes

    What version of Go-Guardian are you using ?

    Go-Guardian Version:  v2.11.5
    Libcache Version: v1.0.5
    

    What did you do?

    Hello, I just want to follow the jwt example https://github.com/shaj13/go-guardian/blob/master/_examples/jwt/main.go But the function RegisterOnExpired was deprecated and no-longer works. Can you update the example directory on this repo.

    What did you expect to see?

    The program init and run

    What did you see instead?

    $> go run ./...
    panic: RegisterOnExpired no longer available
    
    goroutine 1 [running]:
    github.com/shaj13/libcache/internal.(*Cache).RegisterOnExpired(0x18?, 0x7c80a0?)
    	/home/xxx/go/pkg/mod/github.com/shaj13/[email protected]/internal/cache.go:379 +0x27
    github.com/shaj13/libcache.(*cache).RegisterOnExpired(0xc00009e120, 0x6?)
    	/home/xxx/go/pkg/mod/github.com/shaj13/[email protected]/cache.go:245 +0x56
    main.setupGoGuardianJWT()
    	/home/xxx/go/src/gitlab.com/xxx/my-project/cmd/go-guardian-jwt.go:33 +0x17d
    main.main()
    	/home/xxx/go/src/gitlab.com/xxx/my-project/cmd/main.go:20 +0x1d
    exit status 2
    
    
  • Authenticate username, password passed from frontend

    Authenticate username, password passed from frontend

    Hi, I would like to ask how to use authenticator to verify username/pass instead of request

    Here is the authenticator from the go guardian package

           return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    	log.Println("Executing Auth Middleware")
    	for k, v := range r.URL.Query() {
    		log.Printf("%s: %s\n", k, v)
    	}
    	user, err := authenticator.Authenticate(r)
    

    What I want to do is to check the user by cheking the username/password passed from frontend form Like

             func SetupGoGuardian(u, p string) (*authentication.User, error) {
                       // u here is username from form
                       // p here is password from form
                   log.Printf("User username %s", u)
                   cfg := &ldap.Config{
    	            Port:         "389",
    	            Host:         "ldapadmin.test",
    	            BindDN:       "cn=admin,dc=ldapadmin,dc=test",
    	            BindPassword: "root",
    	            BaseDN:       "dc=ldapadmin, dc=test",
    	            Filter:       "(uid=%s)",
                   }
                  authenticator = auth.New()
                  cache = store.NewFIFO(context.Background(), time.Minute*10)
                  strategy := ldap.NewCached(cfg, cache)
                  authenticator.EnableStrategy(ldap.StrategyKey, strategy)
                      user, err := authenticator.Authenticate(u, p) // this what I want to check my username password,
    	      if err != nil {
                          return &authentication.User{}, nil
                      }
                       return (///////////////////you are now allowed)
    

    Any ideas ?

  • Feature: ldap strategy collect user group

    Feature: ldap strategy collect user group

    Context: LDAP strategy does not fetch user groups and only fill the user info and the rest of the data mapped to extensions.

    Tasks:

    • update LDAP strategy to fetch user groups
    • Test changes
Authorization and authentication. Learning go by writing a simple authentication and authorization service.

Authorization and authentication. Learning go by writing a simple authentication and authorization service.

Aug 5, 2022
A simple passwordless authentication middleware that uses only email as the authentication provider
A simple passwordless authentication middleware that uses only email as the authentication provider

email auth A simple passwordless authentication middleware that uses only email as the authentication provider. Motivation I wanted to restrict access

Jul 27, 2022
Authelia: an open-source authentication and authorization server providing two-factor authentication
Authelia: an open-source authentication and authorization server providing two-factor authentication

Authelia is an open-source authentication and authorization server providing two

Jan 5, 2022
Authentication Plugin for implementing Form-Based, Basic, Local, LDAP, OpenID Connect, OAuth 2.0, SAML Authentication
Authentication Plugin for implementing Form-Based, Basic, Local, LDAP, OpenID Connect, OAuth 2.0, SAML Authentication

Authentication Plugin for implementing Form-Based, Basic, Local, LDAP, OpenID Connect, OAuth 2.0, SAML Authentication

Jan 8, 2023
🍍Jeff provides the simplest way to manage web sessions in Go.

jeff A tool for managing login sessions in Go. Motivation I was looking for a simple session management wrapper for Go and from what I could tell ther

Jan 4, 2023
A simple authentication web application in Golang (using jwt)

Simple Authentication WebApp A simple authentication web app in Go (using JWT) Routes Path Method Data /api/v1/auth/register POST {"firstname":,"lastn

Feb 6, 2022
A reverse proxy that provides authentication with Google, Github or other providers.
A reverse proxy that provides authentication with Google, Github or other providers.

A reverse proxy and static file server that provides authentication using Providers (Google, GitHub, and others) to validate accounts by email, domain or group.

Jan 8, 2023
A reverse proxy that provides authentication with Google, Github or other providers.
A reverse proxy that provides authentication with Google, Github or other providers.

A reverse proxy and static file server that provides authentication using Providers (Google, GitHub, and others) to validate accounts by email, domain

Jan 1, 2023
AuthService is a service that provides authentication with Minecraft Mojang.

AuthService AuthService is a service that provides authentication with Minecraft Mojang. Protobuf is managed by Buf. Command to pull Protobuf files wi

Aug 20, 2022
Authentication service that keeps you in control without forcing you to be an expert in web security.
Authentication service that keeps you in control without forcing you to be an expert in web security.

Authentication service that keeps you in control without forcing you to be an expert in web security.

Jan 1, 2023
Handle Web Authentication for Go apps that wish to implement a passwordless solution for users

WebAuthn Library This library is meant to handle Web Authentication for Go apps that wish to implement a passwordless solution for users. While the sp

Dec 30, 2022
Handle Web Authentication for Go apps that wish to implement a passwordless solution for users

WebAuthn Library This library is meant to handle Web Authentication for Go apps that wish to implement a passwordless solution for users. While the sp

Jan 1, 2023
🔥 Golang Rest Api with basic JWT Authentication and Basic Crud Operations.

?? Golang Rest Api with basic JWT Authentication and Basic Crud Operations.

Oct 4, 2022
Example of a simple application which is powered by a third-party oAuth 2.0 server for it's authentication / authorization. Written in Golang.

go mod init github.com/bartmika/osin-thirdparty-example go get github.com/spf13/cobra go get github.com/openshift/osin go get github.com/openshift/osi

Jan 4, 2022
Authenticated and encrypted API tokens using modern crypto

Branca Token Authenticated and encrypted API tokens using modern crypto. What? Branca is a secure, easy to use token format which makes it hard to sho

Dec 25, 2022
fiber api key authentication middleware

fiber-key-auth Secure your fiber endpoints using API keys. Report Bug · Request Feature Table of Contents About The Project Built With Getting Started

Dec 14, 2022
A library and binary to dump authentication configuration from etcd.

A libary and binary to dump authentication information from etcd. The commands are suitable for configuring an empty etcd cluster to get to the same authentication config.

Jan 20, 2022
Simple authentication and books management with GoFiber

Simple authentication and books management with GoFiber Simple authentication system with gofiber. Endpoints GET /api - Welcome message POST /api/auth

Nov 27, 2022
stark key authentication library, signature generator for dydx exchange

stark key authentication library, signature generator for dydx exchange for the following operations: Place an order Withdraw funds link : https://doc

Nov 10, 2022