0

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

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

API 启动.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();
            }
        );
    }

授权服务器提供者

    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);
    }

客户端启动.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?}");
        });
    }

现在当OnAuthorizationAsyncinAuthenticationFilter被调用时,AuthorizationContext.HttpContext.User.Claims它是空的,所以我无法检查这些值。

4

0 回答 0