github.com/volatiletech/authboss@v2.4.1+incompatible/README.md (about) 1 <img src="http://i.imgur.com/fPIgqLg.jpg"/> 2 3 # Authboss 4 5 [![GoDoc](https://godoc.org/github.com/volatiletech/authboss?status.svg)](https://godoc.org/github.com/volatiletech/authboss) 6 [![Build Status](https://circleci.com/gh/volatiletech/authboss.svg?style=shield&circle-token=:circle-token)](https://circleci.com/gh/volatiletech/authboss) 7 [![Coverage Status](https://coveralls.io/repos/volatiletech/authboss/badge.svg?branch=master)](https://coveralls.io/r/volatiletech/authboss?branch=master) 8 [![Mail](https://img.shields.io/badge/mail%20list-authboss-lightgrey.svg)](https://groups.google.com/a/volatile.tech/forum/#!forum/authboss) 9 10 Authboss is a modular authentication system for the web. 11 12 It has several modules that represent authentication and authorization features that are common 13 to websites in general so that you can enable as many as you need, and leave the others out. 14 It makes it easy to plug in authentication to an application and get a lot of functionality 15 for (hopefully) a smaller amount of integration effort. 16 17 # New to v2? 18 19 v1 -> v2 was a very big change. If you're looking to upgrade there is a general guide in 20 [tov2.md](tov2.md) in this project. 21 22 # Why use Authboss? 23 24 Every time you'd like to start a new web project, you really want to get to the heart of what you're 25 trying to accomplish very quickly and it would be a sure bet to say one of the systems you're excited 26 about implementing and innovating on is not authentication. In fact it's very much the opposite: it's 27 one of those things that you have to do and one of those things you loathe to do. Authboss is supposed 28 to remove a lot of the tedium that comes with this, as well as a lot of the chances to make mistakes. 29 This allows you to care about what you're intending to do, rather than care about ancillary support 30 systems required to make what you're intending to do happen. 31 32 Here are a few bullet point reasons you might like to try it out: 33 34 * Saves you time (Authboss integration time should be less than re-implementation time) 35 * Saves you mistakes (at least using Authboss, people can bug fix as a collective and all benefit) 36 * Should integrate with or without any web framework 37 38 # Readme Table of Contents 39 <!-- TOC --> 40 41 - [Authboss](#authboss) 42 - [New to v2?](#new-to-v2) 43 - [Why use Authboss?](#why-use-authboss) 44 - [Readme Table of Contents](#readme-table-of-contents) 45 - [Getting Started](#getting-started) 46 - [App Requirements](#app-requirements) 47 - [CSRF Protection](#csrf-protection) 48 - [Request Throttling](#request-throttling) 49 - [Integration Requirements](#integration-requirements) 50 - [Middleware](#middleware) 51 - [Configuration](#configuration) 52 - [Storage and Core implementations](#storage-and-core-implementations) 53 - [ServerStorer implementation](#serverstorer-implementation) 54 - [User implementation](#user-implementation) 55 - [Values implementation](#values-implementation) 56 - [Config](#config) 57 - [Paths](#paths) 58 - [Modules](#modules) 59 - [Mail](#mail) 60 - [Storage](#storage) 61 - [Core](#core) 62 - [Available Modules](#available-modules) 63 - [Middlewares](#middlewares) 64 - [Use Cases](#use-cases) 65 - [Get Current User](#get-current-user) 66 - [Reset Password](#reset-password) 67 - [User Auth via Password](#user-auth-via-password) 68 - [User Auth via OAuth2](#user-auth-via-oauth2) 69 - [User Registration](#user-registration) 70 - [Confirming Registrations](#confirming-registrations) 71 - [Password Recovery](#password-recovery) 72 - [Remember Me](#remember-me) 73 - [Locking Users](#locking-users) 74 - [Expiring User Sessions](#expiring-user-sessions) 75 - [One Time Passwords](#one-time-passwords) 76 - [Two Factor Authentication](#two-factor-authentication) 77 - [Two-Factor Recovery](#two-factor-recovery) 78 - [Two-Factor Setup E-mail Authorization](#two-factor-setup-e-mail-authorization) 79 - [Time-Based One Time Passwords 2FA (totp)](#time-based-one-time-passwords-2fa-totp) 80 - [Adding 2fa to a user](#adding-2fa-to-a-user) 81 - [Removing 2fa from a user](#removing-2fa-from-a-user) 82 - [Logging in with 2fa](#logging-in-with-2fa) 83 - [Using Recovery Codes](#using-recovery-codes) 84 - [Text Message 2FA (sms)](#text-message-2fa-sms) 85 - [Adding 2fa to a user](#adding-2fa-to-a-user-1) 86 - [Removing 2fa from a user](#removing-2fa-from-a-user-1) 87 - [Logging in with 2fa](#logging-in-with-2fa-1) 88 - [Using Recovery Codes](#using-recovery-codes-1) 89 - [Rendering Views](#rendering-views) 90 - [HTML Views](#html-views) 91 - [JSON Views](#json-views) 92 - [Data](#data) 93 94 <!-- /TOC --> 95 96 # Getting Started 97 98 To get started with Authboss in the simplest way, is to simply create a Config, populate it 99 with the things that are required, and start implementing [use cases](#use-cases). The use 100 cases describe what's required to be able to use a particular piece of functionality, 101 or the best practice when implementing a piece of functionality. Please note the 102 [app requirements](#app-requirements) for your application as well 103 [integration requirements](#integration-requirements) that follow. 104 105 Of course the standard practice of fetching the library is just the beginning: 106 107 ```bash 108 # Get the latest, keep in mind you should be vendoring with dep or using vgo at this point 109 # To ensure versions don't get messed up underneath you 110 go get -u github.com/volatiletech/authboss 111 ``` 112 113 Here's a bit of starter code that was stolen from the sample. 114 115 ```go 116 ab := authboss.New() 117 118 ab.Config.Storage.Server = myDatabaseImplementation 119 ab.Config.Storage.SessionState = mySessionImplementation 120 ab.Config.Storage.CookieState = myCookieImplementation 121 122 ab.Config.Paths.Mount = "/authboss" 123 ab.Config.Paths.RootURL = "https://www.example.com/" 124 125 // This is using the renderer from: github.com/volatiletech/authboss 126 ab.Config.Core.ViewRenderer = abrenderer.New("/auth") 127 // Probably want a MailRenderer here too. 128 129 // Set up defaults for basically everything besides the ViewRenderer/MailRenderer in the HTTP stack 130 defaults.SetCore(&ab.Config, false) 131 132 if err := ab.Init(); err != nil { 133 panic(err) 134 } 135 136 // Mount the router to a path (this should be the same as the Mount path above) 137 // mux in this example is a chi router, but it could be anything that can route to 138 // the Core.Router. 139 mux.Mount("/authboss", http.StripPrefix("/authboss", ab.Config.Core.Router)) 140 ``` 141 142 For a more in-depth look you **definitely should** look at the authboss sample to see what a full 143 implementation looks like. This will probably help you more than any of this documentation. 144 145 [https://github.com/volatiletech/authboss-sample](https://github.com/volatiletech/authboss-sample) 146 147 ## App Requirements 148 149 Authboss does a lot of things, but it doesn't do some of the important things that are required by 150 a typical authentication system, because it can't guarantee that you're doing many of those things 151 in a different way already, so it punts the responsibility. 152 153 ### CSRF Protection 154 155 What this means is you should apply a middleware that can protect the application from crsf 156 attacks or you may be vulnerable. Authboss previously handled this but it took on a dependency 157 that was unnecessary and it complicated the code. Because Authboss does not render views nor 158 consumes data directly from the user, it no longer does this. 159 160 ### Request Throttling 161 162 Currently Authboss is vulnerable to brute force attacks because there are no protections on 163 it's endpoints. This again is left up to the creator of the website to protect the whole website 164 at once (as well as Authboss) from these sorts of attacks. 165 166 ## Integration Requirements 167 168 In terms of integrating Authboss into your app, the following things must be considered. 169 170 ### Middleware 171 172 There are middlewares that are required to be installed in your middleware stack if it's 173 all to function properly, please see [Middlewares](#middlewares) for more information. 174 175 ### Configuration 176 177 There are some required configuration variables that have no sane defaults and are particular 178 to your app: 179 180 * Config.Paths.Mount 181 * Config.Paths.RootURL 182 183 ### Storage and Core implementations 184 185 Everything under Config.Storage and Config.Core are required and you must provide them, 186 however you can optionally use default implementations from the 187 [defaults package](https://github.com/volatiletech/authboss/tree/master/defaults). 188 This also provides an easy way to share implementations of certain stack pieces (like HTML Form Parsing). 189 As you saw in the example above these can be easily initialized with the `SetCore` method in that 190 package. 191 192 The following is a list of storage interfaces, they must be provided by the implementer. Server is a 193 very involved implementation, please see the additional documentation below for more details. 194 195 * Config.Storage.Server 196 * Config.Storage.SessionState 197 * Config.Storage.CookieState (only for "remember me" functionality) 198 199 The following is a list of the core pieces, these typically are abstracting the HTTP stack. 200 Out of all of these you'll probably be mostly okay with the default implementations in the 201 defaults package but there are two big exceptions to this rule and that's the ViewRenderer 202 and the MailRenderer. For more information please see the use case [Rendering Views](#rendering-views) 203 204 * Config.Core.Router 205 * Config.Core.ErrorHandler 206 * Config.Core.Responder 207 * Config.Core.Redirector 208 * Config.Core.BodyReader 209 * Config.Core.ViewRenderer 210 * Config.Core.MailRenderer 211 * Config.Core.Mailer 212 * Config.Core.Logger 213 214 ### ServerStorer implementation 215 216 The [ServerStorer](https://godoc.org//github.com/volatiletech/authboss/#ServerStorer) is 217 meant to be upgraded to add capabilities depending on what modules you'd like to use. 218 It starts out by only knowing how to save and load users, but the `remember` module as an example 219 needs to be able to find users by remember me tokens, so it upgrades to a 220 [RememberingServerStorer](https://godoc.org/github.com/volatiletech/authboss/#RememberingServerStorer) 221 which adds these abilities. 222 223 Your `ServerStorer` implementation does not need to implement all these additional interfaces 224 unless you're using a module that requires it. See the [Use Cases](#use-cases) documentation to know what the requirements are. 225 226 ### User implementation 227 228 Users in Authboss are represented by the 229 [User interface](https://godoc.org//github.com/volatiletech/authboss/#User). The user 230 interface is a flexible notion, because it can be upgraded to suit the needs of the various modules. 231 232 Initially the User must only be able to Get/Set a `PID` or primary identifier. This allows the authboss 233 modules to know how to refer to him in the database. The `ServerStorer` also makes use of this 234 to save/load users. 235 236 As mentioned, it can be upgraded, for example suppose now we want to use the `confirm` module, 237 in that case the e-mail address now becomes a requirement. So the `confirm` module will attempt 238 to upgrade the user (and panic if it fails) to a 239 [ConfirmableUser](https://godoc.org//github.com/volatiletech/authboss/#ConfirmableUser) 240 which supports retrieving and setting of confirm tokens, e-mail addresses, and a confirmed state. 241 242 Your `User` implementation does not need to implement all these additional user interfaces unless you're 243 using a module that requires it. See the [Use Cases](#use-cases) documentation to know what the 244 requirements are. 245 246 ### Values implementation 247 248 The [BodyReader](https://godoc.org//github.com/volatiletech/authboss/#BodyReader) 249 interface in the Config returns 250 [Validator](https://godoc.org//github.com/volatiletech/authboss/#Validator) implementations 251 which can be validated. But much like the storer and user it can be upgraded to add different 252 capabilities. 253 254 A typical `BodyReader` (like the one in the defaults package) implementation checks the page being 255 requested and switches on that to parse the body in whatever way 256 (msgpack, json, url-encoded, doesn't matter), and produce a struct that has the ability to 257 `Validate()` it's data as well as functions to retrieve the data necessary for the particular 258 valuer required by the module. 259 260 An example of an upgraded `Valuer` is the 261 [UserValuer](https://godoc.org//github.com/volatiletech/authboss/#UserValuer) 262 which stores and validates the PID and Password that a user has provided for the modules to use. 263 264 Your body reader implementation does not need to implement all valuer types unless you're 265 using a module that requires it. See the [Use Cases](#use-cases) documentation to know what the 266 requirements are. 267 268 ## Config 269 270 The config struct is an important part of Authboss. It's the key to making Authboss do what you 271 want with the implementations you want. Please look at it's code definition as you read the 272 documentation below, it will make much more sense. 273 274 [Config Struct Documentation](https://godoc.org/github.com/volatiletech/authboss/#Config) 275 276 ### Paths 277 278 Paths are the paths that should be redirected to or used in whatever circumstance they describe. 279 Two special paths that are required are `Mount` and `RootURL` without which certain authboss 280 modules will not function correctly. Most paths get defaulted to `/` such as after login success 281 or when a user is locked out of their account. 282 283 ### Modules 284 285 Modules are module specific configuration options. They mostly control the behavior of modules. 286 For example `RegisterPreserveFields` decides a whitelist of fields to allow back into the data 287 to be re-rendered so the user doesn't have to type them in again. 288 289 ### Mail 290 291 Mail sending related options. 292 293 ### Storage 294 295 These are the implementations of how storage on the server and the client are done in your 296 app. There are no default implementations for these at this time. See the [Godoc](https://godoc.org/github.com/volatiletech/authboss) for more information 297 about what these are. 298 299 ### Core 300 301 These are the implementations of the HTTP stack for your app. How do responses render? How are 302 they redirected? How are errors handled? 303 304 For most of these there are default implementations from the 305 [defaults package](https://github.com/volatiletech/authboss/defaults) available, but not for all. 306 See the package documentation for more information about what's available. 307 308 # Available Modules 309 310 Each module can be turned on simply by importing it and the side-effects take care of the rest. 311 Not all the capabilities of authboss are represented by a module, see [Use Cases](#use-cases) 312 to view the supported use cases as well as how to use them in your app. 313 314 **Note**: The two factor packages do not enable via side-effect import, see their documentation 315 for more information. 316 317 Name | Import Path | Description 318 ----------|-------------------------------------------|------------ 319 Auth | github.com/volatiletech/authboss/auth | Database password authentication for users. 320 Confirm | github.com/volatiletech/authboss/confirm | Prevents login before e-mail verification. 321 Expire | github.com/volatiletech/authboss/expire | Expires a user's login 322 Lock | github.com/volatiletech/authboss/lock | Locks user accounts after authentication failures. 323 Logout | github.com/volatiletech/authboss/logout | Destroys user sessions for auth/oauth2. 324 OAuth2 | github.com/volatiletech/authboss/oauth2 | Provides oauth2 authentication for users. 325 Recover | github.com/volatiletech/authboss/recover | Allows for password resets via e-mail. 326 Register | github.com/volatiletech/authboss/register | User-initiated account creation. 327 Remember | github.com/volatiletech/authboss/remember | Persisting login sessions past session cookie expiry. 328 OTP | github.com/volatiletech/authboss/otp | One time passwords for use instead of passwords. 329 Twofactor | github.com/volatiletech/authboss/otp/twofactor | Regenerate recovery codes for 2fa. 330 Totp2fa | github.com/volatiletech/authboss/otp/twofactor/totp2fa | Use Google authenticator-like things for a second auth factor. 331 Sms2fa | github.com/volatiletech/authboss/otp/twofactor/sms2fa | Use a phone for a second auth factor. 332 333 # Middlewares 334 335 The only middleware that's truly required is the `LoadClientStateMiddleware`, and that's because it 336 enables session and cookie handling for Authboss. Without that, it's not a very useful piece of 337 software. 338 339 The remaining middlewares are either the implementation of an entire module (like expire), 340 or a key part of a module. For example you probably wouldn't want to use the lock module 341 without the middleware that would stop a locked user from using an authenticated resource, 342 because then locking wouldn't be useful unless of course you had your own way of dealing 343 with locking, which is why it's only recommended, and not required. Typically you will 344 use the middlewares if you use the module. 345 346 Name | Requirement | Description 347 ---- | ----------- | ----------- 348 [Middleware](https://godoc.org/github.com/volatiletech/authboss/#Middleware) | Recommended | Prevents unauthenticated users from accessing routes. 349 [LoadClientStateMiddleware](https://godoc.org/github.com/volatiletech/authboss/#Authboss.LoadClientStateMiddleware) | **Required** | Enables cookie and session handling 350 [ModuleListMiddleware](https://godoc.org/github.com/volatiletech/authboss/#Authboss.ModuleListMiddleware) | Optional | Inserts a loaded module list into the view data 351 [confirm.Middleware](https://godoc.org/github.com/volatiletech/authboss/confirm/#Middleware) | Recommended with confirm | Ensures users are confirmed or rejects request 352 [expire.Middleware](https://godoc.org/github.com/volatiletech/authboss/expire/#Middleware) | **Required** with expire | Expires user sessions after an inactive period 353 [lock.Middleware](https://godoc.org/github.com/volatiletech/authboss/lock/#Middleware) | Recommended with lock | Rejects requests from locked users 354 [remember.Middleware](https://godoc.org/github.com/volatiletech/authboss/remember/#Middleware) | Recommended with remember | Logs a user in from a remember cookie 355 356 357 # Use Cases 358 359 ## Get Current User 360 361 CurrentUser can be retrieved by calling 362 [Authboss.CurrentUser](https://godoc.org/github.com/volatiletech/authboss/#Authboss.CurrentUser) 363 but a pre-requisite is that 364 [Authboss.LoadClientState](https://godoc.org/github.com/volatiletech/authboss/#Authboss.LoadClientState) 365 has been called first to load the client state into the request context. 366 This is typically achieved by using the 367 [Authboss.LoadClientStateMiddleware](https://godoc.org/github.com/volatiletech/authboss/#Authboss.LoadClientStateMiddleware), but can 368 be done manually as well. 369 370 ## Reset Password 371 372 Updating a user's password is non-trivial for several reasons: 373 374 1. The bcrypt algorithm must have the correct cost, and also be being used. 375 1. The user's remember me tokens should all be deleted so that previously authenticated sessions are invalid 376 1. Optionally the user should be logged out (**not taken care of by UpdatePassword**) 377 378 In order to do this, we can use the 379 [Authboss.UpdatePassword](https://godoc.org/github.com/volatiletech/authboss/#Authboss.UpdatePassword) 380 method. This ensures the above facets are taken care of which the exception of the logging out part. 381 382 If it's also desirable to have the user logged out, please use the following methods to erase 383 all known sessions and cookies from the user. 384 385 * [authboss.DelKnownSession](https://godoc.org/github.com/volatiletech/authboss/#DelKnownSession) 386 * [authboss.DelKnownCookie](https://godoc.org/github.com/volatiletech/authboss/#DelKnownCookie) 387 388 *Note: DelKnownSession has been deprecated for security reasons* 389 390 ## User Auth via Password 391 392 | Info and Requirements | | 393 | --------------------- | -------- | 394 Module | auth 395 Pages | login 396 Routes | /login 397 Emails | _None_ 398 Middlewares | [LoadClientStateMiddleware](https://godoc.org/github.com/volatiletech/authboss/#Authboss.LoadClientStateMiddleware) 399 ClientStorage | Session and Cookie 400 ServerStorer | [ServerStorer](https://godoc.org/github.com/volatiletech/authboss/#ServerStorer) 401 User | [AuthableUser](https://godoc.org/github.com/volatiletech/authboss/#AuthableUser) 402 Values | [UserValuer](https://godoc.org/github.com/volatiletech/authboss/#UserValuer) 403 Mailer | _None_ 404 405 To enable this side-effect import the auth module, and ensure that the requirements above are met. 406 It's very likely that you'd also want to enable the logout module in addition to this. 407 408 Direct a user to `GET /login` to have them enter their credentials and log in. 409 410 ## User Auth via OAuth2 411 412 | Info and Requirements | | 413 | --------------------- | -------- | 414 Module | oauth2 415 Pages | _None_ 416 Routes | /oauth2/{provider}, /oauth2/callback/{provider} 417 Emails | _None_ 418 Middlewares | [LoadClientStateMiddleware](https://godoc.org/github.com/volatiletech/authboss/#Authboss.LoadClientStateMiddleware) 419 ClientStorage | Session 420 ServerStorer | [OAuth2ServerStorer](https://godoc.org/github.com/volatiletech/authboss/#OAuth2ServerStorer) 421 User | [OAuth2User](https://godoc.org/github.com/volatiletech/authboss/#OAuth2User) 422 Values | _None_ 423 Mailer | _None_ 424 425 This is a tougher implementation than most modules because there's a lot going on. In addition to the 426 requirements stated above, you must also configure the `OAuth2Providers` in the config struct. 427 428 The providers require an oauth2 configuration that's typical for the Go oauth2 package, but in addition 429 to that they need a `FindUserDetails` method which has to take the token that's retrieved from the oauth2 430 provider, and call an endpoint that retrieves details about the user (at LEAST user's uid). 431 These parameters are returned in `map[string]string` form and passed into the `OAuth2ServerStorer`. 432 433 Please see the following documentation for more details: 434 435 * [Package docs for oauth2](https://godoc.org/github.com/volatiletech/authboss/oauth2/) 436 * [authboss.OAuth2Provider](https://godoc.org/github.com/volatiletech/authboss/#OAuth2Provider) 437 * [authboss.OAuth2ServerStorer](https://godoc.org/github.com/volatiletech/authboss/#OAuth2ServerStorer) 438 439 ## User Registration 440 441 | Info and Requirements | | 442 | --------------------- | -------- | 443 Module | register 444 Pages | register 445 Routes | /register 446 Emails | _None_ 447 Middlewares | [LoadClientStateMiddleware](https://godoc.org/github.com/volatiletech/authboss/#Authboss.LoadClientStateMiddleware) 448 ClientStorage | Session 449 ServerStorer | [CreatingServerStorer](https://godoc.org/github.com/volatiletech/authboss/#CreatingServerStorer) 450 User | [AuthableUser](https://godoc.org/github.com/volatiletech/authboss/#AuthableUser), optionally [ArbitraryUser](https://godoc.org/github.com/volatiletech/authboss/#ArbitraryUser) 451 Values | [UserValuer](https://godoc.org/github.com/volatiletech/authboss/#UserValuer), optionally also [ArbitraryValuer](https://godoc.org/github.com/volatiletech/authboss/#ArbitraryValuer) 452 Mailer | _None_ 453 454 Users can self-register for a service using this module. You may optionally want them to confirm 455 themselves, which can be done using the confirm module. 456 457 The complicated part in implementing registrations are around the `RegisterPreserveFields`. This is to 458 help in the case where a user fills out many fields, and then say enters a password 459 which doesn't meet minimum requirements and it fails during validation. These preserve fields should 460 stop the user from having to type in all that data again (it's a whitelist). This **must** be used 461 in conjuction with `ArbitraryValuer` and although it's not a hard requirement `ArbitraryUser` 462 should be used otherwise the arbitrary values cannot be stored in the database. 463 464 When the register module sees arbitrary data from an `ArbitraryValuer`, it sets the data key 465 `authboss.DataPreserve` with a `map[string]string` in the data for when registration fails. 466 This means the (whitelisted) values entered by the user previously will be accessible in the 467 templates by using `.preserve.field_name`. Preserve may be empty or nil so use 468 `{{with ...}}` to make sure you don't have template errors. 469 470 There is additional [Godoc documentation](https://godoc.org/github.com/volatiletech/authboss#Config) on the `RegisterPreserveFields` config option as well as 471 the `ArbitraryUser` and `ArbitraryValuer` interfaces themselves. 472 473 ## Confirming Registrations 474 475 | Info and Requirements | | 476 | --------------------- | -------- | 477 Module | confirm 478 Pages | confirm 479 Routes | /confirm 480 Emails | confirm_html, confirm_txt 481 Middlewares | [LoadClientStateMiddleware](https://godoc.org/github.com/volatiletech/authboss/#Authboss.LoadClientStateMiddleware), [confirm.Middleware](https://godoc.org/github.com/volatiletech/authboss/confirm/#Middleware) 482 ClientStorage | Session 483 ServerStorer | [ConfirmingServerStorer](https://godoc.org/github.com/volatiletech/authboss/#ConfirmingServerStorer) 484 User | [ConfirmableUser](https://godoc.org/github.com/volatiletech/authboss/#ConfirmableUser) 485 Values | [ConfirmValuer](https://godoc.org/github.com/volatiletech/authboss/#ConfirmValuer) 486 Mailer | Required 487 488 Confirming registrations via e-mail can be done with this module (whether or not done via the register 489 module). 490 491 A hook on register kicks off the start of a confirmation which sends an e-mail with a token for the user. 492 When the user re-visits the page, the `BodyReader` must read the token and return a type that returns 493 the token. 494 495 Confirmations carry two values in the database to prevent a timing attack. The selector and the 496 verifier, always make sure in the ConfirmingServerStorer you're searching by the selector and 497 not the verifier. 498 499 ## Password Recovery 500 501 | Info and Requirements | | 502 | --------------------- | -------- | 503 Module | recover 504 Pages | recover_start, recover_middle (not used for renders, only values), recover_end 505 Routes | /recover, /recover/end 506 Emails | recover_html, recover_txt 507 Middlewares | [LoadClientStateMiddleware](https://godoc.org/github.com/volatiletech/authboss/#Authboss.LoadClientStateMiddleware) 508 ClientStorage | Session 509 ServerStorer | [RecoveringServerStorer](https://godoc.org/github.com/volatiletech/authboss/#RecoveringServerStorer) 510 User | [RecoverableUser](https://godoc.org/github.com/volatiletech/authboss/#RecoverableUser) 511 Values | [RecoverStartValuer](https://godoc.org/github.com/volatiletech/authboss/#RecoverStartValuer), [RecoverMiddleValuer](https://godoc.org/github.com/volatiletech/authboss/#RecoverMiddleValuer), [RecoverEndValuer](https://godoc.org/github.com/volatiletech/authboss/#RecoverEndValuer) 512 Mailer | Required 513 514 The flow for password recovery is that the user is initially shown a page that wants their `PID` to 515 be entered. The `RecoverStartValuer` retrieves that on `POST` to `/recover`. 516 517 An e-mail is sent out, and the user clicks the link inside it and is taken back to `/recover/end` 518 as a `GET`, at this point the `RecoverMiddleValuer` grabs the token and will insert it into the data 519 to be rendered. 520 521 They enter their password into the form, and `POST` to `/recover/end` which sends the token and 522 the new password which is retrieved by `RecoverEndValuer` which sets their password and saves them. 523 524 Password recovery has two values in the database to prevent a timing attack. The selector and the 525 verifier, always make sure in the RecoveringServerStorer you're searching by the selector and 526 not the verifier. 527 528 ## Remember Me 529 530 | Info and Requirements | | 531 | --------------------- | -------- | 532 Module | remember 533 Pages | _None_ 534 Routes | _None_ 535 Emails | _None_ 536 Middlewares | LoadClientStateMiddleware, 537 Middlewares | [LoadClientStateMiddleware](https://godoc.org/github.com/volatiletech/authboss/#Authboss.LoadClientStateMiddleware), [remember.Middleware](https://godoc.org/github.com/volatiletech/authboss/remember/#Middleware) 538 ClientStorage | Session, Cookies 539 ServerStorer | [RememberingServerStorer](https://godoc.org/github.com/volatiletech/authboss/#RememberingServerStorer) 540 User | User 541 Values | [RememberValuer](https://godoc.org/github.com/volatiletech/authboss/#RememberValuer) (not a Validator) 542 Mailer | _None_ 543 544 Remember uses cookie storage to log in users without a session via the `remember.Middleware`. 545 Because of this this middleware should be used high up in the stack, but it also needs to be after 546 the `LoadClientStateMiddleware` so that client state is available via the authboss mechanisms. 547 548 There is an intricacy to the `RememberingServerStorer`, it doesn't use the `User` struct at all, 549 instead it simply instructs the storer to save tokens to a pid and recall them just the same. Typically 550 in most databases this will require a separate table, though you could implement using pg arrays 551 or something as well. 552 553 A user who is logged in via Remember tokens is also considered "half-authed" which is a session 554 key (`authboss.SessionHalfAuthKey`) that you can query to check to see if a user should have 555 full rights to more sensitive data, if they are half-authed and they want to change their user 556 details for example you may want to force them to go to the login screen and put in their 557 password to get a full auth first. The `authboss.Middleware` has a boolean flag to `forceFullAuth` 558 which prevents half-authed users from using that route. 559 560 ## Locking Users 561 562 | Info and Requirements | | 563 | --------------------- | -------- | 564 Module | lock 565 Pages | _None_ 566 Routes | _None_ 567 Emails | _None_ 568 Middlewares | [LoadClientStateMiddleware](https://godoc.org/github.com/volatiletech/authboss/#Authboss.LoadClientStateMiddleware), [lock.Middleware](https://godoc.org/github.com/volatiletech/authboss/lock/#Middleware) 569 ClientStorage | Session 570 ServerStorer | [ServerStorer](https://godoc.org/github.com/volatiletech/authboss/#ServerStorer) 571 User | [LockableUser](https://godoc.org/github.com/volatiletech/authboss/#LockableUser) 572 Values | _None_ 573 Mailer | _None_ 574 575 Lock ensures that a user's account becomes locked if authentication (both auth, oauth2, otp) are 576 failed enough times. 577 578 The middleware protects resources from locked users, without it, there is no point to this module. 579 You should put in front of any resource that requires a login to function. 580 581 ## Expiring User Sessions 582 583 | Info and Requirements | | 584 | --------------------- | -------- | 585 Module | expire 586 Pages | _None_ 587 Routes | _None_ 588 Emails | _None_ 589 Middlewares | [LoadClientStateMiddleware](https://godoc.org/github.com/volatiletech/authboss/#Authboss.LoadClientStateMiddleware), [expire.Middleware](https://godoc.org/github.com/volatiletech/authboss/expire/#Middleware) 590 ClientStorage | Session 591 ServerStorer | _None_ 592 User | [User](https://godoc.org/github.com/volatiletech/authboss/#User) 593 Values | _None_ 594 Mailer | _None_ 595 596 **Note:** Unlike most modules in Authboss you must call `expire.Setup()` 597 to enable this module. See the sample to see how to do this. This may be changed in the future. 598 599 Expire simply uses sessions to track when the last action of a user is, if that action is longer 600 than configured then the session is deleted and the user removed from the request context. 601 602 This middleware should be inserted at a high level (closer to the request) in the middleware chain 603 to ensure that "activity" is logged properly, as well as any middlewares down the chain do not 604 attempt to do anything with the user before it's removed from the request context. 605 606 ## One Time Passwords 607 608 | Info and Requirements | | 609 | --------------------- | -------- | 610 Module | otp 611 Pages | otp, otpadd, otpclear 612 Routes | /otp/login, /otp/add, /otp/clear 613 Emails | _None_ 614 Middlewares | [LoadClientStateMiddleware](https://godoc.org/github.com/volatiletech/authboss/#Authboss.LoadClientStateMiddleware) 615 ClientStorage | Session and Cookie 616 ServerStorer | [ServerStorer](https://godoc.org/github.com/volatiletech/authboss/#ServerStorer) 617 User | [otp.User](https://godoc.org/github.com/volatiletech/authboss/otp/#User) 618 Values | [UserValuer](https://godoc.org/github.com/volatiletech/authboss/#UserValuer) 619 Mailer | _None_ 620 621 One time passwords can be useful if users require a backup password in case they lose theirs, 622 or they're logging in on an untrusted computer. This module allows users to add one time passwords, 623 clear them, or log in with them. 624 625 Logging in with a one time password instead of a password is identical to having logged in normally 626 with their typical password with the exception that the one time passwords are consumed immediately 627 upon use and cannot be used again. 628 629 `otp` should not be confused with two factor authentication. Although 2fa also uses one-time passwords 630 the `otp` module has nothing to do with it and is strictly a mechanism for logging in with an alternative 631 to a user's regular password. 632 633 ## Two Factor Authentication 634 635 2FA in Authboss is implemented in a few separate modules: twofactor, totp2fa and sms2fa. 636 637 You should use two factor authentication in your application if you want additional security beyond 638 that of just simple passwords. Each 2fa module supports a different mechanism for verifying a second 639 factor of authentication from a user. 640 641 ### Two-Factor Recovery 642 643 | Info and Requirements | | 644 | --------------------- | -------- | 645 Module | twofactor 646 Pages | recovery2fa 647 Routes | /2fa/recovery/regen 648 Emails | _None_ 649 Middlewares | [LoadClientStateMiddleware](https://godoc.org/github.com/volatiletech/authboss/#Authboss.LoadClientStateMiddleware) 650 ClientStorage | Session 651 ServerStorer | [ServerStorer](https://godoc.org/github.com/volatiletech/authboss/#ServerStorer) 652 User | [twofactor.User](https://godoc.org/github.com/volatiletech/authboss/otp/twofactor/#User) 653 Values | _None_ 654 Mailer | _None_ 655 656 **Note:** Unlike most modules in Authboss you must construct a `twofactor.Recovery` and call `.Setup()` 657 on it to enable this module. See the sample to see how to do this. This may be changed in the future. 658 659 Package twofactor is all about the common functionality of providing backup codes for two factor 660 mechanisms. Instead of each module implementing backup codes on it's own, common functionality has 661 been put here including a route to regenerate backup codes. 662 663 Backup codes are useful in case people lose access to their second factor for authentication. This happens 664 when users lose their phones for example. When this occurs, they can use one of their backup-codes. 665 666 Backup codes are one-time use, they are bcrypted for security, and they only allow bypassing the 2fa 667 authentication part, they cannot be used in lieu of a user's password, for that sort of recovery see 668 the `otp` module. 669 670 ### Two-Factor Setup E-mail Authorization 671 672 | Info and Requirements | | 673 | --------------------- | -------- | 674 Module | twofactor 675 Pages | twofactor_verify 676 Routes | /2fa/recovery/regen 677 Emails | twofactor_verify_email_html, twofactor_verify_email_txt 678 Middlewares | [LoadClientStateMiddleware](https://godoc.org/github.com/volatiletech/authboss/#Authboss.LoadClientStateMiddleware) 679 ClientStorage | Session 680 ServerStorer | [ServerStorer](https://godoc.org/github.com/volatiletech/authboss/#ServerStorer) 681 User | [twofactor.User](https://godoc.org/github.com/volatiletech/authboss/otp/twofactor/#User) 682 Values | [twofactor.EmailVerifyTokenValuer](https://godoc.org/github.com/volatiletech/authboss/otp/twofactor/#EmailVerifyTokenValuer) 683 Mailer | Required 684 685 To enable this feature simply turn on 686 `authboss.Config.Modules.TwoFactorEmailAuthRequired` and new routes and 687 middlewares will be installed when you set up one of the 2fa modules. 688 689 When enabled, the routes for setting up 2fa on an account are protected by a 690 middleware that will redirect to `/2fa/{totp,sms}/email/verify` where 691 Page `twofactor_verify` is displayed. The user is prompted to authorize the 692 addition of 2fa to their account. The data for this page contains `email` and 693 a `url` for the POST. The url is required because this page is shared between 694 all 2fa types. 695 696 Once they POST to the url, a token is stored in their session and an e-mail is 697 sent with that token. When they click the link that goes to 698 `/2fa/{totp,sms}/email/verify/end` with a token in the query string the session 699 token is verified and exchanged for a value that says they're verified and 700 lastly it redirects them to the setup URL for the type of 2fa they were 701 attempting to setup. 702 703 ### Time-Based One Time Passwords 2FA (totp) 704 705 | Info and Requirements | | 706 | --------------------- | -------- | 707 Module | totp2fa 708 Pages | totp2fa_{setup,confirm,remove,validate}, totp2fa_{confirm,remove}_success 709 Routes | /2fa/totp/{setup,confirm,qr,remove,validate} 710 Emails | _None_ 711 Middlewares | [LoadClientStateMiddleware](https://godoc.org/github.com/volatiletech/authboss/#Authboss.LoadClientStateMiddleware) 712 ClientStorage | Session **(SECURE!)** 713 ServerStorer | [ServerStorer](https://godoc.org/github.com/volatiletech/authboss/#ServerStorer) 714 User | [totp2fa.User](https://godoc.org/github.com/volatiletech/authboss/otp/twofactor/totp2fa/#User) 715 Values | [TOTPCodeValuer](https://godoc.org/github.com/volatiletech/authboss/otp/twofactor/totp2fa/#TOTPCodeValuer) 716 Mailer | _None_ 717 718 **Note:** Unlike most modules in Authboss you must construct a `totp2fa.TOTP` and call `.Setup()` 719 on it to enable this module. See the sample to see how to do this This may be changed in the future. 720 721 **Note:** To allow users to regenerate their backup codes, you must also use the `twofactor` module. 722 723 **Note:** Routes are protected by `authboss.Middleware` so only logged in users can access them. 724 You can configure whether unauthenticated users should be redirected to log in or are 404'd using 725 the `authboss.Config.Modules.RoutesRedirectOnUnathed` configuration flag. 726 727 #### Adding 2fa to a user 728 729 When a logged in user would like to add 2fa to their account direct them `GET /2fa/totp/setup`, the `GET` 730 on this page does virtually nothing so you don't have to use it, just `POST` immediately to have 731 a smoother flow for the user. **This puts the 2fa secret in their session temporarily meaning you must 732 have proper secure sessions for this to be secure.** 733 734 They will be redirected to `GET /2fa/totp/confirm` where the data will show `totp2fa.DataTOTPSecret`, 735 this is the key that user's should enter into their Google Authenticator or similar app. Once they've 736 added it they need to send a `POST /2fa/totp/confirm` with a correct code which removes the 2fa secret 737 from their session and permanently adds it to their `totp2fa.User` and 2fa is now enabled for them. 738 The data from the `POST` will contain a key `twofactor.DataRecoveryCodes` that contains an array 739 of recovery codes for the user. 740 741 If you wish to show the user a QR code, `GET /2fa/totp/qr` at any time during or after totp2fa setup 742 will return a 200x200 png QR code that they can scan. 743 744 #### Removing 2fa from a user 745 746 A user begins by going to `GET /2fa/totp/remove` and enters a code which posts to `POST /2fa/totp/remove` 747 and if it's correct they're shown a success page and 2fa is removed from them, if not they get 748 validation errors. 749 750 #### Logging in with 2fa 751 752 When a user goes to log in, the `totp` module checks the user after they log in for the presence of 753 a totp2fa secret, if there is one it does not give them a logged in session value immediately and 754 redirects them to `GET /2fa/totp/validate` where they must enter a correct code to `POST /2fa/totp/validate` 755 if the code is correct they're logged in normally as well as they get the session value 756 `authboss.Session2FA` set to `"totp"` to prove that they've authenticated with two factors. 757 758 #### Using Recovery Codes 759 760 Both when logging in and removing totp2fa from an account, a recovery code may be used instead. They can 761 `POST` to the same url, they simply send a different form field. The recovery code is consumed on use 762 and may not be used again. 763 764 ### Text Message 2FA (sms) 765 766 Package sms2fa uses sms shared secrets as a means to authenticate a user with a second factor: 767 their phone number. 768 769 | Info and Requirements | | 770 | --------------------- | -------- | 771 Module | sms2fa 772 Pages | sms2fa_{setup,confirm,remove,validate}, sms2fa_{confirm,remove}_success 773 Routes | /2fa/{setup,confirm,remove,validate} 774 Emails | _None_ 775 Middlewares | [LoadClientStateMiddleware](https://godoc.org/github.com/volatiletech/authboss/#Authboss.LoadClientStateMiddleware) 776 ClientStorage | Session (**SECURE!**) 777 ServerStorer | [ServerStorer](https://godoc.org/github.com/volatiletech/authboss/#ServerStorer) 778 User | [sms2fa.User](https://godoc.org/github.com/volatiletech/authboss/otp/twofactor/sms2fa/#User), [sms2fa.SMSNumberProvider](https://godoc.org/github.com/volatiletech/authboss/otp/twofactor/sms2fa/#SMSNumberProvider) 779 Values | [SMSValuer](https://godoc.org/github.com/volatiletech/authboss/otp/twofactor/sms2fa/#SMSValuer), [SMSPhoneNumberValuer](https://godoc.org/github.com/volatiletech/authboss/otp/twofactor/sms2fa/#SMSPhoneNumberValuer) 780 Mailer | _None_ 781 782 **Note:** Unlike most modules in Authboss you must construct a `sms2fa.SMS` and call `.Setup()` 783 on it to enable this module. See the sample to see how to do this. This may be changed in the future. 784 785 **Note:** To allow users to regenerate their backup codes, you must also use the `twofactor` module. 786 787 **Note:** Routes are protected by `authboss.Middleware` so only logged in users can access them. 788 You can configure whether unauthenticated users should be redirected to log in or are 404'd using 789 the `authboss.Config.Modules.RoutesRedirectOnUnathed` configuration flag. 790 791 **Note:** sms2fa always stores the code it's expecting in the user's session therefore **you must 792 have secure sessions or the code itself is not secure!** 793 794 **Note:** sms2fa pages all send codes via sms on `POST` when no data code is given. This is also how 795 users can resend the code in case they did not get it (for example a second 796 `POST /2fa/sms/{confirm,remove}` with no form-fields filled in will end up resending the code). 797 798 **Note:** Sending sms codes is rate-limited to 1 sms/10 sec for that user, this is controlled by placing 799 a timestamp in their session to prevent abuse. 800 801 #### Adding 2fa to a user 802 803 When a logged in user would like to add 2fa to their account direct them `GET /2fa/sms/setup` where 804 they must enter a phone number. If the logged in user also implements `sms2fa.SMSNumberProvider` then 805 this interface will be used to retrieve a phone number (if it exists) from the user and put it in 806 `sms2fa.DataSMSPhoneNumber` so that the user interface can populate it for the user, making it convenient 807 to re-use an already saved phone number inside the user. 808 809 Once they `POST /2fa/sms/setup` with a phone number, the `sms2fa.Sender` interface will be 810 invoked to send the SMS code to the user and they will be redirected to `GET /2fa/sms/confirm` where 811 they enter the code they received which does a `POST /2fa/sms/confirm` to store the phone number 812 they were confirming permanently on their user using `sms2fa.User` which enables sms2fa for them. 813 The data from the `POST` will contain a key `twofactor.DataRecoveryCodes` that contains an array 814 of recovery codes for the user. 815 816 #### Removing 2fa from a user 817 818 A user begins by going to `GET /2fa/sms/remove`. This page does nothing on it's own. In order to 819 begin the process `POST /2fa/sms/remove` with no data (or a recovery code to skip needing the sms code) 820 to send the sms code to the user. Then they can `POST /2fa/sms/remove` again with the correct code 821 to have it permanently removed. 822 823 #### Logging in with 2fa 824 825 When a user goes to log in, the `sms` module checks the user after they log in for the presence of 826 a sms2fa phone number, if there is one it does not give them a logged in session value but instead 827 sends an SMS code to their configured number and and redirects them to `GET /2fa/sms/validate` 828 where they must enter a correct code to `POST /2fa/totp/validate`. If the code is correct they're 829 logged in normally as well as they get the session value `authboss.Session2FA` set to `"sms"` to prove 830 that they've authenticated with two factors. 831 832 #### Using Recovery Codes 833 834 Same as totp2fa above. 835 836 ## Rendering Views 837 838 The authboss rendering system is simple. It's defined by one interface: [Renderer](https://godoc.org/github.com/volatiletech/authboss/#Renderer) 839 840 The renderer knows how to load templates, and how to render them with some data and that's it. 841 So let's examine the most common view types that you might want to use. 842 843 ### HTML Views 844 845 When your app is a traditional web application and is generating it's HTML serverside using templates 846 this becomes a small wrapper on top of your rendering setup. For example if you're using `html/template` 847 then you could just use `template.New()` inside the `Load()` method and store that somewhere and 848 call `template.Execute()` in the `Render()` method. 849 850 There is also a very basic renderer: [Authboss Renderer](https://github.com/volatiletech/authboss-renderer) which has some very ugly built in views 851 and the ability to override them with your own if you don't want to integrate your own rendering 852 system into that interface. 853 854 ### JSON Views 855 856 If you're building an API that's mostly backed by a javascript front-end, then you'll probably 857 want to use a renderer that converts the data to JSON. There is a simple json renderer available in 858 the [defaults package](https://github.com/volatiletech/authboss/tree/master/defaults) package if you wish to 859 use that. 860 861 ### Data 862 863 The most important part about this interface is the data that you have to render. 864 There are several keys that are used throughout authboss that you'll want to render in your views. 865 866 They're in the file [html_data.go](https://github.com/volatiletech/authboss/blob/master/html_data.go) 867 and are constants prefixed with `Data`. See the documentation in that file for more information on 868 which keys exist and what they contain. 869 870 The default [responder](https://godoc.org/github.com/volatiletech/authboss/defaults/#Responder) 871 also happens to collect data from the Request context, and hence this is a great place to inject 872 data you'd like to render (for example data for your html layout, or csrf tokens).