Use Openresty build authentication gateway

[Entry] use Openresty building certification Gateway

lwhile
0.5092017.10.07 16:00:03 number of words read 4,112 1,330

Application of the monomer, we can cookie + session, or JSON web token, authentication logic embodied in a single application, simply and efficiently, but also particularly easy.

However, the trend in recent years as more and more fire service (I think this is an inevitable trend, we think about how human society is functioning), many previously non-existent single application problem, and now has become a single application for demolition points during the first obstacle, such as system certification system.

If each ripped out of service have to do a certification (certification is several programmers to write code that is), の code for the soul of idealistic pursuit of agriculture, it is absolutely unacceptable. You said authentication code copy like, do not re-write .no no no, so get out of the architecture not only looked uncomfortable, I felt rotten smell of the code, but sooner or later go wrong.

Certified solve problems after splitting single application service is very conventional, help us to recall a word summary of their ancestral under: ". Any problem in computer science can be solved by another layer of indirection" We can add a service in front of all layer authentication service.

 
Paste_Image.png

This layer is used to see certification services as a total entry of user requests, have experience with Apache or Nginx students naturally think of them. If the function authentication module can be integrated into these Nginx or Apache Web server, would not it be more perfect ?

The protagonist of this article: Openresty, you can help us easily and quickly get the idea this is a complete made. Chun (Github) sponsored project you can Openresty seen as a package Nginx + modules commonly used, but it most. important feature is that we can use logic to achieve Lua Web framework can be achieved in Nginx, will start next article describes how to use Openresty, the above-mentioned certification services integrated into Nginx years.

installation

Openresty installed in two ways, one is to use the source code compiled and installed using precompiled package provided by the official:
specifically refer to the official website of the installation documentation

Hello world

If you have not modified the installation location Openresty, the default will be installed in the demo / use / local under / openresty directory. We can now try to write a Hello world level.

Create a working directory for the Openresty and create profiles:

mkdir ~/openresty_work
cd ~/openresty_work
touch nginx.conf

Next, configure a routing rule in which nginx.conf

worker_processes 1;
error_log logs/error.log; events { worker_connections 1024; } http { server { listen 8080; location /hello { default_type text/html; content_by_lua_block { ngx.say("Hello Openresty.") } } } } 

Nginx configuration file with the ordinary compared to the above configuration of more than a content_by_lua_block instruction, it is through the instruction is called, the time to access the route, will output the corresponding content. This directive is Openresty the LuaNginxModule provide function modules , when a request comes in, Nginx will start lua virtual machine, the contents of the output provided by lua.

We can use content_by_lua_filecommand substitution content_by_lua_block, the relevant code is written into the lua files.

location /hello {
            content_by_lua_file lua/hello.lua;
        }

--- hello.lua
ngx.say("Hello Openresty.") 

With the above bedding, then we can begin to build our certification services, authentication methods using JWT

Openresty a request's life cycle is divided into four stages:

 
Paste_Image.png

Our certification services will be mounted in the second phase, the Rewrite / Access Phase.

Next, prepare a need to use the library:
Lua-Resty-jwt
after clone hello.lua down into the folder where the file and configure lua_package_path to:

lua_package_path "/root/openresty_work/lua/?.lua;/root/openresty_work/lua/lua-resty-jwt/lib/?.lua;;";

Thoughts on the construction is simple, to provide users with a login request, verifying the identity of jwt token will be distributed to users. Then the user needs to access a certified interface, which added to the token in the header, after a request to enter Openresty token extracted from the lua authentication.

Nginx configuration file

server {
                listen 8080;
                location /hello {
                        content_by_lua_file lua/hello.lua;
                }
                location /login {
                        content_by_lua_file lua/sign.lua;
                }
                location /service1 {
                        access_by_lua_file lua/verify.lua;
                        # 需要反向代理在这配置
                }
                location /service {
                        access_by_lua_file lua/verify.lua;
                        # ...
                }
        }

The following is a lua file configuration related
sign.lua ↓:

local jwt = require 'resty.jwt'

-- 只允许POST请求
if ngx.req.get_method() ~= 'POST' then ngx.status = 405 ngx.say("Mehtod Not Allow") return end -- 获取请求body ngx.req.read_body() local body_raw = ngx.req.get_body_data() local body_json = cjson.decode(body_raw) local username = body_json['username'] local password = body_json['password'] if not username or not password then ngx.log(ngx.ERR, username, password) ngx.status = 400 ngx.say('无法获取账号或者密码') return end -- 验证账号和密码是否正确,如果验证失败则做如下处理 if not this_is_a_auth_method(username, password) then ngx.status = 401 ngx.say('认证失败') return end 

verify.lua ↓:

local jwt = require 'resty.jwt'

-- 从请求中提取header并从header从获取token字段
local headers = ngx.req.get_headers()
local token = headers['token']

-- 检查token是否存在
if not token then 
    ngx.status = 400
    ngx.say('无法获取token')
    return 
end 

-- 验证token
local jwt_obj = jwt:verify(vars.jwt_salt(), token)
if not jwt_obj['verified'] then 
    ngx.status = 401
    ngx.say('无效的token')
    return 
end 

At this point a prototype built using Openresty certified gateway has come out. It should be noted sentence, the above code because there is no company related to the operating environment, I did not, so read only tested and proven, can not be copied directly to run :)

If you want to use this authentication gateway in the production environment, there are many things to consider, such as cross-domain issues, agency problems static files, and so on.

Personal contacts Openresty time is not long, place text will inevitably be wrong or poorly expressed welcome to send comments or email me corrections:  [email protected]  , thanks.

For Openresty, personally think that to be interested in it, the key is to recognize not recognize let Nginx to take on more business in addition to the Web server, for Openresty, the benefits it can bring are:

  1. 极致的性能.上文没有提到Openresty的性能, 其实Openresty的编程模型和NodeJS很像, 在Openresty的世界里面,所有东西都是非阻塞的,更难得可贵的是, 它不需要使用NodeJS中的回调函数, 代码写起来其实还是同步模型, 配合C语言编写的Nginx, 最快的脚本语言lua+luajit解释器,这套方案的性能无可挑剔了.

  2. 降低了Nginx模块的开发难度. Nginx + C/C++能做的, Openresty用lua都能做.开发效率高了, 性能还不怎么降, 何乐而不为呢?

Guess you like

Origin www.cnblogs.com/lgj8/p/12095539.html