Skip to main content

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