Skip to content

Commit

Permalink
Handling dynamic config, refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
Nikos Anestos committed Oct 3, 2017
1 parent e0f23d0 commit 21286f7
Show file tree
Hide file tree
Showing 9 changed files with 319 additions and 220 deletions.
169 changes: 119 additions & 50 deletions example-dotnet-openid-connect-client/App_Start/AppConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,59 +7,128 @@ namespace exampledotnetopenidconnectclient.App_Start
{
public class AppConfig
{
//private static string discovery_url = ConfigurationManager.AppSettings["discovery_url"];
//private Dictionary<string, string> dict;

public static void init()
private static AppConfig instance;

private static String client_id;
private static String client_secret;
private static String redirect_uri;
private static String scope;
private static String authorization_endpoint;
private static String token_endpoint;
private static String logout_endpoint;
private static String revocation_endpoint;
private static String jwks_uri;
private static String issuer;
private static String api_endpoint;
private static String base_url;

private AppConfig()
{
client_id = ConfigurationManager.AppSettings["client_id"];
client_secret = ConfigurationManager.AppSettings["client_secret"];
redirect_uri = ConfigurationManager.AppSettings["redirect_uri"];
scope = ConfigurationManager.AppSettings["scope"];
authorization_endpoint = ConfigurationManager.AppSettings["authorization_endpoint"];
token_endpoint = ConfigurationManager.AppSettings["token_endpoint"];
logout_endpoint = ConfigurationManager.AppSettings["logout_endpoint"];
revocation_endpoint = ConfigurationManager.AppSettings["revocation_endpoint"];
jwks_uri = ConfigurationManager.AppSettings["jwks_uri"];
issuer = ConfigurationManager.AppSettings["issuer"];
api_endpoint = ConfigurationManager.AppSettings["api_endpoint"];
base_url = ConfigurationManager.AppSettings["base_url"];

if (!String.IsNullOrEmpty(issuer))
{
var discoveryClient = new HttpClient();


var response = discoveryClient.GetAsync(issuer + "/.well-known/openid-configuration").Result;
if (response.IsSuccessStatusCode)
{
string responseString = response.Content.ReadAsStringAsync().Result;
JObject responseJson = JObject.Parse(responseString);

authorization_endpoint = responseJson["authorization_endpoint"].ToString();
token_endpoint = responseJson["token_endpoint"].ToString();
revocation_endpoint = responseJson["revocation_endpoint"].ToString();
jwks_uri = responseJson["jwks_uri"].ToString();

}
}
}

public String GetLogoutEndpoint()
{
return logout_endpoint;
}

public String GetClientId()
{
return client_id;
}

public String GetClientSecret()
{
return client_secret;
}

public String GetRedirectUri()
{
return redirect_uri;
}

public String GetScope()
{
return scope;
}

public String GetAuthorizationEndpoint()
{
return authorization_endpoint;
}

public String GetTokenEndpoint()
{
return token_endpoint;
}

public String GetRevocationEndpoint()
{
return revocation_endpoint;
}

public String GetJwksUri()
{
// dict = new Dictionary<string, string>
// {
// {"client_id", ConfigurationManager.AppSettings["client_id"]},
// {"client_secret", ConfigurationManager.AppSettings["client_secret"]},
// {"redirect_uri", ConfigurationManager.AppSettings["redirect_uri"]},
// {"scope", ConfigurationManager.AppSettings["scope"]},
// {"authorization_endpoint", ConfigurationManager.AppSettings["authorization_endpoint"]},
// {"token_endpoint", ConfigurationManager.AppSettings["token_endpoint"]},
// {"logout_endpoint", ConfigurationManager.AppSettings["logout_endpoint"]},
// {"revocation_endpoint", ConfigurationManager.AppSettings["revocation_endpoint"]},
// {"jwks_uri", ConfigurationManager.AppSettings["jwks_uri"]},
// {"issuer", ConfigurationManager.AppSettings["issuer"]},
// {"api_endpoint", ConfigurationManager.AppSettings["api_endpoint"]},
// {"base_url", ConfigurationManager.AppSettings["base_url"]}
//};

// if (!String.IsNullOrEmpty(discovery_url))
// {
// var discoveryClient = new HttpClient();


// var response = discoveryClient.GetAsync(discovery_url).Result;
// if (response.IsSuccessStatusCode)
// {
// string responseString = response.Content.ReadAsStringAsync().Result;
// JObject responseJson = JObject.Parse(responseString);



// //config.AppSettings.Settings["authorization_endpoint"].Value = responseJson["authorization_endpoint"].ToString();
// config.AppSettings.Settings["jwks_uri"].Value = responseJson["jwks_uri"].ToString();


// //System.Configuration.ConfigurationManager.AppSettings.Add("introspection_endpoint", responseJson["introspection_endpoint"].ToString());
// //System.Configuration.ConfigurationManager.AppSettings.Add("authorization_endpoint", responseJson["authorization_endpoint"].ToString());
// //System.Configuration.ConfigurationManager.AppSettings["issuer"] = responseJson["issuer"].ToString();
// //System.Configuration.ConfigurationManager.AppSettings["authorization_endpoint"] = responseJson["authorization_endpoint"].ToString();
// //System.Configuration.ConfigurationManager.AppSettings["token_endpoint"] = responseJson["token_endpoint"].ToString();
// //System.Configuration.ConfigurationManager.AppSettings["jwks_uri"] = responseJson["jwks_uri"].ToString();
// //System.Configuration.ConfigurationManager.AppSettings["revocation_endpoint"] = responseJson["revocation_endpoint"].ToString();
// //System.Configuration.ConfigurationManager.AppSettings["userinfo_endpoint"] = responseJson["userinfo_endpoint"].ToString();
//}
//}
return jwks_uri;
}

//public static String get(String key)
//{
// return dict[key];
//}
public String GetIssuer()
{
return issuer;
}

public String GetApiEndpoint()
{
return api_endpoint;
}

public String GetBaseUrl()
{
return base_url;
}


public static AppConfig Instance
{
get
{
if (instance == null)
{
instance = new AppConfig();
}
return instance;
}
}
}
}
107 changes: 38 additions & 69 deletions example-dotnet-openid-connect-client/Controllers/CallbackController.cs
Original file line number Diff line number Diff line change
@@ -1,81 +1,48 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net.Http;
using System.Configuration;
using Newtonsoft.Json.Linq;
using static System.Convert;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Net;
using System.IO;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using System.Threading;
using System.Web.Mvc;
using exampledotnetopenidconnectclient.Helpers;
using System.Security.Cryptography;
using System.Net.Http.Headers;
using Newtonsoft.Json.Linq;
using static System.Convert;

namespace exampledotnetopenidconnectclient.Controllers
{
public class CallbackController : Controller
{
private string client_id = ConfigurationManager.AppSettings["client_id"];
private string client_secret = ConfigurationManager.AppSettings["client_secret"];
private string code = ConfigurationManager.AppSettings["client_id"];
private string redirect_uri = ConfigurationManager.AppSettings["redirect_uri"];
private string token_endpoint = ConfigurationManager.AppSettings["token_endpoint"];
private string issuer = ConfigurationManager.AppSettings["issuer"];
private string jwks_uri = ConfigurationManager.AppSettings["jwks_uri"];
private static Helpers.Client _client = Helpers.Client.Instance;
private string issuer = App_Start.AppConfig.Instance.GetIssuer();
private string jwks_uri = App_Start.AppConfig.Instance.GetJwksUri();

private JObject id_token_obj;

static readonly HttpClient client = new HttpClient();

public ActionResult Index()
{

string code = Request.QueryString["code"];

var values = new Dictionary<string, string>
{
{ "grant_type", "authorization_code" },
{ "client_id", client_id},
{ "client_secret", client_secret },
{ "code" , code },
{ "redirect_uri", redirect_uri}
};

var content = new FormUrlEncodedContent(values);
string responseString = _client.GetToken(Request.QueryString["code"]);


var response = client.PostAsync(token_endpoint, content).Result;
if (response.IsSuccessStatusCode)
if (!String.IsNullOrEmpty(responseString))
{
// by calling .Result you are performing a synchronous call
var responseContent = response.Content;

string responseString = responseContent.ReadAsStringAsync().Result;

saveDataToSession(responseString);
SaveDataToSession(responseString);

}

return Redirect("/");
}

public void saveDataToSession(String curityResponse)
public void SaveDataToSession(String curityResponse)
{
JObject jsonObj = JObject.Parse(curityResponse);

Session["access_token"] = jsonObj.GetValue("access_token");
Session["refresh_token"] = jsonObj.GetValue("refresh_token");
Session["scope"] = jsonObj.GetValue("scope");

if (jsonObj.GetValue("id_token") != null && isJwtValid(jsonObj.GetValue("id_token").ToString()))
if (jsonObj.GetValue("id_token") != null && IsJwtValid(jsonObj.GetValue("id_token").ToString()))
{
Session["id_token"] = jsonObj.GetValue("id_token");
Session["id_token_json0"] = id_token_obj.GetValue("decoded_header").ToString();
Expand All @@ -90,30 +57,30 @@ public void saveDataToSession(String curityResponse)

}

public String safeDecodeBase64(String str)

public String SafeDecodeBase64(String str)
{
return System.Text.Encoding.UTF8.GetString(
getPaddedBase64String(str));
}

private byte[] getPaddedBase64String(string base64Url)
{
string padded = base64Url.Length % 4 == 0 ? base64Url : base64Url + "====".Substring(base64Url.Length % 4);
string base64 = padded.Replace("_", "/")
.Replace("-", "+");
return FromBase64String(base64);
}
private byte[] getPaddedBase64String(string base64Url)
{
string padded = base64Url.Length % 4 == 0 ? base64Url : base64Url + "====".Substring(base64Url.Length % 4);
string base64 = padded.Replace("_", "/")
.Replace("-", "+");
return FromBase64String(base64);
}

public bool isJwtValid(String jwt)
public bool IsJwtValid(String jwt)
{
string[] jwtParts = jwt.Split('.');

String decodedHeader = safeDecodeBase64(jwtParts[0]);
String decodedHeader = SafeDecodeBase64(jwtParts[0]);
id_token_obj = new JObject
{
{"decoded_header", decodedHeader },
{"decoded_payload", safeDecodeBase64(jwtParts[1])}
{"decoded_payload", SafeDecodeBase64(jwtParts[1])}
};

String keyId = JObject.Parse(decodedHeader).GetValue("kid").ToString();
Expand All @@ -123,16 +90,18 @@ public bool isJwtValid(String jwt)
jwksclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var response = jwksclient.GetAsync(jwks_uri).Result;
if (response.IsSuccessStatusCode)
{
// by calling .Result you are performing a synchronous call
var responseContent = response.Content;
if (response.IsSuccessStatusCode)
{
// by calling .Result you are performing a synchronous call
var responseContent = response.Content;

string responseString = responseContent.ReadAsStringAsync().Result;
string responseString = responseContent.ReadAsStringAsync().Result;

JToken keyFound = null;
foreach (JToken key in JObject.Parse(responseString).GetValue("keys").ToArray()) {
if (key["kid"].ToString().Equals(keyId)){
foreach (JToken key in JObject.Parse(responseString).GetValue("keys").ToArray())
{
if (key["kid"].ToString().Equals(keyId))
{
keyFound = key;
}
}
Expand All @@ -142,8 +111,8 @@ public bool isJwtValid(String jwt)
rsa.ImportParameters(
new RSAParameters()
{
Modulus = getPaddedBase64String(keyFound["n"].ToString()),
Exponent = getPaddedBase64String(keyFound["e"].ToString())
Modulus = getPaddedBase64String(keyFound["n"].ToString()),
Exponent = getPaddedBase64String(keyFound["e"].ToString())
});

SHA256 sha256 = SHA256.Create();
Expand All @@ -154,8 +123,8 @@ public bool isJwtValid(String jwt)
if (rsaDeformatter.VerifySignature(hash, getPaddedBase64String(jwtParts[2])))
return true;
}
}
}
return false;
}
}
}
}
Loading

0 comments on commit 21286f7

Please sign in to comment.