我正在编写一个具有2种身份验证方案的ASP.NET Core Web App。一种是基于Cookie的简单方案,另一种使用OAuth。 OAuth身份验证方案仅用于登录政府网站并进行api调用。该应用程序有一个数据库,当我保存记录时,我想使用Cookie身份验证方案中的用户名保存CreatedBy和ModifiedBy。
当我使用Cookie身份验证登录时,将使用cookie身份验证的身份按预期设置User.Identity和User.Identities。但是,如果我随后访问一个需要通过OAuth身份验证方案进行身份验证的页面,那么我将无法再从基于cookie的身份验证中获取用户名。它不会出现在User.Identity或User.Identities中。
身份验证设置如下:
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "OAuthTest";
})
.AddCookie()
.AddOAuth("OAuthTest", options =>
{
options.ClientId = Configuration["HMRC:ClientId"];
options.ClientSecret = Configuration["HMRC:ClientSecret"];
options.CallbackPath = new PathString("/account/auth-redirect");
options.AuthorizationEndpoint = "https://test-api.service.hmrc.gov.uk/oauth/authorize";
options.TokenEndpoint = "https://test-api.service.hmrc.gov.uk/oauth/token";
options.Scope.Add("read:vat");
options.SaveTokens = true;
options.Events = new OAuthEvents
{
OnCreatingTicket = async context =>
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())
};
var identity = new ClaimsIdentity(claims, "OAuthTest", ClaimTypes.NameIdentifier, null);
context.Principal.AddIdentity(identity);
}
};
});
我已将此Authorize属性添加到需要基于cookie身份验证的页面:
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
,并将此Authorize属性分配给需要OAuth身份验证的页面:
[Authorize(AuthenticationSchemes = "OAuthTest")]
我已将应用程序的简化版本推送到github。这只有2页,每个身份验证方案都授权一页。登录按钮自动登录到Cookie身份验证方案。这两个页面都显示User.Identity和User.Identities中包含的数据。