Getting claims in asp.net core using open connect server id
I am about to implement bearer authentication in my main asp.net application. Based on the .NET Framework, the core material is still completely new to me. Getting token from server already works fine. But how can I tell in the next request if the user is authenticated? In .NET Framework projects I have used
(ClaimsIdentity)Thread.CurrentPrincipal.Identity.IsAuthenticated;
However, this returns an id with empty or standard assertions. This is my setup:
I started with the OpenIdConnect.Server framework and sample code in Getting Started . "This works great and my client receives a bearer token. I built it in mine Startup.cs
like this:
public class Startup
{
[...]
public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
services.AddAuthentication();
[...]
}
public void Configure([...])
{
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc();
app.UseOpenIdConnectServer(options =>
{
[code of example]
}
}
On the client side, I use the extracted token for further requests
Now, how do I now access the users' current stated requirements or how do I know if it is authenticated?
I tried
// within api controller:
var isAuth = this.User.Identity.IsAuthenticated
// using DI
public class MyClass(IHttpContextAccessor httpContextAccessor) {
public void MyMethod() {
var isAuth = httpContextAccessor.HttpContext.User.Identity.IsAuthenticated;
}
}
But this always returns false
, and claims are the defaults. Am I missing something? Do I need to install any additional service or middleware?
source to share
One thing to note with the OpenID Connect server middleware is that it doesn't validate access tokens for you (it only issues them). Since you are using the default token format (encrypted), you can use a package AspNet.Security.OAuth.Validation
to do this:
public class Startup
{
[...]
public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
services.AddAuthentication();
[...]
}
public void Configure([...])
{
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseOpenIdConnectServer(options =>
{
[code of example]
});
app.UseOAuthValidation();
app.UseMvc();
}
}
source to share