asp.core 同时兼容JWT身份验证和Cookies 身份验证两种模式(示例详解)

在实际使用中,可能会遇到,aspi接口验证和view页面的登录验证情况。asp.core 同样支持两种兼容。

首先在startup.cs 启用身份验证。

var secrityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecurityKey"]));
            services.AddSingleton(secrityKey);
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(option =>    //cookies 方式
                {
                    option.LoginPath = "/Login";
                })
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>   //jwt 方式
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,//是否验证Issuer
                    ValidateAudience = true,//是否验证Audience
                    ValidateLifetime = true,//是否验证失效时间
                    ClockSkew = TimeSpan.FromSeconds(30),
                    ValidateIssuerSigningKey = true,//是否验证SecurityKey
                    ValidAudience = Configuration["JWTDomain"],//Audience
                    ValidIssuer = Configuration["JWTDomain"],//Issuer
                    IssuerSigningKey = secrityKey//拿到SecurityKey
                };
            });

Configure 方法中须加入

app.UseAuthentication(); //授权
  app.UseAuthorization(); //认证 认证方式有用户名密码认证

            app.MapWhen(context =>
            {
                var excludeUrl = new string[] { "/api/login/getinfo", "/api/login/login", "/api/login/modifypwd" };  //注意小写
                return context.Request.Path.HasValue
                && context.Request.Path.Value.Contains("Login")
                && context.Request.Headers.ContainsKey("Authorization")
                && !(excludeUrl.Contains(context.Request.Path.Value.ToLower()));
            }, _app =>
            {
                _app.Use(async (context, next) =>
                {
                    context.Response.StatusCode = 401;
                });
            });

在login页面,后台代码

var uid = Request.Form["code"] + "";
var pwd = Request.Form["pwd"] + "";

var info = _mysql.users.Where(m => m.user_code == uid&&m.delflag==0).FirstOrDefault();
if (info == null)
{
    return new JsonResult(new
    {
        success = false,
        msg = "用户不存在"
    });
}
if (info.pwd != pwd)
        msg = "用户密码不正确"
//创建一个身份认证
var claims = new List<Claim>() {
            new Claim(ClaimTypes.Sid,info.id), //用户ID
            new Claim(ClaimTypes.Name,info.user_code)  //用户名称
        };
var claimsIdentity = new ClaimsIdentity(
    claims, CookieAuthenticationDefaults.AuthenticationScheme);
//var identity = new ClaimsIdentity(claims, "Login");
//var userPrincipal = new ClaimsPrincipal(identity);
//HttpContext.SignInAsync("MyCookieAuthenticationScheme", userPrincipal, new AuthenticationProperties
//{
//    ExpiresUtc = DateTime.UtcNow.AddMinutes(30),
//    IsPersistent = true
//}).Wait();
var authProperties = new AuthenticationProperties
    //AllowRefresh = <bool>,
    // Refreshing the authentication session should be allowed.
    ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(60),
    // The time at which the authentication ticket expires. A
    // value set here overrides the ExpireTimeSpan option of
    // CookieAuthenticationOptions set with AddCookie.
    IsPersistent = true,
    // Whether the authentication session is persisted across
    // multiple requests. When used with cookies, controls
    // whether the cookie's lifetime is absolute (matching the
    // lifetime of the authentication ticket) or session-based.
    //IssuedUtc = <DateTimeOffset>,
    // The time at which the authentication ticket was issued.
    //RedirectUri = <string>
    // The full path or absolute URI to be used as an http
    // redirect response value.
};
await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,
    new ClaimsPrincipal(claimsIdentity),
    authProperties);

 Controler控制器部分,登录代码:

[HttpPost("Login")]
        public async Task<JsonResult> Login(getdata _getdata)
        {
            var userName = _getdata.username;
            var passWord = _getdata.password;
            var info = _mysql.users.Where(m => m.user_code == userName && m.delflag == 0).FirstOrDefault();
            if (info == null)
            {
                return new JsonResult(new
                {
                    state = false,
                    code = -1,
                    data = "",
                    msg = "用户名不存在!"
                });
            }
            if (CommonOp.MD5Hash(info.pwd).ToLower() != passWord)
                    code = -2,
                    msg = "用户密码不正确!"

            #region 身份认证处理
            var secrityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["SecurityKey"]));
            List<Claim> claims = new List<Claim>();
            claims.Add(new Claim("user_code", info.user_code));
            claims.Add(new Claim("id", info.id));
            var creds = new SigningCredentials(secrityKey, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                issuer: _config["JWTDomain"],
                audience: _config["JWTDomain"],
                claims: claims,
                expires: DateTime.Now.AddMinutes(120),
                signingCredentials: creds);
            return new JsonResult(new
                state = true,
                code = 0,
                data = new JwtSecurityTokenHandler().WriteToken(token),
                msg = "获取token成功"
            });
            #endregion
        }

注意, 受身份验证的控制器部分,要加入如下属性头,才可以生效。

[Authorize(AuthenticationSchemes = "Bearer,Cookies")]
    public class ControllerCommonBase : ControllerBase
    {

     }  

这样一个Controler 控制器,能够兼容两种模式啦。

到此这篇关于asp.core 同时兼容JWT身份验证和Cookies 身份验证两种模式的文章就介绍到这了,更多相关asp.core 身份验证内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • asp.net core中如何使用cookie身份验证

    背景 ASP.NET Core Identity 是一个完整的全功能身份验证提供程序,用于创建和维护登录名. 但是, cookie 不能使用基于的身份验证提供程序 ASP.NET Core Identity . 配置 在 Startup.ConfigureServices 方法中,创建具有 AddAuthentication 和 AddCookie 方法的身份验证中间件服务: services.AddAuthentication(CookieAuthenticationDefaults.Auth

  • Asp.Net Core中基于Session的身份验证的实现

    在Asp.Net框架中提供了几种身份验证方式:Windows身份验证.Forms身份验证.passport身份验证(单点登录验证). 每种验证方式都有适合它的场景: 1.Windowss身份验证通常用于企业内部环境,Windows Active Directory就是基于windows平台的身份验证实现: 2.Forms身份验证是Asp.Net框架中提出的另一种验证方式: 3.passport身份验证是微软提供的基于自己的lives账号实现的单点认证服务. Asp.net Core验证码登录遇到

  • ASP.NET Core 使用Cookie验证身份的示例代码

    ASP.NET Core 1.x提供了通过Cookie 中间件将用户主体序列化为一个加密的Cookie,然后在后续请求中验证Cookie并重新创建主体,并将其分配给HttpContext.User属性.如果您要提供自己的登录界面和用户数据库,可以使用作为独立功能的Cookie中间件. ASP.NET Core 2.x的一个主要变化是不再存在Cookie中间件.取而代之的是在Startup.cs文件中的Configure方法中的调用UseAuthentication方法会添加设置HttpConte

  • asp.core 同时兼容JWT身份验证和Cookies 身份验证两种模式(示例详解)

    在实际使用中,可能会遇到,aspi接口验证和view页面的登录验证情况.asp.core 同样支持两种兼容. 首先在startup.cs 启用身份验证. var secrityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecurityKey"])); services.AddSingleton(secrityKey); services.AddAuthentication(CookieAut

  • 国产化中的 .NET Core 操作达梦数据库DM8的两种方式(操作详解)

    目录 背景 环境 SDK 操作数据库 DbHelperSQL方式 Dapper方式 背景 某个项目需要实现基础软件全部国产化,其中操作系统指定银河麒麟,数据库使用达梦V8,CPU平台的范围包括x64.龙芯.飞腾.鲲鹏等.考虑到这些基础产品对.NET的支持,最终选择了.NET Core 3.1. 环境 CPU平台:x86-64 / Arm64 操作系统:银河麒麟 v4 数据库:DM8 .NET:.NET Core 3.1 SDK 达梦自己提供了.NET操作其数据库的SDK,可以通过NuGet安装,

  • GoLang jwt无感刷新与SSO单点登录限制解除方法详解

    目录 前言 为什么使用JWT Cookie和Session token (header.payload.signature) token 安全性 基于token安全性的处理 客户端与服务端基于无感刷新流程图 golang实现atoken和rtoken 颁发token 校验token 无感刷新token 完整实现代码 SSO(Single Sign On)单用户登录以及无感刷新token 实现思路 实战代码 小结 前言 为什么使用JWT Jwt提供了生成token以及token验证的方法,而tok

  • jQuery.Validate表单验证插件的使用示例详解

    jQuery Validate 插件为表单提供了强大的验证功能,让客户端表单验证变得更简单,同时提供了大量的定制选项,满足应用程序各种需求. 请在这里查看示例 validate示例 示例包含 验证错误时,显示红色错误提示 自定义验证规则 引入中文错误提示 重置表单需要执行2句话 源码示例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <

  • TS 类型兼容教程示例详解

    目录 类型兼容 简单类型兼容 普通对象兼容 函数兼容 参数数量不一致 参数类型不一致 返回不同 类型兼容 因为JS语言不慎过于领过, 真实开发场景中往往无法做到严格一致的类型约束,此时TS就不得不做类型兼容 顶类型:unknown -- 任何类型都可以赋值给unknown 底类型:never -- never兼容任何类型(可以赋值给任何类型) any: 其实不是一个类型,它是一个错误关闭器,用了any就等同于放弃了类型约束 简单类型兼容 子集可以赋值给父级 type name = string

  • Go语言leetcode题解953验证外星语词典示例详解

    目录 题目描述 思路分析 AC 代码 题目描述 953. 验证外星语词典 某种外星语也使用英文小写字母,但可能顺序 order 不同.字母表的顺序(order)是一些小写字母的排列. 给定一组用外星语书写的单词 words,以及其字母表的顺序 order,只有当给定的单词在这种外星语中按字典序排列时,返回 true:否则,返回 false. 示例 1: 输入:words = ["hello","leetcode"], order = "hlabcdefgi

  • ASP.NET Core 6最小API中使用日志和DI示例详解

    目录 在ASP.NET Core 6的最小API中使用日志和DI 如何在ASP.NET Core 6的最小API中实现日志.从配置系统中读取并使用依赖注入 CI/CD?持续集成和持续交付解释 在Visual Studio 2022中创建一个ASP.NET Core minimal web API项目 运行一个最小的网络API 为一个最小的网络API配置多个端口 在最小的Web API中使用日志记录 在最小的API中从配置系统中读取 在最小的网络API中使用依赖性注入 在一个最小的Web API中

  • Django中的用户身份验证示例详解

    前言 这次开发微信抢票程序中,普通用户的身份是由微信管理的.当用户通过微信公众号(测试号)向后台发消息时,微信会将用户的身份标记为一个unique_id来识别,后端可以由此来判断用户身份.这种认证比较特殊,它不存在登陆.登出的操作.如果是一个普通的web应用,应该有用户的登陆.登出操作,当用户未经授权访问某个URL的时候,后端应该拒绝这次请求,或者是重定向到登陆界面. 在这次作业中,因为需要一个后台管理员来管理各种活动的创建和发布,因此也需要有用户的身份认证操作.这次的后端是Django,试了一

  • AngularJs验证重复密码的方法(两种)

    本文给大家分享angularjs验证重复密码的两种方法.具体方法详情如下所示: 第一种: <label for="password">密码</label> <input id="password" name="password" type="password" ng-model="user.password" required> <label for="r

  • .Net Core下HTTP请求IHttpClientFactory示例详解

    使用方式 IHttpClientFactory有四种模式: 基本用法 命名客户端 类型化客户端 生成的客户端 基本用法 在 Startup.ConfigureServices 方法中,通过在 IServiceCollection 上调用 AddHttpClient 扩展方法可以注册 IHttpClientFactory services.AddHttpClient(); 注册之后可以像依赖注入DI似得在类中通过构造函数注入形式使用,伪代码: class A { private readonly

随机推荐