1

I added the [Authorize(Roles="CompanyRole")] annotation to my controller action, and in the Startup class I have:

app.Use(async (context, next) =>
        {
            if(context.Session.GetString("user") != null)
            {
                var tk = JsonConvert.DeserializeObject<UserModel>(context.Session.GetString("user"));
                if (!String.IsNullOrEmpty(tk.Token))
                {
                    context.Request.Headers.Add("Authorization", "Bearer " + tk.Token);
                }
                await next.Invoke();
            }
            else
            {
                context.Request.Path = "/Home/Login";
                await next.Invoke();
            }
        });

If I remove the Authorize attribute, I'm able to get the user information and all the claims using

 var A = User.Identity.Name;

And one of the roles is CompanyRole, but I get an "Unauthorized" when I tried to execute that controller action.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Nathiel Paulino
  • 534
  • 6
  • 17

1 Answers1

1

You should consider middleware's priority and register yours before authorization middleware in Startup.cs file.

app.Use(async (context, next) =>
    {
        if(context.Session.GetString("user") != null)
        {
            var tk = JsonConvert.DeserializeObject<UserModel>(context.Session.GetString("user"));
            if (!String.IsNullOrEmpty(tk.Token))
            {
                context.Request.Headers.Add("Authorization", "Bearer " + tk.Token);
            }
            await next.Invoke();
        }
        else
        {
            context.Request.Path = "/Home/Login";
            await next.Invoke();
        }

    });
app.UseAuthorization();
Mehrdad
  • 1,523
  • 9
  • 23