简体   繁体   中英

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?

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 包

而不是[Authorize] ,使用以下属性:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM