当前位置 主页 > 服务器问题 > nginx问题汇总 >

    在Nginx中增加对OAuth协议的支持的教程(5)

    栏目:nginx问题汇总 时间:2018-10-25 16:33


    if json.access_level < 255 then
        -- Expire their stored token
        ngx.header["Set-Cookie"] = "SGAccessToken=deleted; path=/; Expires=Thu, 01-Jan-1970 00:00:01 GMT"

        -- Disallow access
        ngx.status = ngx.HTTP_UNAUTHORIZED
        ngx.say("{\"status\": 403, \"message\": \"USER_ID"..json.user_id.." has no access to this resource\"}")
        return ngx.exit(ngx.HTTP_OK)
    end

    -- Store the access_token within a cookie
    ngx.header["Set-Cookie"] = "SGAccessToken="..access_token.."; path=/;Max-Age=3000"

    -- Support redirection back to your request if necessary
    local redirect_back = ngx.var.cookie_SGRedirectBack
    if redirect_back then
        ngx.header["Set-Cookie"] = "SGRedirectBack=deleted; path=/; Expires=Thu, 01-Jan-1970 00:00:01 GMT"
        return ngx.redirect(redirect_back)
    end

    现在我们只需要通过一些请求头信息告知我们当前的应用谁登录了就行了。您可以重用REMOTE_USER,如果你有需求的话,就可以用这个取代基本的身份验证,而除此之外的任何事情都是公平的游戏。

    复制代码 代码如下:-- Set some headers for use within the protected endpoint
    ngx.req.set_header("X-USER-ACCESS-LEVEL", json.access_level)
    ngx.req.set_header("X-USER-EMAIL", json.email)

    我现在就可以像任何其它的站点那样在我的应用程序中访问这些http头了,而不是用数百行代码和大量的时间来重新实现身份验证。

    Nginx 和 Lua, 放在树结构里面

    在这一点上,我们应该有一个可以用来阻挡/拒绝访问的LUA脚本。我们可以将这个脚本放到磁盘上的一个文件中,然后使用access_by_lua_file配置来将它应用在我们的nginx站点中。在SeatGeek中,我们使用Chief来模板化输出配置文件,虽然你可以使用Puppet,Fabric,或者其它任何你喜欢的工具。

    下面是你可以用来使所有东西都运行起来的最简单的nginx的网站。你也可能会想要检查下access.lua - 在这里 - 它是上面的lua脚本编译后的文件。

    复制代码 代码如下:# The app we are proxying to
    upstream production-app {
      server localhost:8080;
    }

    # The internal oauth provider
    upstream internal-oauth {
      server localhost:1337;
    }

    server {
      listen       80;
      server_name  private.example.com;
      root         /apps;
      charset      utf-8;

      # This will run for everything but subrequests
      access_by_lua_file "/etc/nginx/access.lua";

      # Used in a subrequest
      location /_access_token { proxy_pass http://internal-oauth/oauth/access_token; }
      location /_user { proxy_pass http://internal-oauth/user; }

      location / {
        proxy_set_header  X-Real-IP  $remote_addr;
        proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header  Host $http_host;
        proxy_redirect    off;