Documentation ¶
Index ¶
- Constants
- Variables
- func FailureReason(ctx iris.Context) error
- func Protect(authKey []byte, cookieOpts ...CookieOption) iris.Handler
- func TemplateField(ctx iris.Context) template.HTML
- func Token(ctx iris.Context) string
- func UnauthorizedHandler(ctx iris.Context)
- func UnsafeSkipCheck(ctx iris.Context)
- type CSRF
- type CookieOption
- type Options
- type Store
Constants ¶
const (
DefaultCookieName string = "_iris_csrf"
)
Context/session keys.
Variables ¶
var ( // DefaultFieldName is the default name value used in form fields. DefaultFieldName = tokenKey // DefaultSameSite sets the `SameSite` cookie attribute, which is // invalid in some older browsers due to changes in the SameSite spec. These // browsers will not send the cookie to the server. // The csrf middleware uses the http.SameSiteLaxMode (SameSite=Lax) as the default one. DefaultSameSite = http.SameSiteLaxMode // DefaultMaxAge sets the default MaxAge for cookies. DefaultMaxAge = 3600 * 12 // DefaultRequestHeader is the default HTTP request header to inspect. DefaultRequestHeader = "X-CSRF-Token" // TemplateTag is the default HTML template tag provides a default template tag, // e.g. {{ .csrfField }} - for use // with the TemplateField function. TemplateTag = "csrfField" )
var ( // ErrNoReferer is returned when a HTTPS request provides an empty Referer // header. ErrNoReferer = errors.New("referer not supplied") // ErrBadReferer is returned when the scheme & host in the URL do not match // the supplied Referer header. ErrBadReferer = errors.New("referer invalid") // ErrNoToken is returned if no CSRF token is supplied in the request. ErrNoToken = errors.New("CSRF token not found in request") // ErrBadToken is returned if the CSRF token in the request does not match // the token in the session, or is otherwise malformed. ErrBadToken = errors.New("CSRF token invalid") // ErrParseURL is returned when the CSRF middleware can't parse the URL ErrParseURL = errors.New("Can't Parse URL from context") )
Functions ¶
func FailureReason ¶
func FailureReason(ctx iris.Context) error
FailureReason makes CSRF validation errors available in the request context. This is useful when you want to log the cause of the error or report it to client.
func Protect ¶
func Protect(authKey []byte, cookieOpts ...CookieOption) iris.Handler
Protect is Iris middleware that provides Cross-Site Request Forgery protection.
It securely generates a masked (unique-per-request) token that can be embedded in the HTTP response (e.g. form field or HTTP header). The original (unmasked) token is stored in the session, which is inaccessible by an attacker (provided you are using HTTPS). Subsequent requests are expected to include this token, which is compared against the session token. Requests that do not provide a matching token are served with a HTTP 403 'Forbidden' error response.
See `New` package-level function for further customizations.
func TemplateField ¶
TemplateField is a template helper for html/template that provides an <input> field populated with a CSRF token.
Example:
// The following tag in our form.tmpl template: {{ .csrfField }} // ... becomes: <input type="hidden" name="csrf.token" value="<token>">
func Token ¶
func Token(ctx iris.Context) string
Token returns a masked CSRF token ready for passing into HTML template or a JSON response body. An empty token will be returned if the middleware has not been applied (which will fail subsequent validation).
func UnauthorizedHandler ¶
func UnauthorizedHandler(ctx iris.Context)
UnauthorizedHandler sets a HTTP 403 Forbidden status and writes the CSRF failure reason to the response.
func UnsafeSkipCheck ¶
func UnsafeSkipCheck(ctx iris.Context)
UnsafeSkipCheck will skip the CSRF check for any requests. This must be called before the CSRF middleware.
Note: You should not set this without otherwise securing the request from CSRF attacks. The primary use-case for this function is to turn off CSRF checks for non-browser clients using authorization tokens against your API.
Types ¶
type CSRF ¶
type CSRF struct {
// contains filtered or unexported fields
}
CSRF represents the CSRF feature.
func (*CSRF) Filter ¶
Filter is the Iris Filter type of the csrf middleware. It can be used instead of the `Protect` method when the caller needs to manually manage the response on success (true) and failure (false). The `ErrorHandler` is not fired.
func (*CSRF) Protect ¶
func (csrf *CSRF) Protect(ctx iris.Context)
Protect is Iris middleware that provides Cross-Site Request Forgery protection.
Read more at the Protect package-level function's documentation.
func (*CSRF) RequestToken ¶
RequestToken returns the issued token (pad + masked token) from the HTTP POST body or HTTP header. It will return nil if the token fails to decode.
type CookieOption ¶
CookieOption represents the Cookie configuration, used by CookieStore.
func CookieName ¶
func CookieName(name string) CookieOption
CookieName changes the name of the CSRF cookie issued to clients.
Note that cookie names should not contain whitespace, commas, semicolons, backslashes or control characters as per RFC6265.
func Domain ¶
func Domain(domain string) CookieOption
Domain sets the cookie domain. Defaults to the current domain of the request only (recommended).
This should be a hostname and not a URL. If set, the domain is treated as being prefixed with a '.' - e.g. "example.com" becomes ".example.com" and matches "www.example.com" and "secure.example.com".
func HTTPOnly ¶
func HTTPOnly(httpOnly bool) CookieOption
HTTPOnly sets the 'HttpOnly' flag on the cookie. Defaults to true (recommended).
func MaxAge ¶
func MaxAge(maxAge int) CookieOption
MaxAge sets the maximum age (in seconds) of a CSRF token's underlying cookie. Defaults to 12 hours. Call csrf.MaxAge(0) to explicitly set session-only cookies.
func Path ¶
func Path(path string) CookieOption
Path sets the cookie path. Defaults to the path the cookie was issued from (recommended).
This instructs clients to only respond with cookie for that path and its subpaths - i.e. a cookie issued from "/register" would be included in requests to "/register/step2" and "/register/submit".
func SameSite ¶
func SameSite(sameSite http.SameSite) CookieOption
SameSite sets the cookie SameSite attribute. Defaults to blank to maintain backwards compatibility, however, Strict is recommended.
SameSite(SameSiteStrictMode) will prevent the cookie from being sent by the browser to the target site in all cross-site browsing context, even when following a regular link (GET request).
SameSite(SameSiteLaxMode) provides a reasonable balance between security and usability for websites that want to maintain user's logged-in session after the user arrives from an external link. The session cookie would be allowed when following a regular link from an external website while blocking it in CSRF-prone request methods (e.g. POST).
func Secure ¶
func Secure(secure bool) CookieOption
Secure sets the 'Secure' flag on the cookie. Defaults to true (recommended). Set this to 'false' in your development environment otherwise the cookie won't be sent over an insecure channel. Setting this via the presence of a 'DEV' environmental variable is a good way of making sure this won't make it to a production environment.
type Options ¶
type Options struct { // Store lets you configure the backend storage of the CRSF session. Store Store // FieldName allows you to change the name attribute of the hidden <input> field // inspected by this package. The default is 'csrf.token'. FieldName string // RequestHeader allows you to change the request header the CSRF middleware // inspects. The default is X-CSRF-Token. RequestHeader string // ErrorHandler allows you to change the handler called when CSRF request // processing encounters an invalid token or request. A typical use would be to // provide a handler that returns a static HTML file with a HTTP 403 status. By // default a HTTP 403 status and a plain text CSRF failure reason are served. // // Note that a custom error handler can also access the csrf.FailureReason(r) // function to retrieve the CSRF validation reason from the request context. ErrorHandler iris.Handler // TrustedOrigins configures a set of origins (Referers) that are considered as trusted. // This will allow cross-domain CSRF use-cases - e.g. where the front-end is served // from a different domain than the API server - to correctly pass a CSRF check. // // You should only provide origins you own or have full control over. TrustedOrigins []string }
Options describes the configuration for the CRSF middleware.
type Store ¶
type Store interface { // Get returns the real CSRF token from the store. Get(ctx iris.Context) ([]byte, error) // Save stores the real CSRF token in the store and writes a // cookie to the http.ResponseWriter. // For non-cookie stores, the cookie should contain a unique (256 bit) ID // or key that references the token in the backend store. // csrf.GenerateRandomBytes is a helper function for generating secure IDs. Save(ctx iris.Context, token []byte) error }
Store represents the session storage used for CSRF tokens.
func NewCookieStore ¶
func NewCookieStore(authKey []byte, cookieOpts ...CookieOption) Store
NewCookieStore returns a new Store that saves and retrieves the CSRF token to and from the client's cookie jar.