I'm working on asp.net MVC project based on .NET 8.0. My site is using ASP.Net Core Identity for user authentication. It's working fine.
I have to connect to remote server which is using OAuth2 authorization. I decided to use OpenIdConnect for that task. The idea is to use OIDC only for the remote server authorization. And to keep Identity for site users authentication.
The problem is that after logging in to the remote server the Identity user is lost!
OIDC Setup:
builder.Services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<IdentityContext>();
builder.Services.AddHttpClient();
// Add OpenIdConnect to OAuth2
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = IdentityConstants.ApplicationScheme;
options.DefaultChallengeScheme = IdentityConstants.ExternalScheme;
})
.AddCookie("Cookies")
.AddOpenIdConnect(options =>
{
options.Authority = "https://remote_server.com/id/";
options.ClientId = "DemoClient";
options.ClientSecret = "myClient";
options.ResponseType = "code id_token";
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("offline_access");
options.SignInScheme = IdentityConstants.ApplicationScheme;
options.Events = new OpenIdConnectEvents
{
OnUserInformationReceived = context =>
{
string rawAccessToken = context.ProtocolMessage.AccessToken;
string rawIdToken = context.ProtocolMessage.IdToken;
var handler = new JwtSecurityTokenHandler();
var accessToken = handler.ReadJwtToken(rawAccessToken);
var idToken = handler.ReadJwtToken(rawIdToken);
System.Diagnostics.Debug.Print($"access-token: {rawAccessToken}, id-token: {rawIdToken}");
return Task.CompletedTask;
},
OnAccessDenied = context =>
{
context.HandleResponse();
context.Response.Redirect("/");
return Task.CompletedTask;
},
OnSignedOutCallbackRedirect = context =>
{
context.HandleResponse();
context.Response.Redirect("/");
return Task.CompletedTask;
}
};
});
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
var app = builder.Build();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
I read the following article text
But it can't solve my problem.
My question: Is it possible to use Identity and OIDC in parallel? Identity to manage site users and roles. OIDC to be used for remote server authorization (with separate users. These are users from the remote server)
Bevor going deeper into your question, I'd like to clarify if each of your applications users has an individual user account at the authorization server of the external service as well?
As far as I see it, you might have mixed up this.
Your applications users authenticate against your asp.net identity, and your application authenticates against the external service. So perhaps all you need is an httpclient which you augment with a clientcredentialmanagement handler from https://docs.duendesoftware.com/foss/accesstokenmanagement/