Nginx(OpenResty + Keyclock)

Все будем делать в контейнерах

Запускаем KeyClock

docker run -itd --rm -p 8080:8080 --name keycloak -e KEYCLOAK_USER=admin -e KEYCLOAK_PASSWORD=admin -e PROXY_ADDRESS_FORWARDING=true jboss/keycloak:latest

Настраиваем KeyClock.

Авторизуемся и добавляем realm ( «myrealm»)

Добавляем Client ( «nginx») 

В поле ValidRedirect URLs указываем адрес nginx 

Client Protocol: confidential

Переходим на вкладку Credentials и запоминаем Secret он нам понадобиться когда будем настраивать Nginx

Добавляем пользователя с помощью которого будем авторизовываться

Теперь займемся Nginx а точнее Openresty ( это форк Nginx с добавленной опцией lua)

Соберём образ Openresty

FROM openresty/openresty:alpine-fat
RUN mkdir /var/log/nginx"
RUN apk add --no-cache openssl-dev
RUN apk add --no-cache git
RUN apk add --no-cache gcc
RUN luarocks install lua-resty-openidc
ENTRYPOINT ["/usr/local/openresty/nginx/sbin/nginx", "-g", "daemon off;"]
docker build --no-cache -t nginxkeyclock .
docker run -d --name nginxkeyclock -p 81:80 -p 3032:3032 nginxkeyclock

Ну и сам конфиг правим перезапускаем

Момент по самоподписанными сертификатами в Lua добавляем такую опцию в конфиг nginx in http

lua_ssl_trusted_certificate /etc/ssl/certs/ca.crt;

vim /usr/local/openresty/nginx/conf/nginx.conf

pcre_jit on;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    client_body_temp_path /var/run/openresty/nginx-client-body;
    proxy_temp_path       /var/run/openresty/nginx-proxy;
    fastcgi_temp_path     /var/run/openresty/nginx-fastcgi;
    uwsgi_temp_path       /var/run/openresty/nginx-uwsgi;
    scgi_temp_path        /var/run/openresty/nginx-scgi;
    sendfile        on;
    keepalive_timeout  65;
       server {
       listen   3032;
       root     /opt/nginx/html;
       resolver 127.0.0.11  valid=1s    ipv6=off;

       access_by_lua '
         local opts = {
           redirect_uri_path = "/redirect_uri",
           accept_none_alg = true,
           discovery = "http://addresskeyclock:8080/auth/realms/myrealm/.well-known/openid-configuration",
           client_id = "Название Клиента",
           client_secret = "ТУТ КЛЮЧ из KeyClock",
           redirect_uri_scheme = "http",
           logout_path = "/logout",
           redirect_after_logout_uri = "http://addresskeyclock:8080/auth/realms/myrealm/protocol/openid-connect/logout?redirect_uri=http://localhost/",
           redirect_after_logout_with_id_token_hint = false,
           session_contents = {id_token=true}
         }
         -- call introspect for OAuth 2.0 Bearer Access Token validation
         local res, err = require("resty.openidc").authenticate(opts)
         if err then
           ngx.status = 403
           ngx.say(err)
           ngx.exit(ngx.HTTP_FORBIDDEN)
         end
      ';
      expires           0;
      add_header        Cache-Control private;
      location / {
          root /usr/share/nginx/html;
      }
   }
}

Для визуализации создадим index.html ( Надеюсь вы понимаете что и конфиг и index.html нужно править внутри контейнера c Openresty и само собой после правки конфига перезапускаем контейнер)

vim /usr/share/nginx/html/index.html

<!DOCTYPE html>
<html>
<body>
<h1>Hello Word</h1>
<p>My first paragraph.</p>
</body>
</html>

Ну пробуем авторизоваться


Добавить комментарий 0