2017-05-19 28 views
13

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 

Trả lời

2

gia tăng các nuget package here và mã sau để khắc phục:

app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions 
{ 
    Authority = "https://localhost:44348/", 
    ApiName = "api" 
}); 

Điều này cho phép API lưu trữ IdentityServer4 và sử dụng chính nó làm authen tication. Sau đó, trong MvcClient, mã thông báo mang có thể được chuyển tới API.

0

Có, bạn cần thêm gói IdentityServer4.AccessTokenValidation vào dự án API của mình. Và kiểm tra các ý kiến ​​dưới đây

app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions 
{ 
    Authority = "https://localhost:44348/", //Identity server host uri 
    ApiName = "api", // Valid Api resource name 
    AllowedScopes = scopes // scopes:List<string> 
}); 

Bạn nên loại bỏ mã dưới đây từ lớp StartUp của API và thay thế với trên một:

services.AddIdentityServer() // Configures OAuth/IdentityServer framework 
      .AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResources()) 
      .AddInMemoryClients(IdentityServerConfig.GetClients(serviceSettings)) 
      .AddAspNetIdentity<ExtranetUser>() 
      .AddTemporarySigningCredential(); 

mã trên được yêu cầu trên của bạn Máy chủ định danh không có trên API hoặc bất kỳ ứng dụng khách nào khác

Các vấn đề liên quan