0

I am implementing OIDC for my legacy application which is based on .net framework v4.6.2. While following the documentation from OpenIDdict website, it does not create tables which OpenIddict requires. Just FYI my legacy app does not support migrations. So i am confused how will OpenIddict will store tokens, authorization code etc. I cannot see any tables being created in my DB though when i hit the \connect\token endpoint the token is being returned. I am sharing following code which might help

  1. OpenIDConnectConfig.cs public static class OpenIDConnectConfig { public static IServiceCollection _services { get; set; }

    public static IServiceProvider serviceProvider { get; set; }
    public static void ConfigureServices()
    {
        _services = new ServiceCollection();
        _services.AddOpenIddict()
            .AddCore(options =>
            {
                options.UseEntityFramework().UseDbContext<HamDbContext>();
            })
            .AddServer(options =>
            {
                options.AllowPasswordFlow();
                options.EnableDegradedMode();
                options.AcceptAnonymousClients();
    
                options.SetTokenEndpointUris("/connect/token");
    
                //TODO: change the following functions to AddEncryptionCertificate() and AddSigningCertificate() for PRODUCTION Mode
    
                options.AddEphemeralEncryptionKey()
                .AddEphemeralSigningKey();
    
                options.UseOwin()
                       .DisableTransportSecurityRequirement();
    
                options.AddEventHandler<ValidateTokenRequestContext>(builder =>
                    builder.UseInlineHandler(context =>
                    {
                        // Client authentication is used in this sample,
                        // so there's nothing to validate here.
    
                        return default;
                    }));
    
                options.AddEventHandler<HandleTokenRequestContext>(builder =>
                    builder.UseInlineHandler(context =>
                    {
                        if (!context.Request.IsPasswordGrantType())
                        {
                            throw new InvalidOperationException("The specified grant type is not supported.");
                        }
    
                        // Validate the username/password parameters.
                        // In a real world application, you'd use likely use a key derivation function like PBKDF2 to slow
                        // the client secret validation process down and a time-constant comparer to prevent timing attacks.
                        if (!string.Equals(context.Request.Username, "[email protected]", StringComparison.Ordinal) ||
                                    !string.Equals(context.Request.Password, "P@ssw0rd", StringComparison.Ordinal))
                        {
                            context.Reject(
                                error: Errors.InvalidGrant,
                                description: "The username/password couple is invalid.");
    
                            return default;
                        }
    
                        var principal = new ClaimsPrincipal(new ClaimsIdentity(OpenIddictServerOwinDefaults.AuthenticationType));
                        principal.SetClaim(Claims.Subject, "Bob");
    
                        context.Principal = principal;
    
                        return default;
                    }));
            })
    
            .AddValidation(options =>
            {
                options.UseLocalServer();
    
                options.UseOwin();
            });
    
        serviceProvider = _services.BuildServiceProvider();
    }
    
    public static void ConfigureOpenIDDictMiddleware(IAppBuilder app)
    {
        ConfigureServices();
    
        // middleware to integrate OpenIDdict to OWIN's pipeline
        // Refer : https://kevinchalet.com/2020/03/03/adding-openiddict-3-0-to-an-owin-application/
    
        // TODO: Integrate with UnityConfig
        app.Use(async (context, next) =>
        {
            var scope = serviceProvider.CreateScope();
    
            // Store the per-request service provider in the OWIN environment.
            context.Set(typeof(IServiceProvider).FullName, scope.ServiceProvider);
    
            try
            {
                // Invoke the rest of the pipeline.
                await next();
            }
    
            finally
            {
                // Remove the scoped service provider from the OWIN environment.
                context.Set<IServiceProvider>(typeof(IServiceProvider).FullName, null);
    
                // Dispose of the scoped service provider.
                if (scope is IAsyncDisposable disposable)
                {
                    await disposable.DisposeAsync();
                }
    
                else
                {
                    scope.Dispose();
                }
            }
        });
    
        app.UseOpenIddictServer();
        app.UseOpenIddictValidation();
    }
    

    }

I have created this as a separate sub project in my application which is then referenced in my main project which is set as startup project The following is how i used it in the startup.cs

OpenIDConnectConfig.ConfigureOpenIDDictMiddleware(app);

This legacy app follows Database approach so i cannot use modelBuilder.UseOpenIddict()..refrence code for the Dbcontext

public partial class LegacyAppEntities : DbContext
{
    public LegacyAppEntities()
        : base("name=LegacyAppEntities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }
}

0

Browse other questions tagged or ask your own question.