Skip to content

Commit

Permalink
Add proxy script for nginx
Browse files Browse the repository at this point in the history
  • Loading branch information
jirutka committed Nov 20, 2015
1 parent 4932777 commit 98353d6
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions src/ngx-oauth-proxy.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
---------
-- Proxy script for OAuth 2.0.

local config = require 'ngx-oauth.config'
local Cookies = require 'ngx-oauth.Cookies'
local ethr = require 'ngx-oauth.either'
local nginx = require 'ngx-oauth.nginx'
local oauth = require 'ngx-oauth.oauth2'

local either = ethr.either

local function write_auth_header (access_token)
ngx.req.set_header('Authorization', 'Bearer '..access_token)
end


local conf, errs = config.load()
if errs then
return nginx.fail(500, 'OAuth proxy error: %s', errs)
end

local cookies = Cookies(conf)
local access_token = cookies.get_access_token()

-- Cookie with access token found; set Authorization header and we're done.
if access_token then
write_auth_header(access_token)

-- Cookie with refresh token found; refresh token and set Authorization header.
elseif cookies.get_refresh_token() then
nginx.log(ngx.INFO, 'refreshing token for user: %s', cookies.get_username())

either (
function(err)
nginx.fail(503, 'Authorization server error: %s', err)
end,
function(token)
cookies.add_token(token)
write_auth_header(token.access_token)
end,
oauth.request_token('refresh_token', conf, cookies.get_refresh_token())
)

-- Neither access token nor refresh token found; bad luck, return HTTP 401.
else
nginx.fail(401, 'No access token found.')
end

0 comments on commit 98353d6

Please sign in to comment.