0

I am facing an issue with Jwt Authentication.

I have an ASP.NET Core 2 WepApi which also serves my SPA App (Its a Vue-App) The SPA App gets the Token from Azure B2C via the MSAL.js library from Microsoft.

When i hit the WebApi where i need to Authorize i get the following error:

info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[1]
      Failed to validate the token [MyTokenHere]
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.<HandleAuthenticateAsync>d__6.MoveNext()
info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[7]
      Bearer was not authenticated. Failure message: IDX10500: Signature validation failed. No security keys were provided to validate the signature.

In the browser i get a 401

GET http://localhost:51420/api/values 401 (Unauthorized)

I face the very same issue with the sample Application provided here An ASP.NET Core web API with Azure AD B2C (with their tanant)

Here is my Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using VueTemplate.SignalR;

namespace VueTemplate
{
    public class Startup
    {
        public string Authority { get; set; } = "https://login.microsoftonline.com/tfp/[MyB2CTenant]/[MyPolicy]/v2.0/";

        public string ClientId { get; set; } = [MyApplicationId];


        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddSignalR();
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options => new JwtBearerOptions() {
                Authority = Authority,
                Audience = ClientId,
                Events = new JwtBearerEvents() { OnAuthenticationFailed = AuthenticationFailed,  }
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions() {
                    HotModuleReplacement = true
                });
            }
            else {
                app.UseExceptionHandler("/Home/Error"); // TODO Create Error page
            }

            app.UseAuthentication();

            app.UseStaticFiles();

            app.UseSignalR(routes => {
                routes.MapHub<ChatHub>("Hub/Chat");
            });

            app.UseMvc(routes => {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}"
                );

                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" }
                );
            });
        }

        private Task AuthenticationFailed(AuthenticationFailedContext arg)
        {
            // For debugging purposes only!
            var s = $"AuthenticationFailed: {arg.Exception.Message}";
            arg.Response.ContentLength = s.Length;
            arg.Response.Body.Write(Encoding.UTF8.GetBytes(s), 0, s.Length);
            return Task.FromResult(0);
        }
    }
}

ValuesController.cs

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace VueTemplate.Controllers
{
    [Authorize]
    [Route("api/[controller]/")]
    public class ValuesController : Controller
    {
        [HttpGet]
        public IActionResult Get() {
            return Ok(new int[] { 1, 2, 3, 4 });
        }
    }
}

Any thoughts? Do i have to provide a security key? Where do i find it in Azure B2C?

VSDekar
  • 1,741
  • 2
  • 21
  • 36
  • Have you tried this [sample](https://github.com/Azure-Samples/active-directory-b2c-dotnetcore-webapi/blob/master/B2C-WebApi/Startup.cs#LC52)? I wonder if you can get your SPA working w/ that backend sample. – spottedmahn Oct 04 '17 at 13:02
  • Yes i have tried this example. I have already refered to it in my question. I am not able to get the sample working with or without my SPA. Does the sample work for you? – VSDekar Oct 04 '17 at 13:06
  • You do not have to provide a security key. The library gets the key dynamically and performs the validation. [Reference 1](https://stackoverflow.com/questions/45623178/wheres-the-key-for-my-azure-ad-b2c-token). [Reference 2 - Token Validation](https://learn.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-reference-tokens#token-validation) – spottedmahn Oct 04 '17 at 13:08
  • Oops, my bad. I see that now. Let me try it out myself. – spottedmahn Oct 04 '17 at 13:09
  • Be sure to take the 2.0 Version. There are 2 branches. I really appreciate that you would try it yourself! – VSDekar Oct 04 '17 at 13:11
  • Just reviewed my notes and yes I got the [msal sample](https://github.com/Azure-Samples/active-directory-b2c-javascript-msal-singlepageapp) working w/ the Asp.Net core 1.1 version. Let me try the 2.0 branch... – spottedmahn Oct 04 '17 at 13:18
  • Upon further review, I got the spa sample working w/ the [node back end sample](https://github.com/Azure-Samples/active-directory-b2c-javascript-nodejs-webapi). I will need asp.net core backend shortly though. Will keep digging... – spottedmahn Oct 04 '17 at 14:32
  • Thx for digging. I am not sure anymore which one i have tried. Some work (I think all the 1.1 versions an node.js) and some not. (Maybe all the 2.0 versions) – VSDekar Oct 04 '17 at 14:37
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/155959/discussion-between-spottedmahn-and-vergall). – spottedmahn Oct 04 '17 at 18:22

1 Answers1

3

I have found a solution to my problem.

The correct way to configure the AddJwtBearer() method is to use the options object which is already provided and not to create a new one.

Bad:

.AddJwtBearer(option => new JwtBearerOptions // <--- Evil 
                {
                    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
                    },
                });

Good:

.AddJwtBearer(options => {
                    options.Authority = string.Format("https://login.microsoftonline.com/tfp/{0}/{1}/v2.0/", Configuration["Authentication:AzureAd:Tenant"], Configuration["Authentication:AzureAd:Policy"]);
                    options.Audience = Configuration["Authentication:AzureAd:ClientId"];
                    options.Events = new JwtBearerEvents {
                        OnAuthenticationFailed = AuthenticationFailed
                    };
                });
VSDekar
  • 1,741
  • 2
  • 21
  • 36