近来工作无事,想做个SSO, 之前做过一个项目用到SSO,自己也没有看明白是个什么东西。现在正好有时间,所以想研究下。
先是从网上看到了SSO的思路:
三个站点:SiteA,SiteB,SiteMain
1想到重写个ActionResult,于是就有了CustomRedirectResult(其实这种方式挺不好的, 不过也想试试看)
public class CustomRedirectResult:ActionResult { public override void ExecuteResult(ControllerContext context)
{
if (context.HttpContext.Session["Token"] == null)//if siteA doesn‘t have token,redirect user to siteMain to get token
{
string url = context.HttpContext.Request.Url.AbsoluteUri;
if (context.HttpContext.Request.QueryString["Token"] == null)
{
url= GetTokenURL();
}
context.HttpContext.Response.Redirect(url);
}
else //if siteA has token,direct user to the right requested page
{
context.HttpContext.Response.Redirect(context.HttpContext.Request.Url.AbsoluteUri + "UserInfo/IndexUserInfo");
}
} }
2 siteMain 里完成用户登录并返回到siteA
public void ReturnUserInfo() { string backurl = Request.Form["backurl"]; string token =GetToken(Request .Form ["Name"],Request.Form ["Password"]); backurl = Server.UrlDecode(backurl); backurl = backurl.Replace("$Token$", token); HttpContext.Response.Redirect(backurl);//backurl="http://localhost:45625/UserInfo/IndexUserInfo",mvc 中要跳转到此路径时
要用方法HttpContext.Response.Redirect(backurl)直接跳转; }
3 siteA通过如下方法来接收返回回来的Token
public ActionResult IndexUserInfo(String token)
{
Session["Token"] = token;
Account.AccountSoapClient account = new AccountSoapClient();//利用webservice来取得用户信息
SiteA.Account .User user = account.GetUserByToken(token) ;
Session["UserName"] = user.Name;
CustomIdentity identity = new CustomIdentity("Admin");
CustomPrincipal principal = new CustomPrincipal(identity, "admin");
HttpContext.Current.User = principal;
return View("IndexUserInfo", user);
}
然后我又增加了一个action,想看看是不是登录后,一些需要认证的action 能顺利访问到,如下:
[Authorize] public ActionResult GoToDesk() { string name = HttpContext.User.Identity.Name; return View("GoToDesk","",name ); }
一运行到GoToDesk就提示我没有权限。原来HttpContext.User在下一次请求已经变成了空,也就是说他只在一次请求的过程中有值。于是想在Global.asax文件的 Application_BeginRequest里再重新给httpcontext.current.user赋值,如下
protected void Application_BeginRequest(object sender, EventArgs e) { CustomIdentity identity = new CustomIdentity("Admin");//Admin is user name CustomPrincipal principal = new CustomPrincipal(identity, "admin");//admin is role name HttpContext.Current.User = principal; //HttpContext.Current.Request.Headers.Add("UserName", "Admin");//该写法在mvc平台下不支持,在webform下支持 }
问题出现了,user name 从什么地方获取呢,现在是写死成Admin了。除了用cookie以后还能有别的方法吗?
同时让我疑惑的是HttpContext.User只在一次请求下有值,那属性[Authorize]不就把所以之后的请求都给屏蔽在外边了吗?一定是我哪一块弄错了,望高人看到后指点一二。先在此谢过。
在网上搜索mvc sso的过程中看到了dotNetOpenAuth,然后写了一把,最终还是遇到了上述的问题,现在被block住了,希望有人来解救。