- Notifications
You must be signed in to change notification settings - Fork87
Authenticator via oauth2, direct, email and telegram
License
go-pkgz/auth
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
This library provides "social login" with Github, Google, Facebook, Microsoft, Twitter, Yandex, Battle.net, Apple, Patreon, Discord and Telegram as well as custom auth providers and email verification.
- Multiple oauth2 providers can be used at the same time
- Special
dev
provider allows local testing and development - JWT stored in a secure cookie with XSRF protection. Cookies can be session-only
- Minimal scopes with user name, id and picture (avatar) only
- Direct authentication with user's provided credential checker
- Verified authentication with user's provided sender (email, im, etc)
- Custom oauth2 server and ability to use any third party provider
- Integrated avatar proxy with an FS, boltdb and gridfs storage
- Support of user-defined storage for avatars
- Identicon for default avatars
- Black list with user-defined validator
- Multiple aud (audience) supported
- Secure key with customizable
SecretReader
- Ability to store an extra information to token and retrieve on login
- Pre-auth and post-auth hooks to handle custom use cases.
- Middleware for easy integration into http routers
- Wrappers to extract user info from the request
- Role based access control
go get -u github.com/go-pkgz/auth
Example with chi router:
funcmain() {// define optionsoptions:= auth.Opts{SecretReader:token.SecretFunc(func(idstring) (string,error) {// secret key for JWTreturn"secret",nil}),TokenDuration:time.Minute*5,// token expires in 5 minutesCookieDuration:time.Hour*24,// cookie expires in 1 day and will enforce re-loginIssuer:"my-test-app",URL:"http://127.0.0.1:8080",AvatarStore:avatar.NewLocalFS("/tmp"),Validator:token.ValidatorFunc(func(_string,claims token.Claims)bool {// allow only dev_* namesreturnclaims.User!=nil&&strings.HasPrefix(claims.User.Name,"dev_")}),}// create auth service with providersservice:=auth.NewService(options)service.AddProvider("github","<Client ID>","<Client Secret>")// add github providerservice.AddProvider("facebook","<Client ID>","<Client Secret>")// add facebook provider// retrieve auth middlewarem:=service.Middleware()// setup http serverrouter:=chi.NewRouter()router.Get("/open",openRouteHandler)// open apirouter.With(m.Auth).Get("/private",protectedRouteHandler)// protected api// setup auth routesauthRoutes,avaRoutes:=service.Handlers()router.Mount("/auth",authRoutes)// add auth handlersrouter.Mount("/avatar",avaRoutes)// add avatar handlerlog.Fatal(http.ListenAndServe(":8080",router))}
github.com/go-pkgz/auth/middleware
provides ready-to-use middleware.
middleware.Auth
- requires authenticated usermiddleware.Admin
- requires authenticated admin usermiddleware.Trace
- doesn't require authenticated user, but adds user info to requestmiddleware.RBAC
- requires authenticated user with passed role(s)
Also, there is a special middlewaremiddleware.UpdateUser
for population and modifying UserInfo in every request. See "Customization" for more details.
Generally, adding support ofauth
includes a few relatively simple steps:
- Setup
auth.Opts
structure with all parameters. Each of themdocumented and most of parameters are optional and have sane defaults. - Create the new
auth.Service
with provided options. - Add all desirable authentication providers.
- Retrievemiddleware andhttp handlers from
auth.Service
- Wire auth and avatar handlers into http router as sub–routes.
For the example above authentication handlers wired as/auth
and provides:
/auth/<provider>/login?site=<site_id>&from=<redirect_url>
- site_id used asaud
claim for the token and can be processed bySecretReader
to load/retrieve/define different secrets. redirect_url is the url to redirect after successful login./avatar/<avatar_id>
- returns the avatar (image). Links to those pictures added into user info automatically, for details see "Avatar proxy"/auth/<provider>/logout
and/auth/logout
- invalidate "session" by removing JWT cookie/auth/list
- gives a json list of active providers/auth/user
- returnstoken.User
(json)/auth/status
- returns status of logged in user (json)
Middleware populatestoken.User
to request's context. It can be loaded withtoken.GetUserInfo(r *http.Request) (user User, err error)
ortoken.MustGetUserInfo(r *http.Request) User
functions.
token.User
object includes all fields retrieved from oauth2 provider:
Name
- user nameID
- hash of user idPicture
- full link to proxied avatar (see "Avatar proxy")
It also has placeholders for fields application can populate with customtoken.ClaimsUpdater
(see "Customization")
IP
- hash of user's IP addressEmail
- user's emailAttributes
- map of string:any-value. To simplify management of this map some setters and getters provided, for exampleusers.StrAttr
,user.SetBoolAttr
and so on. Seeuser.go for more details.
Direct links to avatars won't survive any real-life usage if they linked from a public page. For example, pagelike this may have hundreds of avatars and, most likely, will trigger throttling on provider's side. To eliminate such restrictionauth
library provides an automatic proxy
- On each login the proxy will retrieve user's picture and save it to
AvatarStore
- Local (proxied) link to avatar included in user's info (jwt token)
- API for avatar removal provided as a part of
AvatarStore
- User can leverage one of the provided stores:
- In case of need custom implementations of other stores can be passed in and used by
auth
library. Each store has to implementavatar.Store
interface. - All avatar-related setup done as a part of
auth.Opts
and needs:AvatarStore
- avatar store to use, i.e.avatar.NewLocalFS("/tmp/avatars")
or more genericavatar.NewStore(uri)
- file system uri -
file:///tmp/location
or just/tmp/location
- boltdb -
bolt://tmp/avatars.bdb
- mongo -
"mongodb://127.0.0.1:27017/test?ava_db=db1&ava_coll=coll1
- file system uri -
AvatarRoutePath
- route prefix for direct links to proxied avatar. For example/api/v1/avatars
will make full links like this -http://example.com/api/v1/avatars/1234567890123.image
. The url will be stored in user's token and retrieved by middleware (see "User Info")AvatarResizeLimit
- size (in pixels) used to resize the avatar. Pls note - resize happens once as a part ofPut
call, i.e. on login. 0 size (default) disables resizing.
In addition to oauth2 providersauth.Service
allows to use direct user-defined authentication. This is done by adding direct provider withauth.AddDirectProvider
.
service.AddDirectProvider("local",provider.CredCheckerFunc(func(user,passwordstring) (okbool,errerror) {ok,err=checkUserSomehow(user,password)returnok,err}))
Such provider acts like any other, i.e. will be registered as/auth/local/login
.
The API for this provider supports both GET and POST requests:
- POST request could be encoded as application/x-www-form-urlencoded or application/json:
POST /auth/<name>/login?session=[1|0]body: application/x-www-form-urlencodeduser=<user>&passwd=<password>&aud=<site_id>
POST /auth/<name>/login?session=[1|0]body: application/json{ "user": "name", "passwd": "xyz", "aud": "bar",}
- GET request with user credentials provided as query params, but be aware thatthe https query string is not secure:
GET /auth/<name>/login?user=<user>&passwd=<password>&aud=<site_id>&session=[1|0]
note: password parameter doesn't have to be naked/real password and can be any kind of password hash prepared by caller.
Another non-oauth2 provider allowing user-confirmed authentication, for example by email or slack or telegram. This isdone by adding confirmed provider withauth.AddVerifProvider
.
msgTemplate:="Confirmation email, token: {{.Token}}"service.AddVerifProvider("email",msgTemplate,sender)
Message template may use the follow elements:
{{.Address}}
- user address, for example email{{.User}}
- user name{{.Token}}
- confirmation token{{.Site}}
- site ID
Sender should be provided by end-user and implements a single function interface
typeSenderinterface {Send(addressstring,textstring)error}
For convenience a functional wrapperSenderFunc
provided. Email sender provided inprovider/sender
package and can beused asSender
.
The API for this provider:
GET /auth/<name>/login?user=<user>&address=<address>&aud=<site_id>&from=<url>
- send confirmation request to userGET /auth/<name>/login?token=<conf.token>&sess=[1|0]
- authorize with confirmation token
The provider acts like any other, i.e. will be registered as/auth/email/login
.
For email notify provider, please usegithub.com/go-pkgz/auth/provider/sender
package:
sndr:=sender.NewEmailClient(sender.EmailParams{Host:"email.hostname",Port:567,SMTPUserName:"username",SMTPPassword:"pass",StartTLS:true,InsecureSkipVerify:false,From:"notify@email.hostname",Subject:"subject",ContentType:"text/html",Charset:"UTF-8",},log.Default())authenticator.AddVerifProvider("email","template goes here",sndr)
Seethat documentation for full options list.
Telegram provider allows your users to log in with Telegram account. First, you will need to create your bot.Contact@BotFather and follow his instructions to create your own bot (call it, for example, "My site auth bot")
Next initialize TelegramHandler with following parameters:
ProviderName
- Any unique name to distinguish between providersSuccessMsg
- Message sent to user on successfull authenticationErrorMsg
- Message sent on errors (e.g. login request expired)Telegram
- Telegram API implementation. Use provider.NewTelegramAPI with following arguments- The secret token bot father gave you
- An http.Client for accessing Telegram API's
token:=os.Getenv("TELEGRAM_TOKEN")telegram:= provider.TelegramHandler{ProviderName:"telegram",ErrorMsg:"❌ Invalid auth request. Please try clicking link again.",SuccessMsg:"✅ You have successfully authenticated!",Telegram:provider.NewTelegramAPI(token,http.DefaultClient),L:log.Default(),TokenService:service.TokenService(),AvatarSaver:service.AvatarProxy(),}
After that run provider and register it's handlers:
// Run Telegram provider in the backgroundgofunc() {err:=telegram.Run(context.Background())iferr!=nil {log.Fatalf("[PANIC] failed to start telegram: %v",err)}}()// Register Telegram providerservice.AddCustomHandler(&telegram)
Now all your users have to do is click one of the following links and pressstarttg://resolve?domain=<botname>&start=<token>
orhttps://t.me/<botname>/?start=<token>
Use the following routes to interact with provider:
/auth/<providerName>/login
- Obtain auth token. Returns JSON object withbot
(bot username) andtoken
(token itself) fields./auth/<providerName>/login?token=<token>
- Check if auth request has been confirmed (i.e. user pressed start). Sets session cookie and returns user info on success, errors with 404 otherwise./auth/<providerName>/logout
- Invalidate user session.
This provider brings two extra functions:
- Adds ability to use any third-party oauth2 providers in addition to the list of directly supported. Includedexample demonstrates how to do it for bitbucket.In order to add a new oauth2 provider following input is required:
Name
- any name is allowed except the names from list of supported providers. It is possible to register more than one client for one given oauth2 provider (for example using different namesbitbucket_dev
andbitbucket_prod
)Client
- ID and secret of clientEndpoint
- auth URL and token URL. This information could be obtained from auth2 provider pageInfoURL
- oauth2 provider API method to read information of logged in user. This method could be found in documentation of oauth2 provider (e.g. for bitbuckethttps://developer.atlassian.com/bitbucket/api/2/reference/resource/user)MapUserFn
- function to convert the response fromInfoURL
totoken.User
(s. example below)Scopes
- minimal needed scope to read user information. Client should be authorized to these scopes
c:= auth.Client{Cid:os.Getenv("AEXMPL_BITBUCKET_CID"),Csecret:os.Getenv("AEXMPL_BITBUCKET_CSEC"),}service.AddCustomProvider("bitbucket",c, provider.CustomHandlerOpt{Endpoint: oauth2.Endpoint{AuthURL:"https://bitbucket.org/site/oauth2/authorize",TokenURL:"https://bitbucket.org/site/oauth2/access_token",},InfoURL:"https://api.bitbucket.org/2.0/user/",MapUserFn:func(data provider.UserData,_ []byte) token.User {userInfo:= token.User{ID:"bitbucket_"+token.HashID(sha1.New(),data.Value("username")),Name:data.Value("nickname"),}returnuserInfo},Scopes: []string{"account"},})
- Adds local oauth2 server user can fully customize. It uses
gopkg.in/oauth2.v3
library and example shows howto initialize the server andsetup a provider.- to start local oauth2 server following options are required:
URL
- url of oauth2 server with portWithLoginPage
- flag to define whether login page should be shownLoginPageHandler
- function to handle login request. If not specified default login page will be shown
sopts:= provider.CustomServerOpt{URL:"http://127.0.0.1:9096",L:options.Logger,WithLoginPage:true,}prov:=provider.NewCustomServer(srv,sopts)// Start servergoprov.Run(context.Background())
- to register handler for local oauth2 following option are required:
Name
- any name except the names from list of supported providersClient
- ID and secret of clientHandlerOpt
- handler options of custom oauth provider
service.AddCustomProvider("custom123", auth.Client{Cid:"cid",Csecret:"csecret"},prov.HandlerOpt)
- to start local oauth2 server following options are required:
Additionally it is possible to implement own auth handler. It may be useful if auth provider does not conform to oauth standard. Self-implemented handler has to implementprovider.Provider
interface.
// customHandler implements provider.Provider interfacec:=customHandler{}// add customHandler to stack of auth handlersservice.AddCustomHandler(c)
There are several ways to adjust functionality of the library:
SecretReader
- interface with a single methodGet(aud string) string
to return the secret used for JWT signing and verificationClaimsUpdater
- interface withUpdate(claims Claims) Claims
method. This is the primary way to alter a token at login time and add any attributes, set ip, email, admin status, roles and so on.Validator
- interface withValidate(token string, claims Claims) bool
method. This is post-token hook and will be called oneach request wrapped withAuth
middleware. This will be the place for special logic to reject some tokens or users.UserUpdater
- interface withUpdate(claims token.User) token.User
method. This method will be called oneach request wrapped withUpdateUser
middleware. This will be the place for special logic modify User Info in request context.Example of usage.
All of the interfaces above have corresponding Func adapters -SecretFunc
,ClaimsUpdFunc
,ValidatorFunc
andUserUpdFunc
.
Restricting some users or some tokens is two step process:
ClaimsUpdater
sets an attribute, likeblocked
(orallowed
)Validator
checks the attribute and returns true/false
This technique used in theexample code
The process can be simplified by doing all checks directly inValidator
, but depends on particular case such solutioncan be too expensive becauseValidator
runs on each request as a part of auth middleware. In contrast,ClaimsUpdater
called on token creation/refresh only.
For complex systems a single authenticator may serve multiple distinct subsystems or multiple set of independent users. For example some SaaS offerings may need to provide different authentications for different customers and prevent use of tokens/cookies made by another customer.
Such functionality can be implemented in 3 different ways:
- Different instances of
auth.Service
each one with different secret. Doing this way will ensure the highest level of isolation and cookies/tokens won't be even parsable across the instances. Practically such architecture can be too complicated and not always possible.– Handling "allowed audience" as a part ofClaimsUpdater
andValidator
chain. I.e.ClaimsUpdater
sets a claim indicating expected audience code/id andValidator
making sure it matches. This way a singleauth.Service
could handle multiple groups of auth tokens and reject some based on the audience. - Using the standard JWT
aud
claim. This method conceptually very similar to the previous one, but done by library internally and consumer don't need to define specialClaimsUpdater
andValidator
logic.
In order to allowaud
support the list of allowed audiences should be passed in asopts.Audiences
parameter. Non-empty value will trigger internal checks for token generation (will reject token creation for alienaud
) as well asAuth
middleware.
Working with oauth2 providers can be a pain, especially during development phase. A special, development-only providerdev
can make it less painful. This one can be registered directly, i.e.service.AddProvider("dev", "", "")
orservice.AddDevProvider(port)
and should be activated like this:
// runs dev oauth2 server on :8084 by defaultgofunc() {devAuthServer,err:=service.DevAuth()iferr!=nil {log.Fatal(err)}devAuthServer.Run()}()
It will run fake aouth2 "server" on port :8084 and user could login with any user name. Seeexample for more details.
Warning: this is not the real oauth2 server but just a small fake thing for development and testing only. Don't usedev
provider with any production code.
By default, Dev provider doesn't returnemail
claim from/user
endpoint, to match behaviour of other providers which only request minimal scopes.However sometimes it is useful to haveemail
included into user info. This can be done by configuringdevAuthServer.GetEmailFn
function:
gofunc() {devAuthServer,err:=service.DevAuth()devOauth2Srv.GetEmailFn=func(usernamestring)string {returnusername+"@example.com"}iferr!=nil {log.Fatal(err)}devAuthServer.Run()}()
In addition to the primary method (i.e. JWT cookie with XSRF header) there are two more ways to authenticate:
- Send JWT header as
X-JWT
. This shouldn't be used for web application, however can be helpful for service-to-service authentication. - Send JWT token as query parameter, i.e.
/something?token=<jwt>
- Basic access authentication, for more details see belowBasic authentication.
In some cases themiddleware.Authenticator
allow useBasic access authentication, which transmits credentials as user-id/password pairs, encoded using Base64 (RFC7235).When basic authentication used, client doesn't get auth token in response. It's auth type expect credentials in a headerAuthorization
at every client request. It can be helpful, if client side not support cookie/token store (e.g. embedded device or custom apps).This mode disabled by default and will be enabled with options.
Theauth
package has two options of basic authentication:
- simple basic auth will be enabled if
Opts.AdminPasswd
defined. This will allow access with basic auth admin:<Opts.AdminPasswd> with useradmin. Such method can be used for automation scripts. - basic auth with custom checkerfunction, which allow adding user data from store to context of request. It will be enabled if
Opts.BasicAuthChecker
defined. WhenBasicAuthChecker
defined thenOpts.AdminPasswd
option will be ignore.
options:= auth.Opts{//...AdminPasswd:"admin_secret_password",// will ignore if BasicAuthChecker definedBasicAuthChecker:func(user,passwdstring) (bool, token.User,error) {ifuser=="basic_user"&&passwd=="123456" {returntrue, token.User{Name:user,Role:"test_r"},nil }returnfalse, token.User{},errors.New("basic auth credentials check failed") }//...}
By default, this library doesn't print anything to stdout/stderr, however user can pass a logger implementinglogger.L
interface with a single methodLogf(format string, args ...interface{})
. Functional adapter for this interface included aslogger.Func
. There are two predefined implementations in thelogger
package -NoOp
(prints nothing, default) andStd
wrappinglog.Printf
from stdlib.
Authentication handled by external providers. You should setup oauth2 for all (or some) of them to allow users to authenticate. It is not mandatory to have all of them, but at least one should be correctly configured.
- Create a new project:https://console.developers.google.com/project
- Choose the new project from the top right project dropdown (only if another project is selected)
- In the project Dashboard center pane, choose"API Manager"
- In the left Nav pane, choose"Credentials"
- In the center pane, choose the"OAuth consent screen" tab.
- Select "External" and click "Create"
- Fill in"App name" and selectUser support email
- Upload a logo, if you want to
- In theApp Domain section:
- Application home page - your site URL, e.g.,
https://mysite.com
- Application privacy policy link -
/web/privacy.html
of your Remark42 installation, e.g.https://remark42.mysite.com/web/privacy.html
(please check that it works) - Terms of service - leave empty
- Application home page - your site URL, e.g.,
- Authorized domains - your site domain, e.g.,
mysite.com
- Developer contact information - add your email, and then clickSave and continue
- On theScopes tab, just clickSave and continue
- On theTest users, add your email, then clickSave and continue
- Before going to the next step, set the app to "Production" and send it to verification
- In the center pane, choose the"Credentials" tab
- Open the"Create credentials" drop-down
- Choose"OAuth client ID"
- Choose"Web application"
- ApplicationName is freeform; choose something appropriate, like "Comments on mysite.com"
- Authorized JavaScript Origins should be your domain, e.g.,
https://remark42.mysite.com
- Authorized redirect URIs is the location of OAuth2/callback constructed as domain +
/auth/google/callback
, e.g.,https://remark42.mysite.com/auth/google/callback
- Click"Create"
- Take note of theClient ID andClient Secret
instructions for google oauth2 setup borrowed fromoauth2_proxy
- Register a new applicationusing the Azure portal.
- Under"Authentication/Platform configurations/Web" enter the correct url constructed as domain +
/auth/microsoft/callback
. i.e.https://example.mysite.com/auth/microsoft/callback
- In "Overview" take note of theApplication (client) ID
- Choose the new project from the top right project dropdown (only if another project is selected)
- Select "Certificates & secrets" and click on "+ New Client Secret".
- Create a new"OAuth App":https://github.com/settings/developers
- Fill"Application Name" and"Homepage URL" for your site
- Under"Authorization callback URL" enter the correct url constructed as domain +
/auth/github/callback
. iehttps://example.mysite.com/auth/github/callback
- Take note of theClient ID andClient Secret
- Fromhttps://developers.facebook.com select"My Apps" /"Add a new App"
- Set"Display Name" and"Contact email"
- Choose"Facebook Login" and then"Web"
- Set "Site URL" to your domain, ex:
https://example.mysite.com
- Under"Facebook login" /"Settings" fill "Valid OAuth redirect URIs" with your callback url constructed as domain +
/auth/facebook/callback
- Select"App Review" and turn public flag on. This step may ask you to provide a link to your privacy policy.
To configure this provider, a user requires an Apple developer account (without it setting up a sign in with Apple is impossible).Sign in with Apple lets users log in to your app using their two-factor authentication Apple ID.
Follow to next steps for configuring on the Apple side:
- Log into the developer account.
- If you don't have an App ID yet,create one. Later on, you'll needTeamID, which is an "App ID Prefix" value.
- Enable the "Sign in with Apple" capability for your App ID inthe Certificates, Identifiers & Profiles section.
- CreateService ID and bind with App ID from the previous step. Apple will display the description field value to end-users on sign-in. You'll need that serviceIdentifier as a ClientID later on**.**
- Configure "Sign in with Apple" for created Service ID. Add domain where you will use that auth on to "Domains and subdomains" and its main page URL (like
https://example.com/
to "Return URLs". - Register aNew Key (private key) for the "Sign in with Apple" feature and download it. Write down theKey ID. This key will be used to createJWT Client Secret.
- Add your domain name and sender email in the Certificates, Identifiers & Profiles >>More section as a new Email Source.
After completing the previous steps, you can proceed with configuring the Apple auth provider. Here are the parameters for AppleConfig:
- ClientID (required) - Service ID (or App ID) which is used for Sign with Apple
- TeamID (required) - Identifier a developer account (use as prefix for all App ID)
- KeyID (required) - Identifier a generated key for Sign with Apple
- ResponseMode - Response Mode, please seedocumentation for reference, default is
form_post
// apple config parametersappleCfg:= provider.AppleConfig{TeamID:os.Getenv("AEXMPL_APPLE_TID"),// developer account identifierClientID:os.Getenv("AEXMPL_APPLE_CID"),// Service ID (or App ID)KeyID:os.Getenv("AEXMPL_APPLE_KEYID"),// private key identifier}
Then add an Apple provider that accepts the following parameters:
appleConfig (provider.AppleConfig)
created aboveprivateKeyLoader (PrivateKeyLoaderInterface)
PrivateKeyLoaderInterface
implements a loader for the private key (which you downloaded above) to create aclient_secret
. The user can use a pre-defined functionprovider.LoadApplePrivateKeyFromFile(filePath string)
to load the private key from local file.
AddAppleProvide
tries to load private key at call and return an error if load failed. Always check error when calling this provider.
iferr:=service.AddAppleProvider(appleCfg,provider.LoadApplePrivateKeyFromFile("PATH_TO_PRIVATE_KEY_FILE"));err!=nil {log.Fatalf("[ERROR] failed create to AppleProvider: %v",err)}
Limitation:
Map a userName (if specific scope defined) is only sent in the upon initial user sign up.Subsequent logins to your app using Sign In with Apple with the same account do not share any user info and will only return a user identifier in IDToken claims.This behaves correctly until a user delete sign in for you service with Apple ID in own Apple account profile (security section).It is recommend that you securely cache the at first login containing the user info for bind it with a user UID at next login.Provider always get user
UID
(sub
claim) inIDToken
.Apple doesn't have an API for fetch avatar and user info.
Seeexample before use.
- Create a new"OAuth App":https://oauth.yandex.com/client/new
- Fill"App name" for your site
- UnderPlatforms select"Web services" and enter"Callback URI #1" constructed as domain +
/auth/yandex/callback
. iehttps://example.mysite.com/auth/yandex/callback
- SelectPermissions. You need following permissions only from the"Yandex.Passport API" section:
- Access to user avatar
- Access to username, first name and surname, gender
- Fill out the rest of fields if needed
- Take note of theID andPassword
For more details refer toYandex OAuth andYandex.Passport API documentation.
- Log into Battle.net as a developer:https://develop.battle.net/nav/login-redirect
- Click "+ CREATE CLIENT"https://develop.battle.net/access/clients/create
- For "Client name", enter whatever you want
- For "Redirect URLs", one of the lines must be "http[s]://your_remark_installation:port//auth/battlenet/callback", e.g.https://localhost:8443/auth/battlenet/callback orhttps://remark.mysite.com/auth/battlenet/callback
- For "Service URL", enter the URL to your site or check "I do not have a service URL for this client." checkbox if you don't have any
- For "Intended use", describe the application you're developing
- Click "Save".
- You can see your client ID and client secret athttps://develop.battle.net/access/clients by clicking the client you created
For more details refer toComplete Guide of Battle.net OAuth API and Login Button orthe official Battle.net OAuth2 guide
- Create a new Patreon clienthttps://www.patreon.com/portal/registration/register-clients
- Fill"App Name","Description","App Category" and"Author" for your site
- Under"Redirect URIs" enter the correct url constructed as domain +
/auth/patreon/callback
. iehttps://example.mysite.com/auth/patreon/callback
- Take note of theClient ID andClient Secret
- Log into Discord Developer Portalhttps://discord.com/developers/applications
- Click onNew Application to create the application required for Oauth
- After filling"NAME", navigate to"OAuth2" option on the left sidebar
- Under"Redirects" enter the correct url constructed as domain +
/auth/discord/callback
. iehttps://remark42.mysite.com/auth/discord/callback
- Take note of theCLIENT ID andCLIENT SECRET
- Create a new twitter applicationhttps://developer.twitter.com/en/apps
- FillApp name andDescription andURL of your site
- In the fieldCallback URLs enter the correct url of your callback handler e.g.https://example.mysite.com/{route}/twitter/callback
- UnderKey and tokens take note of theConsumer API Key andConsumer API Secret key. Those will be used as
cid
andcsecret
By default, the XSRF protections will apply to all requests which reach themiddlewares.Auth
,middlewares.Admin
ormiddlewares.RBAC
middlewares. This will require setting a request headerwith a key of<XSRFHeaderKey>
containing the value of the cookie named<XSRFCookieName>
.
To disable all XSRF protections, setDisableXSRF
totrue
. This should probably only be usedduring testing or debugging.
When setting a custom request header is not possible, such as when building a web application whichis not a Single-Page-Application and HTML link tags are used to navigate pages, specific HTTP methodsmay be excluded using theXSRFIgnoreMethods
option. For example, to disable GET requests, set thisoption toXSRFIgnoreMethods: []string{"GET"}
. Adding methods other than GET to this list may resultin XSRF vulnerabilities.
The library extracted fromremark42 project. The original code in production use on multiple sites and seems to work fine.
go-pkgz/auth
library still in development and until version 1 released some breaking changes possible.
About
Authenticator via oauth2, direct, email and telegram