asp.NET 5 MVC6承载令牌授权

时间:2016-03-13 23:17:49

标签: asp.net-core jwt openid-connect aspnet-contrib

我需要一个网站来使用持票令牌验证其对API的请求。同一令牌可用于所有请求,因为站点是公共的,因此不需要用户登录。

我一直在使用来自AspNet.Security.OpenIdConnect.Samples和其他SO问题的mashup。

API Startup.cs

public void ConfigureServices(IServiceCollection services)
    {

    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        //add functionality similar to [ClaimsAuthorize("myclaim")]
        .RequireClaim(ClaimTypes.Name)
        .RequireClaim(ClaimTypes.NameIdentifier)
        .Build();

        services.AddCaching();
        services.AddMvc(options =>
        {
            options.Filters.Add(new AuthenticationFilter(policy));                
        });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        //Authorization
        app.UseJwtBearerAuthentication(options => {
            options.AutomaticAuthenticate = true;
            options.Audience = "https://localhost:44380";
            options.Authority = "https://localhost:44380";
        });

        // Add a new middleware issuing tokens.
        app.UseOpenIdConnectServer
        (
            configuration =>
            {
                configuration.TokenEndpointPath = "/login";
                configuration.AllowInsecureHttp = false;
                configuration.Provider = new AuthorizationServerProvider();
            }
        );
    }

AuthorizationServerProvider

    public override async Task GrantClientCredentials(GrantClientCredentialsContext context)
    {
        DbContext dbContext = context.HttpContext.RequestServices.GetRequiredService<DbContext>();
        Client client = await dbContext.Clients.FirstAsync(x => x.Id == context.ClientId);

        var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme);
        identity.AddClaim(new Claim(ClaimTypes.Name, client.Name));
        identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.ClientId));

        AuthenticationTicket ticket = new AuthenticationTicket(
            new ClaimsPrincipal(identity), 
            new AuthenticationProperties(),
            OpenIdConnectServerDefaults.AuthenticationScheme);

        context.Validated(ticket);
    }

Client Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseIISPlatformHandler();

        app.UseStaticFiles();

        //Used with TempData
        app.UseSession();

        app.UseOpenIdConnectAuthentication(options =>
        {
            options.AuthenticationScheme = OpenIdConnectDefaults.AuthenticationScheme;
            options.RequireHttpsMetadata = false;

            // Note: these settings must match the application details
            // inserted in the database at the server level.
            options.ClientId = Configuration.Get<string>("Constants:ClientMvcId");
            options.ClientSecret = Configuration.Get<string>("Constants:ClientMvcSecret");

            // Use the authorization code flow.
            options.ResponseType = OpenIdConnectResponseTypes.Code;
        });

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

现在,当调用OnAuthorizationAsync中的AuthenticationFilter时,AuthorizationContext.HttpContext.User.Claims为空,因此我无法检查这些值。

0 个答案:

没有答案