海南工程建设资料备案网站,电子商务网站建设调查问卷,中国建设银行威海分行网站,厦门网站制作系统重新创建WebApi项目#xff0c;安装Microsoft.AspNetCore.Authentication.JwtBearer包#xff0c;将之前JwtBearer测试项目中的初始化函数#xff0c;jwt配置类、token生成类全部挪到项目中。 重新编写login函数#xff0c;之前测试Cookie和Session认证时用的函数适合m… 重新创建WebApi项目安装Microsoft.AspNetCore.Authentication.JwtBearer包将之前JwtBearer测试项目中的初始化函数jwt配置类、token生成类全部挪到项目中。 重新编写login函数之前测试Cookie和Session认证时用的函数适合mvc模式WebApi项目下函数返回的是状态码及其它信息直接将开源博客Blog项目中的ApiResult类照搬过来如果登录成功则将token保存到Msg属性中返回客户端。login函数的主要代码如下用户名及密码验证还是写死的后续再调整成从数据库中查询
public async TaskApiResult Login([FromBody]UserInfo info)
{if (info.Name gc_2299 info.Password XXXXXX){ApiResult result new ApiResult();result.UserName info.Name;result.MsgGetToken(info.Name);return result;}else{return new ApiResult(身份验证失败, 500, false);}
}private string GetToken(string name)
{ListClaim claims new ListClaim();claims.Add(new Claim(ClaimTypes.Name, name)); DateTime expres DateTime.Now.AddSeconds(_jwtconfig.Value.Expres);byte[] secbyse Encoding.UTF8.GetBytes(_jwtconfig.Value.Key);var secKey new SymmetricSecurityKey(secbyse);var credetials new SigningCredentials(secKey, SecurityAlgorithms.HmacSha256);var tokenDescriptor new JwtSecurityToken(claims: claims, expires: expres, signingCredentials: credetials, issuer:_jwtconfig.Value.Issuer, audience: _jwtconfig.Value.Audience);return new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);
}前端登录页面也是直接复制的开源博客Blog项目中的后台登录页面简化了不少东西。不过没法直接用它的js代码使用jQuery的post方法调不到后台的login函数暂时不清楚怎么回事儿网上很多示例都是用的ajax所以改成了ajax将登录函数的js代码修改如下
layui.use([layer, form], function () {var layer layui.layer;var form layui.form,$ layui.jquery;form.on(submit(login),function (data) {login();});function login() {var $btn $(#btnLogin);$btn.text(登录中...).attr(disabled, disabled).addClass(layui-disabled);var parm {};$(form input).each(function () {parm[$(this).attr(name)] $(this).val();}); $.ajax({type: POST,url: https://localhost:7051/Login/Login,contentType: application/json,data: JSON.stringify(parm),success: function (result) {if (result.statusCode 200) {layer.msg(登录成功,欢迎 result.userName 你的token result.msg);sessionStorage.setItem(user, result.userName)sessionStorage.setItem(token, result.msg);}else{layer.msg(登录失败错误消息为 result.msg);}$btn.text(登录).removeClass(layui-disabled).removeAttr(disabled);},error: function () {layer.msg(登录失败);$btn.text(登录).removeClass(layui-disabled).removeAttr(disabled);}});}
}); 最后是登录效果截图如下 从浏览器的会话存储空间中可以看到登录成功后保存的用户名及token便于其它页面使用。
参考文献 [1]https://www.jianshu.com/p/a2804e72d296 [2]https://blog.csdn.net/sD7O95O/article/details/85043160 [3]https://www.cnblogs.com/qiongkangle/p/13347283.html [4]https://www.cnblogs.com/xbhp/p/17401507.html [5]https://www.cnblogs.com/superstar/p/16491428.html [6]https://blog.csdn.net/weixin_44877917/article/details/140609294 [7]https://blog.csdn.net/qq_40287041/article/details/143368882