Skip to content

OAuth 2.0 Bearer Token authentication #5717

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
alexjusti opened this issue Jun 23, 2015 · 24 comments
Closed

OAuth 2.0 Bearer Token authentication #5717

alexjusti opened this issue Jun 23, 2015 · 24 comments
Assignees
Labels
area-identity Includes: Identity and providers feature-identity-service
Milestone

Comments

@alexjusti
Copy link

I've been doing some digging, and I can't find anything regarding ASP.Net 5 and OAuth token based authentication. Is this a planned feature for a later release, or am I missing something?

@rustd
Copy link

rustd commented Jun 29, 2015

@danroth27 ?

@alexjusti
Copy link
Author

I want to use Json Web Tokens to create a REST API. From what I understand, ASP.Net 5 doesn't support JWT. Is it a planned feature?

@kevinchalet
Copy link
Contributor

You might be interested in this SO post: http://stackoverflow.com/questions/31007470/does-asp-net-mvc6-support-oauth-2-bearer-tokens/31093557#31093557


TL;DR: the official packages developed by Microsoft for ASP.NET 5 only support OAuth2 bearer token validation.

This means that...

  1. ... you'll be able to authenticate your users using bearer tokens issued by an external identity provider (like Azure Active Directory) with the Microsoft.AspNet.Authentication.OAuthBearer package:

    app.UseOAuthBearerAuthentication(options => {
        options.AutomaticAuthentication = true;
        options.Audience = "http://localhost:50000/";
    
        // Authority is only useful if your JWT tokens
        // are issued by an OpenID Connect server.
        options.Authority = "[OpenID Connect provider address]";
    
    
        // If you don't use an OpenID Connect server, you have to manually update the
        // token validation parameters with the issuer's signing key.
        options.TokenValidationParameters.IssuerSigningKey = new X509SecurityKey(certificate);
    });
    

That said, only JWT tokens are now supported OTB: the OAuth2 bearer middleware shipped with Katana 3 used to natively support opaque tokens produced by the OAuth2 authorization server, but this support has been removed.

  1. ... you won't be able produce your own tokens anymore. The OAuth2 authorization server has been removed and won't be ported to ASP.NET 5: http://stackoverflow.com/questions/29055477/oauth-authorization-service-in-asp-net-mvc-6/.

Luckily, alternatives exist. I'm personally developing an OpenID Connect server middleware based on the OAuth2 server shipped with Katana, that offers the same low-level experience: https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server

For more information, you can take a look at this SO answer: http://stackoverflow.com/questions/30768015/configure-the-authorization-server-endpoint/30788109#30788109

@stephenstroud
Copy link

+1 - #495 Would be nice to have a identity sample template using OpenIdConnectServer and JWT tokens.

@kevinchalet
Copy link
Contributor

I'd be happy to collaborate with someone from the Identity team to create a template 👍

@larsfjerm
Copy link

Any updates on this? #495

@kevinchalet
Copy link
Contributor

No update from MSFT, but you can read these two blog posts about OpenIddict, a new easy-to-use OpenID Connect server for vNext that uses ASP.NET Identity 3 and AspNet.Security.OpenIdConnect.Server:

http://capesean.co.za/blog/asp-net-5-jwt-tokens/
http://overengineer.net/Using-OpenIddict-to-easily-add-token-authentication-to-your-.NET-web-apps/

@leastprivilege
Copy link
Contributor

@danroth27
Copy link
Member

@leastprivilege Nice!

@MaximRouiller
Copy link

Congrats @leastprivilege for the announcement!

@leak
Copy link

leak commented Jan 12, 2016

What I am really missing is a very simple solution to replace cookie authentication with bearer tokens.

The OpenIdict examples above are going in the right direction, sadly the first is broken at the moment and the second one is, even as the folder structure itself claims, "Overengineered" (Multi-project approach, dedicated authentication server).

What I am really looking for is a basic drop in the replacment for cookie authentication that adheres to the OpenId connect standard.

  • No standalone server, it should live on the same webserver for example at /api/openidconnect/
  • No CORS of any sort should be required (since we're living on the same webserver)
  • No 3rd party oauth endpoint integration, google, fb, etc. (for now at least, it should be simple at the start)
  • Asp.Identity integration
  • Persistence integration (preferably EF)
  • Maybe recommendation for a JS Client lib that uses the the provided oidc endpoints and takes care of things like refresh tokens, login and logoff (In my case preferably for AngularJs)
  • Authentication integration with the rest of the applications WebApi methods similar to cookie auth

Special requirement from my end: Since I'm planning on doing a pure AngularJs + WebApi application, I would like the authentication (including forms, etc.) do be done with angular, so basically no MVC stuff should be required for auth.

From what I've read and understand most of these things are actually supported by the projects mentioned above.

Yet I haven't found any working example that provided a decent out of the box experience and kept the whole authentication mechanics and wiring to a bear minimum as described above.

@kevinchalet
Copy link
Contributor

The OpenIdict examples above are going in the right direction, sadly the first is broken at the moment.

@leak if you're still experiencing issues with the OpenIddict nightly builds, feel free to open a new ticket or ping me on JabbR (https://jabbr.net/#/rooms/AspNetvNext) 👏

@larsfjerm
Copy link

@leak I got it working using the first article (http://capesean.co.za/blog/asp-net-5-jwt-tokens/).

@leak
Copy link

leak commented Jan 12, 2016

Ok, after a bit of fiddling i got the example running. (No OpenIddict issue)

One question remains:

As far as i understand OpenIddict was created to get IdentityServer to play nice with ASP.Net 5, now that IdentityServer4 was announced it would be nice if you guys (@PinpointTownes, @leastprivilege) could ellaborate a bit what your future plans are.
Keep two seperate implementations? Merge? Make it an official ASP.Net part (if that is even possible)?

@brockallen
Copy link

As far as i understand OpenIddict was created to get IdentityServer to play nice with ASP.Net 5

They are two different and unrelated OIDC implementations.

As for your original issue -- if all you want is a Web API from your JS, then use cookies with an anti-forgery token. Microsoft is providing samples and support for that.

@leak
Copy link

leak commented Jan 12, 2016

They are two different and unrelated OIDC implementations.

True, my bad, got "OpenIdConnect.Server" mixed up. Still the question remains about the future and their particular goals.

@kevinchalet
Copy link
Contributor

As far as i understand OpenIddict was created to get IdentityServer to play nice with ASP.Net 5, now that IdentityServer4 was announced it would be nice if you guys (@PinpointTownes, @leastprivilege) could ellaborate a bit what your future plans are.

As mentioned by @brockallen, ASOS, OpenIddict and IdentityServer are different stacks (though OpenIddict is based on ASOS):

  • ASOS is inspired from OAuthAuthorizationServerMiddleware and can be seen as an OIDC server framework offering you full flexibility, while IdSrv is rather a ready-to-use server/turnkey solution (that comes with membership abstractions, CORS support, management APIs).
  • OpenIddict was created for people who found existing projects too complex to set up (/cc @Bartmax), not to compete with nor make IdSrv play nicely with vNext 😄

That said, I read IdSrv4's announcement and it's nice to see that @leastprivilege and @brockallen radically changed their minds about the way it integrates with the rest of the world (relying on Web API was a terrible idea and prevented tons of interesting scenarios in IdSrv3).

Keep two seperate implementations? Merge? Make it an official ASP.Net part (if that is even possible)?

There's no plan to merge or abandon anything at this point (and AFAIK, the ASP.NET team is far too busy to directly contribute IdSrv4 or ASOS 😄)

@primico
Copy link

primico commented Jun 17, 2016

Hi PinpointTownes,
I am working on an ASP .NET 5 Web API app with Azure B2C. I notice UseOAuthBearerAuthentication is not available in IApplicationBuilder. Is it not supported anymore? I see UseJwtBearerAuthentication is available. I've tried the following to protect my Web API using the following code:

            app.UseJwtBearerAuthentication(options =>
            {
                options.AutomaticAuthenticate = false;
                options.AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme;
                options.Audience = "My-B2C-App-Guid";
                options.Authority = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}/{1}", policySettings.Value.AadInstance, policySettings.Value.Tenant);
            });

I get my token and add to header, with the following code:

                string token = await new AuthHelper().AcquireTokenAsync();
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(Settings.ApiUrl);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                    using (HttpResponseMessage response = await client.GetAsync("api/customers"))
                    {
                        response.EnsureSuccessStatusCode();
                        using (HttpContent content = response.Content)
                        {
                            string result = await content.ReadAsStringAsync();
                            return result != null ? JsonConvert.DeserializeObject<ObservableCollection<Customer>>(result) : null;
                        }
                    }
                }

I protect my controller with:

[Authorize]

However I always get Unauthorized. Any recommendations?

Thank you so much if you have time to respond!!!

@kevinchalet
Copy link
Contributor

Is it not supported anymore?

It was renamed/replaced by the JWT bearer middleware.

Any recommendations?

Have you tried to enable logging?

@primico
Copy link

primico commented Jun 17, 2016

No I haven't enabled logging. I will try and see what I get.

I have a web app that I am using UseOpenIdConnectAuthentication and I protect my controllers using an ActionFilterAttribute, like this:

[PolicyAuthorize(Policy = "B2C_1_mypolicy", RedirectUri = "/admin/customer")]

And it seems to work (with the exception of a few bugs that might be related to B2C being in preview)

If I can figure out how to get the JWT authentication working in my Web API project, would I do something similar to check specific policies and/or roles?

@kevinchalet
Copy link
Contributor

I have no idea what [PolicyAuthorize] does (it's likely an Azure AD/B2C-specific thing). You should probably ping someone from the Azure AD team.

@primico
Copy link

primico commented Jun 17, 2016

I have asked on Azure forums and support tickets, but I either get no response, or they refer me to old code samples that don't work with the latest .NET framework. It makes me wonder if they are serious with the B2C service and if it will ever get out of preview mode. Anyway, thanks so much for responding. I'll enable logging and see if I can get this figured out.
Take care!!

@aspnet-hello aspnet-hello transferred this issue from aspnet/Identity Dec 18, 2018
@aspnet-hello aspnet-hello assigned danroth27 and unassigned danroth27 Dec 18, 2018
@aspnet-hello aspnet-hello added this to the Backlog milestone Dec 18, 2018
@danroth27
Copy link
Member

We now have support for using IdentityServer with ASP.NET Core 3.0 which I believe covers this scenario: https://docs.microsoft.com/aspnet/core/security/authentication/identity-api-authorization

@BKlippel
Copy link

A day late and a dollar short.

@ghost ghost locked as resolved and limited conversation to collaborators Dec 4, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
area-identity Includes: Identity and providers feature-identity-service
Projects
None yet
Development

No branches or pull requests