My Auth middleware class is given below.
public class AuthMiddleware
{
private readonly RequestDelegate next;
private readonly AppSettings appSettings;
public AuthMiddleware(RequestDelegate next, IOptions<AppSettings> appSettings)
{
this.next = next;
this.appSettings = appSettings.Value;
}
public async Task Invoke(HttpContext context)
{
var token = context.Request.Headers[Constants.Authorization].FirstOrDefault()?.Split(" ").Last();
if (token != null)
await AttachAccountToContext(context, token);
await next(context);
}
private async Task AttachAccountToContext(HttpContext context, string token)
{
try
{
string userinfoResponseText = string.Empty;
HttpWebRequest userinfoRequest = (HttpWebRequest)WebRequest.Create(appSettings.UserInfoEndpoint);
userinfoRequest.Method = Constants.GET;
userinfoRequest.Headers.Add($"{Constants.Authorization}: {Constants.Bearer}{token}");
userinfoRequest.ContentType = Constants.ContentTypeForm;
userinfoRequest.Accept = Constants.TokenAccept;
WebResponse userinfoResponse = await userinfoRequest.GetResponseAsync();
using (StreamReader userinfoResponseReader = new StreamReader(userinfoResponse.GetResponseStream()))
{
userinfoResponseText = await userinfoResponseReader.ReadToEndAsync();
}
UserInfo userInfo = JsonConvert.DeserializeObject<UserInfo>(userinfoResponseText);
if (userInfo != null && !string.IsNullOrEmpty(userInfo.Email))
{
NpgsqlConnection pgcon = new NpgsqlConnection(appSettings.ConnectionStrings);
User user = null;
using (var conn = pgcon)
{
conn.Open();
using (var cmd = new NpgsqlCommand(Db.ProcGetUserByEmail, conn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue(Db.ParmUserEmail, NpgsqlTypes.NpgsqlDbType.Text, userInfo.Email);
string retJson = (string)cmd.ExecuteScalar();
if (!string.IsNullOrEmpty(retJson))
{
user = JsonConvert.DeserializeObject<User>(retJson);
}
}
}
context.Items[Constants.ContextUser] = user;
}
}
catch
{
}
}
}
From the above class, there is a function AttachAccountToContext. there is passing parameter as token. HttpWebRequest does not contains refresh token entity. So how to add the code of refresh token? We are using google authentication(mail id) to access web api. client secret, client id are set in another function.
Appsetting.json file is given below.
{
"AppSettings": {
"Secret": "abcdSecret",
"UserInfoEndpoint": "https://www.googleapis.com/oauth2/v3/userinfo",
"QrCodeEndpoint": "http://website/api/qrcode/",
"ConnectionStrings": "Connection string",
"RefreshTokenTTL": 2
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}