Keycloak with NGINX proxy server not authenticating rest api Keycloak with NGINX proxy server not authenticating rest api nginx nginx

Keycloak with NGINX proxy server not authenticating rest api


Three years later, I have encountered the same problem. Maybe you have solved it, but I guess there are still many people who have encountered this problem like me. My solution is to use openresty. You will find many tutorials or code fragments of openresty. I won't talk more about it here.

I just put access_token in the request header after the openresty authentication is passed, just like this

local opts = {    redirect_uri_path = "/redirect_uri",    discovery = "https://a.b.c.d:8093/auth/realms/xxx/.well-known/openid-configuration",    client_id = "client_id",    client_secret = "client_secret",    redirect_uri_scheme = "https",    logout_path = "/logout",    redirect_after_logout_uri = "https://a.b.c.d:8093/auth/realms/xxx/protocol/openid-connect/logout?redirect_uri=https://a.b.c.d:8093/",    scope = "openid email",    access_token_expires_leeway = 0,    accept_none_alg = false,    accept_unsupported_alg = false,    renew_access_token_on_expiry = true,    session_contents = {access_token=true, id_token = true}}local res, err = require("resty.openidc").authenticate(opts)if err then    ngx.status = 403    ngx.say(err)    ngx.exit(ngx.HTTP_FORBIDDEN)endngx.req.set_header("Authorization", "Bearer " .. res.access_token)

In the nginx configuration file, I did this

    location /auth/ {        proxy_pass http://keycloak:8080/auth/;        proxy_set_header Host $host:$server_port;    }    location / {        access_by_lua_block {            require("oidc/acc")()        }        try_files $uri $uri/ /index.html;        index  index.html;    }    location  /api/ {        access_by_lua_block {            require("oidc/acc")()        }        proxy_set_header  Host  $host:$server_port;        proxy_pass http://gateway:8881/api/;    }