Tôi đã làm việc để di chuyển ứng dụng ASP Core MVC nguyên khối để sử dụng thiết kế kiến trúc dịch vụ. Trang web đầu cuối của MVC sử dụng một số HttpClient
để tải dữ liệu cần thiết từ API Web ASP Core. Một phần nhỏ của ứng dụng MVC front-end cũng yêu cầu xác thực được thực hiện bằng IdentityServer4 (tích hợp với API back-end). Điều này tất cả các công trình lớn, cho đến khi tôi đặt một thuộc tính Authorize
trên một bộ điều khiển hoặc phương pháp trên Web API. Tôi biết tôi cần phải bằng cách nào đó vượt qua ủy quyền người dùng từ front-end đến back-end để làm việc này, nhưng tôi không chắc chắn làm thế nào. Tôi đã thử nhận access_token: User.FindFirst("access_token")
nhưng nó trả về null. Sau đó tôi đã thử phương pháp này và tôi có thể nhận được mã thông báo:Vượt qua xác thực với ASP Core MVC, API Web và IdentityServer4?
var client = new HttpClient("url.com");
var token = HttpContext.Authentication.GetTokenAsync("access_token")?.Result;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
Phương thức này nhận mã thông báo nhưng vẫn không xác thực với API back-end. Tôi khá mới với khái niệm OpenId/IdentityServer này và mọi trợ giúp sẽ được đánh giá cao!
Đây là mã có liên quan từ lớp MVC Khách hàng Startup:
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
},
});
}
và lớp StartUp của 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