How to version an API such that one version of the api will require a bearer token and the other version does not - asp.net-core

I have an asp.net core web api. Say if i want to have two versions of the api such that, version 1 will require a bearer token and version 2 will not require the barer token.
Since the token configuration code resides in the startup.cs file, how do I have two startup.cs files to match my requirement above? i am not even sure if it is legal to have two startup.cs files targeting two different versions of the api because the code to configure versioning of an asp.net core api will also reside in the startup.cs file.
Let me know what options are available to achieve my requirement above.
My current startup.cs file with token authentication enabled look like this..
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AzureADSettings>(Configuration.GetSection("AzureAd"));
var azureADSettings = Configuration.GetSection("AzureAd").Get<AzureADSettings>();
var validAudience = new List<string>
{
azureADSettings.Audience
};
services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o =>
{
o.Authority = $"{azureADSettings.Instance}/{azureADSettings.TenantId}/";
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = true,
//azureADSettings.Audience
ValidAudiences = new List<string>(validAudience)
};
});
}

The Authorize middleware applies that check if you do not explicitly a controller or action as Anonymous. Maybe what you can do is:
Put the [Anonymous] attribute on top of your controller(s).
Mark your v1 API end-points in your controller(s) as [Authorize].
Leave the v2 API end-points as-is.
This way, the v2 API end-points should work fine with users not having a bearer token but v1 API end-points should expect a valid bearer token.

Related

Can I create an Identity Server 4 ASP.NET Core API using 2 different token authentication middleware?

I am trying to figure out if its possible to write an ASP.NET Core API that consumes an identity server token using either Reference Tokens or JWT tokens based on whatever I've configured my identity server to use. The back-end configuration for IS4 is pretty easy, I'm just not convinced that I can configure 2 different token middlewares and my service will both be ok with it and know what to do.
So the idea is:
If my API gets a jwtToken, it attempts to use the jwt middleware for authorization back to identity server.
If my API gets a reference token, it attempts to use the introspection middleware for authorization back to identity server.
Obviously, if the wrong type of token is provided for whatever is configured on the IS4 service, it will fail.
Handling the token endpoint and revocation endpoint should also be easy enough, it's just the middleware magic I'm concerned with.
I know typically you wouldn't want to do this but we have a niche use case for it. All I'm currently concerned with is whether or not its even possible. I'm not familiar with how the auth middleware works in the back-end.
According to the Identity Server 4 Protecting APIs document, we can see that it supports to use both JWTs and reference tokens in asp.net core.
You can setup ASP.NET Core to dispatch to the right handler based on the incoming token, see this blog post for more information.
services.AddAuthentication("token")
// JWT tokens
.AddJwtBearer("token", options =>
{
options.Authority = Constants.Authority;
options.Audience = "resource1";
options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };
// if token does not contain a dot, it is a reference token
options.ForwardDefaultSelector = Selector.ForwardReferenceToken("introspection");
})
// reference tokens
.AddOAuth2Introspection("introspection", options =>
{
options.Authority = Constants.Authority;
options.ClientId = "resource1";
options.ClientSecret = "secret";
});
Supporting both JWTs and reference tokens
In addition to #Zhi Lv post you might need to add Authorization policy, Authentication Schemes to allow validating JWT and reference tokens.
Here is the sample code template replace api name, api secret and audience appropriatly.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddJwtBearer(Options =>
{
Options.Authority = "https://identity.domain.com/identity/";
Options.Audience = "resource1"; //your api baseurl e.g if you want userinfo_endpoint specify https://identity.domain.com/identity/connect/userinfo
Options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };
})
.AddIdentityServerAuthentication(options =>
{
options.Authority = "https://identity.domain.com/identity/";
options.ApiName = "api name / scope";
options.ApiSecret = "api secret / scope secret";
});
services.AddAuthorization(options =>
{
options.AddPolicy("tokens", x =>
{
x.AddAuthenticationSchemes("jwt", "introspection");
x.RequireAuthenticatedUser();
});
});
}
The way I would do it is to use introspection and claims caching in both cases, so that the API does not need to know or care which type of access token it receives.
The introspection would only occur when an access token is first received. Subsequent requests with the same token then use cached claims.
RESOURCES
Blog Post
Sample C# Code

OpenIdConnect with .NET Core 2.2 MVC towards IdentityServer3 using ScopePolicy. How do you get scopes into user principal?

It seems to set up OpenIdConnect authentication from .NET Core 2.2 to IdentityServer3 I have to setup through generic AddOpenIdConnect() call, and in order for scope policy to work, I have overridden OnTokenValidated, where I parse the access token received, and add the scopes in it to the ClaimsPrincipal object.
I have found no other way of getting scope policy to work. This seems a bit hackish though. Is there a better or simpler way, so I don't need to override events, or at least not parse the access token? It is parsed in the framework anyhow, so I would suspect there were other functionality available to get scopes into the claims principal.
Moving our code from .NET 4.5.2 to .NET Core 2.2, I need to set up authentication towards our IdentityServer3 server in a very different way.
I was hoping new functionality in later framework allowed for simple setup of authentication towards IdentityServer3, but I've found no fitting example.
I saw someone saying that IdentityServer4.AccessTokenValidation NuGet package could work towards IdentityServer3, but only example I've found has been with simple JWT authentication not allowing implicit user login flow.
Consequently, I've ended up using standard ASP.NET Core libraries to set up openidconnect, and then I need to tweak the code to make it work.
Not sure if the code below handles all it needs to, but at least I've gotten where I can log in and use the new web site, and write cypress tests. Any suggestions on how to do this better or simpler would be appreciated.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
app.UseMvc();
}
public void ConfigureServices(IServiceCollection services)
{
// Without this, I get "Correlation failed." error from Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.HandleRequestAsync()
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddAuthentication(o => {
o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
}).AddCookie().AddOpenIdConnect(o =>
{
o.Authority = "https://myidentityserver3.myfirm.com";
o.ClientId = "myidentityserver3clientname";
o.SignedOutRedirectUri = "https://localhost:50011/signout";
o.ResponseType = "id_token token";
o.SaveTokens = true;
o.Scope.Add("openid");
o.Scope.Add("roles");
o.Scope.Add("profile");
o.Scope.Add("customrequiredscopeforapi");
o.GetClaimsFromUserInfoEndpoint = false;
{
var old = o.Events.OnTokenValidated;
o.Events.OnTokenValidated = async ctx =>
{
if (old != null) await old(ctx);
var token = MyCustomAuthUtils.ParseBearerToken(ctx.ProtocolMessage.AccessToken);
foreach (var scope in token.Scopes)
{
ctx.Principal.AddIdentity(new ClaimsIdentity(new[] { new Claim("Scope", scope) }));
}
// Our controllers need access token to call other web api's, so putting it here.
// Not sure if that is a good way to do it.
ctx.Principal.AddIdentity(new ClaimsIdentity(new[] { new Claim("access_token", ctx.ProtocolMessage.AccessToken) }));
};
}
});
var mvcBuilder = services.AddMvc(o =>
{
o.Filters.Add(new AuthorizeFilter(ScopePolicy.Create("customrequiredscopeforapi")));
});
services.AddAuthorization();
}
The first thing is you don't need to manally decode the access token , just use ctx.SecurityToken.Claims in OnTokenValidated event to get all claims included in the token .
I'm not sure why you need to use scope to identify the permission . The scope parameter in the OIDC-conformant pipeline determines:
The permissions that an authorized application should have for a given resource server
Which standard profile claims should be included in the ID Token (if the user consents to provide this information to the application)
You can use role to identify whether current login user could access the protected resource . And the OpenID Connect middleware will help mapping the role claim to claim principle .

SPA (Aurelia) + ASP.NET Core WebAPI + Google Authentication

My SPA application (using Aurelia) calls my ASP.NET Core 2 Web API. I need to authenticate users with Google OIDC provider and also secure the Web API with the same method.
Currently I'm able to authenticate user on the client (SPA) side and retrieve id token and access token. With each API call I send the access token in the header.
Now I'm not sure how to handle the server side to validate the token and grant or deny the access to the API. I followed official docs how to add external login providers, but it seem to work only for server-side MVC applications.
Is there any easy way how to do this?
I think for instance IdentityServer4 can support this scenario, but it seems to me too complex for what I need to do. I don't need my own identity/authorization server after all.
Update:
Based on Miroslav Popovic answer, my configuration for ASP.NET Core 2.0 looks like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
{
o.Authority = "https://accounts.google.com";
o.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = "accounts.google.com",
ValidAudience = "xxxxxxxxxxxxx.apps.googleusercontent.com",
ValidateAudience = true,
ValidateIssuer = true
};
});
services.AddMvc();
}
And in Configure() I call app.UseAuthentication().
When using this setup I get failure message No SecurityTokenValidator available for token.
Update 2:
I made it work. The server configuration is correct. The problem was I was sending access_token to the API instead of id_token.
Since you already have the access token, it shouldn't be too hard to use it to add authentication. You would need something along these lines (not tested):
// Inside Startup.cs, ConfigureServices method
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(
options =>
{
var tokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = "accounts.google.com",
ValidateAudience = false
};
options.MetadataAddress = "https://accounts.google.com/.well-known/openid-configuration";
options.TokenValidationParameters = tokenValidationParameters;
});
// Inside Startup.cs, Configure method
app.UseAuthentication(); // Before MVC middleware
app.UseMvc();
// And of course, on your controllers:
[Authorize]
public class MyApiController : Controller
This post from Paul Rowe might help some more, but note that it's written for ASP.NET Core 1.x and authentication APIs changed a bit in 2.0.
There is also a lot of info here on SO, like this question.

Asp.Net Core 2.0 and Azure AD B2C for authentication on WebApp and API

I have an existing small app that I use for test, it is in Asp.Net Core 1.1 for both the Web App and the API, the authentication is done using Azure AD B2C.
I am trying to move it to .Net Core 2.0 but I can't figure how to get it working, I tried using both sample from GitHub Azure-Samples for Web App and API, but I have either an unauthorized or 500 error when trying to access the api, if you have a working example for calling a web api from a web app using 2.0 and protected by AD B2C it will be greatly appreciated.
Edit:
The sample I use to test are :
Web App : WebApp-OpenIDConnect-DotNet core2.0
Web Api : B2C-WebApi core2.0
, I changed the appsettings values to match my b2c directory.
For my asp.net core 1.1 test app I use the same samples as above but from the master branch, with the same value for appsettings.
Edit 2
by default, in startup.cs I have this :
services.AddAuthentication()
.AddJwtBearer(option => new JwtBearerOptions
{
Authority = string.Format("https://login.microsoftonline.com/tfp/{0}/{1}/v2.0/",
Configuration["Authentication:AzureAd:Tenant"], Configuration["Authentication:AzureAd:Policy"]),
Audience = Configuration["Authentication:AzureAd:ClientId"],
Events = new JwtBearerEvents
{
OnAuthenticationFailed = AuthenticationFailed
}
});
which gives me the following error:
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:44352/api/values/5
Microsoft.AspNetCore.Server.Kestrel:Error: Connection id "0HL89JHF4VBLM", Request id "0HL89JHF4VBLM:00000001": An unhandled exception was thrown by the application.
System.InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found.
if modified services.AddAuthentication like that
services.AddAuthentication(sharedOption =>
{
sharedOption.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
the error is now
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler:Information: Failed to validate the token xxx.
Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException: IDX10500: Signature validation failed. No security keys were provided to validate the signature.
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(String token, TokenValidationParameters validationParameters)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken& validatedToken)
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.d__6.MoveNext()
I saw a pull request on the sample which correct this issue (Link), the services.AddAuthentication must be change to:
services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(jwtOptions =>
{
jwtOptions.Authority = $"https://login.microsoftonline.com/tfp/{Configuration["Authentication:AzureAd:Tenant"]}/{Configuration["Authentication:AzureAd:Policy"]}/v2.0/";
jwtOptions.Audience = Configuration["Authentication:AzureAd:ClientId"];
jwtOptions.Events = new JwtBearerEvents
{
OnAuthenticationFailed = AuthenticationFailed
};
});
I got this example working both for Core 1.1 and Core 2.0, please add the Oath Authentication as below,
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddAzureAdB2C(options => Configuration.Bind("Authentication:AzureAdB2C", options))
You configuration options will be defined inside of the class "AzureAdB2CAuthenticationBuilderExtensions", which is found inside of the
azure b2c project
Looks like your token is not being update it from the Azure, are you able to get the token from your web app? could you please verify that you are not getting null
Did you register your api scopes on your azure b2c tenant web app?
"ApiScopes": "https://fabrikamb2c.onmicrosoft.com/demoapi/demo.read"
you have to set scope in your web api and allows to be read on the web app, please follow click the link in order to set it up

JWT Bearer Token Flow

What I want is a method of JWT Generation and JWT Consumption in ASP.NET Core.
No OAuth2 flow, I do have the IdentityServerv3 working with OAuth2 but it is just overkill for a single app accessing an API when I own both sides.
The main source of difficulty I am having is finding out the equivalent of Microsoft.Owin.Security.Jwt in ASP.NET Core. Nothing in this list https://www.myget.org/gallery/aspnetvnext seems to relate. Or is that package actually to stay relevant in with ASP.NET Core?
If you're looking for a (simple) way to generate your own JWT tokens, you should directly use the JwtSecurityTokenHandler. You can find it in the System.IdentityModel.Tokens package on the MyGet repository you mentioned (but the version is a bit old now) or directly on the Azure AD repository, in the System.IdentityModel.Tokens.Jwt package: https://www.myget.org/gallery/azureadwebstacknightly
Of course, using a standard protocol to issue and retrieve your JWT tokens is more than recommended and OAuth2 and OpenID Connect are probably the best candidates for that.
Note that IdentityServer is not the only server that works on ASP.NET 5. I'm personally working on an advanced fork of the OAuth2 authorization server middleware that comes with Katana 3 and that offers a different approach: https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server
app.UseOAuthBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
Audience = "http://localhost:54540/",
Authority = "http://localhost:54540/"
});
app.UseOpenIdConnectServer(options =>
{
options.Provider = new AuthorizationProvider();
});
To learn more about this project, I'd recommend reading http://kevinchalet.com/2016/07/13/creating-your-own-openid-connect-server-with-asos-introduction/.
Feel free to ping me on https://jabbr.net/#/rooms/AspNetCore if you need more information.
I've started using OpenIddict and I think it is exactly what you need.
This is essentially all the configuration I needed:
ConfigureServices:
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders()
.AddOpenIddictCore<Application>(config => config.UseEntityFramework());
Configure
app.UseOpenIddictCore(builder =>
{
// tell openiddict you're wanting to use jwt tokens
builder.Options.UseJwtTokens();
// NOTE: for dev consumption only! for live, this is not encouraged!
builder.Options.AllowInsecureHttp = true;
builder.Options.ApplicationCanDisplayErrors = true;
});
// use jwt bearer authentication
app.UseJwtBearerAuthentication(options =>
{
options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
options.RequireHttpsMetadata = false;
options.Audience = "http://localhost:58292/";
options.Authority = "http://localhost:58292/";
});
There are one or two other minor things, such as your DbContext needs to derive from OpenIddictContext<ApplicationUser, Application, ApplicationRole, string>.
You can see a full length explanation (including links to the github repo) on this blog post of mine:
http://capesean.co.za/blog/asp-net-5-jwt-tokens/