Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC-6 vs MVC-5 BearerAuthentication in Web API

I have a Web API project that use UseJwtBearerAuthentication to my identity server. Config method in startup looks like this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseJwtBearerAuthentication(options =>
    {
        options.AutomaticAuthentication = true;
        options.Authority = "http://localhost:54540/";
        options.Audience = "http://localhost:54540/";
    });

    // Configure the HTTP request pipeline.
    app.UseStaticFiles();

    // Add MVC to the request pipeline.
    app.UseMvc();
}

This is working, and I want to do the same thing in an MVC5 project. I tried to do something like this:

Web api:

public class SecuredController : ApiController
    {
            [HttpGet]
            [Authorize]
            public IEnumerable<Tuple<string, string>> Get()
            {
                var claimsList = new List<Tuple<string, string>>();
                var identity = (ClaimsIdentity)User.Identity;
                foreach (var claim in identity.Claims)
                {
                    claimsList.Add(new Tuple<string, string>(claim.Type, claim.Value));
                }
                claimsList.Add(new Tuple<string, string>("aaa", "bbb"));

                return claimsList;
            }
}

I can't call web api if is set attribute [authorized] (If I remove this than it is working)

I created Startup. This code is never called and I don't know what to change to make it work.

[assembly: OwinStartup(typeof(ProAuth.Mvc5WebApi.Startup))]
namespace ProAuth.Mvc5WebApi
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureOAuth(app);
            HttpConfiguration config = new HttpConfiguration();
            WebApiConfig.Register(config);
            app.UseWebApi(config);
        }

        public void ConfigureOAuth(IAppBuilder app)
        {
            Uri uri= new Uri("http://localhost:54540/");
            PathString path= PathString.FromUriComponent(uri);

            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = path,
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationServerProvider()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

        }

    }

    public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

            context.Validated(identity);

        }
    }

}

goal is to return claims from web api to client app. using Bearer Authentication.
Thanks for help.

like image 341
Raskolnikov Avatar asked Sep 15 '15 08:09

Raskolnikov


1 Answers

TL;DR: you can't.

Authority refers to an OpenID Connect feature that has been added to the bearer middleware in ASP.NET 5: there's no such thing in the OWIN/Katana version.

Note: there's an app.UseJwtBearerAuthentication extension for Katana, but unlike its ASP.NET 5 equivalent, it doesn't use any OpenID Connect feature and must be configured manually: you'll have to provide the issuer name and the certificate used to verify tokens' signatures: https://github.com/jchannon/katanaproject/blob/master/src/Microsoft.Owin.Security.Jwt/JwtBearerAuthenticationExtensions.cs

like image 65
Kévin Chalet Avatar answered Oct 25 '22 00:10

Kévin Chalet