如何解决如何使用谷歌身份验证在 .net 核心中刷新令牌或增加到期时间
下面给出了我的 Auth 中间件类。
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
{
}
}
}
从上面的类中,有一个函数AttachAccountToContext。有传递参数作为令牌。 HttpWebRequest 不包含刷新令牌实体。那么如何添加刷新令牌的代码呢? 我们正在使用谷歌身份验证(邮件 ID)来访问 web api。客户端密钥,客户端 ID 在另一个函数中设置。
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": "*"
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。