近些天,看了一些博客园大牛关于webApi项目的的文章,也有请教师兄一些问题,自己做了个Demo试了试,收获甚多。感谢感谢,下面是我一些学习的总结,如若有错的地方请多多指教!! WebApi登陆与身份验证因为在调用接口的时候都必须传sessionKey参数过去,所以必须先登录 ...
近些天,看了一些博客园大牛关于webApi项目的的文章,也有请教师兄一些问题,自己做了个Demo试了试,收获甚多。感谢感谢,下面是我一些学习的总结,如若有错的地方请多多指教!!
WebApi登陆与身份验证
因为在调用接口的时候都必须传sessionKey参数过去,所以必须先登录验证身份。
如果是已注册用户则账号登陆,获得其身份标识的 sessionkey,如果是非账户用户则可以匿名登陆,要输入用户IP地址或者和客户端设备号等以获得sessionkey,然后可以去注册。
#region 登录API /// <summary> /// 登录API (账号登陆) /// </summary> /// <param name="phone">登录帐号手机号</param> /// <param name="hashedPassword">加密后的密码,这里避免明文,客户端加密后传到API端</param> /// <param name="deviceType">客户端的设备类型</param> /// <param name="clientId">客户端识别号, 一般在APP上会有一个客户端识别号</param> /// <returns></returns> [Route("account/login")] public SessionObject Login(get='_blank'>string phone, string hashedPassword, int deviceType = 0, string clientId = "") { if (string.IsNullOrEmpty(phone)) throw new ApiException("用户名不能为空。", "RequireParameter_userphone"); if (string.IsNullOrEmpty(hashedPassword)) throw new ApiException("hashedPassword 不能为空.", "RequireParameter_hashedPassword"); int timeout = 60; var nowUser = _authenticationService.GetUserByPhone(phone); if (nowUser == null) throw new ApiException("帐户不存在", "Account_NotExits"); #region 验证密码 if (!string.Equals(nowUser.Password, hashedPassword)) { throw new ApiException("错误的密码", "Account_WrongPassword"); } #endregion if (!nowUser.IsActive) throw new ApiException("用户处于非活动状态.", "InactiveUser"); UserDevice existsDevice = _authenticationService.GetUserDevice(nowUser.UserId, deviceType); if (existsDevice == null) { string passkey = MD5CryptoProvider.GetMD5Hash(nowUser.UserId + nowUser.Phone + DateTime.UtcNow+ Guid.NewGuid()); existsDevice = new UserDevice() { UserId = nowUser.UserId, CreateTime = DateTime.UtcNow, ActiveTime = DateTime.UtcNow, ExpiredTime = DateTime.UtcNow.AddMinutes(timeout), DeviceType = deviceType, SessionKey = passkey }; _authenticationService.AddUserDevice(existsDevice); } else { existsDevice.ActiveTime = DateTime.UtcNow; existsDevice.ExpiredTime = DateTime.UtcNow.AddMinutes(timeout); _authenticationService.UpdateUserDevice(existsDevice); } nowUser.Password = ""; return new SessionObject() { SessionKey = existsDevice.SessionKey, LogonUser = nowUser }; } #endregion
海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com
原标题:学习总结之 WebApi 用户登录和匿名登录,及权限验证
关键词:web
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。