skip to Main Content

I have a nginx configuration where with Lua code I want to block all domain except one(example.com). Since I am using Azure, I could not get just domain value from the IDToken so I am using emails([email protected] since email also contains domain name).

Requirement is to block all access if the user email does not contain the string example.com
This is what I have so far but it does not have does not contain string

if res.id_token.email ~= 'example.com' then
  ngx.exit(ngx.HTTP_FORBIDDEN)
end

it blocks all emails with example.com

since email can be anything and its a string that should use "CONTAINS", so its failing. What will be the solution for if condition with does not contain example.com

3

Answers


  1. Chosen as BEST ANSWER

    The following worked:

    if not string.match(res.id_token.email, "@example.com") then
        ngx.exit(ngx.HTTP_FORBIDDEN)
    end
    

    Found that string.match can find a string to match and I have added a not before it.


  2. This is the length of @example.com

    #'@example.com'
    

    Get the suffix of email with the length of @example.com

    res.id_token.email:sub(-#'@example.com')
    

    Compare with @example.com

    res.id_token.email:sub(-#'@example.com') ~= '@example.com'
    
    Login or Signup to reply.
  3. As a presumably more efficient alternative to string.match, you can also use string.find (which returns indices, thus not having to build a match string), and also allows disabling pattern matching:

    if not res.id_token.email:find("@example.com", 1, true) then
        ngx.exit(ngx.HTTP_FORBIDDEN)
    end
    

    Note that your question asks for contains, not ends with.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search