两个系统跳转实现免登录(单点登录)
2.点击跳转,拿着用户名+token重定向到B站,B站在全局路由守卫beforEach判断to.query.token和to.query.userName是否为空,不为空则代码从别的的系统跳转过来的,调用免密登录(用户名+token)获取用户权限数据信息。B站持久化储存或Vuex储存。1.A站登录后,拿着A站账号名获取B站的token,同时在B站保存改账号的信息(用户名+token+过期时间)定义
·
定义:多个系统之间在某个系统登陆一次即可访问所有系统。
假设A站登录,跳转B站无需登录。
1.A站登录后,拿着A站账号名获取B站的token,同时在B站保存改账号的信息(用户名+token+过期时间)
2.点击跳转,拿着用户名+token重定向到B站,B站在全局路由守卫beforEach判断to.query.token和to.query.userName是否为空,不为空则代码从别的的系统跳转过来的,调用免密登录(用户名+token)获取用户权限数据信息。并返回给B站。B站持久化储存或Vuex储存。
3.B站跳转A站同上。
相关代码:
/// <summary>
/// 用户名获取token
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
[HttpPost, HttpGet]
[IgnoreLoginFilter]//忽略过滤器
public async Task<IActionResult> GetLoginToken(string userName)
{
//return await NewTask(() => {
if (string.IsNullOrEmpty(userName))
{
return Ok(new BaseResultModel(code: 200, data: "用户名不能为空"));
}
try
{
SysUsrBLL bll = new SysUsrBLL();
Yw_Sys_Usr user = bll.GetUserByName(userName);
if (user != null && user.usr_id != 0 && user.usr_status == true)
{
Model.UserModel model = new Model.UserModel();
model.UserId = user.usr_id.ToString();
model.LoginName = user.usr_name;
model.Password = "";
model.UserName = user.usr_realname;
model.Station = user.usr_station;
model.IsAdmin = Sys.Tools.ConvertHelper.FormatDBInt(user.usr_isadmin);
model.SessionId = Guid.NewGuid().ToString();
model.HigherName = user.usr_dleadername;
model.HigherId = user.usr_dleaderid;
if (BBSDao.dao.CurDbSession.From<Sys_UserStation_Refer>().Where(p => p.UserId == Convert.ToInt32(model.UserId)).ToFirst() != null)
{
model.CurrentUserStations = BBSDao.dao.CurDbSession.From<Sys_UserStation_Refer>().Where(p => p.UserId == Convert.ToInt32(model.UserId)).ToFirst().SStations;
}
SysRoleService sysRoleService = new SysRoleService();
model.UserType = sysRoleService.GetRoleByUsrid(user.usr_id) != null ? sysRoleService.GetRoleByUsrid(user.usr_id).usr_roleid : "";
//写入Cookie和Session
string sUserInfo = userName + "|" + "";
sUserInfo = EncryptUtil.DesEncrypt(sUserInfo);
string info = JsonHelper.SerializeObject(model);
CookieOptions cookie = new CookieOptions();
//设置过期时间
cookie.Expires = DateTime.Now.AddDays(1); //Cookie设置为1天内过期
Response.Cookies.Append("MaintainceSysUserName", info, cookie);
HttpContext.Session.SetString(model.SessionId, info);//将用户信息存储在session中,根据sessionId找到该用户
//将登陆信息存入Sys_JWT_Login表中--[如果存在则修改过期时间,如果不存在则插入]
string sql = @" select Id,token,expires_in,UserId,LoginName,Password from AirMaintainceDB.dbo.Sys_JWT_Login
where UserId =@UserId ";
Sys_JWT_Login loginModel = new Sys_JWT_Login();
Sys_JWT_Login m = new Sys_JWT_Login();
loginModel = Yw_ComonDao.dao.CurDbSession.FromSql(sql).AddInParameter("UserId", System.Data.DbType.Int64, model.UserId).ToList<Sys_JWT_Login>().FirstOrDefault();
// if (loginModel != null)
// {
// loginModel.expires_in= 3600 * 8; //会话周期8小时
// bool res = Yw_ComonDao.dao.CurDbSession.Update<Sys_JWT_Login>(loginModel) > 0 ? true : false;
// }
// else //新增
// {
m.token = model.SessionId;
m.expires_in = 3600 * 8; //会话周期8小时
m.UserId = user.usr_id.ToString();
m.LoginName = user.usr_name;
m.Password = "";
m.UserName = user.usr_realname;
m.Station = user.usr_station;
m.UserType = model.UserType;
m.IsAdmin = user.usr_isadmin ? "1" : "0";
m.SessionId = Guid.NewGuid().ToString();
m.createTime = DateTime.Now;
m.CurrentUserStations = model.CurrentUserStations;
bool res = Yw_ComonDao.dao.CurDbSession.Insert<Sys_JWT_Login>(m) > 0 ? true : false;
// }
//写入登录日志
Sys_LoginLog log = new Sys_LoginLog();
log.UsrName = userName;
log.Action = userName + "登录;";
log.ActionDate = System.DateTime.Now;
Sys_LoginLogDao.dao.CurDbSession.Insert<Sys_LoginLog>(log);
try
{
//该RemoteIpAddress是类型的IPAddress,不是string。它包含IPv4,IPv6和其他信息,它不像经典的ASP.NET,它对我们更有用。
//string ips = _accessor.HttpContext.Connection.RemoteIpAddress.ToString();
//string ips = _accessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
//log.Ip = ips;
}
catch (Exception ex)
{ }
var claimsIdentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, userName), new Claim("password", "") }, "Cookies");
var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal, new AuthenticationProperties
{
ExpiresUtc = DateTime.UtcNow.AddDays(1),
IsPersistent = false,
AllowRefresh = false
});
return Ok(new BaseResultModel(code: 200, loginToken: m.token));
}
else
{
//写入登录日志
//UserLog log = new UserLog();
//log.Id = Sys_UserDao.dao.GetMaxId<UserLog>();
//log.UserName = userName;
//log.LoginTime = System.DateTime.Now;
//log.IsLoginOk = false;
//Sys_UserDao.dao.Insert<UserLog>(log);
//ViewData["Errormessage"] = "登录失败,用户名密码不正确";
//return View();
CookiesHelper.ClearCookies("MaintainceSysUserName");
// return "账号或密码有误";
// return Redirect("/");
//return Json(new { result = false, msg = "账号或密码有误!" });
return Ok(new BaseResultModel(code: 200, data: "登录失败,用户名不正确"));
}
}
catch (System.Exception ex)
{
LogHelper.Log("登录失败" + ex.ToString());
return Ok(new BaseResultModel(code: 401, data: "登陆失败!"));
}
}
/// <summary>
/// 免密登陆
/// </summary>
/// <param name="userName"></param>
/// <param name="loginToken"></param>
/// <returns></returns>
[HttpPost, HttpGet]
[IgnoreLoginFilter]//忽略过滤器
public async Task<IActionResult> LoginFreePassword(string userName, string loginToken)
{
//return await NewTask(() => {
if (string.IsNullOrEmpty(userName))
{
return Ok(new BaseResultModel(code: 200, data: "用户名不能为空"));
}
if (string.IsNullOrEmpty(loginToken))
{
return Ok(new BaseResultModel(code: 200, data: "token不能为空"));
}
try
{
string sql = @" select Id,token,expires_in,UserId,LoginName,Password,userType from AirMaintainceDB.dbo.Sys_JWT_Login
where UserName =@userName and token=@loginToken ";
Sys_JWT_Login loginModel = new Sys_JWT_Login();
Sys_JWT_Login m = new Sys_JWT_Login();
loginModel = Yw_ComonDao.dao.CurDbSession.FromSql(sql).AddInParameter("@userName", System.Data.DbType.String, userName).AddInParameter("@loginToken", System.Data.DbType.String, loginToken).ToList<Sys_JWT_Login>().FirstOrDefault();
if (loginModel == null)
{
return Ok(new BaseResultModel(code: 401, data: "登陆失败!"));
}
else {
//写入登录日志
Sys_LoginLog log = new Sys_LoginLog();
log.UsrName = userName;
log.Action = userName + "登录;";
log.ActionDate = System.DateTime.Now;
Sys_LoginLogDao.dao.CurDbSession.Insert<Sys_LoginLog>(log);
return Ok(new BaseResultModel(code: 200, data: loginModel));
}
}
catch (System.Exception ex)
{
LogHelper.Log("登录失败" + ex.ToString());
return Ok(new BaseResultModel(code: 401, data: "登陆失败!"));
}
}
jump(){
var name=sessionStorage.getItem('currentUserName');
this.$http({
method: 'GET',
url: 'http://localhost:8086/api/Login/getLoginToken?username='+name
}).then(res => {
if(res.status==200){
window.location.href='http://localhost:9091/#/index?userName='+name+'&loginToken='+res.data.loginToken;
}
}).catch(error => {
console.log(error);
});
},
// 导航守卫
// 使用 router.beforeEach 注册一个全局前置守卫,判断用户是否登陆
router.beforeEach((to, from, next) => {
debugger
if (to.path === '/' || to.path === '') {
next('/login');
}
if (to.path === '/login' || to.path === '/' || to.path === '') {
next();
} else {
// let token = sessionStorage.getItem('Authorization');
let token = to.query.loginToken;
let userName = to.query.userName;
// let token = sessionStorage.getItem('Authorization');
if (token !== 'null' || token !== ''|| token !== null) {
// axios.defaults.withCredentials =false; // 在跨域中允许携带凭证
// axios.post('http://localhost:8886/api/Login/LoginFreePassword',Qs.stringify({userName:userName,'loginToken':token}))
// axios.get('http://localhost:8886/api/Login/LoginFreePassword?userName='+userName+'&loginToken='+token)
.then((res) => {
if(res.data.code==200){
sessionStorage.setItem('Authorization',res.data.data.token);
sessionStorage.setItem("currentUserId",res.data.data.userId);
sessionStorage.setItem('currentUserName',res.data.data.loginName);
if (res.data.data.userType!=undefined)
{
sessionStorage.setItem('roleType', res.data.data.userType);
}
next();
}
else if(res.data.code=='401')
{
// window.location.href=res.data.returnurl;
next('/login');
}
else
{
next('/login');
}
}).catch(error => {
console.log(error);
next('/login');
});
} else {
next();
}
}
});
更多推荐
已为社区贡献1条内容
所有评论(0)