HttpContext 不包含 GetOpenIddictServerRequest 的定义

问题描述 投票:0回答:3

var request = HttpContext.GetOpenIddictServerRequest();

我是否缺少任何名称空间?

asp.net-core authentication asp.net-web-api asp.net-identity openiddict
3个回答
2
投票

如果你想使用

GetOpenIddictServerRequest()
方法,你需要添加NuGet包
OpenIddict.AspNetCore

==================

如果你想在 Minimal Api 中使用它,你可以更改一些代码,例如:

using Microsoft.AspNetCore;

//.........

   app.MapPost("/connect/token", (HttpContext c) =>
   {
    var request = c.GetOpenIddictServerRequest();
     //........
   });

0
投票
using HIL10.OpenIddict.Data.ApplicationDbContext;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using OpenIddict.Abstractions;
using OpenIddict.Server.AspNetCore;
using System.Security.Claims;
using static OpenIddict.Abstractions.OpenIddictConstants;
using Microsoft.AspNetCore;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<ApplicationDbContext>(options => 
{
    options.UseNpgsql(builder.Configuration.GetConnectionString("PostgreSqlConnection"));
    options.UseOpenIddict();
});
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddMvcCore(option => option.EnableEndpointRouting=false);
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie();
//.AddOAuthValidation();

builder.Services.AddOpenIddict()

        // Register the OpenIddict core components.
        .AddCore(options =>
        {
            // Configure OpenIddict to use the Entity Framework Core stores and models.
            // Note: call ReplaceDefaultEntities() to replace the default entities.
            options.UseEntityFrameworkCore()
                   .UseDbContext<ApplicationDbContext>();
        })

        // Register the OpenIddict server components.
        .AddServer(options =>
        {
            // Enable the token endpoint.
            options.SetTokenEndpointUris("/connect/token");

            // Enable the client credentials flow.
            options.AllowClientCredentialsFlow();

            // Register the signing and encryption credentials.
            options.AddDevelopmentEncryptionCertificate()
                   .AddDevelopmentSigningCertificate();

            // Register the ASP.NET Core host and configure the ASP.NET Core options.
            options.UseAspNetCore()
                   .EnableTokenEndpointPassthrough();
        })

        // Register the OpenIddict validation components.
        .AddValidation(options =>
        {
            // Import the configuration from the local OpenIddict server instance.
            options.UseLocalServer();

            // Register the ASP.NET Core host.
            options.UseAspNetCore();
        });


var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.MapPost("/connect/token", async (IOpenIddictApplicationManager applicationManager) => 
{

    var request = HttpContext.GetOpenIddictServerRequest();
    if (!request.IsClientCredentialsGrantType())
    {
        throw new NotImplementedException("The specified grant is not implemented.");
    }

    // Note: the client credentials are automatically validated by OpenIddict:
    // if client_id or client_secret are invalid, this action won't be invoked.

    var application = await applicationManager.FindByClientIdAsync(request.ClientId) ??
        throw new InvalidOperationException("The application cannot be found.");

    // Create a new ClaimsIdentity containing the claims that
    // will be used to create an id_token, a token or a code.
    var identity = new ClaimsIdentity(TokenValidationParameters.DefaultAuthenticationType, Claims.Name, Claims.Role);

    // Use the client_id as the subject identifier.
    identity.AddClaim(Claims.Subject,
        await applicationManager.GetClientIdAsync(application),
        Destinations.AccessToken, Destinations.IdentityToken);

    identity.AddClaim(Claims.Name,
        await applicationManager.GetDisplayNameAsync(application),
        Destinations.AccessToken, Destinations.IdentityToken);

    return (new ClaimsPrincipal(identity), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
});

//app.UseMvcWithDefaultRoute();
app.UseDeveloperExceptionPage();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(options =>
{
    options.MapControllers();
    options.MapDefaultControllerRoute();
});
app.Run();

0
投票
使用 IIS Express 时,

HttpContext.GetOpenIddictServerRequest()
为 null。

根据@Xinran Shen的回答,

GetOpenIddictServerRequest()
,该方法是来自Microsoft.AspNetCore的OpenIdDictRequest lib扩展。

深入

GetOpenIddictServerRequest
return context.Features.Get<OpenIddictServerAspNetCoreFeature>()?.Transaction?.Request;

它将 HttpContext 数据转换为有用的

OpenIddictServerAspNetCoreFeature
模型。

HttpContext.GetOpenIddictServerRequest()
在 IIS Server 或 IIS Express 开发中托管时得到空?

© www.soinside.com 2019 - 2024. All rights reserved.