skip to Main Content

I want to authorize the user based on his email without it getting super messy. Is there a better way to do this?

http {
  map $http_user $user {
    default $http_user;
  }
  
  server {
      ...
      
      location ~ ^(/deployments/).*(xxx).* {
          set $allow 0;
          if($user = "[email protected]" || $user = "[email protected]" || $user = "[email protected]"){
             set $allow 1;
          }
          
          if($allow = 0){
             return 403 {error: you are not authorized}
          }
      }

      location ~ ^(/deployments/).*(yyy).* {
          set $allow 0;
          if($user = "[email protected]" || $user = "[email protected]" || $user = "[email protected]"){
             set $allow 1;
          }
          
          if($allow = 0){
             return 403 {error: you are not authorized}
          }
      }
  
  }

}

Is there a better way to do this?

I tried the above code but it doesn’t work

2

Answers


  1. You code will not work because of the way if functions when inside a location.

    You can use a map instead, which can be cascaded from your existing map.

    For example:

    map $http_user $user {
        default $http_user;
    }
    map $user $reject {
        default 1;
        [email protected] 0;
        [email protected] 0;
        [email protected] 0;
    }
    
    server {
        ...      
        location ... {
            if ($reject) {
                return 403 '{"error": "you are not authorized"}'
            }
        }
    }
    

    Expressions containing brace characters must be quoted, also JSON strings should be quoted.

    Login or Signup to reply.
  2. If you have ngx_http_auth_request_module installed, you can leverage auth_request directive to avoid if block in each location:

    map $http_user  $allow {
        [email protected]   1;
        [email protected]   1;
        [email protected]   1;
        default     0;
    }
    
    server {
    
        location /foo {
            auth_request /_internal/auth;
            ...
        }
    
        location /bar {
            auth_request /_internal/auth;
            ...
        }
    
        location = /_internal/auth {
            internal;
            if ($allow = 1) {
                return 200;
            }
            return 403;
        }
    
        location = /_internal/error/403 {
            internal;
            default_type application/json;
            return 403 '{"error": "you are not authorized"}';
        }
    
        error_page 403 /_internal/error/403;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search