├── .editorconfig ├── .github └── workflows │ ├── clippy-and-fmt.yml │ ├── main.yml │ └── msrv.yml ├── .gitignore ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── examples ├── middleware-closure.rs └── middleware.rs ├── rustfmt.toml └── src ├── extractors ├── basic.rs ├── bearer.rs ├── config.rs ├── errors.rs └── mod.rs ├── headers ├── authorization │ ├── errors.rs │ ├── header.rs │ ├── mod.rs │ └── scheme │ │ ├── basic.rs │ │ ├── bearer.rs │ │ └── mod.rs ├── mod.rs └── www_authenticate │ ├── challenge │ ├── basic.rs │ ├── bearer │ │ ├── builder.rs │ │ ├── challenge.rs │ │ ├── errors.rs │ │ ├── mod.rs │ │ └── tests.rs │ └── mod.rs │ ├── header.rs │ └── mod.rs ├── lib.rs ├── middleware.rs └── utils.rs /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | charset = utf-8 7 | indent_style = space 8 | indent_size = 4 9 | trim_trailing_whitespace = true 10 | 11 | [*.yml] 12 | indent_size = 2 13 | 14 | [*.md] 15 | indent_size = 2 16 | -------------------------------------------------------------------------------- /.github/workflows/clippy-and-fmt.yml: -------------------------------------------------------------------------------- 1 | name: Clippy and rustfmt check 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | 9 | jobs: 10 | clippy_check: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@master 14 | - uses: actions-rs/toolchain@v1 15 | with: 16 | toolchain: nightly 17 | components: clippy, rustfmt 18 | override: true 19 | - name: Clippy 20 | uses: actions-rs/cargo@v1 21 | with: 22 | command: clippy 23 | args: --all-features 24 | - name: rustfmt 25 | uses: actions-rs/cargo@v1 26 | with: 27 | command: fmt 28 | args: --all -- --check 29 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | 9 | jobs: 10 | build_and_test: 11 | strategy: 12 | fail-fast: false 13 | matrix: 14 | toolchain: 15 | - x86_64-pc-windows-msvc 16 | - x86_64-pc-windows-gnu 17 | - x86_64-unknown-linux-gnu 18 | - x86_64-apple-darwin 19 | version: 20 | - stable 21 | - nightly 22 | include: 23 | - toolchain: x86_64-pc-windows-msvc 24 | os: windows-latest 25 | - toolchain: x86_64-pc-windows-gnu 26 | os: windows-latest 27 | - toolchain: x86_64-unknown-linux-gnu 28 | os: ubuntu-latest 29 | - toolchain: x86_64-apple-darwin 30 | os: macOS-latest 31 | 32 | name: ${{ matrix.version }} - ${{ matrix.toolchain }} 33 | runs-on: ${{ matrix.os }} 34 | 35 | steps: 36 | - uses: actions/checkout@master 37 | 38 | - name: Install ${{ matrix.version }} 39 | uses: actions-rs/toolchain@v1 40 | with: 41 | toolchain: ${{ matrix.version }}-${{ matrix.toolchain }} 42 | profile: minimal 43 | override: true 44 | 45 | - name: Generate Cargo.lock 46 | uses: actions-rs/cargo@v1 47 | with: 48 | command: update 49 | - name: Cache cargo registry 50 | uses: actions/cache@v1 51 | with: 52 | path: ~/.cargo/registry 53 | key: ${{ matrix.version }}-${{ matrix.toolchain }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }} 54 | - name: Cache cargo index 55 | uses: actions/cache@v1 56 | with: 57 | path: ~/.cargo/git 58 | key: ${{ matrix.version }}-${{ matrix.toolchain }}-cargo-index-${{ hashFiles('**/Cargo.lock') }} 59 | - name: Cache cargo build 60 | uses: actions/cache@v1 61 | with: 62 | path: target 63 | key: ${{ matrix.version }}-${{ matrix.toolchain }}-cargo-build-${{ hashFiles('**/Cargo.lock') }} 64 | 65 | - name: checks 66 | uses: actions-rs/cargo@v1 67 | with: 68 | command: check 69 | args: --all --bins --examples --tests 70 | 71 | - name: tests (stable) 72 | if: matrix.version == 'stable' 73 | uses: actions-rs/cargo@v1 74 | with: 75 | command: test 76 | args: --all --no-fail-fast -- --nocapture 77 | 78 | - name: tests (nightly) 79 | if: matrix.version == 'nightly' 80 | uses: actions-rs/cargo@v1 81 | with: 82 | command: test 83 | args: --all --all-features --no-fail-fast -- --nocapture 84 | -------------------------------------------------------------------------------- /.github/workflows/msrv.yml: -------------------------------------------------------------------------------- 1 | name: Check MSRV 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | 9 | jobs: 10 | build_and_test: 11 | strategy: 12 | fail-fast: false 13 | 14 | runs-on: ubuntu-latest 15 | 16 | steps: 17 | - uses: actions/checkout@master 18 | 19 | - name: Install Rust 20 | uses: actions-rs/toolchain@v1 21 | with: 22 | toolchain: 1.39.0-x86_64-unknown-linux-gnu 23 | profile: minimal 24 | override: true 25 | - name: Generate Cargo.lock 26 | uses: actions-rs/cargo@v1 27 | with: 28 | command: update 29 | - name: Cache cargo registry 30 | uses: actions/cache@v1 31 | with: 32 | path: ~/.cargo/registry 33 | key: msrv-cargo-registry-${{ hashFiles('**/Cargo.lock') }} 34 | - name: Cache cargo index 35 | uses: actions/cache@v1 36 | with: 37 | path: ~/.cargo/git 38 | key: msrv-cargo-index-${{ hashFiles('**/Cargo.lock') }} 39 | - name: Cache cargo build 40 | uses: actions/cache@v1 41 | with: 42 | path: target 43 | key: msrv-cargo-build-${{ hashFiles('**/Cargo.lock') }} 44 | 45 | - name: checks 46 | uses: actions-rs/cargo@v1 47 | with: 48 | command: check 49 | args: --all --bins --examples --tests 50 | 51 | - name: tests 52 | uses: actions-rs/cargo@v1 53 | with: 54 | command: test 55 | args: --all --no-fail-fast -- --nocapture 56 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) 6 | and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). 7 | 8 | ## [0.4.0] - 2020-01-14 9 | 10 | ### Changed 11 | - Depends on `actix-web = "^2.0"`, `actix-service = "^1.0"`, and `futures = "^0.3"` version now ([#14]) 12 | - Depends on `bytes = "^0.5"` and `base64 = "^0.11"` now 13 | 14 | [#14]: https://github.com/actix/actix-web-httpauth/pull/14 15 | 16 | ## [0.3.2] - 2019-07-19 17 | 18 | ### Changed 19 | - Middleware accepts any `Fn` as a validator function instead of `FnMut` ([#11](https://github.com/actix/actix-web-httpauth/pull/11)) 20 | 21 | ## [0.3.1] - 2019-06-09 22 | 23 | ### Fixed 24 | - Multiple calls to the middleware would result in panic 25 | 26 | ## [0.3.0] - 2019-06-05 27 | 28 | ### Changed 29 | - Crate edition was changed to `2018`, same as `actix-web` 30 | - Depends on `actix-web = "^1.0"` version now 31 | - `WWWAuthenticate` header struct was renamed into `WwwAuthenticate` 32 | - Challenges and extractor configs are now operating with `Cow<'static, str>` types instead of `String` types 33 | 34 | ## [0.2.0] - 2019-04-26 35 | 36 | ### Changed 37 | - `actix-web` dependency is used without default features now ([#6](https://github.com/actix/actix-web-httpauth/pull/6)) 38 | - `base64` dependency version was bumped to `0.10` 39 | 40 | ## [0.1.0] - 2018-09-08 41 | 42 | ### Changed 43 | - Update to `actix-web = "0.7"` version 44 | 45 | ## [0.0.4] - 2018-07-01 46 | 47 | ### Fixed 48 | - Fix possible panic at `IntoHeaderValue` implementation for `headers::authorization::Basic` 49 | - Fix possible panic at `headers::www_authenticate::challenge::bearer::Bearer::to_bytes` call 50 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "actix-web-httpauth" 3 | version = "0.4.0" 4 | authors = ["svartalf ", "Yuki Okushi "] 5 | description = "HTTP authentication schemes for actix-web" 6 | readme = "README.md" 7 | keywords = ["http", "web", "framework"] 8 | homepage = "https://github.com/actix/actix-web-httpauth" 9 | repository = "https://github.com/actix/actix-web-httpauth.git" 10 | documentation = "https://docs.rs/actix-web-httpauth/" 11 | categories = ["web-programming::http-server"] 12 | license = "MIT OR Apache-2.0" 13 | exclude = [".github/*", ".gitignore"] 14 | edition = "2018" 15 | 16 | [dependencies] 17 | actix-web = { version = "^2.0", default_features = false } 18 | actix-service = "1.0" 19 | futures = "0.3" 20 | bytes = "0.5" 21 | base64 = "0.11" 22 | 23 | [dev-dependencies] 24 | actix-rt = "1.0" 25 | 26 | [features] 27 | default = [] 28 | nightly = [] 29 | 30 | [badges] 31 | maintenance = { status = "passively-maintained" } 32 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2017-NOW svartalf and Actix team 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2017 svartalf and Actix team 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # actix-web-httpauth 2 | 3 | [![Latest Version](https://img.shields.io/crates/v/actix-web-httpauth.svg)](https://crates.io/crates/actix-web-httpauth) 4 | [![Latest Version](https://docs.rs/actix-web-httpauth/badge.svg)](https://docs.rs/actix-web-httpauth) 5 | [![dependency status](https://deps.rs/crate/actix-web-httpauth/0.4.0/status.svg)](https://deps.rs/crate/actix-web-httpauth/0.4.0) 6 | ![Build Status](https://github.com/actix/actix-web-httpauth/workflows/CI/badge.svg?branch=master&event=push) 7 | ![Apache 2.0 OR MIT licensed](https://img.shields.io/badge/license-Apache2.0%2FMIT-blue.svg) 8 | 9 | HTTP authentication schemes for [actix-web](https://github.com/actix/actix-web) framework. 10 | 11 | **NOTICE: This repository has been archived. Please visit https://github.com/actix/actix-extras instead.** 12 | 13 | Provides: 14 | * typed [Authorization] and [WWW-Authenticate] headers 15 | * [extractors] for an [Authorization] header 16 | * [middleware] for easier authorization checking 17 | 18 | All supported schemas are actix [Extractors](https://docs.rs/actix-web/1.0.0/actix_web/trait.FromRequest.html), 19 | and can be used both in the middlewares and request handlers. 20 | 21 | ## Supported schemes 22 | 23 | * [Basic](https://tools.ietf.org/html/rfc7617) 24 | * [Bearer](https://tools.ietf.org/html/rfc6750) 25 | -------------------------------------------------------------------------------- /examples/middleware-closure.rs: -------------------------------------------------------------------------------- 1 | use actix_web::{middleware, web, App, HttpServer}; 2 | 3 | use actix_web_httpauth::middleware::HttpAuthentication; 4 | 5 | #[actix_rt::main] 6 | async fn main() -> std::io::Result<()> { 7 | HttpServer::new(|| { 8 | let auth = 9 | HttpAuthentication::basic(|req, _credentials| async { Ok(req) }); 10 | App::new() 11 | .wrap(middleware::Logger::default()) 12 | .wrap(auth) 13 | .service(web::resource("/").to(|| async { "Test\r\n" })) 14 | }) 15 | .bind("127.0.0.1:8080")? 16 | .workers(1) 17 | .run() 18 | .await 19 | } 20 | -------------------------------------------------------------------------------- /examples/middleware.rs: -------------------------------------------------------------------------------- 1 | use actix_web::dev::ServiceRequest; 2 | use actix_web::{middleware, web, App, Error, HttpServer}; 3 | 4 | use actix_web_httpauth::extractors::basic::BasicAuth; 5 | use actix_web_httpauth::middleware::HttpAuthentication; 6 | 7 | async fn validator( 8 | req: ServiceRequest, 9 | _credentials: BasicAuth, 10 | ) -> Result { 11 | Ok(req) 12 | } 13 | 14 | #[actix_rt::main] 15 | async fn main() -> std::io::Result<()> { 16 | HttpServer::new(|| { 17 | let auth = HttpAuthentication::basic(validator); 18 | App::new() 19 | .wrap(middleware::Logger::default()) 20 | .wrap(auth) 21 | .service(web::resource("/").to(|| async { "Test\r\n" })) 22 | }) 23 | .bind("127.0.0.1:8080")? 24 | .workers(1) 25 | .run() 26 | .await 27 | } 28 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | unstable_features = true 2 | edition = "2018" 3 | version = "Two" 4 | wrap_comments = true 5 | comment_width = 80 6 | max_width = 80 7 | merge_imports = false 8 | newline_style = "Unix" 9 | struct_lit_single_line = false 10 | -------------------------------------------------------------------------------- /src/extractors/basic.rs: -------------------------------------------------------------------------------- 1 | //! Extractor for the "Basic" HTTP Authentication Scheme 2 | 3 | use std::borrow::Cow; 4 | 5 | use actix_web::dev::{Payload, ServiceRequest}; 6 | use actix_web::http::header::Header; 7 | use actix_web::{FromRequest, HttpRequest}; 8 | use futures::future; 9 | 10 | use super::config::AuthExtractorConfig; 11 | use super::errors::AuthenticationError; 12 | use super::AuthExtractor; 13 | use crate::headers::authorization::{Authorization, Basic}; 14 | use crate::headers::www_authenticate::basic::Basic as Challenge; 15 | 16 | /// [`BasicAuth`] extractor configuration, 17 | /// used for [`WWW-Authenticate`] header later. 18 | /// 19 | /// [`BasicAuth`]: ./struct.BasicAuth.html 20 | /// [`WWW-Authenticate`]: 21 | /// ../../headers/www_authenticate/struct.WwwAuthenticate.html 22 | #[derive(Debug, Clone, Default)] 23 | pub struct Config(Challenge); 24 | 25 | impl Config { 26 | /// Set challenge `realm` attribute. 27 | /// 28 | /// The "realm" attribute indicates the scope of protection in the manner 29 | /// described in HTTP/1.1 [RFC2617](https://tools.ietf.org/html/rfc2617#section-1.2). 30 | pub fn realm(mut self, value: T) -> Config 31 | where 32 | T: Into>, 33 | { 34 | self.0.realm = Some(value.into()); 35 | self 36 | } 37 | } 38 | 39 | impl AsRef for Config { 40 | fn as_ref(&self) -> &Challenge { 41 | &self.0 42 | } 43 | } 44 | 45 | impl AuthExtractorConfig for Config { 46 | type Inner = Challenge; 47 | 48 | fn into_inner(self) -> Self::Inner { 49 | self.0 50 | } 51 | } 52 | 53 | // Needs `fn main` to display complete example. 54 | #[allow(clippy::needless_doctest_main)] 55 | /// Extractor for HTTP Basic auth. 56 | /// 57 | /// # Example 58 | /// 59 | /// ``` 60 | /// use actix_web::Result; 61 | /// use actix_web_httpauth::extractors::basic::BasicAuth; 62 | /// 63 | /// async fn index(auth: BasicAuth) -> String { 64 | /// format!("Hello, {}!", auth.user_id()) 65 | /// } 66 | /// ``` 67 | /// 68 | /// If authentication fails, this extractor fetches the [`Config`] instance 69 | /// from the [app data] in order to properly form the `WWW-Authenticate` 70 | /// response header. 71 | /// 72 | /// ## Example 73 | /// 74 | /// ``` 75 | /// use actix_web::{web, App}; 76 | /// use actix_web_httpauth::extractors::basic::{BasicAuth, Config}; 77 | /// 78 | /// async fn index(auth: BasicAuth) -> String { 79 | /// format!("Hello, {}!", auth.user_id()) 80 | /// } 81 | /// 82 | /// fn main() { 83 | /// let app = App::new() 84 | /// .data(Config::default().realm("Restricted area")) 85 | /// .service(web::resource("/index.html").route(web::get().to(index))); 86 | /// } 87 | /// ``` 88 | /// 89 | /// [`Config`]: ./struct.Config.html 90 | /// [app data]: https://docs.rs/actix-web/1.0.0-beta.5/actix_web/struct.App.html#method.data 91 | #[derive(Debug, Clone)] 92 | pub struct BasicAuth(Basic); 93 | 94 | impl BasicAuth { 95 | /// Returns client's user-ID. 96 | pub fn user_id(&self) -> &Cow<'static, str> { 97 | &self.0.user_id() 98 | } 99 | 100 | /// Returns client's password. 101 | pub fn password(&self) -> Option<&Cow<'static, str>> { 102 | self.0.password() 103 | } 104 | } 105 | 106 | impl FromRequest for BasicAuth { 107 | type Future = future::Ready>; 108 | type Config = Config; 109 | type Error = AuthenticationError; 110 | 111 | fn from_request( 112 | req: &HttpRequest, 113 | _: &mut Payload, 114 | ) -> ::Future { 115 | future::ready( 116 | Authorization::::parse(req) 117 | .map(|auth| BasicAuth(auth.into_scheme())) 118 | .map_err(|_| { 119 | // TODO: debug! the original error 120 | let challenge = req 121 | .app_data::() 122 | .map(|config| config.0.clone()) 123 | // TODO: Add trace! about `Default::default` call 124 | .unwrap_or_else(Default::default); 125 | 126 | AuthenticationError::new(challenge) 127 | }), 128 | ) 129 | } 130 | } 131 | 132 | impl AuthExtractor for BasicAuth { 133 | type Error = AuthenticationError; 134 | type Future = future::Ready>; 135 | 136 | fn from_service_request(req: &ServiceRequest) -> Self::Future { 137 | future::ready( 138 | Authorization::::parse(req) 139 | .map(|auth| BasicAuth(auth.into_scheme())) 140 | .map_err(|_| { 141 | // TODO: debug! the original error 142 | let challenge = req 143 | .app_data::() 144 | .map(|config| config.0.clone()) 145 | // TODO: Add trace! about `Default::default` call 146 | .unwrap_or_else(Default::default); 147 | 148 | AuthenticationError::new(challenge) 149 | }), 150 | ) 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /src/extractors/bearer.rs: -------------------------------------------------------------------------------- 1 | //! Extractor for the "Bearer" HTTP Authentication Scheme 2 | 3 | use std::borrow::Cow; 4 | use std::default::Default; 5 | 6 | use actix_web::dev::{Payload, ServiceRequest}; 7 | use actix_web::http::header::Header; 8 | use actix_web::{FromRequest, HttpRequest}; 9 | use futures::future; 10 | 11 | use super::config::AuthExtractorConfig; 12 | use super::errors::AuthenticationError; 13 | use super::AuthExtractor; 14 | use crate::headers::authorization; 15 | use crate::headers::www_authenticate::bearer; 16 | pub use crate::headers::www_authenticate::bearer::Error; 17 | 18 | /// [BearerAuth](./struct/BearerAuth.html) extractor configuration. 19 | #[derive(Debug, Clone, Default)] 20 | pub struct Config(bearer::Bearer); 21 | 22 | impl Config { 23 | /// Set challenge `scope` attribute. 24 | /// 25 | /// The `"scope"` attribute is a space-delimited list of case-sensitive 26 | /// scope values indicating the required scope of the access token for 27 | /// accessing the requested resource. 28 | pub fn scope>>(mut self, value: T) -> Config { 29 | self.0.scope = Some(value.into()); 30 | self 31 | } 32 | 33 | /// Set challenge `realm` attribute. 34 | /// 35 | /// The "realm" attribute indicates the scope of protection in the manner 36 | /// described in HTTP/1.1 [RFC2617](https://tools.ietf.org/html/rfc2617#section-1.2). 37 | pub fn realm>>(mut self, value: T) -> Config { 38 | self.0.realm = Some(value.into()); 39 | self 40 | } 41 | } 42 | 43 | impl AsRef for Config { 44 | fn as_ref(&self) -> &bearer::Bearer { 45 | &self.0 46 | } 47 | } 48 | 49 | impl AuthExtractorConfig for Config { 50 | type Inner = bearer::Bearer; 51 | 52 | fn into_inner(self) -> Self::Inner { 53 | self.0 54 | } 55 | } 56 | 57 | // Needs `fn main` to display complete example. 58 | #[allow(clippy::needless_doctest_main)] 59 | /// Extractor for HTTP Bearer auth 60 | /// 61 | /// # Example 62 | /// 63 | /// ``` 64 | /// use actix_web_httpauth::extractors::bearer::BearerAuth; 65 | /// 66 | /// async fn index(auth: BearerAuth) -> String { 67 | /// format!("Hello, user with token {}!", auth.token()) 68 | /// } 69 | /// ``` 70 | /// 71 | /// If authentication fails, this extractor fetches the [`Config`] instance 72 | /// from the [app data] in order to properly form the `WWW-Authenticate` 73 | /// response header. 74 | /// 75 | /// ## Example 76 | /// 77 | /// ``` 78 | /// use actix_web::{web, App}; 79 | /// use actix_web_httpauth::extractors::bearer::{BearerAuth, Config}; 80 | /// 81 | /// async fn index(auth: BearerAuth) -> String { 82 | /// format!("Hello, {}!", auth.token()) 83 | /// } 84 | /// 85 | /// fn main() { 86 | /// let app = App::new() 87 | /// .data( 88 | /// Config::default() 89 | /// .realm("Restricted area") 90 | /// .scope("email photo"), 91 | /// ) 92 | /// .service(web::resource("/index.html").route(web::get().to(index))); 93 | /// } 94 | /// ``` 95 | #[derive(Debug, Clone)] 96 | pub struct BearerAuth(authorization::Bearer); 97 | 98 | impl BearerAuth { 99 | /// Returns bearer token provided by client. 100 | pub fn token(&self) -> &str { 101 | self.0.token() 102 | } 103 | } 104 | 105 | impl FromRequest for BearerAuth { 106 | type Config = Config; 107 | type Future = future::Ready>; 108 | type Error = AuthenticationError; 109 | 110 | fn from_request( 111 | req: &HttpRequest, 112 | _payload: &mut Payload, 113 | ) -> ::Future { 114 | future::ready( 115 | authorization::Authorization::::parse(req) 116 | .map(|auth| BearerAuth(auth.into_scheme())) 117 | .map_err(|_| { 118 | let bearer = req 119 | .app_data::() 120 | .map(|config| config.0.clone()) 121 | .unwrap_or_else(Default::default); 122 | 123 | AuthenticationError::new(bearer) 124 | }), 125 | ) 126 | } 127 | } 128 | 129 | impl AuthExtractor for BearerAuth { 130 | type Future = future::Ready>; 131 | type Error = AuthenticationError; 132 | 133 | fn from_service_request(req: &ServiceRequest) -> Self::Future { 134 | future::ready( 135 | authorization::Authorization::::parse(req) 136 | .map(|auth| BearerAuth(auth.into_scheme())) 137 | .map_err(|_| { 138 | let bearer = req 139 | .app_data::() 140 | .map(|config| config.0.clone()) 141 | .unwrap_or_else(Default::default); 142 | 143 | AuthenticationError::new(bearer) 144 | }), 145 | ) 146 | } 147 | } 148 | 149 | /// Extended error customization for HTTP `Bearer` auth. 150 | impl AuthenticationError { 151 | /// Attach `Error` to the current Authentication error. 152 | /// 153 | /// Error status code will be changed to the one provided by the `kind` 154 | /// Error. 155 | pub fn with_error(mut self, kind: Error) -> Self { 156 | *self.status_code_mut() = kind.status_code(); 157 | self.challenge_mut().error = Some(kind); 158 | self 159 | } 160 | 161 | /// Attach error description to the current Authentication error. 162 | pub fn with_error_description(mut self, desc: T) -> Self 163 | where 164 | T: Into>, 165 | { 166 | self.challenge_mut().error_description = Some(desc.into()); 167 | self 168 | } 169 | 170 | /// Attach error URI to the current Authentication error. 171 | /// 172 | /// It is up to implementor to provide properly formed absolute URI. 173 | pub fn with_error_uri(mut self, uri: T) -> Self 174 | where 175 | T: Into>, 176 | { 177 | self.challenge_mut().error_uri = Some(uri.into()); 178 | self 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /src/extractors/config.rs: -------------------------------------------------------------------------------- 1 | use super::AuthenticationError; 2 | use crate::headers::www_authenticate::Challenge; 3 | 4 | /// Trait implemented for types that provides configuration 5 | /// for the authentication [extractors]. 6 | /// 7 | /// [extractors]: ./trait.AuthExtractor.html 8 | pub trait AuthExtractorConfig { 9 | /// Associated challenge type. 10 | type Inner: Challenge; 11 | 12 | /// Convert the config instance into a HTTP challenge. 13 | fn into_inner(self) -> Self::Inner; 14 | } 15 | 16 | impl From for AuthenticationError<::Inner> 17 | where 18 | T: AuthExtractorConfig, 19 | { 20 | fn from(config: T) -> Self { 21 | AuthenticationError::new(config.into_inner()) 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/extractors/errors.rs: -------------------------------------------------------------------------------- 1 | use std::error::Error; 2 | use std::fmt; 3 | 4 | use actix_web::http::StatusCode; 5 | use actix_web::{HttpResponse, ResponseError}; 6 | 7 | use crate::headers::www_authenticate::Challenge; 8 | use crate::headers::www_authenticate::WwwAuthenticate; 9 | 10 | /// Authentication error returned by authentication extractors. 11 | /// 12 | /// Different extractors may extend `AuthenticationError` implementation 13 | /// in order to provide access to inner challenge fields. 14 | #[derive(Debug)] 15 | pub struct AuthenticationError { 16 | challenge: C, 17 | status_code: StatusCode, 18 | } 19 | 20 | impl AuthenticationError { 21 | /// Creates new authentication error from the provided `challenge`. 22 | /// 23 | /// By default returned error will resolve into the `HTTP 401` status code. 24 | pub fn new(challenge: C) -> AuthenticationError { 25 | AuthenticationError { 26 | challenge, 27 | status_code: StatusCode::UNAUTHORIZED, 28 | } 29 | } 30 | 31 | /// Returns mutable reference to the inner challenge instance. 32 | pub fn challenge_mut(&mut self) -> &mut C { 33 | &mut self.challenge 34 | } 35 | 36 | /// Returns mutable reference to the inner status code. 37 | /// 38 | /// Can be used to override returned status code, but by default 39 | /// this lib tries to stick to the RFC, so it might be unreasonable. 40 | pub fn status_code_mut(&mut self) -> &mut StatusCode { 41 | &mut self.status_code 42 | } 43 | } 44 | 45 | impl fmt::Display for AuthenticationError { 46 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 47 | fmt::Display::fmt(&self.status_code, f) 48 | } 49 | } 50 | 51 | impl Error for AuthenticationError {} 52 | 53 | impl ResponseError for AuthenticationError { 54 | fn error_response(&self) -> HttpResponse { 55 | HttpResponse::build(self.status_code) 56 | // TODO: Get rid of the `.clone()` 57 | .set(WwwAuthenticate(self.challenge.clone())) 58 | .finish() 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/extractors/mod.rs: -------------------------------------------------------------------------------- 1 | //! Type-safe authentication information extractors 2 | 3 | use actix_web::dev::ServiceRequest; 4 | use actix_web::Error; 5 | use futures::future::Future; 6 | 7 | pub mod basic; 8 | pub mod bearer; 9 | mod config; 10 | mod errors; 11 | 12 | pub use self::config::AuthExtractorConfig; 13 | pub use self::errors::AuthenticationError; 14 | 15 | /// Trait implemented by types that can extract 16 | /// HTTP authentication scheme credentials from the request. 17 | /// 18 | /// It is very similar to actix' `FromRequest` trait, 19 | /// except it operates with a `ServiceRequest` struct instead, 20 | /// therefore it can be used in the middlewares. 21 | /// 22 | /// You will not need it unless you want to implement your own 23 | /// authentication scheme. 24 | pub trait AuthExtractor: Sized { 25 | /// The associated error which can be returned. 26 | type Error: Into; 27 | 28 | /// Future that resolves into extracted credentials type. 29 | type Future: Future>; 30 | 31 | /// Parse the authentication credentials from the actix' `ServiceRequest`. 32 | fn from_service_request(req: &ServiceRequest) -> Self::Future; 33 | } 34 | -------------------------------------------------------------------------------- /src/headers/authorization/errors.rs: -------------------------------------------------------------------------------- 1 | use std::convert::From; 2 | use std::error::Error; 3 | use std::fmt; 4 | use std::str; 5 | 6 | use actix_web::http::header; 7 | 8 | /// Possible errors while parsing `Authorization` header. 9 | /// 10 | /// Should not be used directly unless you are implementing 11 | /// your own [authentication scheme](./trait.Scheme.html). 12 | #[derive(Debug)] 13 | pub enum ParseError { 14 | /// Header value is malformed 15 | Invalid, 16 | /// Authentication scheme is missing 17 | MissingScheme, 18 | /// Required authentication field is missing 19 | MissingField(&'static str), 20 | /// Unable to convert header into the str 21 | ToStrError(header::ToStrError), 22 | /// Malformed base64 string 23 | Base64DecodeError(base64::DecodeError), 24 | /// Malformed UTF-8 string 25 | Utf8Error(str::Utf8Error), 26 | } 27 | 28 | impl fmt::Display for ParseError { 29 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 30 | let display = match self { 31 | ParseError::Invalid => "Invalid header value".to_string(), 32 | ParseError::MissingScheme => { 33 | "Missing authorization scheme".to_string() 34 | } 35 | ParseError::MissingField(_) => "Missing header field".to_string(), 36 | ParseError::ToStrError(e) => e.to_string(), 37 | ParseError::Base64DecodeError(e) => e.to_string(), 38 | ParseError::Utf8Error(e) => e.to_string(), 39 | }; 40 | f.write_str(&display) 41 | } 42 | } 43 | 44 | impl Error for ParseError { 45 | fn source(&self) -> Option<&(dyn Error + 'static)> { 46 | match self { 47 | ParseError::Invalid => None, 48 | ParseError::MissingScheme => None, 49 | ParseError::MissingField(_) => None, 50 | ParseError::ToStrError(e) => Some(e), 51 | ParseError::Base64DecodeError(e) => Some(e), 52 | ParseError::Utf8Error(e) => Some(e), 53 | } 54 | } 55 | } 56 | 57 | impl From for ParseError { 58 | fn from(e: header::ToStrError) -> Self { 59 | ParseError::ToStrError(e) 60 | } 61 | } 62 | impl From for ParseError { 63 | fn from(e: base64::DecodeError) -> Self { 64 | ParseError::Base64DecodeError(e) 65 | } 66 | } 67 | impl From for ParseError { 68 | fn from(e: str::Utf8Error) -> Self { 69 | ParseError::Utf8Error(e) 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/headers/authorization/header.rs: -------------------------------------------------------------------------------- 1 | use std::fmt; 2 | 3 | use actix_web::error::ParseError; 4 | use actix_web::http::header::{ 5 | Header, HeaderName, HeaderValue, IntoHeaderValue, AUTHORIZATION, 6 | }; 7 | use actix_web::HttpMessage; 8 | 9 | use crate::headers::authorization::scheme::Scheme; 10 | 11 | /// `Authorization` header, defined in [RFC 7235](https://tools.ietf.org/html/rfc7235#section-4.2) 12 | /// 13 | /// The "Authorization" header field allows a user agent to authenticate 14 | /// itself with an origin server -- usually, but not necessarily, after 15 | /// receiving a 401 (Unauthorized) response. Its value consists of 16 | /// credentials containing the authentication information of the user 17 | /// agent for the realm of the resource being requested. 18 | /// 19 | /// `Authorization` header is generic over [authentication 20 | /// scheme](./trait.Scheme.html). 21 | /// 22 | /// # Example 23 | /// 24 | /// ``` 25 | /// # use actix_web::http::header::Header; 26 | /// # use actix_web::{HttpRequest, Result}; 27 | /// # use actix_web_httpauth::headers::authorization::{Authorization, Basic}; 28 | /// fn handler(req: HttpRequest) -> Result { 29 | /// let auth = Authorization::::parse(&req)?; 30 | /// 31 | /// Ok(format!("Hello, {}!", auth.as_ref().user_id())) 32 | /// } 33 | /// ``` 34 | #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default, Clone)] 35 | pub struct Authorization(S); 36 | 37 | impl Authorization 38 | where 39 | S: Scheme, 40 | { 41 | /// Consumes `Authorization` header and returns inner [`Scheme`] 42 | /// implementation. 43 | /// 44 | /// [`Scheme`]: ./trait.Scheme.html 45 | pub fn into_scheme(self) -> S { 46 | self.0 47 | } 48 | } 49 | 50 | impl From for Authorization 51 | where 52 | S: Scheme, 53 | { 54 | fn from(scheme: S) -> Authorization { 55 | Authorization(scheme) 56 | } 57 | } 58 | 59 | impl AsRef for Authorization 60 | where 61 | S: Scheme, 62 | { 63 | fn as_ref(&self) -> &S { 64 | &self.0 65 | } 66 | } 67 | 68 | impl AsMut for Authorization 69 | where 70 | S: Scheme, 71 | { 72 | fn as_mut(&mut self) -> &mut S { 73 | &mut self.0 74 | } 75 | } 76 | 77 | impl Header for Authorization { 78 | #[inline] 79 | fn name() -> HeaderName { 80 | AUTHORIZATION 81 | } 82 | 83 | fn parse(msg: &T) -> Result { 84 | let header = 85 | msg.headers().get(AUTHORIZATION).ok_or(ParseError::Header)?; 86 | let scheme = S::parse(header).map_err(|_| ParseError::Header)?; 87 | 88 | Ok(Authorization(scheme)) 89 | } 90 | } 91 | 92 | impl IntoHeaderValue for Authorization { 93 | type Error = ::Error; 94 | 95 | fn try_into(self) -> Result::Error> { 96 | self.0.try_into() 97 | } 98 | } 99 | 100 | impl fmt::Display for Authorization { 101 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 102 | fmt::Display::fmt(&self.0, f) 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/headers/authorization/mod.rs: -------------------------------------------------------------------------------- 1 | //! `Authorization` header and various auth schemes 2 | 3 | mod errors; 4 | mod header; 5 | mod scheme; 6 | 7 | pub use self::errors::ParseError; 8 | pub use self::header::Authorization; 9 | pub use self::scheme::basic::Basic; 10 | pub use self::scheme::bearer::Bearer; 11 | pub use self::scheme::Scheme; 12 | -------------------------------------------------------------------------------- /src/headers/authorization/scheme/basic.rs: -------------------------------------------------------------------------------- 1 | use std::borrow::Cow; 2 | use std::fmt; 3 | use std::str; 4 | 5 | use actix_web::http::header::{ 6 | HeaderValue, IntoHeaderValue, InvalidHeaderValue, 7 | }; 8 | use base64; 9 | use bytes::{BufMut, BytesMut}; 10 | 11 | use crate::headers::authorization::errors::ParseError; 12 | use crate::headers::authorization::Scheme; 13 | 14 | /// Credentials for `Basic` authentication scheme, defined in [RFC 7617](https://tools.ietf.org/html/rfc7617) 15 | #[derive(Clone, Eq, Ord, PartialEq, PartialOrd)] 16 | pub struct Basic { 17 | user_id: Cow<'static, str>, 18 | password: Option>, 19 | } 20 | 21 | impl Basic { 22 | /// Creates `Basic` credentials with provided `user_id` and optional 23 | /// `password`. 24 | /// 25 | /// ## Example 26 | /// 27 | /// ``` 28 | /// # use actix_web_httpauth::headers::authorization::Basic; 29 | /// let credentials = Basic::new("Alladin", Some("open sesame")); 30 | /// ``` 31 | pub fn new(user_id: U, password: Option

) -> Basic 32 | where 33 | U: Into>, 34 | P: Into>, 35 | { 36 | Basic { 37 | user_id: user_id.into(), 38 | password: password.map(Into::into), 39 | } 40 | } 41 | 42 | /// Returns client's user-ID. 43 | pub fn user_id(&self) -> &Cow<'static, str> { 44 | &self.user_id 45 | } 46 | 47 | /// Returns client's password if provided. 48 | pub fn password(&self) -> Option<&Cow<'static, str>> { 49 | self.password.as_ref() 50 | } 51 | } 52 | 53 | impl Scheme for Basic { 54 | fn parse(header: &HeaderValue) -> Result { 55 | // "Basic *" length 56 | if header.len() < 7 { 57 | return Err(ParseError::Invalid); 58 | } 59 | 60 | let mut parts = header.to_str()?.splitn(2, ' '); 61 | match parts.next() { 62 | Some(scheme) if scheme == "Basic" => (), 63 | _ => return Err(ParseError::MissingScheme), 64 | } 65 | 66 | let decoded = base64::decode(parts.next().ok_or(ParseError::Invalid)?)?; 67 | let mut credentials = str::from_utf8(&decoded)?.splitn(2, ':'); 68 | 69 | let user_id = credentials 70 | .next() 71 | .ok_or(ParseError::MissingField("user_id")) 72 | .map(|user_id| user_id.to_string().into())?; 73 | let password = credentials 74 | .next() 75 | .ok_or(ParseError::MissingField("password")) 76 | .map(|password| { 77 | if password.is_empty() { 78 | None 79 | } else { 80 | Some(password.to_string().into()) 81 | } 82 | })?; 83 | 84 | Ok(Basic { 85 | user_id, 86 | password, 87 | }) 88 | } 89 | } 90 | 91 | impl fmt::Debug for Basic { 92 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 93 | f.write_fmt(format_args!("Basic {}:******", self.user_id)) 94 | } 95 | } 96 | 97 | impl fmt::Display for Basic { 98 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 99 | f.write_fmt(format_args!("Basic {}:******", self.user_id)) 100 | } 101 | } 102 | 103 | impl IntoHeaderValue for Basic { 104 | type Error = InvalidHeaderValue; 105 | 106 | fn try_into(self) -> Result::Error> { 107 | let mut credentials = BytesMut::with_capacity( 108 | self.user_id.len() 109 | + 1 // ':' 110 | + self.password.as_ref().map_or(0, |pwd| pwd.len()), 111 | ); 112 | 113 | credentials.extend_from_slice(self.user_id.as_bytes()); 114 | credentials.put_u8(b':'); 115 | if let Some(ref password) = self.password { 116 | credentials.extend_from_slice(password.as_bytes()); 117 | } 118 | 119 | // TODO: It would be nice not to allocate new `String` here but write 120 | // directly to `value` 121 | let encoded = base64::encode(&credentials); 122 | let mut value = BytesMut::with_capacity(6 + encoded.len()); 123 | value.put(&b"Basic "[..]); 124 | value.put(&encoded.as_bytes()[..]); 125 | 126 | HeaderValue::from_maybe_shared(value.freeze()) 127 | } 128 | } 129 | 130 | #[cfg(test)] 131 | mod tests { 132 | use super::{Basic, Scheme}; 133 | use actix_web::http::header::{HeaderValue, IntoHeaderValue}; 134 | 135 | #[test] 136 | fn test_parse_header() { 137 | let value = 138 | HeaderValue::from_static("Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); 139 | let scheme = Basic::parse(&value); 140 | 141 | assert!(scheme.is_ok()); 142 | let scheme = scheme.unwrap(); 143 | assert_eq!(scheme.user_id, "Aladdin"); 144 | assert_eq!(scheme.password, Some("open sesame".into())); 145 | } 146 | 147 | #[test] 148 | fn test_empty_password() { 149 | let value = HeaderValue::from_static("Basic QWxhZGRpbjo="); 150 | let scheme = Basic::parse(&value); 151 | 152 | assert!(scheme.is_ok()); 153 | let scheme = scheme.unwrap(); 154 | assert_eq!(scheme.user_id, "Aladdin"); 155 | assert_eq!(scheme.password, None); 156 | } 157 | 158 | #[test] 159 | fn test_empty_header() { 160 | let value = HeaderValue::from_static(""); 161 | let scheme = Basic::parse(&value); 162 | 163 | assert!(scheme.is_err()); 164 | } 165 | 166 | #[test] 167 | fn test_wrong_scheme() { 168 | let value = HeaderValue::from_static("THOUSHALLNOTPASS please?"); 169 | let scheme = Basic::parse(&value); 170 | 171 | assert!(scheme.is_err()); 172 | } 173 | 174 | #[test] 175 | fn test_missing_credentials() { 176 | let value = HeaderValue::from_static("Basic "); 177 | let scheme = Basic::parse(&value); 178 | 179 | assert!(scheme.is_err()); 180 | } 181 | 182 | #[test] 183 | fn test_missing_credentials_colon() { 184 | let value = HeaderValue::from_static("Basic QWxsYWRpbg=="); 185 | let scheme = Basic::parse(&value); 186 | 187 | assert!(scheme.is_err()); 188 | } 189 | 190 | #[test] 191 | fn test_into_header_value() { 192 | let basic = Basic { 193 | user_id: "Aladdin".into(), 194 | password: Some("open sesame".into()), 195 | }; 196 | 197 | let result = basic.try_into(); 198 | assert!(result.is_ok()); 199 | assert_eq!( 200 | result.unwrap(), 201 | HeaderValue::from_static("Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==") 202 | ); 203 | } 204 | } 205 | -------------------------------------------------------------------------------- /src/headers/authorization/scheme/bearer.rs: -------------------------------------------------------------------------------- 1 | use std::borrow::Cow; 2 | use std::fmt; 3 | 4 | use actix_web::http::header::{ 5 | HeaderValue, IntoHeaderValue, InvalidHeaderValue, 6 | }; 7 | use bytes::{BufMut, BytesMut}; 8 | 9 | use crate::headers::authorization::errors::ParseError; 10 | use crate::headers::authorization::scheme::Scheme; 11 | 12 | /// Credentials for `Bearer` authentication scheme, defined in [RFC6750](https://tools.ietf.org/html/rfc6750) 13 | /// 14 | /// Should be used in combination with 15 | /// [`Authorization`](./struct.Authorization.html) header. 16 | #[derive(Clone, Eq, Ord, PartialEq, PartialOrd)] 17 | pub struct Bearer { 18 | token: Cow<'static, str>, 19 | } 20 | 21 | impl Bearer { 22 | /// Creates new `Bearer` credentials with the token provided. 23 | /// 24 | /// ## Example 25 | /// 26 | /// ``` 27 | /// # use actix_web_httpauth::headers::authorization::Bearer; 28 | /// let credentials = Bearer::new("mF_9.B5f-4.1JqM"); 29 | /// ``` 30 | pub fn new(token: T) -> Bearer 31 | where 32 | T: Into>, 33 | { 34 | Bearer { 35 | token: token.into(), 36 | } 37 | } 38 | 39 | /// Gets reference to the credentials token. 40 | pub fn token(&self) -> &Cow<'static, str> { 41 | &self.token 42 | } 43 | } 44 | 45 | impl Scheme for Bearer { 46 | fn parse(header: &HeaderValue) -> Result { 47 | // "Bearer *" length 48 | if header.len() < 8 { 49 | return Err(ParseError::Invalid); 50 | } 51 | 52 | let mut parts = header.to_str()?.splitn(2, ' '); 53 | match parts.next() { 54 | Some(scheme) if scheme == "Bearer" => (), 55 | _ => return Err(ParseError::MissingScheme), 56 | } 57 | 58 | let token = parts.next().ok_or(ParseError::Invalid)?; 59 | 60 | Ok(Bearer { 61 | token: token.to_string().into(), 62 | }) 63 | } 64 | } 65 | 66 | impl fmt::Debug for Bearer { 67 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 68 | f.write_fmt(format_args!("Bearer ******")) 69 | } 70 | } 71 | 72 | impl fmt::Display for Bearer { 73 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 74 | f.write_fmt(format_args!("Bearer {}", self.token)) 75 | } 76 | } 77 | 78 | impl IntoHeaderValue for Bearer { 79 | type Error = InvalidHeaderValue; 80 | 81 | fn try_into(self) -> Result::Error> { 82 | let mut buffer = BytesMut::with_capacity(7 + self.token.len()); 83 | buffer.put(&b"Bearer "[..]); 84 | buffer.extend_from_slice(self.token.as_bytes()); 85 | 86 | HeaderValue::from_maybe_shared(buffer.freeze()) 87 | } 88 | } 89 | 90 | #[cfg(test)] 91 | mod tests { 92 | use super::{Bearer, Scheme}; 93 | use actix_web::http::header::{HeaderValue, IntoHeaderValue}; 94 | 95 | #[test] 96 | fn test_parse_header() { 97 | let value = HeaderValue::from_static("Bearer mF_9.B5f-4.1JqM"); 98 | let scheme = Bearer::parse(&value); 99 | 100 | assert!(scheme.is_ok()); 101 | let scheme = scheme.unwrap(); 102 | assert_eq!(scheme.token, "mF_9.B5f-4.1JqM"); 103 | } 104 | 105 | #[test] 106 | fn test_empty_header() { 107 | let value = HeaderValue::from_static(""); 108 | let scheme = Bearer::parse(&value); 109 | 110 | assert!(scheme.is_err()); 111 | } 112 | 113 | #[test] 114 | fn test_wrong_scheme() { 115 | let value = HeaderValue::from_static("OAuthToken foo"); 116 | let scheme = Bearer::parse(&value); 117 | 118 | assert!(scheme.is_err()); 119 | } 120 | 121 | #[test] 122 | fn test_missing_token() { 123 | let value = HeaderValue::from_static("Bearer "); 124 | let scheme = Bearer::parse(&value); 125 | 126 | assert!(scheme.is_err()); 127 | } 128 | 129 | #[test] 130 | fn test_into_header_value() { 131 | let bearer = Bearer::new("mF_9.B5f-4.1JqM"); 132 | 133 | let result = bearer.try_into(); 134 | assert!(result.is_ok()); 135 | assert_eq!( 136 | result.unwrap(), 137 | HeaderValue::from_static("Bearer mF_9.B5f-4.1JqM") 138 | ); 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/headers/authorization/scheme/mod.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::{Debug, Display}; 2 | 3 | use actix_web::http::header::{HeaderValue, IntoHeaderValue}; 4 | 5 | pub mod basic; 6 | pub mod bearer; 7 | 8 | use crate::headers::authorization::errors::ParseError; 9 | 10 | /// Authentication scheme for [`Authorization`](./struct.Authorization.html) 11 | /// header. 12 | pub trait Scheme: 13 | IntoHeaderValue + Debug + Display + Clone + Send + Sync 14 | { 15 | /// Try to parse the authentication scheme from the `Authorization` header. 16 | fn parse(header: &HeaderValue) -> Result; 17 | } 18 | -------------------------------------------------------------------------------- /src/headers/mod.rs: -------------------------------------------------------------------------------- 1 | //! Typed HTTP headers 2 | 3 | pub mod authorization; 4 | pub mod www_authenticate; 5 | -------------------------------------------------------------------------------- /src/headers/www_authenticate/challenge/basic.rs: -------------------------------------------------------------------------------- 1 | //! Challenge for the "Basic" HTTP Authentication Scheme 2 | 3 | use std::borrow::Cow; 4 | use std::default::Default; 5 | use std::fmt; 6 | use std::str; 7 | 8 | use actix_web::http::header::{ 9 | HeaderValue, IntoHeaderValue, InvalidHeaderValue, 10 | }; 11 | use bytes::{BufMut, Bytes, BytesMut}; 12 | 13 | use super::Challenge; 14 | use crate::utils; 15 | 16 | /// Challenge for [`WWW-Authenticate`] header with HTTP Basic auth scheme, 17 | /// described in [RFC 7617](https://tools.ietf.org/html/rfc7617) 18 | /// 19 | /// ## Example 20 | /// 21 | /// ``` 22 | /// # use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer}; 23 | /// use actix_web_httpauth::headers::www_authenticate::basic::Basic; 24 | /// use actix_web_httpauth::headers::www_authenticate::WwwAuthenticate; 25 | /// 26 | /// fn index(_req: HttpRequest) -> HttpResponse { 27 | /// let challenge = Basic::with_realm("Restricted area"); 28 | /// 29 | /// HttpResponse::Unauthorized() 30 | /// .set(WwwAuthenticate(challenge)) 31 | /// .finish() 32 | /// } 33 | /// ``` 34 | /// 35 | /// [`WWW-Authenticate`]: ../struct.WwwAuthenticate.html 36 | #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default, Clone)] 37 | pub struct Basic { 38 | // "realm" parameter is optional now: https://tools.ietf.org/html/rfc7235#appendix-A 39 | pub(crate) realm: Option>, 40 | } 41 | 42 | impl Basic { 43 | /// Creates new `Basic` challenge with an empty `realm` field. 44 | /// 45 | /// ## Example 46 | /// 47 | /// ``` 48 | /// # use actix_web_httpauth::headers::www_authenticate::basic::Basic; 49 | /// let challenge = Basic::new(); 50 | /// ``` 51 | pub fn new() -> Basic { 52 | Default::default() 53 | } 54 | 55 | /// Creates new `Basic` challenge from the provided `realm` field value. 56 | /// 57 | /// ## Examples 58 | /// 59 | /// ``` 60 | /// # use actix_web_httpauth::headers::www_authenticate::basic::Basic; 61 | /// let challenge = Basic::with_realm("Restricted area"); 62 | /// ``` 63 | /// 64 | /// ``` 65 | /// # use actix_web_httpauth::headers::www_authenticate::basic::Basic; 66 | /// let my_realm = "Earth realm".to_string(); 67 | /// let challenge = Basic::with_realm(my_realm); 68 | /// ``` 69 | pub fn with_realm(value: T) -> Basic 70 | where 71 | T: Into>, 72 | { 73 | Basic { 74 | realm: Some(value.into()), 75 | } 76 | } 77 | } 78 | 79 | #[doc(hidden)] 80 | impl Challenge for Basic { 81 | fn to_bytes(&self) -> Bytes { 82 | // 5 is for `"Basic"`, 9 is for `"realm=\"\""` 83 | let length = 5 + self.realm.as_ref().map_or(0, |realm| realm.len() + 9); 84 | let mut buffer = BytesMut::with_capacity(length); 85 | buffer.put(&b"Basic"[..]); 86 | if let Some(ref realm) = self.realm { 87 | buffer.put(&b" realm=\""[..]); 88 | utils::put_quoted(&mut buffer, realm); 89 | buffer.put_u8(b'"'); 90 | } 91 | 92 | buffer.freeze() 93 | } 94 | } 95 | 96 | impl fmt::Display for Basic { 97 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { 98 | let bytes = self.to_bytes(); 99 | let repr = str::from_utf8(&bytes) 100 | // Should not happen since challenges are crafted manually 101 | // from `&'static str`'s and Strings 102 | .map_err(|_| fmt::Error)?; 103 | 104 | f.write_str(repr) 105 | } 106 | } 107 | 108 | impl IntoHeaderValue for Basic { 109 | type Error = InvalidHeaderValue; 110 | 111 | fn try_into(self) -> Result::Error> { 112 | HeaderValue::from_maybe_shared(self.to_bytes()) 113 | } 114 | } 115 | 116 | #[cfg(test)] 117 | mod tests { 118 | use super::Basic; 119 | use actix_web::http::header::IntoHeaderValue; 120 | 121 | #[test] 122 | fn test_plain_into_header_value() { 123 | let challenge = Basic { 124 | realm: None, 125 | }; 126 | 127 | let value = challenge.try_into(); 128 | assert!(value.is_ok()); 129 | let value = value.unwrap(); 130 | assert_eq!(value, "Basic"); 131 | } 132 | 133 | #[test] 134 | fn test_with_realm_into_header_value() { 135 | let challenge = Basic { 136 | realm: Some("Restricted area".into()), 137 | }; 138 | 139 | let value = challenge.try_into(); 140 | assert!(value.is_ok()); 141 | let value = value.unwrap(); 142 | assert_eq!(value, "Basic realm=\"Restricted area\""); 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /src/headers/www_authenticate/challenge/bearer/builder.rs: -------------------------------------------------------------------------------- 1 | use std::borrow::Cow; 2 | 3 | use super::{Bearer, Error}; 4 | 5 | /// Builder for the [`Bearer`] challenge. 6 | /// 7 | /// It is up to implementor to fill all required fields, 8 | /// neither this `Builder` or [`Bearer`] does not provide any validation. 9 | /// 10 | /// [`Bearer`]: struct.Bearer.html 11 | #[derive(Debug, Default)] 12 | pub struct BearerBuilder(Bearer); 13 | 14 | impl BearerBuilder { 15 | /// Provides the `scope` attribute, as defined in [RFC6749, Section 3.3](https://tools.ietf.org/html/rfc6749#section-3.3) 16 | pub fn scope(mut self, value: T) -> Self 17 | where 18 | T: Into>, 19 | { 20 | self.0.scope = Some(value.into()); 21 | self 22 | } 23 | 24 | /// Provides the `realm` attribute, as defined in [RFC2617](https://tools.ietf.org/html/rfc2617) 25 | pub fn realm(mut self, value: T) -> Self 26 | where 27 | T: Into>, 28 | { 29 | self.0.realm = Some(value.into()); 30 | self 31 | } 32 | 33 | /// Provides the `error` attribute, as defined in [RFC6750, Section 3.1](https://tools.ietf.org/html/rfc6750#section-3.1) 34 | pub fn error(mut self, value: Error) -> Self { 35 | self.0.error = Some(value); 36 | self 37 | } 38 | 39 | /// Provides the `error_description` attribute, as defined in [RFC6750, Section 3](https://tools.ietf.org/html/rfc6750#section-3) 40 | pub fn error_description(mut self, value: T) -> Self 41 | where 42 | T: Into>, 43 | { 44 | self.0.error_description = Some(value.into()); 45 | self 46 | } 47 | 48 | /// Provides the `error_uri` attribute, as defined in [RFC6750, Section 3](https://tools.ietf.org/html/rfc6750#section-3) 49 | /// 50 | /// It is up to implementor to provide properly-formed absolute URI. 51 | pub fn error_uri(mut self, value: T) -> Self 52 | where 53 | T: Into>, 54 | { 55 | self.0.error_uri = Some(value.into()); 56 | self 57 | } 58 | 59 | /// Consumes the builder and returns built `Bearer` instance. 60 | pub fn finish(self) -> Bearer { 61 | self.0 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/headers/www_authenticate/challenge/bearer/challenge.rs: -------------------------------------------------------------------------------- 1 | use std::borrow::Cow; 2 | use std::fmt; 3 | use std::str; 4 | 5 | use actix_web::http::header::{ 6 | HeaderValue, IntoHeaderValue, InvalidHeaderValue, 7 | }; 8 | use bytes::{BufMut, Bytes, BytesMut}; 9 | 10 | use super::super::Challenge; 11 | use super::{BearerBuilder, Error}; 12 | use crate::utils; 13 | 14 | /// Challenge for [`WWW-Authenticate`] header with HTTP Bearer auth scheme, 15 | /// described in [RFC 6750](https://tools.ietf.org/html/rfc6750#section-3) 16 | /// 17 | /// ## Example 18 | /// 19 | /// ``` 20 | /// # use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer}; 21 | /// use actix_web_httpauth::headers::www_authenticate::bearer::{ 22 | /// Bearer, Error, 23 | /// }; 24 | /// use actix_web_httpauth::headers::www_authenticate::WwwAuthenticate; 25 | /// 26 | /// fn index(_req: HttpRequest) -> HttpResponse { 27 | /// let challenge = Bearer::build() 28 | /// .realm("example") 29 | /// .scope("openid profile email") 30 | /// .error(Error::InvalidToken) 31 | /// .error_description("The access token expired") 32 | /// .error_uri("http://example.org") 33 | /// .finish(); 34 | /// 35 | /// HttpResponse::Unauthorized() 36 | /// .set(WwwAuthenticate(challenge)) 37 | /// .finish() 38 | /// } 39 | /// ``` 40 | /// 41 | /// [`WWW-Authenticate`]: ../struct.WwwAuthenticate.html 42 | #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default, Clone)] 43 | pub struct Bearer { 44 | pub(crate) scope: Option>, 45 | pub(crate) realm: Option>, 46 | pub(crate) error: Option, 47 | pub(crate) error_description: Option>, 48 | pub(crate) error_uri: Option>, 49 | } 50 | 51 | impl Bearer { 52 | /// Creates the builder for `Bearer` challenge. 53 | /// 54 | /// ## Example 55 | /// 56 | /// ``` 57 | /// # use actix_web_httpauth::headers::www_authenticate::bearer::{Bearer}; 58 | /// let challenge = Bearer::build() 59 | /// .realm("Restricted area") 60 | /// .scope("openid profile email") 61 | /// .finish(); 62 | /// ``` 63 | pub fn build() -> BearerBuilder { 64 | BearerBuilder::default() 65 | } 66 | } 67 | 68 | #[doc(hidden)] 69 | impl Challenge for Bearer { 70 | fn to_bytes(&self) -> Bytes { 71 | let desc_uri_required = self 72 | .error_description 73 | .as_ref() 74 | .map_or(0, |desc| desc.len() + 20) 75 | + self.error_uri.as_ref().map_or(0, |url| url.len() + 12); 76 | let capacity = 6 77 | + self.realm.as_ref().map_or(0, |realm| realm.len() + 9) 78 | + self.scope.as_ref().map_or(0, |scope| scope.len() + 9) 79 | + desc_uri_required; 80 | let mut buffer = BytesMut::with_capacity(capacity); 81 | buffer.put(&b"Bearer"[..]); 82 | 83 | if let Some(ref realm) = self.realm { 84 | buffer.put(&b" realm=\""[..]); 85 | utils::put_quoted(&mut buffer, realm); 86 | buffer.put_u8(b'"'); 87 | } 88 | 89 | if let Some(ref scope) = self.scope { 90 | buffer.put(&b" scope=\""[..]); 91 | utils::put_quoted(&mut buffer, scope); 92 | buffer.put_u8(b'"'); 93 | } 94 | 95 | if let Some(ref error) = self.error { 96 | let error_repr = error.as_str(); 97 | let remaining = buffer.remaining_mut(); 98 | let required = desc_uri_required + error_repr.len() + 9; // 9 is for `" error=\"\""` 99 | if remaining < required { 100 | buffer.reserve(required); 101 | } 102 | buffer.put(&b" error=\""[..]); 103 | utils::put_quoted(&mut buffer, error_repr); 104 | buffer.put_u8(b'"') 105 | } 106 | 107 | if let Some(ref error_description) = self.error_description { 108 | buffer.put(&b" error_description=\""[..]); 109 | utils::put_quoted(&mut buffer, error_description); 110 | buffer.put_u8(b'"'); 111 | } 112 | 113 | if let Some(ref error_uri) = self.error_uri { 114 | buffer.put(&b" error_uri=\""[..]); 115 | utils::put_quoted(&mut buffer, error_uri); 116 | buffer.put_u8(b'"'); 117 | } 118 | 119 | buffer.freeze() 120 | } 121 | } 122 | 123 | impl fmt::Display for Bearer { 124 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { 125 | let bytes = self.to_bytes(); 126 | let repr = str::from_utf8(&bytes) 127 | // Should not happen since challenges are crafted manually 128 | // from `&'static str`'s and Strings 129 | .map_err(|_| fmt::Error)?; 130 | 131 | f.write_str(repr) 132 | } 133 | } 134 | 135 | impl IntoHeaderValue for Bearer { 136 | type Error = InvalidHeaderValue; 137 | 138 | fn try_into(self) -> Result::Error> { 139 | HeaderValue::from_maybe_shared(self.to_bytes()) 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /src/headers/www_authenticate/challenge/bearer/errors.rs: -------------------------------------------------------------------------------- 1 | use std::fmt; 2 | 3 | use actix_web::http::StatusCode; 4 | 5 | /// Bearer authorization error types, described in [RFC 6750](https://tools.ietf.org/html/rfc6750#section-3.1) 6 | #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] 7 | pub enum Error { 8 | /// The request is missing a required parameter, includes an unsupported 9 | /// parameter or parameter value, repeats the same parameter, uses more 10 | /// than one method for including an access token, or is otherwise 11 | /// malformed. 12 | InvalidRequest, 13 | 14 | /// The access token provided is expired, revoked, malformed, or invalid 15 | /// for other reasons. 16 | InvalidToken, 17 | 18 | /// The request requires higher privileges than provided by the access 19 | /// token. 20 | InsufficientScope, 21 | } 22 | 23 | impl Error { 24 | /// Returns [HTTP status code] suitable for current error type. 25 | /// 26 | /// [HTTP status code]: `actix_web::http::StatusCode` 27 | #[allow(clippy::trivially_copy_pass_by_ref)] 28 | pub fn status_code(&self) -> StatusCode { 29 | match self { 30 | Error::InvalidRequest => StatusCode::BAD_REQUEST, 31 | Error::InvalidToken => StatusCode::UNAUTHORIZED, 32 | Error::InsufficientScope => StatusCode::FORBIDDEN, 33 | } 34 | } 35 | 36 | #[doc(hidden)] 37 | #[allow(clippy::trivially_copy_pass_by_ref)] 38 | pub fn as_str(&self) -> &str { 39 | match self { 40 | Error::InvalidRequest => "invalid_request", 41 | Error::InvalidToken => "invalid_token", 42 | Error::InsufficientScope => "insufficient_scope", 43 | } 44 | } 45 | } 46 | 47 | impl fmt::Display for Error { 48 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 49 | f.write_str(self.as_str()) 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/headers/www_authenticate/challenge/bearer/mod.rs: -------------------------------------------------------------------------------- 1 | //! Challenge for the "Bearer" HTTP Authentication Scheme 2 | 3 | mod builder; 4 | mod challenge; 5 | mod errors; 6 | 7 | pub use self::builder::BearerBuilder; 8 | pub use self::challenge::Bearer; 9 | pub use self::errors::Error; 10 | 11 | #[cfg(test)] 12 | mod tests; 13 | -------------------------------------------------------------------------------- /src/headers/www_authenticate/challenge/bearer/tests.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | 3 | #[test] 4 | fn to_bytes() { 5 | let b = Bearer::build() 6 | .error(Error::InvalidToken) 7 | .error_description( 8 | "Subject 8740827c-2e0a-447b-9716-d73042e4039d not found", 9 | ) 10 | .finish(); 11 | 12 | assert_eq!( 13 | "Bearer error=\"invalid_token\" error_description=\"Subject 8740827c-2e0a-447b-9716-d73042e4039d not found\"", 14 | format!("{}", b) 15 | ); 16 | } 17 | -------------------------------------------------------------------------------- /src/headers/www_authenticate/challenge/mod.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::{Debug, Display}; 2 | 3 | use actix_web::http::header::IntoHeaderValue; 4 | use bytes::Bytes; 5 | 6 | pub mod basic; 7 | pub mod bearer; 8 | 9 | /// Authentication challenge for `WWW-Authenticate` header. 10 | pub trait Challenge: 11 | IntoHeaderValue + Debug + Display + Clone + Send + Sync 12 | { 13 | /// Converts the challenge into a bytes suitable for HTTP transmission. 14 | fn to_bytes(&self) -> Bytes; 15 | } 16 | -------------------------------------------------------------------------------- /src/headers/www_authenticate/header.rs: -------------------------------------------------------------------------------- 1 | use actix_web::error::ParseError; 2 | use actix_web::http::header::{ 3 | Header, HeaderName, HeaderValue, IntoHeaderValue, WWW_AUTHENTICATE, 4 | }; 5 | use actix_web::HttpMessage; 6 | 7 | use super::Challenge; 8 | 9 | /// `WWW-Authenticate` header, described in [RFC 7235](https://tools.ietf.org/html/rfc7235#section-4.1) 10 | /// 11 | /// This header is generic over [Challenge](./trait.Challenge.html) trait, 12 | /// see [Basic](./basic/struct.Basic.html) and 13 | /// [Bearer](./bearer/struct.Bearer.html) challenges for details. 14 | #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default, Clone)] 15 | pub struct WwwAuthenticate(pub C); 16 | 17 | impl Header for WwwAuthenticate { 18 | fn name() -> HeaderName { 19 | WWW_AUTHENTICATE 20 | } 21 | 22 | fn parse(_msg: &T) -> Result { 23 | unimplemented!() 24 | } 25 | } 26 | 27 | impl IntoHeaderValue for WwwAuthenticate { 28 | type Error = ::Error; 29 | 30 | fn try_into(self) -> Result::Error> { 31 | self.0.try_into() 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/headers/www_authenticate/mod.rs: -------------------------------------------------------------------------------- 1 | //! `WWW-Authenticate` header and various auth challenges 2 | 3 | mod challenge; 4 | mod header; 5 | 6 | pub use self::challenge::basic; 7 | pub use self::challenge::bearer; 8 | pub use self::challenge::Challenge; 9 | pub use self::header::WwwAuthenticate; 10 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! HTTP Authorization support for [actix-web](https://actix.rs) framework. 2 | //! 3 | //! Provides: 4 | //! * typed [Authorization] and [WWW-Authenticate] headers 5 | //! * [extractors] for an [Authorization] header 6 | //! * [middleware] for easier authorization checking 7 | //! 8 | //! ## Supported schemes 9 | //! 10 | //! * `Basic`, as defined in [RFC7617](https://tools.ietf.org/html/rfc7617) 11 | //! * `Bearer`, as defined in [RFC6750](https://tools.ietf.org/html/rfc6750) 12 | //! 13 | //! [Authorization]: `crate::headers::authorization::Authorization` 14 | //! [WWW-Authenticate]: `crate::headers::www_authenticate::WwwAuthenticate` 15 | //! [extractors]: https://actix.rs/docs/extractors/ 16 | //! [middleware]: ./middleware/ 17 | 18 | #![deny(bare_trait_objects)] 19 | #![deny(missing_docs)] 20 | #![deny(nonstandard_style)] 21 | #![deny(rust_2018_idioms)] 22 | #![deny(unused)] 23 | #![deny(clippy::all)] 24 | #![cfg_attr(feature = "nightly", feature(test))] 25 | 26 | pub mod extractors; 27 | pub mod headers; 28 | pub mod middleware; 29 | mod utils; 30 | -------------------------------------------------------------------------------- /src/middleware.rs: -------------------------------------------------------------------------------- 1 | //! HTTP Authentication middleware. 2 | 3 | use std::marker::PhantomData; 4 | use std::pin::Pin; 5 | use std::sync::Arc; 6 | 7 | use actix_service::{Service, Transform}; 8 | use actix_web::dev::{ServiceRequest, ServiceResponse}; 9 | use actix_web::Error; 10 | use futures::future::{self, Future, FutureExt, LocalBoxFuture, TryFutureExt}; 11 | use futures::lock::Mutex; 12 | use futures::task::{Context, Poll}; 13 | 14 | use crate::extractors::{basic, bearer, AuthExtractor}; 15 | 16 | /// Middleware for checking HTTP authentication. 17 | /// 18 | /// If there is no `Authorization` header in the request, 19 | /// this middleware returns an error immediately, 20 | /// without calling the `F` callback. 21 | /// 22 | /// Otherwise, it will pass both the request and 23 | /// the parsed credentials into it. 24 | /// In case of successful validation `F` callback 25 | /// is required to return the `ServiceRequest` back. 26 | #[derive(Debug, Clone)] 27 | pub struct HttpAuthentication 28 | where 29 | T: AuthExtractor, 30 | { 31 | process_fn: Arc, 32 | _extractor: PhantomData, 33 | } 34 | 35 | impl HttpAuthentication 36 | where 37 | T: AuthExtractor, 38 | F: Fn(ServiceRequest, T) -> O, 39 | O: Future>, 40 | { 41 | /// Construct `HttpAuthentication` middleware 42 | /// with the provided auth extractor `T` and 43 | /// validation callback `F`. 44 | pub fn with_fn(process_fn: F) -> HttpAuthentication { 45 | HttpAuthentication { 46 | process_fn: Arc::new(process_fn), 47 | _extractor: PhantomData, 48 | } 49 | } 50 | } 51 | 52 | impl HttpAuthentication 53 | where 54 | F: Fn(ServiceRequest, basic::BasicAuth) -> O, 55 | O: Future>, 56 | { 57 | /// Construct `HttpAuthentication` middleware for the HTTP "Basic" 58 | /// authentication scheme. 59 | /// 60 | /// ## Example 61 | /// 62 | /// ``` 63 | /// # use actix_web::Error; 64 | /// # use actix_web::dev::ServiceRequest; 65 | /// # use actix_web_httpauth::middleware::HttpAuthentication; 66 | /// # use actix_web_httpauth::extractors::basic::BasicAuth; 67 | /// // In this example validator returns immediately, 68 | /// // but since it is required to return anything 69 | /// // that implements `IntoFuture` trait, 70 | /// // it can be extended to query database 71 | /// // or to do something else in a async manner. 72 | /// async fn validator( 73 | /// req: ServiceRequest, 74 | /// credentials: BasicAuth, 75 | /// ) -> Result { 76 | /// // All users are great and more than welcome! 77 | /// Ok(req) 78 | /// } 79 | /// 80 | /// let middleware = HttpAuthentication::basic(validator); 81 | /// ``` 82 | pub fn basic(process_fn: F) -> Self { 83 | Self::with_fn(process_fn) 84 | } 85 | } 86 | 87 | impl HttpAuthentication 88 | where 89 | F: Fn(ServiceRequest, bearer::BearerAuth) -> O, 90 | O: Future>, 91 | { 92 | /// Construct `HttpAuthentication` middleware for the HTTP "Bearer" 93 | /// authentication scheme. 94 | /// 95 | /// ## Example 96 | /// 97 | /// ``` 98 | /// # use actix_web::Error; 99 | /// # use actix_web::dev::ServiceRequest; 100 | /// # use actix_web_httpauth::middleware::HttpAuthentication; 101 | /// # use actix_web_httpauth::extractors::bearer::{Config, BearerAuth}; 102 | /// # use actix_web_httpauth::extractors::{AuthenticationError, AuthExtractorConfig}; 103 | /// async fn validator(req: ServiceRequest, credentials: BearerAuth) -> Result { 104 | /// if credentials.token() == "mF_9.B5f-4.1JqM" { 105 | /// Ok(req) 106 | /// } else { 107 | /// let config = req.app_data::() 108 | /// .map(|data| data.get_ref().clone()) 109 | /// .unwrap_or_else(Default::default) 110 | /// .scope("urn:example:channel=HBO&urn:example:rating=G,PG-13"); 111 | /// 112 | /// Err(AuthenticationError::from(config).into()) 113 | /// } 114 | /// } 115 | /// 116 | /// let middleware = HttpAuthentication::bearer(validator); 117 | /// ``` 118 | pub fn bearer(process_fn: F) -> Self { 119 | Self::with_fn(process_fn) 120 | } 121 | } 122 | 123 | impl Transform for HttpAuthentication 124 | where 125 | S: Service< 126 | Request = ServiceRequest, 127 | Response = ServiceResponse, 128 | Error = Error, 129 | > + 'static, 130 | S::Future: 'static, 131 | F: Fn(ServiceRequest, T) -> O + 'static, 132 | O: Future> + 'static, 133 | T: AuthExtractor + 'static, 134 | { 135 | type Request = ServiceRequest; 136 | type Response = ServiceResponse; 137 | type Error = Error; 138 | type Transform = AuthenticationMiddleware; 139 | type InitError = (); 140 | type Future = future::Ready>; 141 | 142 | fn new_transform(&self, service: S) -> Self::Future { 143 | future::ok(AuthenticationMiddleware { 144 | service: Arc::new(Mutex::new(service)), 145 | process_fn: self.process_fn.clone(), 146 | _extractor: PhantomData, 147 | }) 148 | } 149 | } 150 | 151 | #[doc(hidden)] 152 | pub struct AuthenticationMiddleware 153 | where 154 | T: AuthExtractor, 155 | { 156 | service: Arc>, 157 | process_fn: Arc, 158 | _extractor: PhantomData, 159 | } 160 | 161 | impl Service for AuthenticationMiddleware 162 | where 163 | S: Service< 164 | Request = ServiceRequest, 165 | Response = ServiceResponse, 166 | Error = Error, 167 | > + 'static, 168 | S::Future: 'static, 169 | F: Fn(ServiceRequest, T) -> O + 'static, 170 | O: Future> + 'static, 171 | T: AuthExtractor + 'static, 172 | { 173 | type Request = ServiceRequest; 174 | type Response = ServiceResponse; 175 | type Error = S::Error; 176 | type Future = LocalBoxFuture<'static, Result, Error>>; 177 | 178 | fn poll_ready( 179 | &mut self, 180 | ctx: &mut Context<'_>, 181 | ) -> Poll> { 182 | self.service 183 | .try_lock() 184 | .expect("AuthenticationMiddleware was called already") 185 | .poll_ready(ctx) 186 | } 187 | 188 | fn call(&mut self, req: Self::Request) -> Self::Future { 189 | let process_fn = self.process_fn.clone(); 190 | // Note: cloning the mutex, not the service itself 191 | let inner = self.service.clone(); 192 | 193 | async move { 194 | let (req, credentials) = Extract::::new(req).await?; 195 | let req = process_fn(req, credentials).await?; 196 | let mut service = inner.lock().await; 197 | service.call(req).await 198 | } 199 | .boxed_local() 200 | } 201 | } 202 | 203 | struct Extract { 204 | req: Option, 205 | f: Option>>, 206 | _extractor: PhantomData T>, 207 | } 208 | 209 | impl Extract { 210 | pub fn new(req: ServiceRequest) -> Self { 211 | Extract { 212 | req: Some(req), 213 | f: None, 214 | _extractor: PhantomData, 215 | } 216 | } 217 | } 218 | 219 | impl Future for Extract 220 | where 221 | T: AuthExtractor, 222 | T::Future: 'static, 223 | T::Error: 'static, 224 | { 225 | type Output = Result<(ServiceRequest, T), Error>; 226 | 227 | fn poll( 228 | mut self: Pin<&mut Self>, 229 | ctx: &mut Context<'_>, 230 | ) -> Poll { 231 | if self.f.is_none() { 232 | let req = 233 | self.req.as_ref().expect("Extract future was polled twice!"); 234 | let f = T::from_service_request(req).map_err(Into::into); 235 | self.f = Some(f.boxed_local()); 236 | } 237 | 238 | let f = self 239 | .f 240 | .as_mut() 241 | .expect("Extraction future should be initialized at this point"); 242 | let credentials = futures::ready!(Future::poll(f.as_mut(), ctx))?; 243 | 244 | let req = self.req.take().expect("Extract future was polled twice!"); 245 | Poll::Ready(Ok((req, credentials))) 246 | } 247 | } 248 | -------------------------------------------------------------------------------- /src/utils.rs: -------------------------------------------------------------------------------- 1 | use std::str; 2 | 3 | use bytes::BytesMut; 4 | 5 | enum State { 6 | YieldStr, 7 | YieldQuote, 8 | } 9 | 10 | struct Quoted<'a> { 11 | inner: ::std::iter::Peekable>, 12 | state: State, 13 | } 14 | 15 | impl<'a> Quoted<'a> { 16 | pub fn new(s: &'a str) -> Quoted<'_> { 17 | Quoted { 18 | inner: s.split('"').peekable(), 19 | state: State::YieldStr, 20 | } 21 | } 22 | } 23 | 24 | impl<'a> Iterator for Quoted<'a> { 25 | type Item = &'a str; 26 | 27 | fn next(&mut self) -> Option { 28 | match self.state { 29 | State::YieldStr => match self.inner.next() { 30 | Some(s) => { 31 | self.state = State::YieldQuote; 32 | Some(s) 33 | } 34 | None => None, 35 | }, 36 | State::YieldQuote => match self.inner.peek() { 37 | Some(_) => { 38 | self.state = State::YieldStr; 39 | Some("\\\"") 40 | } 41 | None => None, 42 | }, 43 | } 44 | } 45 | } 46 | 47 | /// Tries to quote the quotes in the passed `value` 48 | pub fn put_quoted(buf: &mut BytesMut, value: &str) { 49 | for part in Quoted::new(value) { 50 | buf.extend_from_slice(part.as_bytes()); 51 | } 52 | } 53 | 54 | #[cfg(test)] 55 | mod tests { 56 | use std::str; 57 | 58 | use bytes::BytesMut; 59 | 60 | use super::put_quoted; 61 | 62 | #[test] 63 | fn test_quote_str() { 64 | let input = "a \"quoted\" string"; 65 | let mut output = BytesMut::new(); 66 | put_quoted(&mut output, input); 67 | let result = str::from_utf8(&output).unwrap(); 68 | 69 | assert_eq!(result, "a \\\"quoted\\\" string"); 70 | } 71 | 72 | #[test] 73 | fn test_without_quotes() { 74 | let input = "non-quoted string"; 75 | let mut output = BytesMut::new(); 76 | put_quoted(&mut output, input); 77 | let result = str::from_utf8(&output).unwrap(); 78 | 79 | assert_eq!(result, "non-quoted string"); 80 | } 81 | 82 | #[test] 83 | fn test_starts_with_quote() { 84 | let input = "\"first-quoted string"; 85 | let mut output = BytesMut::new(); 86 | put_quoted(&mut output, input); 87 | let result = str::from_utf8(&output).unwrap(); 88 | 89 | assert_eq!(result, "\\\"first-quoted string"); 90 | } 91 | 92 | #[test] 93 | fn test_ends_with_quote() { 94 | let input = "last-quoted string\""; 95 | let mut output = BytesMut::new(); 96 | put_quoted(&mut output, input); 97 | let result = str::from_utf8(&output).unwrap(); 98 | 99 | assert_eq!(result, "last-quoted string\\\""); 100 | } 101 | 102 | #[test] 103 | fn test_double_quote() { 104 | let input = "quote\"\"string"; 105 | let mut output = BytesMut::new(); 106 | put_quoted(&mut output, input); 107 | let result = str::from_utf8(&output).unwrap(); 108 | 109 | assert_eq!(result, "quote\\\"\\\"string"); 110 | } 111 | } 112 | --------------------------------------------------------------------------------