前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >.net core 认证与授权(一)

.net core 认证与授权(一)

作者头像
梁规晓
发布2020-02-19 15:03:50
5900
发布2020-02-19 15:03:50
举报
文章被收录于专栏:DotNet程序园DotNet程序园

前言

.net core web并不是一个非常新的架构,很多文章提及到认证与授权这个过程,但是一般都会提及到里面的方法怎么用的,而不是模拟一个怎样的过程,所以我打算记录自己的理解。 什么是认证?我们大学毕业有学士证书和毕业证书,来证明你是一个学士。 什么是授权,比如说你被认证是我的朋友后,你可以拿着这个身份,可以进入我的朋友圈看动态。 那么.net core 的认证与授权是一个什么样的过程,在这里提出简单模式是我给你颁发了证书,证明了你的身份,然后呢,你可以拿到你的身份卡之后,你要经过验证,得到授权,然后进入中华人民共和国,就是这个过程。 正文部分均为我的理解,可能存在误差,如果不对请指正。

正文

代码语言:javascript
复制
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [Authorize]
    public IActionResult Secret()
    {
        return View();
    }

    public IActionResult Authenticate()
    {
        return RedirectToAction("Index");
    }
}

我有一个control,里面action有index ,Secret ,Authenticate。 index View:

代码语言:javascript
复制
<h1>Home Page</h1>

Secret View:

代码语言:javascript
复制
<h1>Secret</h1>

然后我们访问 https://localhost:44350/Home/Index 效果:

如我意料,完全ok的。 然后访问: https://localhost:44350/Home/Secret 出现了错误:

给了非常详细的提示,未指定认证方案。 我们看到,唯一和index 不同的是加入了Authorize这个属性标签,这是个授权的意思,但是提示给我们的是我们没有认证。 好的,说明吧授权之前要认证,要识别出身份,现实中也是这样,能证明你的只有你的身份证,没有身份证我怎么给你授权。 好的,那么就添加认证过程: 认证有非常多种,这里就以cookie来简单的介绍。

代码语言:javascript
复制
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("CookieAuth").AddCookie("CookieAuth", config =>
    {
        config.Cookie.Name = "Cook.Name";
        config.LoginPath = "/Home/Authenticate";
    });

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

我添加了一段:

代码语言:javascript
复制
services.AddAuthentication("CookieAuth").AddCookie("CookieAuth", config =>
{
    config.Cookie.Name = "Cook.Name";
    config.LoginPath = "/Home/Authenticate";
});

如果没有cookie认证,那么就跳转到/Home/Authenticate 去认证。 在/Home/Authenticate 下面我没有做任何事情,仅仅是去跳转到/Home/Index 那么正常情况下,是会跳转到/Home/Index。 是的,当我们访问: https://localhost:44350/Home/Secret 看到的效果是: https://localhost:44350/Home/Index 这是如我们所料的,那么我们就在/Home/Authenticate做一些事情,比如说颁发证书。 好的,那我们就在/home/Authenticate 中颁发证书:

代码语言:javascript
复制
public IActionResult Authenticate()
{
    var SchoolClaims = new List<Claim>()
    {
        new Claim(ClaimTypes.Name,"Jack"),
        new Claim(ClaimTypes.Email,"Jack@fmail.com")
    };

    var LicensClaims = new List<Claim>()
    {
        new Claim(ClaimTypes.Name,"Jack.li"),
        new Claim(ClaimTypes.Email,"Jack@fmail.com"),
        new Claim("begin","2000.10.1")
    };
    var SchoolIdentity = new ClaimsIdentity(SchoolClaims,"Student Identity");
    var CarManagerIdentity = new ClaimsIdentity(LicensClaims, "Licens Identity");
    var userPrincipal = new ClaimsPrincipal(new[] { SchoolIdentity, CarManagerIdentity });
    
    HttpContext.SignInAsync(userPrincipal);
    return RedirectToAction("Index");
}

看下代码顺序: 我们创建了List<Claim>(),这些是什么呢? 就是我们的信息。 比如我们驾驶证上有我们的名字,编号。 然后通过: new ClaimsIdentity(LicensClaims, "Licens Identity"); 生成了一个identity,也就是产生了一张证书,这种证书叫做:Licens Identity,当然我们随意名字。 var userPrincipal = new ClaimsPrincipal(new[] { SchoolIdentity, CarManagerIdentity }); 我们一生中有身份证,学位证,驾驶证,这么多证书是不是需要一个管理的呢?ClaimsPrincipal就是用来管理证书的。 HttpContext.SignInAsync(userPrincipal); 就会产生证书并且输入到前台。

请看,对这个cooke.name 是不是特别熟悉呢?就是我们启用了cookie 认证,如果忘记了请往上看。 但是访问: https://localhost:44350/Home/Secret 看到的效果还是: https://localhost:44350/Home/Index 这是为啥呢?不是认证了吗? 其实:

代码语言:javascript
复制
services.AddAuthentication("CookieAuth").AddCookie("CookieAuth", config =>
{
    config.Cookie.Name = "Cook.Name";
    config.LoginPath = "/Home/Authenticate";
});

和:

代码语言:javascript
复制
public IActionResult Authenticate()
{
    var SchoolClaims = new List<Claim>()
    {
        new Claim(ClaimTypes.Name,"Jack"),
        new Claim(ClaimTypes.Email,"Jack@fmail.com")
    };

    var LicensClaims = new List<Claim>()
    {
        new Claim(ClaimTypes.Name,"Jack.li"),
        new Claim(ClaimTypes.Email,"Jack@fmail.com"),
        new Claim("begin","2000.10.1")
    };
    var SchoolIdentity = new ClaimsIdentity(SchoolClaims,"Student Identity");
    var CarManagerIdentity = new ClaimsIdentity(LicensClaims, "Licens Identity");
    var userPrincipal = new ClaimsPrincipal(new[] { SchoolIdentity, CarManagerIdentity });
    
    HttpContext.SignInAsync(userPrincipal);
    return RedirectToAction("Index");
}

重新来看这两个的关系。 得到的错误是没有一个认证的方案,然后写了添加了cookie验证,然后下面的是去实现把证书装配到cookie中。 验证机制生效了,证书也到前台了。最大可能的可能就是没有去拿证书,或者说证书机制除了验证其他的步骤都没有,也就是没有启动证书验证这套流程。 需要加上在:

代码语言:javascript
复制
// 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?}");
    });
}

启动身份认证:

代码语言:javascript
复制
app.UseAuthentication();

也就是我们说:

代码语言:javascript
复制
services.AddAuthentication("CookieAuth").AddCookie("CookieAuth", config =>
{
    config.Cookie.Name = "Cook.Name";
    config.LoginPath = "/Home/Authenticate";
});

是去验证证书,而app.UseAuthentication();是去拿证书,整理证书,没有拿到证书相当于没有证书,所以一直不通过。 然后在.net core 3.0中,分的更细,还有问我们是否启动授权。而2.0 app.UseAuthentication()就可以了。

总结

以上只是个人的理解,在后续介绍如何与数据库建立联系。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-02-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 DotNet程序园 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 正文
  • 总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档