B1B
B1B

Reputation: 303

Unable to implement authorization with asp.net core

I am using asp.net core 2.2. I created an empty web application using Visual Studio 2019. I added this code in Startup.cs, in the configure services method:

    services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});

So my method looks like this:

public void ConfigureServices(IServiceCollection services)
    {

        services.AddDbContextPool<AppDBContext>(options => options.UseSqlServer(_config.GetConnectionString("EmployeeDBConnection")));

        services.AddIdentity<IdentityUser, IdentityRole>(options =>
        {
            options.Password.RequiredLength = 10;
            options.Password.RequiredUniqueChars = 3;
            options.Password.RequireNonAlphanumeric = false;
        }).AddEntityFrameworkStores<AppDBContext>();



        services.AddMvc(config =>
        {
            var policy = new AuthorizationPolicyBuilder()
                        .RequireAuthenticatedUser()
                        .Build();

            config.Filters.Add(new AuthorizeFilter(policy));
        });

        //services.AddMvc();
        services.AddScoped<IEmployeeRepository, SQLEmployeeRepository>();
    }

I expected this to make the whole application require authorization, however if I go to any controller and action, I can just view that without signing in. Do I need to do anything extra to configure this or force it?

I tried to add the [Authorize] attribute on the class itself. Here's how the beginning of my controller looks like:

using System.Threading.Tasks;
using EmployeeManagement.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc; 
namespace EmployeeManagement.Controllers
{
    [Authorize]
    public class AccountController : Controller
    {
        private readonly UserManager<IdentityUser> userManager;
        private readonly SignInManager<IdentityUser> signInManager;

        public AccountController(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager)
        {
            this.userManager = userManager;
            this.signInManager = signInManager;
        }

.
.
.

What else do I need to do to force pages to require login/authorization?

Upvotes: 1

Views: 4456

Answers (2)

Hasan Mhd Amin
Hasan Mhd Amin

Reputation: 417

Instead of [Authorize], use the following Attribute:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

Upvotes: 0

Chad W
Chad W

Reputation: 11

I think you also need to update the Configure method in the Startup as well to enable authorization. Try adding this:

    public void Configure(IApplicationBuilder app)
    {
        app.UseAuthorization();
    }

NuGet package required

Upvotes: 1

Related Questions