{
  "name": "OIDC flow",
  "nodes": [
    {
      "parameters": {
        "path": "891ad1cd-6a50-4a88-8789-95680c78f14c",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "9a4b1923-be78-4fb1-ac12-ee6fafbfeab4",
      "name": "Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 1,
      "position": [
        -300,
        480
      ],
      "webhookId": "891ad1cd-6a50-4a88-8789-95680c78f14c"
    },
    {
      "parameters": {
        "jsCode": "let myCookies = {};\nlet cookies = [];\n\ncookies = $input.item.json.headers.cookie.split(';')\nfor (item of cookies ) {\n  myCookies[item.split('=')[0].trim()]=item.split('=')[1].trim();\n}\n\nreturn myCookies;"
      },
      "id": "903ccd84-0cf9-4324-807b-f072a871298f",
      "name": "Code",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        80,
        480
      ],
      "continueOnFail": true
    },
    {
      "parameters": {
        "url": "={{ $('Set variabes : auth, token, userinfo, client id, scope').item.json.userinfo_endpoint }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "=Bearer  {{ $json['n8n-custom-auth'] }}"
            }
          ]
        },
        "options": {}
      },
      "id": "d886c363-6c9e-4eaa-b30d-56463c2e943c",
      "name": "user info",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.1,
      "position": [
        500,
        340
      ],
      "continueOnFail": true
    },
    {
      "parameters": {
        "respondWith": "text",
        "responseBody": "={{ $json.html }}",
        "options": {}
      },
      "id": "3d64b5b0-69aa-45a6-ac1e-91b159d82d54",
      "name": "send back login page",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1,
      "position": [
        1120,
        620
      ]
    },
    {
      "parameters": {
        "conditions": {
          "number": [
            {
              "value1": "={{ $json['n8n-custom-auth'] }}",
              "operation": "isNotEmpty"
            }
          ]
        }
      },
      "id": "7c7b05eb-d440-49f0-81e7-aa5b1188a711",
      "name": "IF token is present",
      "type": "n8n-nodes-base.if",
      "typeVersion": 1,
      "position": [
        280,
        460
      ],
      "continueOnFail": true
    },
    {
      "parameters": {
        "html": "<!DOCTYPE html>\n\n<html>\n<head>\n  <meta charset=\"UTF-8\" />\n  <title>My HTML document</title>\n</head>\n<body>\n  <div class=\"container\">\n    <h1>Welcome {{$('user info').item.json.email }} </h1>\n  </div>\n</body>\n</html>\n\n<style>\n.container {\n  background-color: #ffffff;\n  text-align: center;\n  padding: 16px;\n  border-radius: 8px;\n}\n\nh1 {\n  color: #ff6d5a;\n  font-size: 24px;\n  font-weight: bold;\n  padding: 8px;\n}\n\nh2 {\n  color: #909399;\n  font-size: 18px;\n  font-weight: bold;\n  padding: 8px;\n}\n</style>\n"
      },
      "id": "cde5d4cb-af0f-47f2-ada2-9775df5db949",
      "name": "Welcome page",
      "type": "n8n-nodes-base.html",
      "typeVersion": 1,
      "position": [
        940,
        300
      ]
    },
    {
      "parameters": {
        "respondWith": "text",
        "responseBody": "={{ $json.html }}",
        "options": {}
      },
      "id": "c35b71a5-da56-42e6-ac8e-9050a0ef066e",
      "name": "send back welcome page",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1,
      "position": [
        1140,
        300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "number": [
            {
              "value1": "={{ $json.email }}",
              "operation": "isNotEmpty"
            }
          ]
        }
      },
      "id": "f4d5fa0b-1933-417d-9ea6-f9c657f63bdb",
      "name": "IF user info ok",
      "type": "n8n-nodes-base.if",
      "typeVersion": 1,
      "position": [
        720,
        400
      ],
      "continueOnFail": true
    },
    {
      "parameters": {
        "html": "<!-- Thanks to https://github.com/curityio/pkce-javascript-example/tree/master -->\n<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\">\n    <title>Login</title>\n  </head>\n  <style>\n.container {\n  background-color: #ffffff;\n  text-align: center;\n  padding: 16px;\n  border-radius: 8px;\n}\n\nh1 {\n  color: #ff6d5a;\n  font-size: 24px;\n  font-weight: bold;\n  padding: 8px;\n}\n\nh2 {\n  color: #909399;\n  font-size: 18px;\n  font-weight: bold;\n  padding: 8px;\n}\n</style>\n  <body>\n    <div id=\"result\"></div>\n    <script>\n    const authorizeEndpoint = \"{{ $('Set variabes : auth, token, userinfo, client id, scope').item.json.auth_endpoint }}\";\n    const tokenEndpoint = \"{{ $('Set variabes : auth, token, userinfo, client id, scope').item.json.token_endpoint }}\";\n    const clientId = \"{{ $('Set variabes : auth, token, userinfo, client id, scope').item.json.client_id }}\";\n    const scope = \"{{ $('Set variabes : auth, token, userinfo, client id, scope').item.json.scope }}\";\n        if (window.location.search) {\n            var args = new URLSearchParams(window.location.search);\n            var code = args.get(\"code\");\n\n            if (code) {\n                var xhr = new XMLHttpRequest();\n\n                xhr.onload = function() {\n                    var response = xhr.response;\n                    var message;\n\n                    if (xhr.status == 200) {\n                        message = \"Access Token: \" + response.access_token;\n                        document.cookie = \"n8n-custom-auth=\"+response.access_token;\n                        location.reload();\n                    }\n                    else {\n                        message = \"Error: \" + response.error_description + \" (\" + response.error + \")\";\n                    }\n\n                    document.getElementById(\"result\").innerHTML = message;\n                };\n                xhr.responseType = 'json';\n                xhr.open(\"POST\", tokenEndpoint, true);\n                xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');\n                xhr.send(new URLSearchParams({\n                    client_id: clientId,\n                    code_verifier: window.sessionStorage.getItem(\"code_verifier\"),\n                    grant_type: \"authorization_code\",\n                    redirect_uri: location.href.replace(location.search, ''),\n                    code: code\n                }));\n            }\n        }\n        async function generateCodeChallenge(codeVerifier) {\n            var digest = await crypto.subtle.digest(\"SHA-256\",\n                new TextEncoder().encode(codeVerifier));\n\n            return btoa(String.fromCharCode(...new Uint8Array(digest)))\n                .replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_')\n        }\n\n        function generateRandomString(length) {\n            var text = \"\";\n            var possible = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\n            for (var i = 0; i < length; i++) {\n                text += possible.charAt(Math.floor(Math.random() * possible.length));\n            }\n\n            return text;\n        }\n\n        if (!crypto.subtle) {\n            document.writeln('<p>' +\n                    '<b>WARNING:</b> The script will fall back to using plain code challenge as crypto is not available.</p>' +\n                    '<p>Javascript crypto services require that this site is served in a <a href=\"https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts\">secure context</a>; ' +\n                    'either from <b>(*.)localhost</b> or via <b>https</b>. </p>' +\n                    '<p> You can add an entry to /etc/hosts like \"127.0.0.1 public-test-client.localhost\" and reload the site from there, enable SSL using something like <a href=\"https://letsencrypt.org/\">letsencypt</a>, or refer to this <a href=\"https://stackoverflow.com/questions/46468104/how-to-use-subtlecrypto-in-chrome-window-crypto-subtle-is-undefined\">stackoverflow article</a> for more alternatives.</p>' +\n                    '<p>If Javascript crypto is available this message will disappear.</p>')\n        }\n\n      var codeVerifier = generateRandomString(64);\n\n            const challengeMethod = crypto.subtle ? \"S256\" : \"plain\"\n\n            Promise.resolve()\n                .then(() => {\n                    if (challengeMethod === 'S256') {\n                        return generateCodeChallenge(codeVerifier)\n                    } else {\n                        return codeVerifier\n                    }\n                })\n                .then(function(codeChallenge) {\n                    window.sessionStorage.setItem(\"code_verifier\", codeVerifier);\n\n                    var redirectUri = window.location.href.split('?')[0];\n                    var args = new URLSearchParams({\n                        response_type: \"code\",\n                        client_id: clientId,\n                        code_challenge_method: challengeMethod,\n                        code_challenge: codeChallenge,\n                        redirect_uri: redirectUri,\n                        scope: scope\n                    });\n                window.location = authorizeEndpoint + \"?\" + args;\n            });\n    </script>\n  </body>\n</html>"
      },
      "id": "401cdb99-1f60-4dde-b13b-783e17607b45",
      "name": "login form",
      "type": "n8n-nodes-base.html",
      "typeVersion": 1,
      "position": [
        920,
        620
      ]
    },
    {
      "parameters": {
        "values": {
          "string": [
            {
              "name": "auth_endpoint",
              "value": "https://app.please-open.it/auth/realms/fe6b4729-039f-4b54-bd50-d47f1cd541d8/protocol/openid-connect/auth"
            },
            {
              "name": "token_endpoint",
              "value": "https://app.please-open.it/auth/realms/fe6b4729-039f-4b54-bd50-d47f1cd541d8/protocol/openid-connect/token"
            },
            {
              "name": "userinfo_endpoint",
              "value": "https://app.please-open.it/auth/realms/fe6b4729-039f-4b54-bd50-d47f1cd541d8/protocol/openid-connect/userinfo"
            },
            {
              "name": "client_id",
              "value": "n8n"
            },
            {
              "name": "scope",
              "value": "openid"
            }
          ]
        },
        "options": {}
      },
      "id": "0922799b-705b-459a-a045-97fa177c75d0",
      "name": "Set variabes : auth, token, userinfo, client id, scope",
      "type": "n8n-nodes-base.set",
      "typeVersion": 2,
      "position": [
        -120,
        320
      ]
    },
    {
      "parameters": {
        "content": "In this set, you have to retrieve from your identity provider : \n- auth url\n- token url\n- userinfo url\n- the client id you created for this flow\n- scopes to use, at least \"openid\" scope",
        "height": 207,
        "width": 510
      },
      "id": "a3000528-9025-4002-b75c-1ca1df6d3945",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -280,
        100
      ]
    },
    {
      "parameters": {
        "content": "At this point the user is authenticated, you have access to his profile from the user info result",
        "height": 126.59025787965624
      },
      "id": "da710979-148f-4843-a592-179f4ef24393",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        880,
        160
      ]
    },
    {
      "parameters": {
        "content": "## Example with Keycloak\nFrom \"realm settings\", open \"OpenID Endpoint Configuration\" and get auth, token and userinfo uris.\n\nCreate a client for your flow, disable \"client authentication\", check only \"Standard flow\".\n\nIn \"Valid redirect URIs\", copy and paste the \"production URL\" of this webhook. \nUn \"web origins\", just enter \"+\".\n\nNow you're done :) \n",
        "height": 336,
        "width": 776
      },
      "id": "0ed463f8-c2bc-4e5b-be57-f8e3b9725135",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -520,
        700
      ]
    }
  ],
  "pinData": {},
  "connections": {
    "Webhook": {
      "main": [
        [
          {
            "node": "Set variabes : auth, token, userinfo, client id, scope",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code": {
      "main": [
        [
          {
            "node": "IF token is present",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "user info": {
      "main": [
        [
          {
            "node": "IF user info ok",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "IF token is present": {
      "main": [
        [
          {
            "node": "user info",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "login form",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Welcome page": {
      "main": [
        [
          {
            "node": "send back welcome page",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "IF user info ok": {
      "main": [
        [
          {
            "node": "Welcome page",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "login form",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "login form": {
      "main": [
        [
          {
            "node": "send back login page",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set variabes : auth, token, userinfo, client id, scope": {
      "main": [
        [
          {
            "node": "Code",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": true,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "d44c9ea7-268a-4933-a310-9a9d5b10538c",
  "id": "nCqO61FICfBi8Q1P",
  "meta": {
    "instanceId": "11f0bca80fdd47e21bd156f4266eada6e64a6bc4c37f34dc8ae14ccf768e9285"
  },
  "tags": []
}