Ant Design Pro V5 从零开始到用户登录鉴权(javascript版)
Posted シ゛甜虾
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ant Design Pro V5 从零开始到用户登录鉴权(javascript版)相关的知识,希望对你有一定的参考价值。
一、工程创建
安装Node.js
Node.jsNode.js® is a javascript runtime built on Chrome's V8 JavaScript engine.https://nodejs.org/zh-cn/安装完成后,以管理员运行cmd,进入自己的工程目录
# 使用 yarn
yarn create umi myapp
#选择ant-design-pro
❯ ant-design-pro - Create project with a layout-only ant-design-pro boilerplate, use together with umi block.
#选择JavaScript
TypeScript
❯ JavaScript
#选择simple
❯ simple
complete
#cd进入myapp目录
#yarn安装依赖
#yarn start运行
二、代理设置
Ant Design Pro V5 代理设置(javascript版)
设置拦截器,也可以不设置,不设置每次请求前需要手动把Authorization加入到headers中
三、前端登录接口修改
先注释掉仿真登录数据
注释掉2个接口的大段内容
'GET /api/currentUser'
'POST /api/login/account'
注释后
在src下新建utils文件夹建立token.js内容如下
export default {
get() {
return window.sessionStorage.getItem('TOKEN');
},
save(token) {
window.sessionStorage.setItem('TOKEN', token);
},
};
按照标记内容进行修改
user/login.js内容修改
增加如下代码
import token from '@/utils/token';
let access = ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site' ? 'admin' : '';
修改如下代码
保存运行即可
四、后端接口修改
这里后端使用.net 6 webapi
//添加鉴权
builder.Services.AddAuthentication(option =>
{
option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; //jwt Bearer默认值
option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(option => {
option.TokenValidationParameters = new TokenValidationParameters
{
//是否验证签发者
ValidateIssuer = true,
//签发者
ValidIssuer = "sweat dripped the soil",
//是否验证接受者
ValidateAudience = true,
//接受者
ValidAudience = "who knows what's on the plate",
//是否验证签名密钥
ValidateIssuerSigningKey = true,
//签名密钥
IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes("farmers are weeding at noon")),
验证令牌过期时间
ValidateLifetime = true,
//令牌安全时是否保存令牌
SaveSigninToken = true,
//令牌过期时间的偏移值
ClockSkew = TimeSpan.FromSeconds(1)
};
});
使用权限认证,2行代码顺序不能反,别问我怎么知道的
app.UseAuthentication();
app.UseAuthorization();
创建JwtManager类
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
namespace EdgeService.WebApi.Controllers.Authorize
{
public static class JwtManager
{
public static string CreatJwtToken()
{
//签名密钥
string jwtKey = "farmers are weeding at noon";
//签发者
string jwtIssuser = "sweat dripped the soil";
//接收者
string jwtAudience = "who knows what's on the plate";
//令牌所承载的信息
var claims = new[]
{
//用户Id
new Claim("Id","userId"),
new Claim("Name","userName"),
new Claim("Role","admin")
};
//获取对称密钥
var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(jwtKey));
//使用has256加密密钥
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
//生成token
var token = new JwtSecurityToken(
//签发者
jwtIssuser,
//接收者
jwtAudience,
//jwt令牌数据体
claims: claims,
//令牌过期时间
expires: DateTime.Now.AddMinutes(10),
//为数字签名定义SecurityKey
signingCredentials: creds
);
return "Bearer " + new JwtSecurityTokenHandler().WriteToken(token);
}
}
}
登录后返回token,用户再次请求用户信息时,需要带上token
using EdgeService.WebApi.Controllers.Authorize;
using EdgeService.WebApi.Controllers.Login.Dto;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
namespace EdgeService.WebApi.Controllers.Login
{
[ApiController]
[Route("api/[controller]")]
public class LoginController : Hub
{
//所有用户均可以访问
[AllowAnonymous]
[HttpPost("account")]
public LoginResultDto Login(LoginDto loginDto)
{
if(loginDto.Password.Equals("admin") && loginDto.Username.Equals("admin"))
{
string token = JwtManager.CreatJwtToken();
return new LoginResultDto() { Status = "ok", Type = loginDto.Type, CurrentAuthority = "admin", Token = token };
}
else
{
return new LoginResultDto() { Status = "error", Type = loginDto.Type, CurrentAuthority = "guest" };
}
}
[HttpGet("currentUser")]
[Authorize]
public CurrentUserResultDto CurrentUser()
{
CurrentUserResultDto currentUserResultDto = new CurrentUserResultDto();
if (true)
{
currentUserResultDto.Data.Name = "admin";
currentUserResultDto.Success = true;
}
else
{
currentUserResultDto.ErrorCode = "401";
currentUserResultDto.ErrorMessage = "请先登录";
currentUserResultDto.Success = false;
}
return currentUserResultDto;
}
}
}
使用用户名密码登录,返回JWT Token
获取用户信息使用JWT Token
以上是关于Ant Design Pro V5 从零开始到用户登录鉴权(javascript版)的主要内容,如果未能解决你的问题,请参考以下文章
Ant Design Pro V5 初体验(typescript版)
Ant Design Pro V5 代理设置(javascript版)
Ant Design Pro V5 去掉界面水印(JavaScript版)