asp.net core 2.x 的 简单认证授权

基本配置,按 AddCookie搞的

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace auth.mvc {
    public class Startup {
        public Startup(IConfiguration configuration) {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services) {
            //services.Configure<CookiePolicyOptions>(options => {
            //    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            //    options.CheckConsentNeeded = context => true;
            //    options.MinimumSameSitePolicy = SameSiteMode.None;
            //});

            services.AddAuthentication(x => {
                x.DefaultScheme="alber";
                x.DefaultChallengeScheme = "alber";
                x.DefaultAuthenticateScheme = "alber";
                x.DefaultForbidScheme = "alber";
                x.DefaultSignInScheme = "alber";
                x.DefaultSignOutScheme = "alber";
            })
                .AddCookie("alber",
                    config => {
                        //config.LoginPath = "/home/loginview";
                        config.AccessDeniedPath = "/home/loginview";
                    }
                );
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
            if (env.IsDevelopment()) {
                app.UseDeveloperExceptionPage();
            } else {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

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

登录,与保护拦截

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using auth.mvc.Models;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;

namespace auth.mvc.Controllers {
    public class HomeController : Controller {
        public IActionResult Index() {
            return View();
        }
        public IActionResult Welcome(string userName) {
            if (string.IsNullOrWhiteSpace(userName)) {
                ViewBag.userName=this.TempData["towelcome"];
                this.TempData.Clear();
            } else {
                ViewBag.userName = userName;
            }
            return View();
        }
        [Authorize(AuthenticationSchemes ="alber")]
        public IActionResult Privacy() {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error() {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
        public IActionResult LoginView() {
            return View();
        }
        public async Task Login(LoginModel p) {
            if (p.account != "tom.write" && p.pwd != "111223") {
                await Task.FromException(new Exception("account or pwd has wrong"));
            }
            var ci = new ClaimsIdentity("alber");// 之前这里有个大坑,没写里面的字符串,就始终不能访问受保护资源,原因就在这里
            ci.AddClaim(new Claim(ClaimTypes.Name, p.account));
            var cp = new ClaimsPrincipal();
            cp.AddIdentity(ci);
            await this.HttpContext.SignInAsync(cp);
            //  if (string.IsNullOrEmpty(HttpContext.Request.Form["ReturnUrl"])) HttpContext.Response.Redirect($"/Home/Welcome?userName={p.account}");
            if (string.IsNullOrEmpty(HttpContext.Request.Form["ReturnUrl"])) {

                //RedirectToAction($"Welcome",new{userName=p.account });
                HttpContext.Response.Redirect("Welcome");
                this.TempData["towelcome"] = p.account;
            } else HttpContext.Response.Redirect(HttpContext.Request.Form["ReturnUrl"]);
        }
    }
}

这样我完成了最简单的验证查看请求所带cookie发现的确在请求 headers里面存在由HttpContext.SignInAsync 扩展方法所写入的cookie值,这正是发按认证与授权验证的凭据。

猜你喜欢

转载自www.cnblogs.com/ProjectDD/p/10995650.html