簡體   English   中英

在ASP.NET Core中使用Cookie進行身份驗證

[英]Authentication with Cookies in ASP.NET Core

我正在努力使用CookieAuthentication對我的.net核心站點的當前用戶進行身份驗證。 登錄后我沒有被重定向到任何網址,我仍然在登錄表單上。 調試時,我可以看到我的用戶仍然沒有通過身份驗證,如果我導航到我的“authtorized”控制器,我會得到'302 found'(?)。

我在startup.cs中進行了以下設置。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = ctx =>
                {
                    const int durationInSeconds = 60 * 60 * 24;
                    ctx.Context.Response.Headers[HeaderNames.CacheControl] =
                        "public,max-age=" + durationInSeconds;
                }
            });
            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationScheme = "myCustomScheme",
                LoginPath = new PathString("/Account/Unauthorized/"),
                AccessDeniedPath = new PathString("/Account/Forbidden/"),
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                CookieSecure = env.IsDevelopment() ? CookieSecurePolicy.SameAsRequest : CookieSecurePolicy.Always
            });
            app.UseMvc(routes =>
            {

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

AdminController.cs我的受保護控制器(我不確定是否需要指定方案)

 [Authorize(ActiveAuthenticationSchemes = "myCustomScheme")]
    public class AdminController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }

的AccountController:

[HttpPost]
        public async Task<IActionResult> Unauthorized(LoginModel model, string ReturnUrl)
        {
            if (ModelState.IsValid)
            {
                if (model.Username.ToLower() == "test" && model.Password == "test")
                {
                    var principal = User as ClaimsPrincipal;
                    await HttpContext.Authentication.SignInAsync("myCustomScheme", principal, new AuthenticationProperties
                    {
                        IsPersistent = true,
                    });

                    return RedirectToAction(nameof(AdminController.Index));

                }
                return View(model);
            }
            return View(model);

        }

Unauthorized操作方法,你不必要求this.User 代替

var principal = User as ClaimsPrincipal;

您需要使用自己的聲明創建新標識並將其傳遞給SignIn方法:

var principal = new ClaimsPrincipal(new ClaimsIdentity(
           new[] { new Claim(ClaimTypes.Name, model.Username) },
           "myCustomScheme"));

await HttpContext.Authentication.SignInAsync("myCustomScheme", principal, new AuthenticationProperties
                {
                    IsPersistent = true,
                });

有關如何使用cookie的簡單示例可以在aspnet / Security repo中找到

您還需要在ConfigureServices下的Startup.cs中配置所有策略:

        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc();

            // some samples (this section must contain all the authorization policies used anywhere in the application)
            services.AddAuthorization(options => {
                options.AddPolicy("EmployeeOnly", policy => policy.RequireClaim("CompanyName", "YourCompany"));
                options.AddPolicy("SalesOnly", policy => { policy.RequireClaim("department", "sales"); });
                options.AddPolicy("HumanResources", policy => { policy.RequireClaim("department", "HR"); });
                options.AddPolicy("FinanceSupervisor", policy => {
                    policy.RequireClaim("department", "finance");
                    policy.RequireClaim("jobTitle", "supervisor");
                });
            });


            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();
        }

其余的幾乎是相同的(這里的樣本只是為了使它與上面的工作):

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            AuthenticationScheme = "yourcookiename",                    
            CookieName = "YourCookieName",
            LoginPath = new PathString("/Account/Login"),
            AccessDeniedPath = new PathString("/Account/AccessDenied"),
            AutomaticAuthenticate = true,
            AutomaticChallenge = true
        });

        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment()) {
            app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); app.UseBrowserLink();
        } else { app.UseExceptionHandler("/Home/Error"); }

        app.UseStaticFiles();
        app.UseIdentity();

        // Add external authentication middleware below. To configure them please see https://go.microsoft.com/fwlink/?LinkID=532715

        app.UseMvc(routes => {
            routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}");
        });

    }

在構造函數中的AccountController.cs下添加db上下文以從數據庫中提取策略

    private readonly YourDB_Context _yourDB_context; 

    public AccountController(YourDB_Context context)
    {
        _yourDB_context = context;
    }

在登錄下添加

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;
        if (ModelState.IsValid)
        {                
            // modify below to match your user table structure to pull user info
            userTable vUser = _yourDB_Context.userTable.SingleOrDefault(m => m.Email == model.Email && m.password == model.Password);
            const string Issuer = "optional: company name / issuer name";
            List<Claim> claims = new List<Claim> {
                new Claim("CompanyName", "YourCompany"), // hardcoded to authorize EmployeeOnly
                //new Claim("department", "HR"),
                //new Claim(ClaimTypes.Name, vUser.Name, ClaimValueTypes.String, Issuer),
                new Claim(ClaimTypes.Email, vUser.Email, ClaimValueTypes.String, Issuer),
                //new Claim(ClaimTypes.Role, vUser.Roles, ClaimValueTypes.String, Issuer)
            };
            var userIdentity = new ClaimsIdentity(claims, "local", "name", "role");
            var userPrincipal = new ClaimsPrincipal(userIdentity);
            await HttpContext.Authentication.SignInAsync("yourcookiename", userPrincipal,
                new AuthenticationProperties {
                    ExpiresUtc = DateTime.UtcNow.AddMinutes(30),
                    IsPersistent = false,
                    AllowRefresh = false
                });
            return RedirectToLocal(returnUrl);                
        }

        return View(model);
    }

然后在你的控制器下的respetive部分需要授權

[Authorize(Policy = "EmployeeOnly")]
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [Authorize(Policy = "HumanResources")]
    public IActionResult Contact()
    {
        ViewData["Message"] = "Your contact page.";

        return View();
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM