actix_web_security/authentication/endpoint_matcher/mod.rs
1//! The credentials extraction and authentication can be limited to specific endpoints or applied
2//! to all endpoints. A `EndpointMatcher` must be instantiated. There are two default implementations
3//! available: `AllEndpointsMatcher` to protect all endpoints and `SpecificUrlsMatcher` to protect
4//! the URS with the exact matching URLs. Custom ones can be implemented if the defaults are not
5//! applicable for the use-case.
6
7use actix_web::dev::ServiceRequest;
8
9/// An `EndpointMatcher` is an implementation that takes a `actix_web::dev::ServiceRequest` instance and
10/// decides whether the request must be authenticated or not.
11pub trait EndpointMatcher: Send + Sync {
12 /// Checks whether the `actix_web::dev::ServiceRequest` must be authenticated or not.
13 /// Returns **true** if the request must be authenticated, **false** otherwise.
14 fn do_match(&self, req: &ServiceRequest) -> bool;
15}
16
17/// The `AllEndpointsMatcher` protects all endpoints. Valid credentials / token are required for all requests.
18#[derive(Clone)]
19pub struct AllEndpointsMatcher {}
20
21impl AllEndpointsMatcher {
22 pub fn new() -> AllEndpointsMatcher {
23 AllEndpointsMatcher {}
24 }
25}
26
27impl Default for AllEndpointsMatcher {
28 fn default() -> Self {
29 Self::new()
30 }
31}
32
33impl EndpointMatcher for AllEndpointsMatcher {
34 fn do_match(&self, _req: &ServiceRequest) -> bool {
35 true
36 }
37}
38
39/// The `SpecificUrlsMatcher` can be used to protect endpoints with specific URLs.
40/// Endpoints that do not match the given URLS are unprotected.
41/// Valid credentials / token are required for all requests.
42#[derive(Clone)]
43pub struct SpecificUrlsMatcher {
44 paths: Vec<String>,
45}
46
47impl SpecificUrlsMatcher {
48 pub fn new(paths: Vec<String>) -> SpecificUrlsMatcher {
49 SpecificUrlsMatcher { paths }
50 }
51}
52
53impl EndpointMatcher for SpecificUrlsMatcher {
54 fn do_match(&self, req: &ServiceRequest) -> bool {
55 let request_path = req.uri().path().to_string();
56 for path in &self.paths {
57 if *path == request_path {
58 return true;
59 }
60 }
61 false
62 }
63}