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.

1

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.