2017-05-19 32 views
13

Pracowałem nad migracją monolitycznej aplikacji ASP Core MVC do korzystania z projektu architektury usług. Strona front-end MVC używa HttpClient do ładowania niezbędnych danych z interfejsu API ASP Core Web. Niewielka część front-endowej aplikacji MVC wymaga również uwierzytelnienia, które jest w użyciu przy użyciu IdentityServer4 (zintegrowanego z back-end API). To wszystko działa świetnie, dopóki nie wstawię atrybutu Authorize do kontrolera lub metody w Web API. Wiem, że muszę jakoś przekazać autoryzację użytkownika z front-endu do back-end, aby to zadziałało, ale nie jestem pewien jak. Próbowałem uzyskać access_token: User.FindFirst("access_token"), ale zwraca null. Następnie próbowałem tej metody i jestem w stanie uzyskać token:Przejść przez uwierzytelnianie z ASP Core MVC, Web API i IdentityServer4?

var client = new HttpClient("url.com"); 
var token = HttpContext.Authentication.GetTokenAsync("access_token")?.Result; 
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); 

Ta metoda pobiera token ale nadal nie Uwierzytelnianie API back-end. Jestem nowicjuszem w tej koncepcji OpenId/IdentityServer i każda pomoc będzie doceniana!

Oto odpowiedni kod z klasy MVC Client 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 
      }, 


     }); 
    } 

a klasa StartUp 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 

Odpowiedz

2

dodał nuget package here i następujący kod naprawić:

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

Pozwala to interfejsowi API hostować IdentityServer4 i używać go jako authen tication. Następnie w MvcClient token na okaziciela może zostać przekazany do API.

0

Tak, musisz dodać pakiet IdentityServer4.AccessTokenValidation do swojego projektu interfejsu API. I sprawdzić komentarze poniżej

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

Należy usunąć poniższy kod z klasy Autostart API i zastąpić wyżej jednym:

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

powyższy kod jest wymagany na swoje Serwer tożsamości nie w interfejsie API ani w żadnym innym kliencie

Powiązane problemy