Bearer error="invalid_token", error_description="The issuer is invalid" - c#

I have a simple web api project, which looks like this:
[Authorize]
[Route("Get")]
public ActionResult<string> SayHello()
{
return "Hello World";
}
I am trying to test it with Postman. By following the steps here: https://kevinchalet.com/2016/07/13/creating-your-own-openid-connect-server-with-asos-testing-your-authorization-server-with-postman/
1) Send the request below and receive a token as expected:
2) Attempt to send another request with the authorization token as shown below:
Why do I get a 401 (unauthorized) error? The WWW-Authenticate response header says: Bearer error="invalid_token", error_description="The issuer is invalid". I am using .Net Core 3.1. I have commented out the sensitive information in the screenshots.
The web api works as expected when accessed from an MVC application.
Here is the startup code:
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = identityUrl; //identityurl is a config item
options.RequireHttpsMetadata = false;
options.ApiName = apiName;
});

I ran into a similar issue. I was generating my token via Postman when sending in my request and using an external IP to access my Keycloak instance running inside of my kubernetes cluster. When my service inside the cluster tried to verify the token against the authority, it failed because the internal service name (http://keycloak) it used to validated the token was different than what Postman had used to generate the token (<external-keycloak-ip).
Since this was just for testing, I set the ValidateIssuer to false.
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false
};

I'm on dotnet 5.0, adding swagger (NSwag.AspNetCore) to my AzureAD "protected" web api and got a similar error about invalid issuer:
date: Tue,16 Mar 2021 22:50:58 GMT
server: Microsoft-IIS/10.0
www-authenticate: Bearer error="invalid_token",error_description="The issuer 'https://sts.windows.net/<your-tenant-id>/' is invalid"
x-powered-by: ASP.NET
So, instead of not validating the issuer, I just added sts.windows.net to the list (important parts in the end):
// Enable JWT Bearer Authentication
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
Configuration.Bind("AzureAd", options);
// Authority will be Your AzureAd Instance and Tenant Id
options.Authority = $"{Configuration["AzureAd:Instance"]}{Configuration["AzureAd:TenantId"]}/v2.0";
// The valid audiences are both the Client ID(options.Audience) and api://{ClientID}
options.TokenValidationParameters.ValidAudiences = new[]
{
Configuration["AzureAd:ClientId"], $"api://{Configuration["AzureAd:ClientId"]}",
};
// Valid issuers here:
options.TokenValidationParameters.ValidIssuers = new[]
{
$"https://sts.windows.net/{Configuration["AzureAd:TenantId"]}/",
$"{Configuration["AzureAd:Instance"]}{Configuration["AzureAd:TenantId"]}/"
};
});
This solved my problems. Now, why NSwag uses sts.windows.net as token issuer, I don't know. Seems wrong. I'm using these package versions:
<PackageReference Include="Microsoft.AspNetCore.Authentication" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.3" />
<PackageReference Include="NSwag.AspNetCore" Version="13.10.8" />

The Authority of AddIdentityServerAuthentication middleware should be the base-address of your identityserver , middleware will contact the identity server's OIDC metadata endpoint to get the public keys to validate the JWT token .
Please confirm that the Authority is the url of identity server where you issued the jwt token .

Setting ValidateIssuer = false like #nedstark179 proposes will work but it will also remove a security validation.
If you use a ASP.NET Core template with Individual Accounts (IdentityServer) and receive this error:
WWW-Authenticate: Bearer error="invalid_token", error_description="The issuer 'https://example.com' is invalid"
It is probably related to this issue:
https://github.com/dotnet/aspnetcore/issues/28880
For example a new Blazor Webassembly App with Individual Accounts and ASP.NET Core hosted from Visual Studio.
.NET 6.0 Known Issues only mentions it could happen in development but it can happen in production hosted as an Azure App Service as well.
https://github.com/dotnet/core/blob/main/release-notes/6.0/known-issues.md#spa-template-issues-with-individual-authentication-when-running-in-development
I created an issue about that here:
https://github.com/dotnet/aspnetcore/issues/42072
The example fix for development was not enough.
Started of by adding a new Application settings for the Azure App Service called IdentityServer:IssuerUri with value https://example.com/. This can of course be placed in appsettings.json as well. I then added the code below:
//Used until https://github.com/dotnet/aspnetcore/issues/42072 is fixed
if (!string.IsNullOrEmpty(settings.IdentityServer.IssuerUri))
{
builder.Services.Configure<JwtBearerOptions>(IdentityServerJwtConstants.IdentityServerJwtBearerScheme, o => o.Authority = settings.IdentityServer.IssuerUri);
}
below this code:
builder.Services.AddAuthentication()
.AddIdentityServerJwt();
I have not verified if it matters where the code is placed but AddIdentityServerJwt() calls AddPolicyScheme and .AddJwtBearer(IdentityServerJwtConstants.IdentityServerJwtBearerScheme, null, o => { });. Therefore I deemed it appropriate to set it after this code has been called.
After doing this the app still failed with the same error. I then modified AddIdentityServer like this:
builder.Services.AddIdentityServer(options =>
{
//Used until https://github.com/dotnet/aspnetcore/issues/42072 is fixed
if (!string.IsNullOrEmpty(settings.IdentityServer.IssuerUri))
{
options.IssuerUri = settings.IdentityServer.IssuerUri;
}
})
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
and then it started working for me. If you still experience a problem you could also try to set AuthenticatorIssuer like this:
builder.Services.AddDefaultIdentity<ApplicationUser>(options =>
{
options.SignIn.RequireConfirmedAccount = true;
//Used until https://github.com/dotnet/aspnetcore/issues/42072 is fixed
if (!string.IsNullOrEmpty(settings.IdentityServer.IssuerUri))
{
options.Tokens.AuthenticatorIssuer = settings.IdentityServer.IssuerUri;
}
})
.AddEntityFrameworkStores<ApplicationDbContext>();

In my case, simply adding /v2.0 to the Authority was sufficient.
Case:
services.AddAuthentication(x => {
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options => {
options.Audience = "client id here";
options.Authority = "https://login.microsoftonline.com/tenant id here/v2.0";
});

Related

Microsoft Identity Web: Change Redirect Uri

I am using .net 5, Identity Web Ui to access Microsoft Graph. Where can I configure my Redirect URI?
I need to specify the full Uri, since the generated one from callbackUri is incorrect due to being behind a Load Balancer with SSL offload.
Here is my current ConfigureServices section
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();
I was facing a similar problem with a WebApp exposed only behind a front door, the WebApp had to call a custom downstream WebApi.
My service configuration that worked on my localhost dev machine:
// AzureAdB2C
services
.AddMicrosoftIdentityWebAppAuthentication(
Configuration,
"AzureAdB2C", subscribeToOpenIdConnectMiddlewareDiagnosticsEvents: true)
.EnableTokenAcquisitionToCallDownstreamApi(p =>
{
p.RedirectUri = redUri; // NOT WORKING, WHY?
p.EnablePiiLogging = true;
},
[... an array with my needed scopes]
)
.AddInMemoryTokenCaches();
I tried the AddDownstreamWebApi but did not manage to make it work so I just fetched the needed token with ITokenAcquisition and added it to an HttpClient to make my request.
Then I needed AzureAd/B2C login redirect to the uri with the front door url:
https://example.org/signin-oidc and things broke. I solved it like this:
First of all you have to add this url to your App registration in the azure portal, very important is case sensitive it cares about trailing slashes and I suspect having many urls that point to the very same controller and the order of these have some impact, I just removed everything and kept the bare minimum.
Then in the configure services method:
services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.SaveTokens = true; // this saves the token for the downstream api
options.Events = new OpenIdConnectEvents
{
OnRedirectToIdentityProvider = async ctxt =>
{
// Invoked before redirecting to the identity provider to authenticate. This can be used to set ProtocolMessage.State
// that will be persisted through the authentication process. The ProtocolMessage can also be used to add or customize
// parameters sent to the identity provider.
ctxt.ProtocolMessage.RedirectUri = "https://example.org/signin-oidc";
await Task.Yield();
}
};
});
With that the redirect worked, but I entered a loop between the protected page and the AzureB2C login.
After a succesful login and a correct redirect to the signin-oidc controller (created by the Identity.Web package) I was correctly redirected again to the page that started all this authorization thing, but there it did not find the authorization. So I added/modded also this:
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
options.Secure = CookieSecurePolicy.Always;
});
With this the authorization worked, but I was not able to get the token to call the downstream API, before this redirect thing ITokenAcquisition worked, but now when trying to get the token it throws an exception.
So in my controller/service to get the token I modified and used:
var accessToken = await _contextAccessor.HttpContext
.GetTokenAsync(OpenIdConnectDefaults.AuthenticationScheme, "access_token");
So now with the token I add it to my HttpRequestMessage like this:
request.Headers.Add("Authorization", $"Bearer {accessToken}");
I lived on StackOverflow and microsoft docs for 3 days, I am not sure this is all "recommended" but this worked for me.
I had the same problem running an asp.net application under Google Cloud Run, which terminates the TLS connection. I was getting the error:
AADSTS50011: The reply URL specified in the request does not match the reply URLs configured for the application.
Using fiddler, I examined the request to login.microsoftonline.com and found that the query parameter redirect_uri exactly matched the url I'd configured in the application in Azure except that it started http rather than https.
I initially tried the other answers involving handling the OpenIdConnectEvents event and updating the redirect uri. This fixed the redirect_url parameter in the call to login.microsoftonline.com and it then worked until I added in the graph api. Then I found my site's signin-oidc page would give its own error about the redirect uri not matching. This would then cause it to go into a loop between my site and login.microsoftonline.com repeatedly trying to authenticate until eventually I'd get a login failure.
On further research ASP.net provides middleware to properly handle this scenario. Your SSL load balancer should add the standard header X-Forwarded-Proto with value HTTPS to the request. It should also send the X-Forwarded-For header with the originating IP address which could be useful for debugging, geoip etc.
In your ASP.net application, to configure the middleware:
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders =
ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
options.KnownNetworks.Clear();
options.KnownProxies.Clear();
});
Then enable the middleware:
app.UseForwardedHeaders();
Importantly, you must include this before the calls to app.UseAuthentication/app.UseAuthorization that depends on it.
Source: https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-5.0
If your load balancer doesn't add the X-Forwarded-Proto header and can't be configured to do so then the document above outlines other options.
I was facing with similar issue for 3 days. The below code helped me to get out of the issue.
string[] initialScopes = Configuration.GetValue<string>("CallApi:ScopeForAccessToken")?.Split(' ');
services.AddMicrosoftIdentityWebAppAuthentication(Configuration, "AzureAd")
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddInMemoryTokenCaches();
services.AddControllers();
services.AddRazorPages().AddMvcOptions(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser().Build();
options.Filters.Add(new AuthorizeFilter(policy));
}).AddMicrosoftIdentityUI();
services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.SaveTokens = true; // this saves the token for the downstream api
options.Events = new OpenIdConnectEvents
{
OnRedirectToIdentityProvider = async ctxt =>
{
ctxt.ProtocolMessage.RedirectUri = "https://example.org/signin-oidc";
await Task.Yield();
}
};
});

.Net Core 5 AddMicrosoftIdentityWebAppAuthentication, how to combine OpenId and Bearer now?

Porting from .NET Core 3 to .NET Core 5 Authentication, I am required to replace services.AddSignIn (deprecated) by services.AddMicrosoftIdentityWebAppAuthentication or other related MicrosoftIdentity extensions. I need to support both OpenId user login and Bearer token policies for API access. These both worked with services.AddSignIn but I can't get this combination working with the new MicrosftIdentity extensions.
I have a .Net Core Blazor Server with OpenId login to Azure AD B2C. This works fine as:
services.AddMicrosoftIdentityWebAppAuthentication(
configuration,
aadB2CConfigName,
OpenIdConnectDefaults.AuthenticationScheme,
CookieAuthenticationDefaults.AuthenticationScheme,
true);
But when I add the Bearer Token handling directly after it, as follows, then it overrides the OpenId, so only the Bearer API works (and vice versa):
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(
options =>
{
configuration.Bind("AzureAd", options);
options.ForwardDefaultSelector = ctx =>
ctx.Request.Path.StartsWithSegments("/api", System.StringComparison.InvariantCulture)
? JwtBearerDefaults.AuthenticationScheme
: null;
options.Authority = configuration["AzureAd:Authority"];
options.TokenValidationParameters.NameClaimType = "name";
options.TokenValidationParameters.RoleClaimType = "roles";
}, options =>
{
configuration.Bind(aadB2CConfigName, options);
});
For completeness, followed by (worked fine in .net core 3)
services.AddControllersWithViews()
.AddMicrosoftIdentityUI();
services.AddAuthorization(options =>
{
options.AddPolicy("Tst1AuthPolicy", policy => policy.RequireRole("Tst1AppRole"));
options.AddPolicy("Tst2AuthPolicy", policy => policy.RequireRole("Tst2AppRole"));
});
The chaining of extension methods does not seem to work as it did with AddSignIn. How do I make both of these work again in parallel in the new .net core 5 context? i.e. OpenId as default, and Bearer Tokens when the WebApi (/api) is hit.
Got it working as follows. I don't feel totally confident that this is the intended/best usage here, but it works:
Replace the above "null" as follows with the alternate login scheme, which is the oreo cookie scheme in our case:
options.ForwardDefaultSelector = ctx =>
ctx.Request.Path.StartsWithSegments("/api", System.StringComparison.InvariantCulture)
? JwtBearerDefaults.AuthenticationScheme
: CookieAuthenticationDefaults.AuthenticationScheme;
This will probably mean that, instead of a HTTP-Status error, I get a HTML login page if the Bearer Token fails, so there must be a better way ... if anybody cares to chime in.
Have you tried explicitly calling out the authentication scheme on the controllers?
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Microsoft.AspNetCore.Components.Route("api/[Controller]")]
[ApiController]
public class LoginController :ControllerBase
{
}

User is authenticated but where is the access token?

I have a web Application which authenticates a user to an Identity Server 4, using an implicit client. I need the access token for this user so that I can make a call to another API.
To be clear:
I have an identity Server. Created using Identity server 4.
I have the web app in question created in Asp .net core mvc.
API created in .net core.
The Web application authenticates the user against the identity server. Once they are authenticated we use bearer tokens to access the API.
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddAuthentication(options =>
{
options.DefaultScheme = "cookie";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("cookie")
.AddOpenIdConnect("oidc", options =>
{
options.Authority = Configuration["ServiceSettings:IdentityServerEndpoint"];
options.ClientId = "f91ece52-81cf-4b7b-a296-26356f50841f";
options.SignInScheme = "cookie";
});
The user is authenticating fine and i am able to access the controller below. I need an access token for this user so that i can make a request to another API.
[Authorize]
public async Task<IActionResult> Index(int clientId, string error)
{
ViewData["Title"] = "Secrets";
if (User.Identity.IsAuthenticated)
{
// All of the below attempts result in either null or empty array
var attempt1 = Request.Headers["Authorization"];
var attempt2 = await HttpContext.GetTokenAsync("access_token");
var attempt3 = _httpContextAccessor.HttpContext.Request.Headers["Authorization"];
var attempt4 = await _httpContextAccessor.HttpContext.GetTokenAsync("access_token");
}
return View();
}
The following does contain a header called cookie. Is there a way of getting the access token out of that?
var h = _httpContextAccessor.HttpContext.Request.Headers.ToList();
How can i find an access token for the current authenticated user? Using Implicit login.
Note on Hybrid vs implicit login: I cant use hybrid login due to the issue posted here Authentication limit extensive header size As i have not been able to find a solution to that problem a suggestion was to switch to an implicit login rather than hybrid. Implicit does not appear to create the giant cooking the hybrid did.
I have been following this to create the implicit client Getting started with Identityserver 4
By default the OpenID Connect middleware only requests an identity token (a response_type of id_token).
You'll need to first update your OpenIdConnectOptions with the following:
options.ResponseType = "id_token token";
You can then save the tokens to your cookie using:
options.SaveTokens = true;
And then finally, you can access the token using:
await HttpContext.GetTokenAsync("access_token");
Note that you will also need to set the AllowAccessTokensViaBrowser flag in your IdentityServer client configuration when using the implicit flow.
Use options.SaveTokens = true
then grab your access token from the claims or use HttpContext.GetTokenAsync
here's the link to the blogpost with example: https://www.jerriepelser.com/blog/accessing-tokens-aspnet-core-2/
I solved using the IHttpContextAccessor:
var token = _accessor.HttpContext.Request.Headers["Authorization"];
return token.ToString().Replace("Bearer ", string.Empty);

Swashbuckle.AspNetCore v1.0.0 with OAuth2, flow : application -> IdentityServer4

I can't seem to make my .net core web API work with swashbuckle, OAuth2 with an application flow. When I click the Authorize button, Fiddler shows that the call is OK and my local IdentityServer(4) replies with an access_token. That's all great and all but I don't think Swagger picks this up, there's nothing happening and I can't trigger my controller methods without getting a 401. I see no cookies, nothing. I'm sure I'm missing something super trivial. Can someone help me out?
Relevant code :
ConfigureServices in Startup.cs
c.AddSecurityDefinition("oauth2", new OAuth2Scheme
{
Type = "oauth2",
Flow = "application",
TokenUrl = "http://localhost:61798/connect/token",
Scopes = new Dictionary<string, string>
{
{ "readAccess", "Access read operations" },
{ "writeAccess", "Access write operations" }
}
});
Configure in Startup.cs
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = "http://localhost:61798",
RequireHttpsMetadata = false,
ApiName = "api1",
AutomaticAuthenticate = true, //Doesn't change anything...
});
....
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs");
c.ConfigureOAuth2("Swagger", "swaggersecret", "swaggerrealm", "Swagger UI");
});
My IdentityServer is configured OK. I can call this API in Postman and a simple client without any problem. My only problem is Swagger (Swashbuckle.AspNetCore 1.0.0).
We have a very similar setup for a current project. Our rest api is secured with jwt bearer authentication and azure ad b2c. In this case there is no way swagger to pick up automatically the token.
This solution works perfect for us: https://stackoverflow.com/a/39759152/536196
services.AddSwaggerGen(c =>
{
c.OperationFilter<AuthorizationHeaderParameterOperationFilter>();
});
After that when you run your swagger UI, you should see an additional field for the token.

Configure the authorization server endpoint

Question
How do we use a bearer token with ASP.NET 5 using a username and password flow? For our scenario, we want to let a user register and login using AJAX calls without needing to use an external login.
To do this, we need to have an authorization server endpoint. In the previous versions of ASP.NET we would do the following and then login at the ourdomain.com/Token URL.
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14)
};
In the current version of ASP.NET, though, the above doesn't work. We've been trying to figure out the new approach. aspnet/identity example on GitHub, for instance, configures Facebook, Google, and Twitter authentication but does not appear to configure a non-external OAuth authorization server endpoint, unless that's what AddDefaultTokenProviders() does, in which case we're wondering what the URL to the provider would be.
Research
We've learned from reading the source here that we can add "bearer authentication middleware" to the HTTP pipeline by calling IAppBuilder.UseOAuthBearerAuthentication in our Startup class. This is a good start though we're still not sure of how to set its token endpoint. This didn't work:
public void Configure(IApplicationBuilder app)
{
app.UseOAuthBearerAuthentication(options =>
{
options.MetadataAddress = "meta";
});
// if this isn't here, we just get a 404
app.Run(async context =>
{
await context.Response.WriteAsync("Hello World.");
});
}
On going to ourdomain.com/meta we just receive our hello world page.
Further research showed that we can also use the IAppBuilder.UseOAuthAuthentication extension method, and that it takes a OAuthAuthenticationOptions parameter. That parameter has a TokenEndpoint property. So though we're not sure what we're doing, we tried this, which of course didn't work.
public void Configure(IApplicationBuilder app)
{
app.UseOAuthAuthentication("What is this?", options =>
{
options.TokenEndpoint = "/token";
options.AuthorizationEndpoint = "/oauth";
options.ClientId = "What is this?";
options.ClientSecret = "What is this?";
options.SignInScheme = "What is this?";
options.AutomaticAuthentication = true;
});
// if this isn't here, we just get a 404
app.Run(async context =>
{
await context.Response.WriteAsync("Hello World.");
});
}
In other words, in going to ourdomain.com/token, there is no error there is just again our hello world page.
EDIT (01/28/2021): AspNet.Security.OpenIdConnect.Server has been merged into OpenIddict as part of the 3.0 update. To get started with OpenIddict, visit documentation.openiddict.com.
Okay, let's recap the different OAuth2 middleware (and their respective IAppBuilder extensions) that were offered by OWIN/Katana 3 and the ones that will be ported to ASP.NET Core:
app.UseOAuthBearerAuthentication/OAuthBearerAuthenticationMiddleware: its name was not terribly obvious, but it was (and still is, as it has been ported to ASP.NET Core) responsible for validating access tokens issued by the OAuth2 server middleware. It's basically the token counterpart of the cookies middleware and is used to protect your APIs. In ASP.NET Core, it has been enriched with optional OpenID Connect features (it is now able to automatically retrieve the signing certificate from the OpenID Connect server that issued the tokens).
Note: starting with ASP.NET Core beta8, it is now namedapp.UseJwtBearerAuthentication/JwtBearerAuthenticationMiddleware.
app.UseOAuthAuthorizationServer/OAuthAuthorizationServerMiddleware: as the name suggests, OAuthAuthorizationServerMiddleware was an OAuth2 authorization server middleware and was used to create and issue access tokens. This middleware won't be ported to ASP.NET Core: OAuth Authorization Service in ASP.NET Core.
app.UseOAuthBearerTokens: this extension didn't really correspond to a middleware and was simply a wrapper around app.UseOAuthAuthorizationServer and app.UseOAuthBearerAuthentication. It was part of the ASP.NET Identity package and was just a convenient way to configure both the OAuth2 authorization server and the OAuth2 bearer middleware used to validate access tokens in a single call. It won't be ported to ASP.NET Core.
ASP.NET Core will offer a whole new middleware (and I'm proud to say I designed it):
app.UseOAuthAuthentication/OAuthAuthenticationMiddleware: this new middleware is a generic OAuth2 interactive client that behaves exactly like app.UseFacebookAuthentication or app.UseGoogleAuthentication but that supports virtually any standard OAuth2 provider, including yours. Google, Facebook and Microsoft providers have all been updated to inherit from this new base middleware.
So, the middleware you're actually looking for is the OAuth2 authorization server middleware, aka OAuthAuthorizationServerMiddleware.
Though it is considered as an essential component by a large part of the community, it won't be ported to ASP.NET Core.
Luckily, there's already a direct replacement: AspNet.Security.OpenIdConnect.Server (https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server)
This middleware is an advanced fork of the OAuth2 authorization server middleware that comes with Katana 3 but that targets OpenID Connect (which is itself based on OAuth2). It uses the same low-level approach that offers a fine-grained control (via various notifications) and allows you to use your own framework (Nancy, ASP.NET Core MVC) to serve your authorization pages like you could with the OAuth2 server middleware. Configuring it is easy:
ASP.NET Core 1.x:
// Add a new middleware validating access tokens issued by the server.
app.UseOAuthValidation();
// Add a new middleware issuing tokens.
app.UseOpenIdConnectServer(options =>
{
options.TokenEndpointPath = "/connect/token";
// Create your own `OpenIdConnectServerProvider` and override
// ValidateTokenRequest/HandleTokenRequest to support the resource
// owner password flow exactly like you did with the OAuth2 middleware.
options.Provider = new AuthorizationProvider();
});
ASP.NET Core 2.x:
// Add a new middleware validating access tokens issued by the server.
services.AddAuthentication()
.AddOAuthValidation()
// Add a new middleware issuing tokens.
.AddOpenIdConnectServer(options =>
{
options.TokenEndpointPath = "/connect/token";
// Create your own `OpenIdConnectServerProvider` and override
// ValidateTokenRequest/HandleTokenRequest to support the resource
// owner password flow exactly like you did with the OAuth2 middleware.
options.Provider = new AuthorizationProvider();
});
There's an OWIN/Katana 3 version, and an ASP.NET Core version that supports both .NET Desktop and .NET Core.
Don't hesitate to give the Postman sample a try to understand how it works. I'd recommend reading the associated blog post, that explains how you can implement the resource owner password flow.
Feel free to ping me if you still need help.
Good luck!
With #Pinpoint's help, we've wired together the rudiments of an answer. It shows how the components wire together without being a complete solution.
Fiddler Demo
With our rudimentary project setup, we were able to make the following request and response in Fiddler.
Request
POST http://localhost:50000/connect/token HTTP/1.1
User-Agent: Fiddler
Host: localhost:50000
Content-Length: 61
Content-Type: application/x-www-form-urlencoded
grant_type=password&username=my_username&password=my_password
Response
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 1687
Content-Type: application/json;charset=UTF-8
Expires: -1
X-Powered-By: ASP.NET
Date: Tue, 16 Jun 2015 01:24:42 GMT
{
"access_token" : "eyJ0eXAiOi ... 5UVACg",
"expires_in" : 3600,
"token_type" : "bearer"
}
The response provides a bearer token that we can use to gain access to the secure part of the app.
Project Structure
This is the structure of our project in Visual Studio. We had to set its Properties > Debug > Port to 50000 so that it acts as the identity server that we configured. Here are the relevant files:
ResourceOwnerPasswordFlow
Providers
AuthorizationProvider.cs
project.json
Startup.cs
Startup.cs
For readability, I've split the Startup class into two partials.
Startup.ConfigureServices
For the very basics, we only need AddAuthentication().
public partial class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication();
}
}
Startup.Configure
public partial class Startup
{
public void Configure(IApplicationBuilder app)
{
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();
// Add a new middleware validating access tokens issued by the server.
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
Audience = "resource_server_1",
Authority = "http://localhost:50000/",
RequireHttpsMetadata = false
});
// Add a new middleware issuing tokens.
app.UseOpenIdConnectServer(options =>
{
// Disable the HTTPS requirement.
options.AllowInsecureHttp = true;
// Enable the token endpoint.
options.TokenEndpointPath = "/connect/token";
options.Provider = new AuthorizationProvider();
// Force the OpenID Connect server middleware to use JWT
// instead of the default opaque/encrypted format.
options.AccessTokenHandler = new JwtSecurityTokenHandler
{
InboundClaimTypeMap = new Dictionary<string, string>(),
OutboundClaimTypeMap = new Dictionary<string, string>()
};
// Register an ephemeral signing key, used to protect the JWT tokens.
// On production, you'd likely prefer using a signing certificate.
options.SigningCredentials.AddEphemeralKey();
});
app.UseMvc();
app.Run(async context =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}
AuthorizationProvider.cs
public sealed class AuthorizationProvider : OpenIdConnectServerProvider
{
public override Task ValidateTokenRequest(ValidateTokenRequestContext context)
{
// Reject the token requests that don't use
// grant_type=password or grant_type=refresh_token.
if (!context.Request.IsPasswordGrantType() &&
!context.Request.IsRefreshTokenGrantType())
{
context.Reject(
error: OpenIdConnectConstants.Errors.UnsupportedGrantType,
description: "Only grant_type=password and refresh_token " +
"requests are accepted by this server.");
return Task.FromResult(0);
}
// Since there's only one application and since it's a public client
// (i.e a client that cannot keep its credentials private), call Skip()
// to inform the server that the request should be accepted without
// enforcing client authentication.
context.Skip();
return Task.FromResult(0);
}
public override Task HandleTokenRequest(HandleTokenRequestContext context)
{
// Only handle grant_type=password token requests and let the
// OpenID Connect server middleware handle the other grant types.
if (context.Request.IsPasswordGrantType())
{
// Validate the credentials here (e.g using ASP.NET Core Identity).
// You can call Reject() with an error code/description to reject
// the request and return a message to the caller.
var identity = new ClaimsIdentity(context.Options.AuthenticationScheme);
identity.AddClaim(OpenIdConnectConstants.Claims.Subject, "[unique identifier]");
// By default, claims are not serialized in the access and identity tokens.
// Use the overload taking a "destinations" parameter to make sure
// your claims are correctly serialized in the appropriate tokens.
identity.AddClaim("urn:customclaim", "value",
OpenIdConnectConstants.Destinations.AccessToken,
OpenIdConnectConstants.Destinations.IdentityToken);
var ticket = new AuthenticationTicket(
new ClaimsPrincipal(identity),
new AuthenticationProperties(),
context.Options.AuthenticationScheme);
// Call SetResources with the list of resource servers
// the access token should be issued for.
ticket.SetResources("resource_server_1");
// Call SetScopes with the list of scopes you want to grant
// (specify offline_access to issue a refresh token).
ticket.SetScopes("profile", "offline_access");
context.Validate(ticket);
}
return Task.FromResult(0);
}
}
project.json
{
"dependencies": {
"AspNet.Security.OpenIdConnect.Server": "1.0.0",
"Microsoft.AspNetCore.Authentication.JwtBearer": "1.0.0",
"Microsoft.AspNetCore.Mvc": "1.0.0",
}
// other code omitted
}

Categories