Asp.Net Core、JWT 和 OpenIdConnectServer

Posted

技术标签:

【中文标题】Asp.Net Core、JWT 和 OpenIdConnectServer【英文标题】:Asp.Net Core, JWT and OpenIdConnectServer 【发布时间】:2016-06-17 19:48:48 【问题描述】:

我正在尝试了解有关 Asp.Net Core 中 JWT 令牌的所有这些内容。在因大量误解而流血工作后,我陷入了困境。我的任务是制作带有两个控制器(受保护和不受保护)的 WebApi 服务器。我应该从服务器授予令牌并能够获得受保护的资源。当我运行服务器并尝试从邮递员那里获取受保护的资源时,一切似乎都很好。但是当我在我的 Angular 客户端做同样的事情时,从另一个域我有奇怪的事情。我可以得到未受保护的资源,但我无法得到受保护的资源并出现这样的错误:

XMLHttpRequest cannot load http://localhost:10450/api/prvalues. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:10377' is therefore not allowed access.

为了清楚起见,我展示了我所有的尝试。我的 project.json 看起来像

  "dependencies": 
     "AspNet.Security.OpenIdConnect.Server": "1.0.0-beta4",
     "EntityFramework.Core": "7.0.0-rc1-final",
     "EntityFramework.InMemory": "7.0.0-rc1-final",
     "Microsoft.AspNet.Authentication.JwtBearer": "1.0.0-rc1-final",
     "Microsoft.AspNet.Diagnostics": "1.0.0-rc1-final",
     "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final",
     "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
     "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
     "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
     "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
     "Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-rc1-final",
     "Microsoft.Extensions.Logging": "1.0.0-rc1-final",
     "Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
     "Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final",
     "NWebsec.Middleware": "1.0.0-gamma-39",
     "Microsoft.AspNet.Mvc.Cors": "6.0.0-rc1-final",
     "Microsoft.AspNet.Cors": "6.0.0-rc1-final"
,

我的Startup.ConfigureServices() 看起来像

public void ConfigureServices(IServiceCollection 服务)

        services.AddCors(options =>
        
            options.AddPolicy("AllowAllOrigins",
                    builder =>
                    
                        builder.AllowAnyOrigin();
                        builder.AllowAnyHeader();
                    );
        );

        services.AddEntityFramework()
           .AddInMemoryDatabase()
           .AddDbContext<ApplicationDbContext<ApplicationUser, Application, IdentityRole, string>>(options => 
               options.UseInMemoryDatabase();
           );
        services.AddScoped<IAuthStore<ApplicationUser,Application>, AuthStore<ApplicationUser, Application, IdentityRole, 
            ApplicationDbContext<ApplicationUser, Application, IdentityRole, string>, string>>();
        services.AddScoped<AuthManager<ApplicationUser, Application>>();
        services.AddIdentity<ApplicationUser, IdentityRole>(options =>
        
            options.Password = new PasswordOptions()
            
                RequiredLength = 1,
                RequireDigit = false,
                RequireLowercase = false,
                RequireUppercase = false,
                RequireNonLetterOrDigit = false

            ;
        ).AddEntityFrameworkStores<ApplicationDbContext<ApplicationUser, Application, IdentityRole, string>>().AddDefaultTokenProviders();
        services.AddAuthentication();

        // Add framework services.

        services.AddCaching();
        services.AddMvc();
    

AuthManager 和 AuthStore 是从 OpenIddict 中窃取的。我稍后会展示给他们看。我的Startup.Configure() 看起来像:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();
        app.UseCors("AllowAllOrigins");
        app.UseIISPlatformHandler();
        app.UseDeveloperExceptionPage();
        app.UseStaticFiles();

        // Create a new branch where the registered middleware will be executed only for API calls.            

        app.UseWhen(context => context.Request.Path.StartsWithSegments(new PathString("/api")), branch =>
        
            branch.UseJwtBearerAuthentication(options =>
            

                options.AutomaticAuthenticate = true;
                options.AutomaticChallenge = true;
                options.RequireHttpsMetadata = false;
                // Thisi is test, if I uncomment this and SetResource in AuthorizationProvider everything works in postman
                //options.Audience = "http://localhost:10450/";
                // My Angular client
                options.Audience = "http://localhost:10377/";
                // My Api
                options.Authority = "http://localhost:10450/";

            );
        );



        // Note: visit https://docs.nwebsec.com/en/4.2/nwebsec/Configuring-csp.html for more information.
        app.UseCsp(options => options.DefaultSources(configuration => configuration.Self())
                                     .ImageSources(configuration => configuration.Self().CustomSources("data:"))
                                     .ScriptSources(configuration => configuration.UnsafeInline())
                                     .StyleSources(configuration => configuration.Self().UnsafeInline()));

        app.UseXContentTypeOptions();

        app.UseXfo(options => options.Deny());

        app.UseXXssProtection(options => options.EnabledWithBlockMode());

        app.UseOpenIdConnectServer(options =>
        

            options.Provider = new AuthorizationProvider();
            // Note: see AuthorizationController.cs for more
            // information concerning ApplicationCanDisplayErrors.
            options.ApplicationCanDisplayErrors = true;
            options.AllowInsecureHttp = true;
            options.AuthorizationEndpointPath = PathString.Empty;
            options.TokenEndpointPath = "/token";
            // Note: by default, tokens are signed using dynamically-generated
            // RSA keys but you can also use your own certificate:
            // options.SigningCredentials.AddCertificate(certificate);
        );

        app.UseMvc();
        var hasher = new PasswordHasher<Application>();
        using (var database = app.ApplicationServices.GetService<ApplicationDbContext<ApplicationUser, Application, IdentityRole, string>>())
                      
            database.Applications.Add(new Application
            
                Id = "myPublicClient",
                DisplayName = "My client application",
                Type = ApplicationTypes.Public
            );
            database.Applications.Add(new Application
            
                Id = "myConfidentialClient",
                DisplayName = "My client application",
                Secret = hasher.HashPassword(null, "secret_secret_secret"),
                Type = ApplicationTypes.Confidential
            );

            database.SaveChanges();
            CreateUser(app).Wait();
                
    

最后,我的AthorizationProvider.GrantResourceOwnerCredentials()(我使用 AspNet.Security.OpenIdConnect.Server)是:

    public override async Task GrantResourceOwnerCredentials(GrantResourceOwnerCredentialsContext context)
    

        #region UserChecking
        var manager = context.HttpContext.RequestServices.GetRequiredService<AuthManager<ApplicationUser, Application>>();

        var user = await manager.FindByNameAsync(context.UserName);
        if (user == null)
        
            context.Rejected(
                error: OpenIdConnectConstants.Errors.InvalidGrant,
                description: "Invalid credentials.");

            return;
        

        // Ensure the user is not already locked out.
        if (manager.SupportsUserLockout && await manager.IsLockedOutAsync(user))
        
            context.Rejected(
                error: OpenIdConnectConstants.Errors.InvalidGrant,
                description: "Account locked out.");

            return;
        

        // Ensure the password is valid.
        if (!await manager.CheckPasswordAsync(user, context.Password))
        
            context.Rejected(
                error: OpenIdConnectConstants.Errors.InvalidGrant,
                description: "Invalid credentials.");

            if (manager.SupportsUserLockout)
            
                await manager.AccessFailedAsync(user);

                // Ensure the user is not locked out.
                if (await manager.IsLockedOutAsync(user))
                
                    context.Rejected(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "Account locked out.");
                
            

            return;
        

        if (manager.SupportsUserLockout)
        
            await manager.ResetAccessFailedCountAsync(user);
        


        if (context.Request.ContainsScope(OpenIdConnectConstants.Scopes.Profile) &&
           !context.Request.ContainsScope(OpenIdConnectConstants.Scopes.Email) &&
            string.Equals(await manager.GetUserNameAsync(user),
                          await manager.GetEmailAsync(user),
                          StringComparison.OrdinalIgnoreCase))
        
            context.Rejected(
                error: OpenIdConnectConstants.Errors.InvalidRequest,
                description: "The 'email' scope is required.");

            return;
        

        #endregion

        var identity = await manager.CreateIdentityAsync(user, context.Request.GetScopes());

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

        //ticket.SetResources(context.Request.GetResources());
        // When I tested with postman
        //ticket.SetResources(new[]  "http://localhost:10450/" );
        ticket.SetResources(new[]  "http://localhost:10377" );
        ticket.SetScopes(context.Request.GetScopes());

        context.Validated(ticket);


    

我已经展示了所有我认为可能导致问题的代码。对不起,如果它很长,但我不知道女巫部分会导致问题。

为了访问我的 protecetd 资源(简单地用[Authorize] 装饰),我使用来自 Angular 客户端的此类虚拟代码

$http.defaults.headers.common['Authorization'] = 'Bearer ' + 'token here';
return $http.get('http://localhost:10450/' + 'api/prvalues');

正如我所说,我对此类请求有错误。但是,如果我尝试获取不受保护的资源(从控制器中删除 [Authorize] 属性)一切正常。

【问题讨论】:

您是否尝试过将AllowCredentials()AllowAnyMethod() 一起使用,就像在 github 上的 Cors 示例中一样? github.com/aspnet/Mvc/blob/… 是的。没有效果 【参考方案1】:

我找到了解决方案。当我在 AthorizationProvider.GrantResourceOwnerCredentials() 中设置资源时,我设置了 "http://localhost:10377" ,但在 UseJwtBearerAuthentication 中间件中,我在权限选项中设置了 "http://localhost:10377/" (最后包含斜线)。这是非常愚蠢的错误。

【讨论】:

以上是关于Asp.Net Core、JWT 和 OpenIdConnectServer的主要内容,如果未能解决你的问题,请参考以下文章

ASP.NET Core JWT 和声明

将 OpenID Connect 与 .NET Core 3.0 ASP.NET Core API 服务一起使用时出错

ASP.NET Core OpenID Connect 中的单点注销

Asp.net Core、JWT 和 CORS 标头

Jwt 和 ASP.NET CORE 授权 AspNetRoleClaims

ASP.NET Core 和 JWT 令牌生命周期