无法使用asp.net核心实施授权

时间:2020-01-03 18:49:26

标签: c# asp.net-core asp-net-mvc-1

我正在使用asp.net core 2.2。我使用Visual Studio 2019创建了一个空的Web应用程序。我将此代码添加到了Startup.cs的configure services方法中:

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

所以我的方法如下:

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>();
    }

我希望这会使整个应用程序都需要授权,但是,如果我使用任何控制器和操作,我都可以直接查看而无需登录。我是否需要做任何额外的事情来配置或强制执行?

我试图在类本身上添加[Authorize]属性。这是我的控制器开头的样子:

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;
        }

.
.
.

我还需要做什么来强制页面要求登录/授权?

1 个答案:

答案 0 :(得分:1)

我认为您还需要更新启动中的Configure方法以启用授权。尝试添加此内容:

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

NuGet package required

相关问题