Skip to main content
Version: 4.18.1

Node JS Express

  • The constants we used are exported in settings.js file.

  • settings.js

const OIDC_AUTH_END_POINT = "https://tenantname.aws1.test1.com/auth/realms/{tenantname}/protocol/openid-connect/auth"
const OIDC_CLIENT = "openidtestclient"
const OIDC_CLIENT_SECRET = "0086d90a-221f-431c-ad35-741e6599bf6c"
const OIDC_TOKEN_URI = "https://tenantname.aws1.test1.com/auth/realms/{tenantname}/protocol/openid-connect/token"

module.exports = {
OIDC_AUTH_END_POINT: OIDC_AUTH_END_POINT,
OIDC_CLIENT: OIDC_CLIENT,
OIDC_CLIENT_SECRET: OIDC_CLIENT_SECRET,
OIDC_TOKEN_URI: OIDC_TOKEN_URI
}

  • index.js
  • Used libraries:
const MongoClient = require('mongodb').MongoClient; // Database, de─či┼čtirilebilir.
const express = require("express");
const bodyParser = require("body-parser"); // json ve form encoded ikisi de etkin
const crypto = require("crypto"); // nonce olu┼čturumak i├žin
const axios = require("axios").default; // istek atmak i├žin
const qs = require("querystring"); // objeleri form encode hale getiriyor
const jwt = require("jsonwebtoken"); // jwt decode etmek i├žin

/auth/oidc (GET)ÔÇő

app.get("/auth/oidc", (req, res, next) => {
const redirect_uri = req.query.redirect_uri;
getNonce(4, (nonce) => {
const url = `${OIDC_AUTH_END_POINT}?client_id=${OIDC_CLIENT}&redirect_uri=${redirect_uri}&scope=openid&response_type=code&response_mode=query&nonce=${nonce}`;
const data = {
client_id: OIDC_CLIENT,
auth_url: OIDC_AUTH_END_POINT,
composed_url: url,
};
res.status(200).json(data);
});
});

//Yard─▒mc─▒ getNonce fonksiyonu random string ├╝retmeye yar─▒yor.
const getNonce = (half_length, callback) => {
if (half_length < 1) {
return "";
}
crypto.randomBytes(half_length, (err, buf) => {
if (err) console.log(err);
callback(buf.toString("hex"));
});
};

/auth/code (POST)ÔÇő

app.post("/auth/code", async (req, res, next) => {
const code = req.body.code;
const redirect_uri = req.body.redirect_uri;
const data = {
code: code,
client_id: OIDC_CLIENT,
grant_type: "authorization_code",
client_secret: OIDC_CLIENT_SECRET,
redirect_uri: redirect_uri
};

try {
const resp = await axios.post(OIDC_TOKEN_URI, qs.stringify(data));
const id_token = resp.data.id_token;
if(!id_token)res.status(400).json("bad request");
const id_token_decoded = jwt.decode(id_token);
const email = id_token_decoded.email;
// Bu email ile kullan─▒c─▒ veri taban─▒nda var m─▒ diye bak─▒l─▒r.
const users = db.collection('users');
users.find({email: email}).toArray((err, docs) => {
if(docs.length == 0){ // Kullan─▒c─▒ yoksa burada kay─▒t edebilirsiniz.
await users.insertOne({email: email})
}else{ // Varsa token ile giri┼č yap─▒labilir.
const token = jwt.sign(docs[0], "secretkey");
const data = {
token: token,
user: user
};
res.status(200).json(data);
}
});
} catch (error) {
res.status(500).json(error);
}
});


info