1.IIS建立3个MVC
1)SSO创建Login.csHtml
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>管理员登陆 - 统一权限管理平台</title>
<link rel="stylesheet" href="~/Scripts/static/common/layui/css/layui.css">
<link rel="stylesheet" href="~/Scripts/static/admin/css/login.css">
<script src="~/Scripts/static/common/jquery-3.3.1.min.js"></script>
<script src="~/Scripts/static/common/layui/layui.js"></script>
<script src="~/Scripts/static/admin/js/canvas.js"></script>
</head>
<body id="login">
<div class="login">
<h2>统一权限管理平台</h2>
<form class="layui-form" method="post" action="">
<div class="layui-form-item">
<input type="username" name="Name" id="username" placeholder="用户名" required lay-verify="required" class="layui-input">
<i class="layui-icon input-icon"></i>
</div>
<div class="layui-form-item">
<input type="password" name="Password" id="pwd" placeholder="密码" required lay-verify="required" class="layui-input">
<i class="layui-icon input-icon"></i>
</div>
<div class="layui-form-item">
<input type="text" name="Code" id="code" value="" placeholder="请输入验证码" class="layui-input" style="Width:160px;float:left">
<canvas id="canvas" width="100" height="38"></canvas>
</div>
<div class="layui-form-item">
<input type="checkbox" name="IsCheck" lay-skin="primary" title="记住密码" checked="">
</div>
<div class="layui-form-item">
<button style="width: 100%" class="layui-btn" lay-submit lay-filter="login" onclick="return false;">立即登录</button>
</div>
</form>
<script>
$(function () {
//页面加载刷新验证码
var show_num = [];
draw(show_num);
//点击图片刷新验证码
$("#canvas").on('click', function () {
draw(show_num);
})
layui.use('form', function () {
var form = layui.form,
layer = layui.layer,
$ = layui.jquery;
//表单提交
form.on('submit(login)', function (data) {
//验证码校验
var val = $("#code").val().toLowerCase();
var num = show_num.join("");
if (val == '') {
layer.alert('请输入验证码!');
} else if (val != num) {
layer.alert('验证码错误!请重新输入!');
$("#code").val('');
draw(show_num);
}
else {
$.ajax({
url: '/Home/ValidateLogin',
method: 'post',
data: data.field,
dataType: 'JSON',
success: function (result) {
window.location.href = result.Url;
}
});
}
});
});
});
</script>
</div>
</body>
</html>
2.每个Mvc连接Redis(引用ServiceStack.Redis包)
1)管理NewGet包安装StackExchange.Redis安装包
2)在三个MVC Web.Congif 添加节点
<add key="RedisServer" value="127.0.0.1"/>
<!--过期时间-->
<add key="Timeout" value="30"/>
3)test1 和test2 额外添加
<add key="UserAuthUrl" value="http://www.SSO.com" />
<!--redis服务器-->
<add key="RedisServer" value="127.0.0.1" />
<!--过期时间-->
<add key="Timeout" value="30" />
4)三个Mvc 添加实体和上下文
public class UserInfo
{
public string UserName { get; set; }
public string PassWord { get; set; }
}
public class UserInfoContext
{
public static UserInfoContext Context =new UserInfoContext();
//创建Key
private string SessionKey = "USERINFO_KEY";
//存储对象及会话
public HttpSessionState httpSessionState => HttpContext.Current.Session;
//存储用户对象
public UserInfo userInfo
{
get
{
return httpSessionState[SessionKey] as UserInfo;
}
set
{
httpSessionState[SessionKey] = value;
}
}
}
5)test1和test2 Home控制器写入方法
using System.Configuration;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using Test2.Models;
namespace Test2.Controllers
{
public class HomeController : Controller
{
/// <summary>
/// 获取跳转url
/// </summary>
/// <returns></returns>
public string TokenReplace()
{
string strHost = HttpContext.Request.Url.Host;
string strPort = HttpContext.Request.Url.Port.ToString();
string url = String.Format("http://{0}:{1}{2}", strHost, strPort, HttpContext.Request.RawUrl);
url = Regex.Replace(url, @"(\?|&)Token=.*", "", RegexOptions.IgnoreCase);
return ConfigurationManager.AppSettings["UserAuthUrl"] + "?backurl=" + url;
}
public ActionResult Index()
{
var token = GetCookie("token");
RedisClient client = new RedisClient(ConfigurationManager.AppSettings["RedisServer"], 6379, "123456");
UserInfo userInfo = client.Get<UserInfo>(token);
if (userInfo == null)
{
SetCookie("token", token, -1);
//令牌错误,重新登录
HttpContext.Response.Redirect(TokenReplace(), false);
}
else
{
SetCookie("token", token, Int32.Parse(ConfigurationManager.AppSettings["Timeout"]));
UserInfoContext.Context.userInfo = userInfo;
}
return View();
}
public ActionResult Login()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
/// <summary>
/// 添加一个Cookie
/// </summary>
/// <param name="cookiename">cookie名</param>
/// <param name="cookievalue">cookie值</param>
/// <param name="expires">过期时间 DateTime</param>
public void SetCookie(string cookiename, string cookievalue, int seconds)
{
HttpCookie cookie = new HttpCookie(cookiename)
{
Value = cookievalue,
Expires = DateTime.Now.AddSeconds(seconds)
};
HttpContext.Response.Cookies.Add(cookie);
}
/// <summary>
/// 获取一个Cookie
/// </summary>
/// <param name="cookiename">cookie名</param>
public string GetCookie(string cookiename)
{
HttpCookie cookie = HttpContext.Request.Cookies.Get(cookiename);
if (cookie == null)
return string.Empty;
return cookie.Value;
}
}
}
6)SSO Home控制器中写入方法
public JsonResult ValidateLogin(string name,string password)
{
OperateResult operateResult = new OperateResult();
if (name == "admin" && password == "admin")
{
UserInfo userInfo = new UserInfo()
{
UserName = "admin",
PassWord = "admin"
};
//生成token
var token = Guid.NewGuid().ToString();
//写入token
SetCookie("token", token, Int32.Parse(ConfigurationManager.AppSettings["Timeout"]));
//写入凭证
RedisClient client = new RedisClient(ConfigurationManager.AppSettings["RedisServer"], 6379,"123456");
client.Set<UserInfo>(token, userInfo);
//跳转回分站
if (Request.QueryString["backurl"] != null)
{
operateResult.Url = Request.QueryString["backurl"];
}
else
{
operateResult.Url = ConfigurationManager.AppSettings["DefaultUrl"];
}
}
return Json(operateResult);
}
7)IIS运行测试