Added closure documentation for redirect (#700)

This commit is contained in:
Kyle Stubblefield 2022-08-13 07:44:20 -07:00 committed by GitHub
parent 4c731052e8
commit 0fe2c349f5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 14 additions and 0 deletions

View File

@ -756,8 +756,22 @@ When protecting routes for an API, you traditionally return an HTTP response wit
let protectedRoutes = app.grouped(User.redirectMiddleware(path: "/login?loginRequired=true"))
```
The `RedirectMiddleware` object also supports passing a closure that returns the redirect path as a `String` during creation for advanced url handling. For instance, including the path redirected from as query parameter to the redirect target for state management.
```swift
let redirectMiddleware = User.redirectMiddleware { req -> String in
return "/login?authRequired=true&next=\(req.url.path)"
}
```
This works similar to the `GuardMiddleware`. Any requests to routes registered to `protectedRoutes` that aren't authenticated will be redirected to the path provided. This allows you to tell your users to log in, rather than just providing a **401 Unauthorized**.
Be sure to include a Session Authenticator before the `RedirectMiddleware` to ensure the authenticated user is loaded before running through the `RedirectMiddleware`.
```swift
let protectedRoutes = app.grouped([User.SessionAuthenticator(), redirecteMiddleware])
```
### Form Log In
To authenticate a user and future requests with a session, you need to log a user in. Vapor provides a `ModelCredentialsAuthenticatable` protocol to conform to. This handles log in via a form. First conform your `User` to this protocol: