Lal P J
Lal P J

Reputation: 31

HttpContext does not contain definition for GetOpenIddictServerRequest

var request = HttpContext.GetOpenIddictServerRequest();

Am I missing any namespace ?

Upvotes: 3

Views: 1726

Answers (3)

Txuver Jhi Wei
Txuver Jhi Wei

Reputation: 328

HttpContext.GetOpenIddictServerRequest() got null when using IIS Express.

According @Xinran Shen answer if Minimal API, GetOpenIddictServerRequest(), the method is OpenIdDictRequest lib extend from Microsoft.AspNetCore.

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

it convert HttpContext data to useful OpenIddictServerAspNetCoreFeature model.

why HttpContext.GetOpenIddictServerRequest() got null when hosting in IIS Server or IIS Express development?

Upvotes: 0

Xinran Shen
Xinran Shen

Reputation: 9993

If you want to use GetOpenIddictServerRequest() method , you need to add NuGet Packages OpenIddict.AspNetCore.

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

IF you want to use it in Minimal Api , you can change some code like :

using Microsoft.AspNetCore;

//.........

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

Upvotes: 3

Lal P J
Lal P J

Reputation: 31

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

Upvotes: 0

Related Questions