11

Ich versuche, einen einfachen Endpunkt zu erhalten, der JWT-Token mit AspNew.Security.OpenIdConnect.Server ausgibt und konsumiert, um das Token auszustellen und zu validieren Verwenden von Microsoft.AspNetCore.Authentication.JwtBearer.AspNetCore.Authentication.JwtBearer schlägt mit Kein SecurityTokenValidator für Token mit .net Kern RC2 frei

kann ich das Token Fein erzeugen, aber versucht, das Token zur Authentifizierung schlägt mit dem Fehler Bearer was not authenticated. Failure message: No SecurityTokenValidator available for token: {token}

An dieser Stelle habe ich alles aus und haben die folgende gestrippt haben:

project.json

{ 
    "dependencies": { 
    "Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final", 
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-rc2-final", 
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final", 
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-rc2-final", 
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0-rc2-final", 
    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc2-final", 
    "Microsoft.Extensions.Logging": "1.0.0-rc2-final", 
    "Microsoft.Extensions.Logging.Console": "1.0.0-rc2-final", 
    "Microsoft.Extensions.Logging.Debug": "1.0.0-rc2-final", 
    "AspNet.Security.OAuth.Validation": "1.0.0-alpha1-final", 
    "AspNet.Security.OpenIdConnect.Server": "1.0.0-beta5-final", 
    "Microsoft.AspNetCore.Authentication": "1.0.0-rc2-final", 
    "Microsoft.AspNetCore.Authentication.JwtBearer": "1.0.0-rc2-final" 
    }, 

    "tools": { 
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": { 
     "version": "1.0.0-preview1-final", 
     "imports": "portable-net45+win8+dnxcore50" 
    } 
    }, 

    "frameworks": { 
    "net461": { } 
    }, 

    "buildOptions": { 
    "emitEntryPoint": true, 
    "preserveCompilationContext": true 
    }, 

    "publishOptions": { 
    "include": [ 
     "wwwroot", 
     "Views", 
     "appsettings.json", 
     "web.config" 
    ] 
    }, 

    "scripts": { 
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ] 
    } 
} 

Startup.cs Methoden:

// This method gets called by the runtime. Use this method to add services to the container. 
     public void ConfigureServices(IServiceCollection services) 
     { 
      services.AddAuthorization(options => 
       { 
        options.AddPolicy(JwtBearerDefaults.AuthenticationScheme, 
         builder => 
         { 
          builder. 
          AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme). 
          RequireAuthenticatedUser(). 
          Build(); 
         } 
        ); 
       } 
      ); 

      services.AddAuthentication(); 
      services.AddDistributedMemoryCache(); 
      services.AddMvc(); 
      services.AddOptions(); 
     } 

     // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
     public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
     { 
      loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
      loggerFactory.AddDebug(); 

      var jwtOptions = new JwtBearerOptions() 
      { 
       AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme, 
       AutomaticAuthenticate = true, 
       Authority = "http://localhost:5000/", 
       Audience = "http://localhost:5000/", 
       RequireHttpsMetadata = false 
      }; 

      jwtOptions.ConfigurationManager = new ConfigurationManager<OpenIdConnectConfiguration> 
       (
        metadataAddress: jwtOptions.Authority + ".well-known/openid-configuration", 
        configRetriever: new OpenIdConnectConfigurationRetriever(), 
        docRetriever: new HttpDocumentRetriever { RequireHttps = false } 
       ); 


      app.UseJwtBearerAuthentication(jwtOptions); 

      app.UseOpenIdConnectServer(options => 
      { 
       options.AllowInsecureHttp = true; 
       options.AuthorizationEndpointPath = Microsoft.AspNetCore.Http.PathString.Empty; 
       options.Provider = new OpenIdConnectServerProvider 
       { 
        OnValidateTokenRequest = context => 
        { 
         context.Skip(); 
         return Task.FromResult(0); 
        }, 

        OnGrantResourceOwnerCredentials = context => 
        { 
         var identity = new ClaimsIdentity(context.Options.AuthenticationScheme); 
         identity.AddClaim(ClaimTypes.NameIdentifier, "[unique id]"); 

         identity.AddClaim("urn:customclaim", "value", OpenIdConnectConstants.Destinations.AccessToken, OpenIdConnectConstants.Destinations.IdentityToken); 

         var ticket = new AuthenticationTicket(
          new ClaimsPrincipal(identity), 
          new Microsoft.AspNetCore.Http.Authentication.AuthenticationProperties(), 
          context.Options.AuthenticationScheme); 

         ticket.SetScopes("profile", "offline_access"); 

         context.Validate(ticket); 

         return Task.FromResult(0); 
        } 
       }; 
      });    

      app.UseMvc(); 
     } 

Senden von x-url-codierten POST an http://localhost:5000 mit grant_type = password, username = foo, password = bar generiert das erwartete access_token.

Ich habe das Attribut [Authorize("Bearer")] dem ValuesController hinzugefügt, und dies funktioniert wie erwartet in der JwtBearerMiddlewear wird aufgerufen, aber ich bin nicht in der Lage, das Token zu validieren.

Hat jemand dieses mit .net Kern RC2 arbeiten? Ich habe das gleiche an RC1 gearbeitet, aber ich konnte das nicht in Gang bringen.

Danke.

Antwort

8

Beginnend mit beta5 (für ASP.NET Core RC2), the OpenID Connect server middleware no longer uses JWT as the default format for access tokens. Stattdessen werden opake Tokens verwendet, die durch den grundsoliden ASP.NET Core Data Protection-Stack (genau wie Authentifizierungscookies) verschlüsselt werden.

Sie haben 3 Möglichkeiten, den Fehler zu beheben, die Sie sehen:

  • Verwenden Sie die new OAuth2 validation middleware entwickelt, um undurchsichtige Token (die empfohlene Option, wenn Ihre API und Ihre Autorisierungsserver zu unterstützen Teil derselben sind App). Halten Sie dafür die AspNet.Security.OAuth.Validation Referenz, die Sie in project.json haben, und ersetzen Sie app.UseJwtBearerAuthentication(...) durch nur app.UseOAuthValidation(). Sie können auch Microsoft.AspNetCore.Authentication.JwtBearer von project.json entfernen.

  • den Server Middleware OpenID Connect Erzwingen JWT Token zu verwenden, indem options.AccessTokenHandler = new JwtSecurityTokenHandler(); in den Optionen aufrufen. Beachten Sie, dass Sie auch ticket.SetResources(...) anrufen müssen, um die entsprechende Zielgruppe mit den JWT-Tokens zu verbinden (weitere Informationen finden Sie in diesem Artikel unter SO post).

  • die new introspection middleware verwenden. Diese Option ist komplexer und erfordert das Implementieren des ValidateIntrospectionRequest-Ereignisses, um die Clientanmeldeinformationen zu überprüfen. Verwenden Sie es nur, wenn Sie wissen, was Sie tun.
+0

Wenn Sie sich entscheiden Innerlichkeit zu verwenden, das Paket, das Sie wollen, ist [hier] (https://www.nuget.org/packages/AspNet.Security.OAuth.Introspection/). Nicht 'AspNet.Security.OAuth.Extensions' – paulio