.NET Framework 旧系统新增SSO单点登录实例
最近公司的很多项目都要改单点登录了,不过大部分都还没敲定,目前立刻要做的就只有一个比较老的项目先改一个试试手,主要目标就是最短最快实现功能
首先因为要保留原登录方式,所以页面上的改动就是在原来登录页面下加一个SSO登录入口
用超链接写的入口,页面改造后如下图:
其中超链接的 href="StaffLogin.aspx"
新建Web窗体StaffLogin.aspx(名字可以随便起,只要能对应的上,不必非要叫StaffLogin),
前台不用管,直接写对应的后台StaffLogin.aspx.cs
注意添加引用:using Saml;
具体代码如下:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var samlEndpoint = "https://login.microsoftonline.com/fdaaaaa1-bfc1-4234-a91c-72bbbbbb9e26/saml2";
var request = new AuthRequest(
"aaaprd", //TODO: put your app's "entity ID" here
"https://xxxx此处替换为网址xxxx.com/Auth" //TODO: put Assertion Consumer URL (where the provider should redirect users after authenticating)
);
//now send the user to the SAML provider
string redirturl = request.GetRedirectUrl(samlEndpoint);
Response.Write("");
}
}request里面两个参数,第一个是entityID(是系统的唯一标识) 第二个是单点登录验证通过后回调的url
新建Web窗体Auth.aspx(名字可以随便起,只要能对应的上,不必非要叫Auth,这里叫这个名字是因为跟对接的人约定的回调URL是这个),
前台不用管,直接写对应的后台Auth.aspx.cs
具体代码如下:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{if (Request.Form.HasKeys() && null != Request.Form["SAMLResponse"])
{
string samlCertificate = @"-----BEGIN CERTIFICATE-----
此处为证书编码
-----END CERTIFICATE-----";<br> var samlResponse = new Response(samlCertificate, Request.Form["SAMLResponse"]);<br> if (samlResponse.IsValid())
{
var mail = samlResponse.GetNameID(); //let's get the username
DFS_S_UserInfo modelUser = new DFS_S_UserInfoBll().GetModelByMail(mail);
if (modelUser == null)
{string redirectUrl = string.Format("~/login.aspx?errorMessage={0}", HttpUtility.UrlEncode("系统内用户不存在"));
Response.Redirect(redirectUrl);
}
else
{
LoginInfo.SetInfo(modelUser.UserID);
if (LoginInfo.GetCurrentLoginInfo() != null)
{if (LoginInfo.GetCurrentLoginInfo().UserID > 0)
{
Response.Redirect("~/home.aspx", false); // 注意:endResponse设置为false
Context.ApplicationInstance.CompleteRequest(); // 手动结束请求
}
}
else
{string redirectUrl = string.Format("~/login.aspx?errorMessage={0}", HttpUtility.UrlEncode("人员登录验证失败"));
Response.Redirect(redirectUrl);
}
}
}
else
{string redirectUrl = string.Format("~/login.aspx?errorMessage={0}", HttpUtility.UrlEncode("人员登录验证失败"));
Response.Redirect(redirectUrl);
}
}
else
{string redirectUrl = string.Format("~/login.aspx?errorMessage={0}", HttpUtility.UrlEncode("人员登录验证失败"));
Response.Redirect(redirectUrl);
}
}
catch(Exception ex)
{
string redirectUrl = string.Format("~/login.aspx?errorMessage={0}", HttpUtility.UrlEncode("系统错误,请联系IT"));
Response.Redirect(redirectUrl);
}
}
}上述代码里证书samlCertificate是客户方提供的,entityID也是在拿到证书前先提供过去的
实际开发中,肯定要有的,这个不用担心,拿到证书替换进去既可,具体代码结构跟我这个应该差不多
samlResponse.IsValid()验证过就说明单点登录已经完成
里面的部分就是承接原系统的正常登录逻辑,仅供参考,具体按照系统的登录调整
来源:https://www.cnblogs.com/fkcxy/p/18242504
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页:
[1]