@@ -44,10 +44,65 @@ Also ensure you add it as a dependency to your target:
4444targets: [
4545 .target (name : " App" , dependencies : [
4646 .product (name : " Vapor" , package : " vapor" ),
47- ... ,
47+ // ...,
4848 " VaporCSRF" ]),
4949 // ...
5050]
5151```
5252
53- ## Usage
53+ ## Usage
54+
55+ You must be using the ` SessionsMiddleware ` on all routes you interact with CSRF with. You can enable this globally in ** configure.swift** with:
56+
57+ ``` swift
58+ app.middleware .use (app.sessions .middleware )
59+ ```
60+
61+ For more information on sessions, [ see the documentation] ( https://docs.vapor.codes/4.0/sessions/ ) .
62+
63+ ### GET routes
64+
65+ In GET routes that could return a POST request you want to protect, store a CSRF token in the session:
66+
67+ ``` swift
68+ let csrfToken = req.csrf .storeToken ()
69+ ```
70+
71+ This function returns a token you can then pass to your HTML page. For example, with Leaf this would look like:
72+
73+ ``` swift
74+ let csrfToken = req.csrf .storeToken ()
75+ let context = MyPageContext (csrfToken : csrfToken)
76+ return req.view .render (" myPage" , context)
77+ ```
78+
79+ ### POST routes
80+
81+ You can protect your POST routes either with Middleware or manually verifying the token.
82+
83+ #### Middleware
84+
85+ VaporCSRF provides a middleware that checks the token for you. You can apply this to your routes with:
86+
87+ ``` swift
88+ let csrfTokenPotectedRoutes = app.grouped (CSRFMiddleware ())
89+ ```
90+
91+ #### Manual Verification
92+
93+ If you want to control when you verify the CSRF token, you can do this manually in your route handler with ` try req.csrf.verifyToken() ` . E.g.:
94+
95+ ``` swift
96+ app.post (" myForm" ) { req -> EventLoopFuture< Response> in
97+ try req.csrf .verifyToken ()
98+ // ...
99+ }
100+ ```
101+
102+ ### Configuration
103+
104+ By default, VaporCSRF looks for a value with the key ` csrfToken ` in the POST body. You can change the key with:
105+
106+ ``` swift
107+ app.csrf .setTokenContentKey (" aDifferentKey" )
108+ ```
0 commit comments