IUserClaimsPrincipalFactory`1 not registered error in IndentityServer implementation - identityserver4

I am getting below exception even after registering the AddDefaultIdentity
System.InvalidOperationException: Service type: IUserClaimsPrincipalFactory`1 not registered.
Here's the Identity registration code:
services.AddDefaultIdentity<ApplicationUser>(options =>
{
//Disable account confirmation.
options.SignIn.RequireConfirmedAccount = false;
options.SignIn.RequireConfirmedEmail = false;
options.SignIn.RequireConfirmedPhoneNumber = false;
})
.AddEntityFrameworkStores<ApplicationDbContext>();
And here's the IdentityServer code:
var builder = services.AddIdentityServer()
.AddInMemoryApiScopes(IdentityServerConfig.ApiScopes)
.AddInMemoryIdentityResources(IdentityServerConfig.IdentityResources)
.AddInMemoryApiResources(IdentityServerConfig.ApiResources)
.AddInMemoryClients(IdentityServerConfig.Clients)
.AddAspNetIdentity<IdentityUser>();

I spent hours solving this typo.
The problem was that my registration was wrong.
I was working with ApplicationUser but I was registering IdentityUser in the identity server.
I fixed my problem by setting the ApplicationUser in both AddIdentityServer() and AddDefaultIdentity().
Here's the working code: .Net Core Identity
services.AddDefaultIdentity<ApplicationUser>(options =>
{
//Disable account confirmation.
options.SignIn.RequireConfirmedAccount = false;
options.SignIn.RequireConfirmedEmail = false;
options.SignIn.RequireConfirmedPhoneNumber = false;
})
.AddEntityFrameworkStores<ApplicationDbContext>();
IdentityServer4:
var builder = services.AddIdentityServer()
.AddInMemoryApiScopes(IdentityServerConfig.ApiScopes)
.AddInMemoryIdentityResources(IdentityServerConfig.IdentityResources)
.AddInMemoryApiResources(IdentityServerConfig.ApiResources)
.AddInMemoryClients(IdentityServerConfig.Clients)
.AddAspNetIdentity<ApplicationUser>();
Notice the use of ApplicationUser.
I posted question here so that I remember it next time.

I fixed this error by changing the order. I had
var builder = services.AddIdentityServer()
.AddInMemoryIdentityResources(Config.IdentityResources)
.AddInMemoryClients(Config.Clients)
.AddAspNetIdentity<ApplicationUser>();
builder.AddDeveloperSigningCredential();
services.AddDbContext<ApplicationDbContext>(options =>
options.UseMySql(Configuration.GetConnectionString("ApplicationDbContext")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
Now I have:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseMySql(Configuration.GetConnectionString("ApplicationDbContext")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
var builder = services.AddIdentityServer()
.AddInMemoryIdentityResources(Config.IdentityResources)
.AddInMemoryClients(Config.Clients)
.AddAspNetIdentity<ApplicationUser>();
builder.AddDeveloperSigningCredential();

Related

Role based authorization policy does not work

I currently have ASP.NET Core Web API back-end. I'm using react google login, it works fine. Now I want to implement role-based authorization to authorize some back-end api.
When I use[Authorize], it works fine.
But I use [Authorize(Policy = "readpolicy")], it can not hit the method.
I tried lots of approaches together, therefore the Program.cs looks terrible. Below What I tried, :
The entire Program.cs, anyone knows and how to fix the problem? Even help me to reorganize the code what I need and don't need and I'm not sure that the sequence of these services functions is correct.
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using WTSS_Portal_Middleware.Data;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.AddJsonFile("appsettings.json")
.Build();
builder.Services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
}
);
builder.Services.AddDbContext<TSTWTSSPortalContext>(options =>
options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddDbContext<UserDbContext>(options =>
options.UseSqlServer(configuration.GetConnectionString("UserDbConnection")));
builder.Services.AddControllers();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new() { Title = "WTSS_Portal_Middleware", Version = "v1" });
});
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer()
.AddCookie()
;
builder.Services.AddTransient<IConfigureOptions<JwtBearerOptions>, ConfigureJwtBearerOptions>();
builder.Services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<UserDbContext>();
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("readpolicy",
policy => policy.RequireRole("WTSS support", "System owner", "Regular user", "Company owner", "Unauthenticated"));
options.AddPolicy("writepolicy",
policy => policy.RequireRole("WTSS support", "System owner"));
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (builder.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "WTSS_Portal_Middleware V1");
c.RoutePrefix = string.Empty;
});
}
app.UseRouting();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();
app.UseHttpsRedirection();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.Run();
assign role to logged in user
ClaimsIdentity identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, payload.Name),
new Claim(ClaimTypes.Role, "Regular user") //default role
}, JwtBearerDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
var login = HttpContext.SignInAsync(JwtBearerDefaults.AuthenticationScheme, principal);

CORS Policy Not Working in IdentityServer4

I am using IdentityServer4 (IS4) to connect to AzureAD for authentication. I have created the app on AzureAD and used the correct ClientID and Tenant ID as well.
I am getting the following error while signing in:
[15:13:04 Information] Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler
AuthenticationScheme: OpenIdConnect was challenged.
[15:13:06 Debug] IdentityServer4.Hosting.CorsPolicyProvider
CORS request made for path: /signin-oidc from origin: https://login.microsoftonline.com but was ignored because path was not for an allowed IdentityServer CORS endpoint
[15:13:06 Information] Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler
AuthenticationScheme: Identity.External signed in.
Please, I requesting to guide me, as in what is going wrong here.
Here's how my entire Startup.cs looks like:
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityServer4;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;
using IdentityServerHost.Quickstart.UI;
using System.Reflection;
using IdentityServer.Models;
using Microsoft.AspNetCore.Identity;
using IdentityServer.Data;
using IdentityServer4.Configuration;
using System;
using Microsoft.AspNetCore.Authentication;
using IdentityServer4.Services;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
namespace IdentityServer
{
public class Startup
{
public IWebHostEnvironment Environment { get; }
public IConfiguration Configuration { get; }
public Startup(IWebHostEnvironment environment, IConfiguration configuration)
{
Environment = environment;
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
var connectionString = Configuration.GetConnectionString("DefaultConnection");
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
services.AddControllersWithViews();
services.AddDbContext<IdentityServerContext>(options =>
options.UseMySql(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly))
);
services.AddDbContext<Data.ConfigurationDbContext>(options => options.UseMySql(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly)));
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.SignIn.RequireConfirmedEmail = false;
//New added
options.Password.RequiredLength = 4;
options.Password.RequireLowercase = false;
options.Password.RequireUppercase = false;
options.Password.RequireDigit = false;
options.Password.RequireNonAlphanumeric = false;
options.Lockout.AllowedForNewUsers = true;
options.Lockout.DefaultLockoutTimeSpan = new TimeSpan(0, 15, 00);
options.Lockout.MaxFailedAccessAttempts = 5;
})
.AddEntityFrameworkStores<IdentityServerContext>()
.AddDefaultTokenProviders();
var builder = services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
// see https://identityserver4.readthedocs.io/en/latest/topics/resources.html
options.EmitStaticAudienceClaim = true;
options.UserInteraction.LoginUrl = "/Account/Login";
options.UserInteraction.LogoutUrl = "/Account/Logout";
options.Authentication = new IdentityServer4.Configuration.AuthenticationOptions()
{
CookieLifetime = TimeSpan.FromHours(10), // ID server cookie timeout set to 10 hours
CookieSlidingExpiration = true
};
})
//.AddTestUsers(TestUsers.Users)
// this adds the config data from DB (clients, resources, CORS)
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = builder => builder.UseMySql(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));
})
// this adds the operational data from DB (codes, tokens, consents)
.AddOperationalStore(options =>
{
options.ConfigureDbContext = builder => builder.UseMySql(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));
// this enables automatic token cleanup. this is optional.
options.EnableTokenCleanup = true;
})
.AddAspNetIdentity<ApplicationUser>()
.AddProfileService<IdentityProfileService>();
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
var autBuilder = services.AddAuthentication();
//Azure AD
autBuilder.AddAzureAd(options => Configuration.Bind("AzureAd", options));
// not recommended for production - you need to store your key material somewhere secure
builder.AddDeveloperSigningCredential();
/*
services.AddAuthentication()
.AddGoogle(options =>
{
options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
// register your IdentityServer with Google at https://console.developers.google.com
// enable the Google+ API
// set the redirect URI to https://localhost:5001/signin-google
options.ClientId = "copy client ID from Google here";
options.ClientSecret = "copy client secret from Google here";
});
*/
}
public void Configure(IApplicationBuilder app)
{
if (Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
app.UseStaticFiles();
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseIdentityServer();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
}
}
}
And the Azure Extension.cs
using System;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Authentication
{
public static class AzureAdAuthenticationBuilderExtensions
{
public static AuthenticationBuilder AddAzureAd(this AuthenticationBuilder builder)
=> builder.AddAzureAd(_ => { });
public static AuthenticationBuilder AddAzureAd(this AuthenticationBuilder builder, Action<AzureAdOptions> configureOptions)
{
builder.Services.Configure(configureOptions);
builder.Services.AddSingleton<IConfigureOptions<OpenIdConnectOptions>, ConfigureAzureOptions>();
builder.AddOpenIdConnect();
return builder;
}
private class ConfigureAzureOptions: IConfigureNamedOptions<OpenIdConnectOptions>
{
private readonly AzureAdOptions _azureOptions;
public ConfigureAzureOptions(IOptions<AzureAdOptions> azureOptions)
{
_azureOptions = azureOptions.Value;
}
public void Configure(string name, OpenIdConnectOptions options)
{
options.ClientId = _azureOptions.ClientId;
options.Authority = $"{_azureOptions.Instance}{_azureOptions.TenantId}";
options.UseTokenLifetime = true;
options.CallbackPath = _azureOptions.CallbackPath;
options.RequireHttpsMetadata = false;
}
public void Configure(OpenIdConnectOptions options)
{
Configure(Options.DefaultName, options);
}
}
}
}
And the appsettings.json
Appsettings.json
{
"ConnectionStrings": {
//"DefaultConnection": "connectiong_string"
},
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "",
"TenantId": "xxxxxxxxxxxxxxxxxxxxxxxxxx",
"ClientId": "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy",
"CallbackPath": "/signin-oidc"
},
"TimeSettings": {
"AbsoluteRefreshTokenLifetime": 15552000,
"SlidingRefreshTokenLifetime": 1296000,
"IdentityTokenLifetime": 300,
"AccessTokenLifetime": 300,
"AuthorizationCodeLifetime": 300
}
}
IdentityServer has its own CORS settings for requests made by its clients.
You use the AllowedCorsOrigins collection on the client configuration to set this up. Simply add the origin of the client to the collection and the default configuration in IdentityServer will consult these values to allow cross-origin calls from the origins.
new Client
{
...
AllowedCorsOrigins = new List<string>
{
"http://www.myclient.com"
}
}
Hard to tell, one thought is if the use of "CallbackPath": "/signin-oidc" should be changed to some other URL to not conflict with other things that uses /signin-oidc.
For example in the code here they use:
.AddOpenIdConnect("aad", "Sign-in with Azure AD", options =>
{
...
options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
options.SignOutScheme = IdentityServerConstants.SignoutScheme;
options.ResponseType = "id_token";
options.CallbackPath = "/signin-aad";
options.SignedOutCallbackPath = "/signout-callback-aad";
options.RemoteSignOutPath = "/signout-aad";

IdentityServer4 External Authentication (Azure Active Directory) fails

I created project from template: "is4aspid" and added Azure Active Directory authentication.
In Startup.cs added this code:
// preserve OIDC state in cache (solves problems with AAD and URL lenghts)
services.AddOidcStateDataFormatterCache();
// cookie policy to deal with temporary browser incompatibilities
services.AddSameSiteCookiePolicy();
services.AddAuthentication()
.AddOpenIdConnect("aad", "Sign-in with Azure AD", options =>
{
options.Authority = "https://login.microsoftonline.com/common";
options.ClientId = "myClientId";
options.ClientSecret = "myClientSecret";
options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
options.SignOutScheme = IdentityServerConstants.SignoutScheme;
options.ResponseType = "id_token";
options.CallbackPath = "/signin-aad";
options.SignedOutCallbackPath = "/signout-callback-aad";
options.RemoteSignOutPath = "/signout-aad";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
NameClaimType = "name",
RoleClaimType = "role"
};
});
I added redirect uri on Azure: http://localhost:5000/signin-aad
Error occure where Callback method is called.
HttpContext.AuthenticateAsync(IdentityConstants.ExternalScheme) Success is always false
[HttpGet]
public async Task<IActionResult> Callback()
{
var result = await HttpContext.AuthenticateAsync(IdentityConstants.ExternalScheme);
if (result?.Succeeded != true)
{
throw new Exception("External authentication error");
}
// some code
}
Where is my error?
Solution
Must define IdentityConstants.ExternalScheme in startup and callback

Error connecting to http://localhost:8000/.well-known/openid-configuration/jwks. Object reference not set to an instance of an object

I host my identity server use address http://10.2.5.90:8000 and use nginx map https://10.2.5.90:8888 to http://10.2.5.90:8000.
When i tried to request discovery document like quickstart in client, "Error connecting to http://localhost:8000/.well-known/openid-configuration/jwks. Object reference not set to an instance of an object.." occurred.
I tried to change Issuer to https address and used customized DiscoveryDocumentRequest. But it was not work.
When I remove the nginx and access http://10.2.5.90:8000, It worked well.
IdentityServer:Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// ...other codes
var builder = services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
options.IssuerUri = "https://10.2.5.90:8888";
});
// ...other codes
}
Client: Program.cs
private static async Task<string> GetAccessTokenAsync()
{
var client = new HttpClient();
var req = new DiscoveryDocumentRequest
{
Address = "https://10.2.5.90:8888",
Policy = new DiscoveryPolicy
{
ValidateIssuerName = false,
ValidateEndpoints = false,
}
};
var disco = await client.GetDiscoveryDocumentAsync(req);
if (disco.IsError)
{
Console.WriteLine(disco.Error);
// output: Error connecting to http://localhost:8000/.well-known/openid-configuration/jwks. Object reference not set to an instance of an object..
return null;
}
// ...other codes
}
Edit:
I changed the code when config identity server and it works when running discovery.
var builder = services.AddIdentityServer(options =>
{
options.PublicOrigin = "https://10.2.5.90:8888";
});
However, I still couldn't access my api. The error is Exception occurred while processing message.IDX20803: Unable to obtain configuration from: 'http://localhost:8000/.well-known/openid-configuration' and I'm researchig the solution
You have to change de Authority property in your api. The api needs to access to the discovery endpoint through nginx (port 8888):
services.AddAuthentication("Bearer")
.AddJwtBearer(options =>
{
options.Audience = "api1";
options.RequireHttpsMetadata = true;
options.Authority = "https://10.2.5.90:8888";
});
If you have a public IP and your backend farm use internal uris you can adjust your host uri data in the middleware. Try to put this middleware in the first position:
app.Use(async (context, next) =>
{
context.Request.Scheme = "https";
context.Request.Host = new HostString("10.2.5.90.8888");
context.Request.PathBase = "yourApplicationPathBase";
await next.Invoke();
});
Of course, you have to parameterize this strings by environment in your configuration.

Getting ArgumentOutOfRangeException error Idenity Server4

We are using Entity framework core with Identity server4 and getting the ArgumentOutOfRangeException when calling the token endpoint via code. Here is our ConfigurationServices method in Identity server project:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfiguration>(Configuration);
string connectionString = Configuration.GetConnectionString("IdentityServer");
var rsaProvider = new RSACryptoServiceProvider(512);
SecurityKey key = new RsaSecurityKey(rsaProvider);
var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials
(key, SecurityAlgorithms.RsaSha512Signature);
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
services.AddIdentityServer()
.AddSigningCredential(credentials)
// this adds the config data from DB (clients, resources)
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
}) // this adds the operational data from DB (codes, tokens, consents)
.AddOperationalStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
// this enables automatic token cleanup. this is optional.
// options.EnableTokenCleanup = true;
// options.TokenCleanupInterval = 30;
});
// Add S3 to the ASP.NET Core dependency injection framework.
services.AddAWSService<Amazon.S3.IAmazonS3>();
}
Here is our client application that calling identity server project("http://localhost:3000/"):
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> Get(string client, string secret)
{
IActionResult result = null;
//discover endpoints from metadata
var disco = await DiscoveryClient.GetAsync("http://localhost:3000/");
if (disco.IsError)
{
result = NotFound(disco.Error);
return result;
}
//request token
var tokenClient = new TokenClient(disco.TokenEndpoint, client, secret);
var tokenResponse = await tokenClient.RequestClientCredentialsAsync(scope: "sup");
if (tokenResponse.IsError)
{
result = NotFound(tokenResponse.Error);
}
result = Ok(tokenResponse.Json);
return result;
}
Here is error we have got:

Resources