我正在使用 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;
}
.
.
.
我还需要做什么来强制页面要求登录/授权?