Identityserver4 not authorized api in blazor client - asp.net-core

I use identity server 4 with blazor server side client
everything is ok but token not authorized api methods but token works in server authorized controllers
is something wrong with grant type or code flow ?
server config class :
public static class Configurations
{
public static IEnumerable<IdentityResource> GetIdentityResources() =>
new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
};
public static IEnumerable<ApiResource> GetApis() =>
new List<ApiResource> {
new ApiResource("api1")
};
public static IEnumerable<ApiScope> GetApiScopes()
{
return new List<ApiScope>
{
// backward compat
new ApiScope("api1")
};
}
public static IEnumerable<Client> GetClients() => new List<Client>
{
new Client
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.Code,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = {
"api1" ,
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
},
RedirectUris = { "https://localhost:44372/signin-oidc" },
AlwaysIncludeUserClaimsInIdToken = true,
AllowOfflineAccess = true,
RequireConsent = false,
RequirePkce = true,
}
};
}
server start up class :
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(config =>
{
config.UseInMemoryDatabase("Memory");
});
// AddIdentity registers the services
services.AddIdentity<IdentityUser, IdentityRole>(config =>
{
config.Password.RequiredLength = 4;
config.Password.RequireDigit = false;
config.Password.RequireNonAlphanumeric = false;
config.Password.RequireUppercase = false;
})
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(config =>
{
config.Cookie.Name = "IdentityServer.Cookie";
config.LoginPath = "/Auth/Login";
config.LogoutPath = "/Auth/Logout";
});
services.AddIdentityServer()
.AddAspNetIdentity<IdentityUser>()
//.AddInMemoryApiResources(Configurations.GetApis())
.AddInMemoryIdentityResources(Configurations.GetIdentityResources())
.AddInMemoryApiScopes(Configurations.GetApiScopes())
.AddInMemoryClients(Configurations.GetClients())
.AddDeveloperSigningCredential();
services.AddControllersWithViews();
}
api start up class :
services.AddAuthentication("Bearer").AddIdentityServerAuthentication(option =>
{
option.Authority = "https://localhost:44313";
option.RequireHttpsMetadata = false;
option.ApiName = "api1";
});
blazor server side start up class:
services.AddAuthentication(config =>
{
config.DefaultScheme = "Cookie";
config.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookie")
.AddOpenIdConnect("oidc", config =>
{
config.Authority = "https://localhost:44313/";
config.ClientId = "client";
config.ClientSecret = "secret";
config.SaveTokens = true;
config.ResponseType = "code";
config.SignedOutCallbackPath = "/";
config.Scope.Add("openid");
config.Scope.Add("api1");
config.Scope.Add("offline_access");
});
services.AddMvcCore(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser() // site-wide auth
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});

To fix this issue, you have 2 options:
1- (Recommended) To add the scopes to API resource like this:
public static IEnumerable<ApiResource> GetApis() =>
new List<ApiResource> {
new ApiResource("api1")
{
Scopes = new []{ "api1" }
}
};
public static IEnumerable<ApiScope> GetApiScopes()
{
return new List<ApiScope>
{
// backward compat
new ApiScope("api1")
};
}
2- On API change your code to set ValidateAudience = false, like this:
services.AddAuthentication("Bearer").AddJwtBearer("Bearer",
options =>
{
options.Authority = "http://localhost:5000";
options.Audience = "api1";
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new
TokenValidationParameters()
{
ValidateAudience = false
};
});
Here is my blog about migrating IdentityServer4 to v4 https://nahidfa.com/posts/migrating-identityserver4-to-v4/

I have not actually used AddIdentityServerAuthentication in API but can you try the below code. Technically its same thing, but maybe this will work.
Change your api authentication from AddIdentityServerAuthentication to AddJwtBearer:
services.AddAuthentication("Bearer").AddIdentityServerAuthentication(option =>
{
option.Authority = "https://localhost:44313";
option.RequireHttpsMetadata = false;
option.ApiName = "api1";
});
to
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", option =>
{
option.Authority = "https://localhost:44313";
option.Audience = "api1";
option.SaveToken = true;
});

Related

IdentityServer4 - Error: Unknown client or not enabled: oauthClient

I've been trying to setup a project with IdentityServer4 for a while. However I'm getting the following error:
Sso.Application.CentralHandler: Information: AuthenticationScheme: central was challenged.
IdentityServer4.Hosting.IdentityServerMiddleware: Information: Invoking IdentityServer endpoint: IdentityServer4.Endpoints.AuthorizeEndpoint for /connect/authorize
IdentityServer4.Validation.AuthorizeRequestValidator: Error: Unknown client or not enabled: oauthClient
IdentityServer4.Endpoints.AuthorizeEndpoint: Error: Request validation failed
IdentityServer4.Endpoints.AuthorizeEndpoint: Information: {
"SubjectId": "anonymous",
"RequestedScopes": "",
"PromptMode": "",
"Raw": {
"client_id": "oauthClient",
"scope": "weatherforecasts.read",
"response_type": "code",
"redirect_uri": "https://localhost:44375/signin-central",
"code_challenge": "Rdi0rU5OkG1gWzh9xfvOxbZLiGbDHqujbMzl9d3u7Qs",
"code_challenge_method": "S256",
"state": "CfDJ8PC7ZLg_v2RDsl0VaXUuuT_-sT-at-LgQD1krwu8LESVXDKkQxQd8_eUQZJqOiGREAzBtfZ4U9X0BJDIn15AvYXKR2omUEBW5LzJm1Vz3ykaScc_kC89f6hCimDBmqCAdUOF0wnEn8FfDD8GPJtPBgxqoqrCNnyGKxh58XOIa85sN-zDSU5Oa73pzKt5FrFIkBCqUOfpCM_KZajZR_3DWFNCbwn8tS-XR0of7ga72XDILC--N9bCqA2eIlTSxf9HHPXmmLninU1ri7RM-XMsOzH__mtQQPOXCuaHw3Q0Nkedmpj4NaTCdcB1k55IdsX1eLrub8ptagCWzMIzXcYIWlJc74Zj-_H2uDZE4M-Blbdr"
}
}
I've been looking on SO for how to solve this error for the entire day, but I can't figure out what's wrong with it.
This is the code in the Startup of the IdentityProvider project:
services
.AddDbContext<SsoCentralContext>();
//.AddScoped<Repositories.IAccountRepository, Repositories.AccountRepository>();
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<SsoCentralContext>();
var isb = services.AddIdentityServer();
isb
.AddInMemoryClients(new List<Client>
{
new Client
{
ClientId = "oauthClient",
ClientName = "oauthClient",
AllowedGrantTypes = GrantTypes.CodeAndClientCredentials,
Enabled = true,
ClientSecrets = new List<Secret> {new Secret("SuperSecretPassword".Sha256())}, // change me!
AllowedScopes = new List<string> {"weatherforecasts.read"},
RedirectUris = new List<string>
{
"https://localhost:44375/signin-central"
},
}
})
.AddInMemoryIdentityResources(new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResources.Email(),
new IdentityResource
{
Name = "role",
UserClaims = new List<string> {"role"}
}
})
.AddInMemoryApiResources(new List<ApiResource>
{
new ApiResource
{
Name = "api1",
DisplayName = "API #1",
Description = "Allow the application to access API #1 on your behalf",
Scopes = new List<string> { "weatherforecasts.read", "weatherforecasts.write"},
ApiSecrets = new List<Secret> {new Secret("ScopeSecret".Sha256())},
UserClaims = new List<string> {"role"}
}
})
.AddInMemoryApiScopes(new List<ApiScope>
{
new ApiScope("weatherforecasts.read", "Read Access to API #1"),
new ApiScope("weatherforecasts.write", "Write Access to API #1")
})
.AddTestUsers(new List<IdentityServer4.Test.TestUser>
{
new IdentityServer4.Test.TestUser
{
SubjectId = "5BE86359-073C-434B-AD2D-A3932222DABE",
Username = "Pieterjan",
Password = "password",
Claims = new List<System.Security.Claims.Claim> {
new System.Security.Claims.Claim(IdentityModel.JwtClaimTypes.Email, "pieterjan#example.com"),
new System.Security.Claims.Claim(IdentityModel.JwtClaimTypes.Role, "admin")
}
}
})
.AddDeveloperSigningCredential();
isb
.AddOperationalStore(options =>
{
options.ConfigureDbContext = (builder) => builder.UseInMemoryDatabase("SsoCentral");
})
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = (builder) => builder.UseInMemoryDatabase("SsoCentral");
});
isb.AddAspNetIdentity<IdentityUser>();
The above code is definitely being called, so the oauthClient should exist for sure. Also the client is definitely enabled.
This is the code in Startup of the Identity project:
services
.AddAuthentication(options =>
{
})
.AddOAuth<CentralOptions, CentralHandler>("central", options =>
{
options.ClaimsIssuer = "https://localhost:44359"; // This is the URL of the IdentityProvider
options.SaveTokens = true;
options.ClientId = "oauthClient";
options.ClientSecret = "SuperSecretPassword";
options.Scope.Add("weatherforecasts.read");
options.UsePkce = true;
});
How can I fix this error? Would anyone know how to figure out what's wrong here?
Also would I still need to use OpenIdConnect on top of what's been configured here?
Update:
I've added a call just to get the clients from the IS4 ClientStore:
[HttpGet("Clients")]
public async Task<IActionResult> GetClients()
{
//var client = await clientStore.FindClientByIdAsync("SsoApplicationClient");
var _inner = (IdentityServer4.EntityFramework.Stores.ClientStore)clientStore.GetType().GetField("_inner", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(clientStore);
var Context = (IdentityServer4.EntityFramework.DbContexts.ConfigurationDbContext)_inner.GetType().GetField("Context", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(_inner);
var Clients = Context.Clients;
return Ok(Clients);
}
To my amazement, what I get from this is an entirely empty list:
Alright, so when you have the following configuration:
services.AddIdentityServer()
...
.AddOperationalStore(options =>
{
options.ConfigureDbContext = (builder) => builder.UseInMemoryDatabase("SsoCentral");
})
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = (builder) => builder.UseInMemoryDatabase("SsoCentral");
})
The InMemoryClients don't exist anymore. Just commented it out and it seems to be working now.

Use JWT token in multiple projects

I have 3 projects JWT.IDP, JWT.API, JWT.MVC.
JWT.IDP - an API project validates user and issues the JWT token.
JWT.API - an API project for my business logic, CURD etc
JWT.MVC - an MVC application for UI.
My intention is to use this token generated in JWT.IDP and call the JWT.API functions from JWT.MVC
The IDP token is working perfectly fine, I can generate the token and my JWT.MVC Login controller is able to receive it. But when I am trying to use this token to access the JWT.API it gives a 500 error (Please see the last function in the below code (GetWeatherData)).
Can someone help, I am not an advanced user, the code written below is taken from several samples. So I am not sure whether it really is the right code.
namespace JWT.MVC.Controllers
{
public class LoginController : Controller
{
public IActionResult DoLogin()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DoLogin([Bind("EmailOrName,Password")] LoginRequestModel loginRequestModel)
{
var apiName = $"https://localhost:44318/api/User/login";
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.PostAsJsonAsync(apiName, loginRequestModel);
var jasonString = await response.Content.ReadAsStreamAsync();
var data = await JsonSerializer.DeserializeAsync<IEnumerable<AccessibleDb>>
(jasonString, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
foreach (var item in data)
{
item.UserName = loginRequestModel.EmailOrName;
}
return View("SelectDatabase" , data);
}
public async Task<IActionResult> PostLogin(string db, string user)
{
TokenRequestModel tokenRequestModel = new TokenRequestModel() { Database = db, UserName = user };
var apiName = $"https://localhost:44318/api/User/tokenonly";
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.PostAsJsonAsync(apiName, tokenRequestModel);
var jasonString = await response.Content.ReadAsStreamAsync();
var data = await JsonSerializer.DeserializeAsync<AuthenticationModel>
(jasonString, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
var stream = data.Token;
var handler = new JwtSecurityTokenHandler();
var jsonToken = handler.ReadToken(stream);
var tokenS = jsonToken as JwtSecurityToken;
var selectedDb = tokenS.Claims.First(claim => claim.Type == "Database").Value;
ViewBag.SelectedDb = selectedDb;
return View(data);
}
public async Task<IActionResult> GetWeatherData(string token)
{
var apiName = $"https://localhost:44338/weatherforecast";
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = await httpClient.GetAsync(apiName);
if (!response.IsSuccessStatusCode)
{
ViewBag.Error = response.StatusCode;
return View("Weatherdata");
}
var jasonString = await response.Content.ReadAsStreamAsync();
var data = await JsonSerializer.DeserializeAsync<WeatherForecast>
(jasonString, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
return View("Weatherdata" , data);
}
}
}
Startup class for JWT.MVC is as below
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Audience = "SecureApiUser";
options.Authority = "https://localhost:44318";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false
};
});
}
Startup class for JWT.API is as below
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
//Copy from IS4
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Audience = "SecureApiUser";
options.Authority = "https://localhost:44318";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false
};
});
//End
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "JWT.API", Version = "v1" });
});
}
Startup class for JWT.IDP is as below
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
//Configuration from AppSettings
services.Configure<JwtSettings>(Configuration.GetSection("JWT"));
//User Manager Service
services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<IdentityDbContext>();
services.AddScoped<IUserService, UserService>();
//Adding DB Context with MSSQL
services.AddDbContext<IdentityDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("IdentityDbConnectionString"),
b => b.MigrationsAssembly(typeof(IdentityDbContext).Assembly.FullName)));
//Adding Athentication - JWT
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o =>
{
o.RequireHttpsMetadata = false;
o.SaveToken = false;
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ClockSkew = TimeSpan.FromMinutes(Convert.ToInt32(Configuration["JWT:DurationInMinutes"])),
ValidIssuer = Configuration["JWT:Issuer"],
ValidAudience = Configuration["JWT:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Key"]))
};
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "JWT.IDP", Version = "v1" });
});
}
And the JWT Setting is as below
"JWT": {
"key": "C1CF4B7DC4C4175B6618DE4F55CA4",
"Issuer": "http://localhost:44318",
"Audience": "SecureApiUser",
"DurationInMinutes": 60
},
It's quite surprising that no one was able to identify the mistake. I made the following changes and it works perfectly fine now.
The ConfigureServices is like below in both MVC and API projects. No other changes to any other codes.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
var authenticationProviderKey = "IdentityApiKey";
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("C1CF4B7DC4C4175B6618DE4F55CA4"));
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = true,
ValidIssuer = "http://localhost:44318",
ValidateAudience = true,
ValidAudience = "SecureApiUser",
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
RequireExpirationTime = true,
};
services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = authenticationProviderKey;
})
.AddJwtBearer(authenticationProviderKey, x =>
{
x.RequireHttpsMetadata = false;
x.TokenValidationParameters = tokenValidationParameters;
});
//services.AddAuthentication(options =>
//{
// options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
// options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
//}).AddJwtBearer(options =>
//{
// options.Authority = "https://localhost:44318"; ;
// options.RequireHttpsMetadata = false;
// options.Audience = "SecureApiUser";
//});
//End
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "JWT.API2", Version = "v1" });
});
}

Using JWT Token in Client API

I have an API in .NET5 uses JWTBearer to secure the API. Now I wanted to configure my client app to use the token generated from the api/gettoken. It works fine in swagger, but I don't know how to configure my MVC and API(consuming API) to use this token. Can somebody help by providing the configureservices and configure methods in the startup
To Glenn,
I have 3 projects JWT.IDP, JWT.API, JWT.MVC. JWT.IDP issues the token, my intention is to use that token in JWT.API and call the JWT.API function from JWT.MVC. The IDP is working perfectly, I can generate the token and my JWT.MVC Login controller is able to receive it. The last function in the below code (GetWeatherData) is coded according to the idea you have given. If I don't pass the token, I used to get 401 error, now I get 500 Internal Server Error
namespace JWT.MVC.Controllers
{
public class LoginController : Controller
{
public IActionResult DoLogin()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DoLogin([Bind("EmailOrName,Password")] LoginRequestModel loginRequestModel)
{
var apiName = $"https://localhost:44318/api/User/login";
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.PostAsJsonAsync(apiName, loginRequestModel);
var jasonString = await response.Content.ReadAsStreamAsync();
var data = await JsonSerializer.DeserializeAsync<IEnumerable<AccessibleDb>>
(jasonString, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
foreach (var item in data)
{
item.UserName = loginRequestModel.EmailOrName;
}
return View("SelectDatabase" , data);
}
public async Task<IActionResult> PostLogin(string db, string user)
{
TokenRequestModel tokenRequestModel = new TokenRequestModel() { Database = db, UserName = user };
var apiName = $"https://localhost:44318/api/User/tokenonly";
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.PostAsJsonAsync(apiName, tokenRequestModel);
var jasonString = await response.Content.ReadAsStreamAsync();
var data = await JsonSerializer.DeserializeAsync<AuthenticationModel>
(jasonString, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
var stream = data.Token;
var handler = new JwtSecurityTokenHandler();
var jsonToken = handler.ReadToken(stream);
var tokenS = jsonToken as JwtSecurityToken;
var selectedDb = tokenS.Claims.First(claim => claim.Type == "Database").Value;
ViewBag.SelectedDb = selectedDb;
return View(data);
}
public async Task<IActionResult> GetWeatherData(string token)
{
var apiName = $"https://localhost:44338/weatherforecast";
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = await httpClient.GetAsync(apiName);
if (!response.IsSuccessStatusCode)
{
ViewBag.Error = response.StatusCode;
return View("Weatherdata");
}
var jasonString = await response.Content.ReadAsStreamAsync();
var data = await JsonSerializer.DeserializeAsync<WeatherForecast>
(jasonString, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
return View("Weatherdata" , data);
}
}
}
Startup class for JWT.MVC is as below
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Audience = "SecureApiUser";
options.Authority = "https://localhost:44318";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false
};
});
}
Startup class for JWT.API is as below
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
//Copy from IS4
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Audience = "SecureApiUser";
options.Authority = "https://localhost:44318";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false
};
});
//End
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "JWT.API", Version = "v1" });
});
}
Startup class for JWT.IDP is as below
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
//Configuration from AppSettings
services.Configure<JwtSettings>(Configuration.GetSection("JWT"));
//User Manager Service
services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<IdentityDbContext>();
services.AddScoped<IUserService, UserService>();
//Adding DB Context with MSSQL
services.AddDbContext<IdentityDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("IdentityDbConnectionString"),
b => b.MigrationsAssembly(typeof(IdentityDbContext).Assembly.FullName)));
//Adding Athentication - JWT
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o =>
{
o.RequireHttpsMetadata = false;
o.SaveToken = false;
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ClockSkew = TimeSpan.FromMinutes(Convert.ToInt32(Configuration["JWT:DurationInMinutes"])),
ValidIssuer = Configuration["JWT:Issuer"],
ValidAudience = Configuration["JWT:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Key"]))
};
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "JWT.IDP", Version = "v1" });
});
}
And the JWT Setting is as below
"JWT": {
"key": "C1CF4B7DC4C4175B6618DE4F55CA4",
"Issuer": "http://localhost:44318",
"Audience": "SecureApiUser",
"DurationInMinutes": 60
},
The short answer is
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", [token])
Keep "Bearer" as it is, it's just a constant. Replace [token], with the base 64 encoded token value returned to us from the OAuth protocol you are using.

Error connecting to https://localhost:5002/.well-known/openid-configuration

I am using Identity Server 4 and ASP.NET Core 2.1.
I have an API and an Auth application and tried to following:
var discoveryClient = new DiscoveryClient("https://localhost:5002");
discoveryClient.Policy.RequireHttps = true;
var discovery = await discoveryClient.GetAsync();
if (discovery.IsError)
Console.WriteLine(discovery.Error);
But I got the following error:
Error connecting to https://localhost:5002/.well-known/openid-configuration:
The SSL connection could not be established
The remote certificate is invalid according to the validation procedure.
However if I access the url "https://localhost:5002/.well-known/openid-configuration" in the browser I get the correct information and not errors.
What am I doing wrong?
The API application has the following configuration:
public void ConfigureServices(IServiceCollection services) {
services
.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddRouting(x => { x.LowercaseUrls = true; });
services.AddHsts(x => {
x.Preload = true;
x.IncludeSubDomains = true;
x.MaxAge = TimeSpan.FromDays(60);
});
services.AddHttpsRedirection(x => {
x.RedirectStatusCode = StatusCodes.Status301MovedPermanently;
x.HttpsPort = 5001;
});
services.AddApiVersioning(x => {
x.ApiVersionSelector = new CurrentImplementationApiVersionSelector(x);
x.AssumeDefaultVersionWhenUnspecified = true;
x.DefaultApiVersion = new ApiVersion(1, 0);
x.ReportApiVersions = false;
});
services.AddCors(x => {
x.AddPolicy("AllowAll", y => y.AllowAnyMethod().AllowAnyOrigin().AllowAnyHeader());
});
services.AddAuthorization();
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(x => {
x.ApiName = "api";
x.Authority = "https://localhost:5002";
x.RequireHttpsMetadata = false;
});
} // ConfigureServices
public void Configure(IApplicationBuilder application, IHostingEnvironment environment) {
if (environment.IsDevelopment()) {
application.UseDeveloperExceptionPage();
} else {
application.UseHsts();
}
application.UseAuthentication();
application.UseHttpsRedirection();
application.UseMvc();
} // Configure
And the Auth application with the following configuration:
public void ConfigureServices(IServiceCollection services) {
services
.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddRouting(x => { x.LowercaseUrls = true; });
services.AddHsts(x => {
x.Preload = true;
x.IncludeSubDomains = true;
x.MaxAge = TimeSpan.FromDays(60);
});
services.AddHttpsRedirection(x => {
x.RedirectStatusCode = StatusCodes.Status301MovedPermanently;
x.HttpsPort = 5002;
});
services
.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
.AddTestUsers(Config.GetTestUsers());
} // ConfigureServices
public void Configure(IApplicationBuilder application, IHostingEnvironment environment) {
if (environment.IsDevelopment()) {
application.UseDeveloperExceptionPage();
} else {
application.UseHsts();
}
application.UseHttpsRedirection();
application.UseIdentityServer();
application.UseMvc();
} // Configure
Where Config that defines Clients, Resources and Test Users is:
public class Config {
public static List<ApiResource> GetApiResources() {
return new List<ApiResource> {
new ApiResource("api", "API Resource")
};
}
public static List<IdentityResource> GetIdentityResources() {
return new List<IdentityResource> {
new IdentityResources.OpenId(),
new IdentityResources.Profile()
};
}
public static List<Client> GetClients() {
return new List<Client> {
new Client {
ClientId = "app",
ClientName = "APP Client",
ClientSecrets = { new Secret("app".Sha256()) },
AllowedGrantTypes = GrantTypes.ClientCredentials,
AllowedScopes = { "api" }
},
new Client {
ClientId = "mvc",
ClientName = "MVC Client",
ClientSecrets = { new Secret("mvc".Sha256()) },
Enabled = true,
AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
AllowOfflineAccess = true,
RequireConsent = false,
RedirectUris = { "http://localhost:5002/signin-oidc" },
PostLogoutRedirectUris = { "http://localhost:5002" },
FrontChannelLogoutUri = "http://localhost:5002/signout-oidc",
AllowedScopes = {
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.Email,
"api"
}
},
new Client {
ClientId = "spa",
ClientName = "SPA Client",
ClientSecrets = { new Secret("spa".Sha256()) },
Enabled = true,
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
RequireConsent = false,
AllowedScopes = {
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.Email,
"api"
},
RedirectUris = { "https://localhost:5000" },
PostLogoutRedirectUris = { "https://localhost:5000/home" },
AllowedCorsOrigins = { "https://localhost:5000" }
}
};
}
public static List<TestUser> GetTestUsers() {
return new List<TestUser> {
new TestUser { SubjectId = "1", Username = "john", Password = "john", Claims = new List<Claim> { new Claim("name", "John") } },
};
}
} // Config

The function IntrospectionClient in Identityserver4 always returns Unauthorized

I want to use the function IntrospectionClient to verify the token in identity server, but it always returns: Unauthorized
Identity server startup code:
services.AddIdentityServer()
.AddSigningCredential(myPrivatecert)
.AddInMemoryApiResources(Config.GetResources())
.AddInMemoryClients(Config.GetClients())
.AddTestUsers(Config.GetTestUsers())
.AddValidationKey(myPubliccert)
.AddJwtBearerClientAuthentication()
.AddValidators();
I add a api resource, a client info and a test user in config file
My Config is :
public class Config
{
//ApiResource
public static IEnumerable<ApiResource> GetResources()
{
return new List<ApiResource>
{
new ApiResource("api")
};
}
//Client
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client()
{
ClientId = "site",
AccessTokenLifetime = 180,
RefreshTokenExpiration = TokenExpiration.Absolute,
AbsoluteRefreshTokenLifetime = 1800,
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AlwaysSendClientClaims = true,
AllowAccessTokensViaBrowser = true,
RequireConsent = false,
AllowedScopes =
{
"api"
},
AccessTokenType = AccessTokenType.Jwt,
AllowOfflineAccess = true
},
};
}
//TestUser
public static List<TestUser> GetTestUsers()
{
return new List<TestUser>{
new TestUser{
SubjectId="1",
Username="wyt",
Password="123456",
Claims = new List<Claim>()
{
new Claim("wawa", "aoao"),
}
}
};
}
}
My Client Startup is:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).
AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:6001";
options.RequireHttpsMetadata = false;
options.ApiName = "api";
});
get token :
//token
var tokenClient = new TokenClient(dico.TokenEndpoint, "site", "secret");
var tokenResponse = tokenClient.RequestResourceOwnerPasswordAsync("wyt", "123456").Result;
want use introspection:
var introspectionClient = new IntrospectionClient(
dico.IntrospectionEndpoint,
"api",
"secret");
var vresponse = await introspectionClient.SendAsync
(
new IntrospectionRequest { Token = tokenResult.AccessToken }
);
but the vresponse is always Unauthorized
where is wrong?
I ran into the same issue, the documentation is not very clear.
You need to add an ApiSecret to your ApiResource:
public static IEnumerable<ApiResource> GetResources()
{
return new List<ApiResource>
{
new ApiResource("api")
{
ApiSecrets = { new Secret("secret".Sha256()) }
}
};
}
And then you call the introspection endpoint passing the api name and the api secret, like you did:
var introspectionClient = new IntrospectionClient(
dico.IntrospectionEndpoint,
"api",
"secret");