标签:net rip 保存 cti bind func 修改 private 缓存
前后台项目已经搭建完成,接下来要处理微信网页授权、获取用户信息并且绑定到后台
0、修改util.js
// 已经授权登录过并且token未过期的就不用再授权了
if (uni.getStorageSync(‘jwtToken‘) != ‘‘ &&
uni.getStorageSync(‘jwtTokenTimestamp‘) - new Date() > 60000)
return;
else if (uni.getStorageSync(‘jwtToken‘) != ‘‘ &&
uni.getStorageSync(‘jwtTokenTimestamp‘) - new Date() < 60000) {
// 已经授权登录过并且token快过期的就刷新token(60秒)
tsRequest.get(
api_host + ‘/api/_Account/getRefreshToken‘,
{‘refreshToken‘: uni.getStorageSync(‘jwtRefresh_token‘)},
{"Authorization":"Bearer "+uni.getStorageSync(‘jwtToken‘)}
).then(
function(res) {
if (res.statusCode == 200) that.setJwtToken(res.data);
},
function(err) {
console.log("login.vue_err:" + JSON.stringify(err));
});
return;
}
// 如果拿到code,调用授权接口,没有拿到就跳转微信授权链接获取
if (params.code) {
// 调用后台接口,授权
tsRequest.get(
api_host + ‘/api/_Wx/BindUserInfo‘, {
‘code‘: params.code,
‘scope‘: scope
},
).then(
function(res) {
if (res.statusCode == 200) that.setJwtToken(res.data.Result);
},
function(err) {
console.log("login.vue_err:" + JSON.stringify(err));
});
} else {
let uri = encodeURIComponent(link);
let authURL =
`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=${scope}&state=123#wechat_redirect`;
window.location.href = authURL;
}
//setJwtToken函数,把jwtToken保存到缓存
setJwtToken(data){
//缓存token和过期时间
uni.setStorageSync(‘jwtToken‘, data.access_token);//token
uni.setStorageSync(‘jwtRefresh_token‘, data.refresh_token);//用于到期刷新token
uni.setStorageSync(‘jwtTokenTimestamp‘, new Date().getTime() + data.expires_in * 1000);//token过期时间,服务端返回expires_in 单位是秒,因此乘以1000转化为毫秒
}
1、后台提供两个Get接口,BindUserInfo、getRefreshToken,这里使用直接使用WTM框架提供的JWT认证模式
#region 绑定用户信息
/// <summary>
/// 绑定用户信息
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
[AllowAnonymous]
[HttpGet("[action]")]
public async Task<IActionResult> BindUserInfo(string code,string scope= "snsapi_base")
{
OAuthAccessTokenResult oAuthAccessTokenResult = await GetAccessTokenAsync(AppId, AppSecret, code);
OAuthUserInfo oAuthUserInfo = new OAuthUserInfo();
if (scope== "snsapi_userinfo")
oAuthUserInfo = await GetUserInfoAsync(oAuthAccessTokenResult.access_token, oAuthAccessTokenResult.openid);
var up = DC.Set<Tb_Userplatform>()
.Where(x => x.OpenID == oAuthAccessTokenResult.openid).FirstOrDefault();
var u = new Tb_User();
//该用户被伪删
if (up != null && up.Status == 1)
{
u = DC.Set<Tb_User>()
.Where(x => x.ID == up.UserID).FirstOrDefault();
if (u != null && u.Status == 1)
{
u.Status = 0;
DC.Set<Tb_User>().Update(u);
}
up.Status = 0;
DC.Set<Tb_Userplatform>().Update(up);
DC.SaveChanges();
}
else if (up != null && up.Status == 0)
{
//登录,并同步更新昵称头像
u = DC.Set<Tb_User>()
.Where(x => x.ID == up.UserID).FirstOrDefault();
u.NickName = string.IsNullOrWhiteSpace(oAuthUserInfo.nickname)
? u.NickName
: oAuthUserInfo.nickname;
u.HeadImg = string.IsNullOrWhiteSpace(oAuthUserInfo.headimgurl)
? u.HeadImg
: oAuthUserInfo.headimgurl;
DC.Set<Tb_User>().Update(u);
DC.SaveChanges();
}
else if (up == null)
{//新用户注册并登录
u = new Tb_User()
{
HeadImg = oAuthUserInfo.headimgurl,
AddTime = DateTime.Now,
Integral = 0,
NickName = string.IsNullOrWhiteSpace(oAuthUserInfo.nickname)
? "小可爱"
: oAuthUserInfo.nickname,
Status = 0,
VipLevel = 1,
Balance = 0,
RegTime = DateTime.Now
};
u = DC.Set<Tb_User>().Add(u).Entity;
DC.SaveChanges();
//WTM默认jwt认证
up = new Tb_Userplatform()
{
AddTime = DateTime.Now,
Status = 0,
BindTime = DateTime.Now,
LoginNum = 1,
OpenID = oAuthAccessTokenResult.openid,
PlatformType = 0,
UserID = u.ID
};
up = DC.Set<Tb_Userplatform>().Add(up).Entity;
DC.SaveChanges();
}
LoginUserInfo user = new LoginUserInfo()
{
ITCode = u.ID + "",
Name=u.NickName,
TenantCode = oAuthAccessTokenResult.openid
};
string token = loginToToken(user);
return Ok(token);
}
private string loginToToken(LoginUserInfo user)
{
user.LoadBasicInfoAsync(Wtm);
Wtm.LoginUserInfo = user;
var authService = HttpContext.RequestServices.GetService(typeof(ITokenService)) as ITokenService;
var token = authService.IssueTokenAsync(Wtm.LoginUserInfo);
return JsonSerializer.Serialize(token);
}
#endregion
//过期刷新token接口
[HttpGet("[action]")]
[AllRights]
[ProducesResponseType(typeof(Token), StatusCodes.Status200OK)]
public async Task<Token> getRefreshToken(string refreshToken)
{
return await _authService.RefreshTokenAsync(refreshToken);
}
基于.net5 wtm框架、uni-app微信公众号开发三、Jwt认证 and oAuth
标签:net rip 保存 cti bind func 修改 private 缓存
原文地址:https://www.cnblogs.com/wuxyjian/p/14330892.html