Skip to content
Snippets Groups Projects
Commit 1916612f authored by Alfredo Chissotti's avatar Alfredo Chissotti
Browse files

ancora da mettere il domain in https

parent 751d7b69
No related branches found
No related tags found
No related merge requests found
Showing
with 150 additions and 94 deletions
...@@ -22,6 +22,7 @@ import javax.net.ssl.HttpsURLConnection; ...@@ -22,6 +22,7 @@ import javax.net.ssl.HttpsURLConnection;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpsExchange;
import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpHandler;
public class ObtainToken implements HttpHandler{ public class ObtainToken implements HttpHandler{
...@@ -33,7 +34,8 @@ public class ObtainToken implements HttpHandler{ ...@@ -33,7 +34,8 @@ public class ObtainToken implements HttpHandler{
} }
@Override @Override
public void handle(HttpExchange exchange) throws IOException { public void handle(HttpExchange ex) throws IOException {
HttpsExchange exchange = (HttpsExchange) ex;
URI requestURI = exchange.getRequestURI(); URI requestURI = exchange.getRequestURI();
String stringURI = requestURI.toString(); String stringURI = requestURI.toString();
boolean wantsRedirectPage = Helper.compareText(stringURI,URI.create("/").toString()); boolean wantsRedirectPage = Helper.compareText(stringURI,URI.create("/").toString());
......
...@@ -10,18 +10,22 @@ import java.util.ArrayList; ...@@ -10,18 +10,22 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpsExchange;
import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpHandler;
public class Resources implements HttpHandler { public class Resources implements HttpHandler {
@Override @Override
public void handle(HttpExchange exchange) throws IOException { public void handle(HttpExchange ex) throws IOException {
HttpsExchange exchange = (HttpsExchange) ex;
String requestURI = exchange.getRequestURI().toASCIIString().replace("/secured/home/","/"); String requestURI = exchange.getRequestURI().toASCIIString().replace("/secured/home/","/");
String requestMethod = exchange.getRequestMethod(); String requestMethod = exchange.getRequestMethod();
if (Helper.compareText(requestMethod, "GET")) { if (Helper.compareText(requestMethod, "GET")) {
String response = getLocalPage(requestURI); String response = getLocalPage(requestURI);
if(requestURI.contains("conf"))
System.out.println("URI: " + requestURI+"\tresponse: "+response);
if(response.equals("fail")){ if(response.equals("fail")){
//nel caso in cui non ci sia il file (perche non stato scaricato), allora creo un file fittizzio per non far crashare tutto il resto //nel caso in cui non ci sia il file (perche non stato scaricato), allora creo un file fittizzio per non far crashare tutto il resto
String[] requestedPath = requestURI.split("/"); String[] requestedPath = requestURI.split("/");
......
package code; package code;
/*import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileInputStream;
import java.security.KeyStore; import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.KeyManagerFactory;
...@@ -11,11 +12,17 @@ import javax.net.ssl.TrustManagerFactory; ...@@ -11,11 +12,17 @@ import javax.net.ssl.TrustManagerFactory;
import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsParameters; import com.sun.net.httpserver.HttpsParameters;
import com.sun.net.httpserver.HttpsServer;*/ import com.sun.net.httpserver.HttpsServer;
import java.io.IOException; import java.io.IOException;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.security.KeyStore;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import com.sun.net.httpserver.HttpServer;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.TrustManagerFactory;
public class Server { public class Server {
...@@ -31,17 +38,17 @@ public class Server { ...@@ -31,17 +38,17 @@ public class Server {
e.printStackTrace(); e.printStackTrace();
} }
KeyCloak kcs = new KeyCloak(CLIENT_PATH + "/keycloak.json", CLIENT_PATH + "/params.json"); KeyCloak kcs = new KeyCloak(CLIENT_PATH + "/keycloak.json", CLIENT_PATH + "/params.json");
// HttpsServer server = HttpsServer.create(new InetSocketAddress(port), 0); HttpsServer server = HttpsServer.create(new InetSocketAddress(port), 0);
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); // HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
// initialise the HTTPS server // initialise the HTTPS server
/*try { try {
SSLContext sslContext = SSLContext.getInstance("TLS"); SSLContext sslContext = SSLContext.getInstance("TLS");
// initialise the keystore // initialise the keystore
char[] password = "simulator".toCharArray(); char[] password = "miapasswd".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS"); KeyStore ks = KeyStore.getInstance("JKS");
FileInputStream fis = new FileInputStream("testkey.jks"); FileInputStream fis = new FileInputStream("../lig.keystore");
ks.load(fis, password); ks.load(fis, password);
// setup the key manager factory // setup the key manager factory
...@@ -71,50 +78,46 @@ public class Server { ...@@ -71,50 +78,46 @@ public class Server {
} catch (Exception ex) { } catch (Exception ex) {
System.out.println("Failed to create HTTPS port"); System.out.println("Failed to create HTTPS port");
ex.printStackTrace();
} }
} }
}); });
//API del server //API del server
server.createContext("/js/",new Resources()); server.createContext("/js/authentication/",new Resources());
server.createContext("/css/",new Resources()); server.createContext("/js/templates/",new Resources());
server.createContext("/res/",new ImageRes()); server.createContext("/css/",new Resources());
server.createContext("/",new Home()); server.createContext("/conf/",new Resources());
server.createContext("/res/",new ImageRes());
server.createContext("/secured/home/js/",new Resources());
server.createContext("/secured/home/css/",new Resources());
server.createContext("/secured/home/res/",new ImageRes());
server.createContext("/secured/home/",new Home());
server.createContext("/secured",new ObtainToken(kcs));
server.createContext("/",new ObtainToken(kcs));
// server.setExecutor(Executors.newFixedThreadPool(11));
server.setExecutor(Executors.newCachedThreadPool()); server.setExecutor(Executors.newCachedThreadPool());
server.start(); server.start();
System.out.println("webserver running on localhost:"+port); System.out.println("webserver running on https://localhost:"+port);
} catch (Exception e) { } catch (Exception e) {
System.out.println("Failed to create HTTPS server on port " + port + " of localhost"); System.out.println("Failed to create HTTPS server on port " + port + " of localhost");
e.printStackTrace(); e.printStackTrace();
}*/ }
//API del server //API del server
// server.createContext("/api/luci/",new Luci());//post, get [put, delete] {luogo e stato di tutte luci} // server.createContext("/js/authentication/",new Resources());
// server.createContext("/api/luci/stato/",new Luci());//put {aggiorna lo stato di una luce} // server.createContext("/js/templates/",new Resources());
// server.createContext("/api/scenari/",new Scenari());//get {nome e data di tutti gli scenari} // server.createContext("/css/",new Resources());
// server.createContext("/api/scenari/attiva/",new Scenari());//put {attiva/disattiva} // server.createContext("/res/",new ImageRes());
// server.createContext("/api/scenari/registra/",new Scenari());//put {registra/termina} // server.createContext("/secured/home/js/",new Resources());
// server.createContext("/api/scenari/salva/",new Scenari());//post {conferma salvataggio, altrimenti cancella dopo timer; ritorna i valori dello scenario} // server.createContext("/secured/home/css/",new Resources());
// server.createContext("/api/antifurto/",new Antifurto());//get {stato, allarme, attenzione, soglia, sensori} // server.createContext("/secured/home/res/",new ImageRes());
// server.createContext("/api/antifurto/stato/",new Antifurto());//get, put {se l'antifurto e' attivo + aggiornamento} // server.createContext("/secured/home/",new Home());
// server.createContext("/api/antifurto/allarme/",new Antifurto());//get, put {se l'allarme sta suonando + aggiornamento} // server.createContext("/secured",new ObtainToken(kcs));
// server.createContext("/api/antifurto/attenzione/",new Antifurto());//put {valore della progress bar} // server.createContext("/",new ObtainToken(kcs));
// server.createContext("/api/antifurto/soglia/",new Antifurto());//put {valore scelto dall'utente per la soglia}
server.createContext("/js/authentication/",new Resources()); // server.setExecutor(Executors.newCachedThreadPool());
server.createContext("/js/templates/",new Resources()); // server.start();
server.createContext("/css/",new Resources()); // System.out.println("webserver running on http://localhost:"+port);
server.createContext("/res/",new ImageRes());
server.createContext("/secured/home/js/",new Resources());
server.createContext("/secured/home/css/",new Resources());
server.createContext("/secured/home/res/",new ImageRes());
server.createContext("/secured/home/",new Home());
server.createContext("/secured",new ObtainToken(kcs));
server.createContext("/",new ObtainToken(kcs));
server.setExecutor(Executors.newCachedThreadPool());
server.start();
System.out.println("webserver running on localhost:"+port);
} }
} }
-----BEGIN CERTIFICATE-----
MIIDdzCCAl+gAwIBAgIEMELchTANBgkqhkiG9w0BAQsFADBsMQswCQYDVQQGEwJJ
VDELMAkGA1UECBMCQUwxFDASBgNVBAcTC0FsZXNzYW5kcmlhMQ8wDQYDVQQKEwZV
TklVUE8xDjAMBgNVBAsTBURJU0lUMRkwFwYDVQQDExBhdHRpbGlvIGdpb3JkYW5h
MB4XDTIxMTIyMDIxMDI0NFoXDTIyMDMyMDIxMDI0NFowbDELMAkGA1UEBhMCSVQx
CzAJBgNVBAgTAkFMMRQwEgYDVQQHEwtBbGVzc2FuZHJpYTEPMA0GA1UEChMGVU5J
VVBPMQ4wDAYDVQQLEwVESVNJVDEZMBcGA1UEAxMQYXR0aWxpbyBnaW9yZGFuYTCC
ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAIzW4E3AvS/9rpyOCmuxIuA2
g4Dc6f1DxVzAsuHSglUSW+dI/WZB8AhgFnL42VDBqtRieOLzBmdL+iBcK5ZaRJRK
i7ya68OOKT3L+gcq1lY2HRly54DX+tjw1KVJ6Dh+MzUjL8Y4k872SLpyu2FQGgH+
iXufrqSCDHWidPDCDA+O2iZ6+5NoGb92jFUPQm7GZz5l9WBorxOR8VqDWNw56ipi
D6Ly7wkn/57SUotcHo6ZlaCh0dRGwLjtgfR2kHlhZ+151MSzeHDCul91QjS23XKf
eEQjxK1uiABUnUj0WC8FJp7MYwwFS4sPA5S5HTali+1C+ROk0zkorH+mYHPv0J8C
AwEAAaMhMB8wHQYDVR0OBBYEFHlvC8ECltT2lXei3X96D2MWikpVMA0GCSqGSIb3
DQEBCwUAA4IBAQBUmE1aB5ofz0/AQanNg22oAq9gy5G4xOOUbYDhUmuimq7QkrpT
L/3Y4uGDflk2IM3Dj5piBipLJ0EgK6qSudSLWbfM1OcTU112NBf/OUBxa88Yv9II
/zVI1Sw9g1hX88C7stpqKNTtqAAFffmfwUJkxtTUoG9XXrsIY792FX/5YvL0mdgb
HIBEWK21F+38SvaLi/cInnC2BrnwPfOioGXvK/LAGhXV+Rsp/Iq94f6mE1bT2aCD
+rnIPgLkCY0/Px+xpc9rg6q0mfKPXxF/neiURNhcXpWvyfC1W0sZ4eq+3AqIrj2q
sgUc4uC/WGqomJXd/KB4Q+raFuu8QTQgkBdQ
-----END CERTIFICATE-----
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
{"soglia":32,"stato":0,"valore":0,"tempoAllarme":"2022-09-12T17:55:30.663368"} {"soglia":32,"stato":0,"valore":0}
\ No newline at end of file \ No newline at end of file
...@@ -221,7 +221,7 @@ public class Antifurto { ...@@ -221,7 +221,7 @@ public class Antifurto {
public static void main(String args[]) { public static void main(String args[]) {
while(true) { // while(true) {
try { try {
startSystem(); startSystem();
} }
...@@ -229,7 +229,7 @@ public class Antifurto { ...@@ -229,7 +229,7 @@ public class Antifurto {
System.out.println("Error: "+ e.getMessage() + "\nRestarting system..."); System.out.println("Error: "+ e.getMessage() + "\nRestarting system...");
e.printStackTrace(); e.printStackTrace();
} }
} // }
} }
......
{
"self-server-url": "https://localhost:3000/",
"keycloak": {
"realm": "test00",
"base-server-url": "http://localhost:8080/"
},
"domain": {
"base-server-url": "http://localhost:3001/"
}
}
\ No newline at end of file
"use strict";
import conf from '../../conf/conf.json';
class Configuration {
static getMyURL() {
return conf["self-server-url"];
}
static getKeycloakInfo() {
return conf.keycloak;
}
static getKeycloakRealm() {
return conf.keycloak.realm;
}
static getKeycloakURL() {
return conf.keycloak["base-server-url"];
}
static getDomainURL() {
return conf.domain["base-domain-url"];
}
}
export default Configuration;
\ No newline at end of file
...@@ -2,6 +2,9 @@ ...@@ -2,6 +2,9 @@
import {getToken} from "./script.js"; import {getToken} from "./script.js";
import Domain from "./domain.js"; import Domain from "./domain.js";
import Configuration from "./configuration.js";
const configuration = new Configuration();
class RequestToDomain { class RequestToDomain {
constructor() { constructor() {
...@@ -13,22 +16,7 @@ class RequestToDomain { ...@@ -13,22 +16,7 @@ class RequestToDomain {
* sui domini dell'utente che ha effettuato il login * sui domini dell'utente che ha effettuato il login
*/ */
static async getMyDomains() { static async getMyDomains() {
/*const div = document.createElement('div'); const responseDomain = await fetch(`${configuration.getDomainURL()}secured/domains/`, { // DA FARE: controllare che l'uri che ho specificato qui coincida con quello specificato dal domain manager
div.innerHTML = "cliccami per avere info";
div.addEventListener('click', async () => {
const responseDomain = await fetch('http://localhost:8080/realms/test00/protocol/openid-connect/userinfo', { // DA FARE: controllare che l'uri che ho specificato qui coincida con quello specificato dal domain manager
method: 'GET',
headers: {
'Authorization': `Bearer ${await getToken()}`
}
}) ;
const domainsJson = await responseDomain.json();
if(responseDomain.ok) {
console.log(domainsJson);
}
});
document.getElementsByTagName('body')[0].appendChild(div);*/
const responseDomain = await fetch('http://localhost:3001/secured/domains/', { // DA FARE: controllare che l'uri che ho specificato qui coincida con quello specificato dal domain manager
method: 'GET', method: 'GET',
headers: { headers: {
'Authorization': `Bearer ${await getToken()}` 'Authorization': `Bearer ${await getToken()}`
...@@ -54,7 +42,7 @@ class RequestToDomain { ...@@ -54,7 +42,7 @@ class RequestToDomain {
* false altrimenti. * false altrimenti.
*/ */
static async createNewDomain(json) { static async createNewDomain(json) {
const response = await fetch('http://localhost:3001/install/', { const response = await fetch(`${configuration.getDomainURL()}install/`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Authorization': `Bearer ${await getToken()}` 'Authorization': `Bearer ${await getToken()}`
...@@ -75,7 +63,7 @@ class RequestToDomain { ...@@ -75,7 +63,7 @@ class RequestToDomain {
* disponibili. * disponibili.
*/ */
static async getAllServices() { static async getAllServices() {
const responseDomain = await fetch('http://localhost:3001/secured/services', { // DA FARE: controllare che l'uri che ho specificato qui coincida con quello specificato dal domain manager const responseDomain = await fetch(`${configuration.getDomainURL()}secured/services`, { // DA FARE: controllare che l'uri che ho specificato qui coincida con quello specificato dal domain manager
method: 'GET', method: 'GET',
headers: { headers: {
'Authorization': `Bearer ${await getToken()}` 'Authorization': `Bearer ${await getToken()}`
...@@ -96,7 +84,7 @@ class RequestToDomain { ...@@ -96,7 +84,7 @@ class RequestToDomain {
* @returns * @returns
*/ */
static async getUsedServices(domain) { static async getUsedServices(domain) {
const response = await fetch(`http://localhost:3001/secured/services?domain=${domain}`, { const response = await fetch(`${configuration.getDomainURL()}secured/services?domain=${domain}`, {
method: 'GET', method: 'GET',
headers: { headers: {
'Authorization': `Bearer ${await getToken()}` 'Authorization': `Bearer ${await getToken()}`
...@@ -117,7 +105,7 @@ class RequestToDomain { ...@@ -117,7 +105,7 @@ class RequestToDomain {
* false altrimenti. * false altrimenti.
*/ */
static async startDomain(d) { static async startDomain(d) {
const response = await fetch('http://localhost:3001/start/', { const response = await fetch(`${configuration.getDomainURL()}start/`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Authorization': `Bearer ${await getToken()}` 'Authorization': `Bearer ${await getToken()}`
...@@ -140,7 +128,7 @@ class RequestToDomain { ...@@ -140,7 +128,7 @@ class RequestToDomain {
* false altrimenti. * false altrimenti.
*/ */
static async stopDomain(d) { static async stopDomain(d) {
const response = await fetch('http://localhost:3001/stop/', { const response = await fetch(`${configuration.getDomainURL()}stop/`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Authorization': `Bearer ${await getToken()}` 'Authorization': `Bearer ${await getToken()}`
...@@ -163,7 +151,7 @@ class RequestToDomain { ...@@ -163,7 +151,7 @@ class RequestToDomain {
* false altrimenti. * false altrimenti.
*/ */
static async deleteDomain(d) { static async deleteDomain(d) {
const response = await fetch('http://localhost:3001/delete/', { const response = await fetch(`${configuration.getDomainURL()}delete/`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Authorization': `Bearer ${await getToken()}` 'Authorization': `Bearer ${await getToken()}`
...@@ -183,7 +171,7 @@ class RequestToDomain { ...@@ -183,7 +171,7 @@ class RequestToDomain {
* @returns * @returns
*/ */
static async getUserPriviledges(domain) { static async getUserPriviledges(domain) {
const response = await fetch(`http://localhost:3001/secured/priviledges?domain=${domain}`, { const response = await fetch(`${configuration.getDomainURL()}secured/priviledges?domain=${domain}`, {
method: 'GET', method: 'GET',
headers: { headers: {
'Authorization': `Bearer ${await getToken()}` 'Authorization': `Bearer ${await getToken()}`
......
...@@ -4,6 +4,8 @@ import App from './app.js'; ...@@ -4,6 +4,8 @@ import App from './app.js';
import RequestToDomain from './requests-to-domain.js'; import RequestToDomain from './requests-to-domain.js';
// import * as jose from 'jose'; // per la gestione del token // import * as jose from 'jose'; // per la gestione del token
import Configuration from './configuration.js';
const configuration = new Configuration();
const mySecure = new Secure(); const mySecure = new Secure();
...@@ -13,29 +15,29 @@ let alreadyRefreshed = false; // true se ho appena fatto la richiesta del token ...@@ -13,29 +15,29 @@ let alreadyRefreshed = false; // true se ho appena fatto la richiesta del token
let oldTimeout = null; let oldTimeout = null;
const uri = window.location.toString(); const uri = window.location.toString();
if(!uri.includes('#') && !uri.includes("/secured/home/")) { if(!uri.includes(`#`) && !uri.includes("/secured/home/")) {
const a = document.getElementById("my-link"); const a = document.getElementById("my-link");
a.href = a.href.replace("$MY_CODE_CHALLENGE", mySecure.codeChallenge).replace("$MY_STATE", mySecure.state); a.href = a.href.replace("$MY_CODE_CHALLENGE", mySecure.codeChallenge).replace("$MY_STATE", mySecure.state);
sessionStorage.setItem("stateSent", mySecure.state); // state inviato durante la richiesta dell'authcode sessionStorage.setItem("stateSent", mySecure.state); // state inviato durante la richiesta dell`authcode
sessionStorage.setItem("codeVerifier", mySecure.codeVerifier); sessionStorage.setItem("codeVerifier", mySecure.codeVerifier);
//automatically redirect to the login page //automatically redirect to the login page
window.location.href = a.href; window.location.href = a.href;
} }
else if(uri.includes("#")){ else if(uri.includes("#")){
// l'uri e' del tipo localhost:3000/secured# seguito da parametri // l`uri e` del tipo localhost:3000/secured# seguito da parametri
const uriSplit = uri.split('#'); const uriSplit = uri.split(`#`);
const params = uriSplit[1].split('&'); const params = uriSplit[1].split(`&`);
const uriState = queryStringGetValue(params[0]); const uriState = queryStringGetValue(params[0]);
const uriAuthCode = queryStringGetValue(params[2]); const uriAuthCode = queryStringGetValue(params[2]);
if(!sessionStorage.stateSent || sessionStorage.stateSent !== uriState) { if(!sessionStorage.stateSent || sessionStorage.stateSent !== uriState) {
// get the body element // get the body element
const body = document.getElementsByTagName('body')[0]; const body = document.getElementsByTagName(`body`)[0];
body.innerHTML = `Errors in the request!`; body.innerHTML = `Errors in the request!`;
} }
else { else {
await requestFirstToken(uriAuthCode); // post per la richiesta del token await requestFirstToken(uriAuthCode); // post per la richiesta del token
if(token !== null) { if(token !== null) {
expirationTime = moment().add(token.expires_in,'s'); expirationTime = moment().add(token.expires_in,`s`);
sessionStorage.setItem("expirationTime", expirationTime.toJSON()); sessionStorage.setItem("expirationTime", expirationTime.toJSON());
const myDomains = await RequestToDomain.getMyDomains(); const myDomains = await RequestToDomain.getMyDomains();
...@@ -49,12 +51,12 @@ else if(uri.includes("#")){ ...@@ -49,12 +51,12 @@ else if(uri.includes("#")){
// {nome: "casa4", stato:"on", admin: false} // {nome: "casa4", stato:"on", admin: false}
// ]; // ];
const app = new App(myDomains); const app = new App(myDomains,configuration);
} }
} }
} else if(uri.includes('/secured/home/')) { } else if(uri.includes(`/secured/home/`)) {
token = JSON.parse(sessionStorage.getItem('token')); token = JSON.parse(sessionStorage.getItem(`token`));
expirationTime = moment(sessionStorage.getItem('expirationTime')); expirationTime = moment(sessionStorage.getItem(`expirationTime`));
oldTimeout = timeoutRefresh(); oldTimeout = timeoutRefresh();
} }
...@@ -64,7 +66,7 @@ else if(uri.includes("#")){ ...@@ -64,7 +66,7 @@ else if(uri.includes("#")){
* @returns il valore associato al parametro. * @returns il valore associato al parametro.
*/ */
function queryStringGetValue(queryString) { function queryStringGetValue(queryString) {
const arr = queryString.split('='); const arr = queryString.split(`=`);
return arr[1]; return arr[1];
} }
...@@ -75,18 +77,18 @@ function queryStringGetValue(queryString) { ...@@ -75,18 +77,18 @@ function queryStringGetValue(queryString) {
*/ */
async function requestFirstToken(uriAuthCode) { async function requestFirstToken(uriAuthCode) {
const url = 'http://localhost:8080/realms/test00/protocol/openid-connect/token'; const url = `${configuration.getKeycloakURL()}realms/${configuration.getKeycloakRealm()}/protocol/openid-connect/token`;
const response = await fetch(url, { const response = await fetch(url, {
method: 'POST', method: `POST`,
headers: { headers: {
'Content-type':'application/x-www-form-urlencoded' 'Content-type':`application/x-www-form-urlencoded`
}, },
body: new URLSearchParams({ body: new URLSearchParams({
grant_type: 'authorization_code', grant_type: `authorization_code`,
client_id: 'myclient', client_id: `myclient`,
code_verifier: sessionStorage.getItem("codeVerifier"), code_verifier: sessionStorage.getItem("codeVerifier"),
code: uriAuthCode, code: uriAuthCode,
redirect_uri: 'http://localhost:3000/secured' redirect_uri: `${configuration.getMyURL()}secured`
}) })
}); });
token = await response.json(); token = await response.json();
...@@ -113,15 +115,15 @@ async function getToken() { ...@@ -113,15 +115,15 @@ async function getToken() {
* Post per la richiesta del token usando il refresh token. * Post per la richiesta del token usando il refresh token.
*/ */
async function requestUsingRefreshToken() { async function requestUsingRefreshToken() {
const url = 'http://localhost:8080/realms/test00/protocol/openid-connect/token'; const url = `${configuration.getKeycloakURL()}realms/${configuration.getKeycloakRealm()}/protocol/openid-connect/token`;
const response = await fetch(url, { const response = await fetch(url, {
method: 'POST', method: `POST`,
headers: { headers: {
'Content-type':'application/x-www-form-urlencoded' 'Content-type':`application/x-www-form-urlencoded`
}, },
body: new URLSearchParams({ body: new URLSearchParams({
grant_type: 'refresh_token', grant_type: `refresh_token`,
client_id: 'myclient', client_id: `myclient`,
refresh_token: `${token.refresh_token}` refresh_token: `${token.refresh_token}`
}) })
}); });
...@@ -129,7 +131,7 @@ async function getToken() { ...@@ -129,7 +131,7 @@ async function getToken() {
if(response.ok) { if(response.ok) {
alreadyRefreshed = true; alreadyRefreshed = true;
sessionStorage.setItem("token", JSON.stringify(token)); sessionStorage.setItem("token", JSON.stringify(token));
expirationTime = moment().add(token.expires_in,'s'); expirationTime = moment().add(token.expires_in,`s`);
sessionStorage.setItem("expirationTime", expirationTime.toJSON()); sessionStorage.setItem("expirationTime", expirationTime.toJSON());
oldTimeout = timeoutRefresh(); oldTimeout = timeoutRefresh();
} }
...@@ -163,7 +165,7 @@ async function logoutKeycloak() { ...@@ -163,7 +165,7 @@ async function logoutKeycloak() {
if(token == null) if(token == null)
return; return;
clearTimeout(oldTimeout); // DA FARE: funziona, ma vedere se fare il redirect alla pagina iniziale. clearTimeout(oldTimeout); // DA FARE: funziona, ma vedere se fare il redirect alla pagina iniziale.
window.location.href = `http://localhost:8080/realms/test00/protocol/openid-connect/logout?id_token_hint=${await getIdToken()}`; window.location.href = `${configuration.getKeycloakURL()}realms/${configuration.getKeycloakRealm()}/protocol/openid-connect/logout?id_token_hint=${await getIdToken()}`;
} }
......
...@@ -7,7 +7,6 @@ import Scenari from "./scenari.js"; ...@@ -7,7 +7,6 @@ import Scenari from "./scenari.js";
import Luci from './luci.js'; import Luci from './luci.js';
import Admin from './adminControls.js'; import Admin from './adminControls.js';
const logout = document.getElementById("button-logout"); const logout = document.getElementById("button-logout");
logout.addEventListener('click', () => { logout.addEventListener('click', () => {
logoutKeycloak(); logoutKeycloak();
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment