Search code examples
c#.netasp.net-core-2.0identityserver4openid-connect

How to convert ASPNetIdentity to OpenIdConnect


I have a project that uses .NET Framework 4.6 AspNetIdentity, and I'm trying to upgrade it to use OpenIdConnect. Has anyone had any success replacing ASPNetIdentity with OpenIdConnect using .NET Framework 4.6?

I've looked into owin examples and some .NET core 2.0 quickstart samples such as these, but they seem to be incompatible with what I'm trying to accomplish.

I'm trying to specifically add something resembling the following code snippet taken from one of the above samples:

services.AddAuthentication(options =>
{
    options.DefaultScheme = "Cookies";
    options.DefaultChallengeScheme = "oidc";
});
    .AddCookie("Cookies")
    .AddOpenIdConnect("oidc", options =>
    {
        options.SignInScheme = "Cookies";

        options.Authority = "http://xxx.xxx.xxx.xxx:5000";
        options.RequireHttpsMetadata = false;

        options.ClientId = "foo";
        options.ClientSecret = "secret";
        options.ResponseType = "code id_token";

        options.SaveTokens = true;
        options.GetClaimsFromUserInfoEndpoint = true;

        options.Scope.Add("api1");
        options.Scope.Add("offline_access");
    });

I need something similar to this AddAuthentication() extension of the IServiceCollection services parameter in the ConfigureServices() method of my Startup.cs file to be able to allow a client to login via IdentityServer4.


Solution

  • Thanks for the responses! I would say @Nan Yu probably had the answer that ended up being closest to the solution that I came up with, but I figured I'd share what I ultimately ended up going with in the Configure() method of my Startup.cs file.

    using Microsoft.AspNetCore.Authentication.OpenIdConnect;
    using Microsoft.IdentityModel.Protocols.OpenIdConnect;
    ...
    var openidOptions = new OpenIdConnectOptions(authenticationScheme)
    {
        ClientSecret = secret,
        AutomaticAuthenticate = true,
        SignInScheme = "Identity.External",
        Authority = identityServerAddress,
        ClientId = clientId,
        RequireHttpsMetadata = true,
        ResponseType = OpenIdConnectResponseType.CodeIdToken,
        AutomaticChallenge= true,
        GetClaimsFromUserInfoEndpoint = true,
        SaveTokens = true,
        Events = new OpenIdConnectEvents
        {
            OnRemoteSignOut = async remoteSignOutContext =>
            {
                remoteSignOutContext.HttpContext.Session.Clear();
            },
        },
    };
    openidOptions.Scope.Clear();
    openidOptions.Scope.Add("openid");
    app.UseOpenIdConnectAuthentication(openidOptions);
    

    Adding this to my .NET Framework 4.6 client ended up letting me communicate with my .NET Core 2.0 Identity Server successfully! I appreciate everyone that tried to help :)