1

我正在使用 asp.net 核心 2.2。我使用 Visual Studio 2019 创建了一个空的 Web 应用程序。我在 Startup.cs 的配置服务方法中添加了此代码:

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

.
.
.

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

4

2 回答 2

1

我认为您还需要更新 Startup 中的 Configure 方法以启用授权。尝试添加这个:

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

需要 NuGet 包

于 2020-01-03T19:10:05.783 回答
0

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

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
于 2021-11-03T10:43:07.607 回答