我一直在努力移植一個單一的ASP核心MVC應用程序來使用服務架構設計。 MVC前端網站使用HttpClient
從ASP Core Web API加載必要的數據。前端MVC應用程序的一小部分還要求使用IdentityServer4(與後端API集成)進行身份驗證。這一切都很好,直到我將一個Authorize
屬性放在Web API上的控制器或方法上。我知道我需要以某種方式將用戶授權從前端傳遞到後端才能實現,但我不知道如何。我嘗試過獲取access_token:User.FindFirst("access_token")
,但它返回null。那麼這個方法我試過,我能夠獲得令牌:通過與ASP核心MVC,Web API和IdentityServer4認證?
var client = new HttpClient("url.com");
var token = HttpContext.Authentication.GetTokenAsync("access_token")?.Result;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
這種方法得到令牌,但仍無法與後端API認證。我對這個OpenId/IdentityServer概念相當陌生,希望有任何幫助。
下面是從MVC客戶端啓動類的相關代碼:
private void ConfigureAuthentication(IApplicationBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "Cookies",
AutomaticAuthenticate = true,
ExpireTimeSpan = TimeSpan.FromMinutes(60)
});
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
AuthenticationScheme = "oidc",
SignInScheme = "Cookies",
Authority = "https://localhost:44348/",
RequireHttpsMetadata = false,
ClientId = "clientid",
ClientSecret = "secret",
ResponseType = "code id_token",
Scope = { "openid", "profile" },
GetClaimsFromUserInfoEndpoint = true,
AutomaticChallenge = true, // Required to 302 redirect to login
SaveTokens = true,
TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
NameClaimType = "Name",
RoleClaimType = "Role",
SaveSigninToken = true
},
});
}
,並啓動類的API:
// Add authentication
services.AddIdentity<ExtranetUser, IdentityRole>(options =>
{
// Password settings
options.Password.RequireDigit = true;
options.Password.RequiredLength = 8;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequireUppercase = true;
options.Password.RequireLowercase = true;
// Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.MaxFailedAccessAttempts = 10;
// User settings
options.User.RequireUniqueEmail = true;
})
.AddDefaultTokenProviders();
services.AddScoped<IUserStore<ExtranetUser>, ExtranetUserStore>();
services.AddScoped<IRoleStore<IdentityRole>, ExtranetRoleStore>();
services.AddSingleton<IAuthorizationHandler, AllRolesRequirement.Handler>();
services.AddSingleton<IAuthorizationHandler, OneRoleRequirement.Handler>();
services.AddSingleton<IAuthorizationHandler, EditQuestionAuthorizationHandler>();
services.AddSingleton<IAuthorizationHandler, EditExamAuthorizationHandler>();
services.AddAuthorization(options =>
{
/* ... etc .... */
});
var serviceProvider = services.BuildServiceProvider();
var serviceSettings = serviceProvider.GetService<IOptions<ServiceSettings>>().Value;
services.AddIdentityServer() // Configures OAuth/IdentityServer framework
.AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResources())
.AddInMemoryClients(IdentityServerConfig.GetClients(serviceSettings))
.AddAspNetIdentity<ExtranetUser>()
.AddTemporarySigningCredential(); // ToDo: Add permanent SigningCredential for IdentityServer