From 781ae8900de1255213f7eeb87b7017a6dcaa84eb Mon Sep 17 00:00:00 2001 From: yubaolee Date: Fri, 8 Jul 2016 18:51:48 +0800 Subject: [PATCH] =?UTF-8?q?v1.2=E7=89=88=EF=BC=8C=E5=85=A8=E9=9D=A2?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0SSO=E7=99=BB=E9=99=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- OpenAuth.App/LoginApp.cs | 25 +---- OpenAuth.App/ModuleManagerApp.cs | 4 +- OpenAuth.App/OpenAuth.App.csproj | 2 + OpenAuth.App/SSO/AuthUtil.cs | 65 ++++++++++++- OpenAuth.App/SSO/SSOController.cs | 86 ++++++++++++++++++ OpenAuth.App/SSO/UserAuthSession.cs | 20 ++++ OpenAuth.App/ViewModel/LoginUserVM.cs | 1 - OpenAuth.Mvc/Controllers/BaseController.cs | 12 +-- OpenAuth.Mvc/Controllers/LoginController.cs | 31 +++++-- OpenAuth.Mvc/Global.asax.cs | 62 ++++++------- .../Areas/SSO/Controllers/CheckController.cs | 38 ++++++++ .../SSO/Controllers/PassportController.cs | 18 ---- .../Areas/SSO/Views/Login/Index.cshtml | 2 +- OpenAuth.WebApi/OpenAuth.WebApi.csproj | 3 +- .../Controllers/HomeController.cs | 9 ++ .../Controllers/LoginController.cs | 8 +- OpenAuth.WebTest/Scripts/_references.js | Bin 600 -> 600 bytes OpenAuth.WebTest/Views/Home/Index.cshtml | 79 +++++++--------- OpenAuth.WebTest/Views/Login/Index.cshtml | 8 +- 19 files changed, 326 insertions(+), 147 deletions(-) create mode 100644 OpenAuth.App/SSO/SSOController.cs create mode 100644 OpenAuth.App/SSO/UserAuthSession.cs create mode 100644 OpenAuth.WebApi/Areas/SSO/Controllers/CheckController.cs delete mode 100644 OpenAuth.WebApi/Areas/SSO/Controllers/PassportController.cs diff --git a/OpenAuth.App/LoginApp.cs b/OpenAuth.App/LoginApp.cs index 3e30590d..b27fa436 100644 --- a/OpenAuth.App/LoginApp.cs +++ b/OpenAuth.App/LoginApp.cs @@ -4,6 +4,7 @@ using System.Web; using Infrastructure; using OpenAuth.App.ViewModel; using System.Web.Security; +using OpenAuth.App.SSO; using OpenAuth.Domain.Service; namespace OpenAuth.App @@ -17,31 +18,14 @@ namespace OpenAuth.App _service = service; } - public void Login(string userName, string password) - { - _service.Check(userName, password); - FormsAuthentication.SetAuthCookie(userName, true); - - } - - /// - /// 开发者登陆 - /// - public void LoginByDev() - { - _service.SetSysUser(); - FormsAuthentication.SetAuthCookie("System", true); - - } - public LoginUserVM GetLoginUser() { - if (!HttpContext.Current.User.Identity.IsAuthenticated) + if (!AuthUtil.CheckLogin()) { throw new HttpException(401,"未登录"); } - string username = HttpContext.Current.User.Identity.Name; - return GetLoginUser(username); + + return AuthUtil.GetCurrentUser(); } public LoginUserVM GetLoginUser(string username) @@ -53,7 +37,6 @@ namespace OpenAuth.App AccessedOrgs = _service.Orgs, Modules = _service.Modules.MapToList(), Resources = _service.Resources, - Token = GenerateId.GetGuidHash() }; foreach (var moduleView in user.Modules) diff --git a/OpenAuth.App/ModuleManagerApp.cs b/OpenAuth.App/ModuleManagerApp.cs index 714ffff5..d28b6593 100644 --- a/OpenAuth.App/ModuleManagerApp.cs +++ b/OpenAuth.App/ModuleManagerApp.cs @@ -2,6 +2,7 @@ using OpenAuth.Domain; using System.Collections.Generic; using System.Web; +using OpenAuth.App.SSO; using OpenAuth.Domain.Service; namespace OpenAuth.App @@ -20,8 +21,7 @@ namespace OpenAuth.App /// public dynamic Load(int parentId, int pageindex, int pagesize) { - string loginuser = HttpContext.Current.User.Identity.Name; - return _moduleManService.Load(loginuser, parentId, pageindex, pagesize); + return _moduleManService.Load(AuthUtil.GetCurrentUser().User.Account, parentId, pageindex, pagesize); } public void Delete(int id) diff --git a/OpenAuth.App/OpenAuth.App.csproj b/OpenAuth.App/OpenAuth.App.csproj index 0c1d0acf..5d0b7ab9 100644 --- a/OpenAuth.App/OpenAuth.App.csproj +++ b/OpenAuth.App/OpenAuth.App.csproj @@ -80,8 +80,10 @@ + + diff --git a/OpenAuth.App/SSO/AuthUtil.cs b/OpenAuth.App/SSO/AuthUtil.cs index d1cc159f..fad765cf 100644 --- a/OpenAuth.App/SSO/AuthUtil.cs +++ b/OpenAuth.App/SSO/AuthUtil.cs @@ -1,17 +1,42 @@ +// *********************************************************************** +// Assembly : OpenAuth.App +// Author : yubaolee +// Created : 07-08-2016 +// +// Last Modified By : yubaolee +// Last Modified On : 07-08-2016 +// Contact : Microsoft +// File: AuthUtil.cs +// *********************************************************************** + + using System; using System.Configuration; using System.Web; using Infrastructure; +using OpenAuth.App.ViewModel; namespace OpenAuth.App.SSO { public class AuthUtil { static HttpHelper _helper = new HttpHelper(ConfigurationManager.AppSettings["SSOPassport"]); + + private static string GetToken() + { + string token = HttpContext.Current.Request.QueryString["Token"]; + if (!string.IsNullOrEmpty(token)) return token; + + var cookie = HttpContext.Current.Request.Cookies["Token"]; + return cookie == null ? string.Empty : cookie.Value; + } + public static bool CheckLogin(string token, string remark = "") { - - var requestUri = string.Format("/api/Passport?token={0}&requestid={1}", token, remark); + if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(GetToken())) + return false; + + var requestUri = string.Format("/SSO/Check/GetStatus?token={0}&requestid={1}", token, remark); try { @@ -24,6 +49,34 @@ namespace OpenAuth.App.SSO } } + public static bool CheckLogin(string remark="") + { + return CheckLogin(GetToken(), remark); + } + + public static LoginUserVM GetCurrentUser(string remark = "") + { + + var requestUri = string.Format("/SSO/Check/GetUser?token={0}&requestid={1}", GetToken(), remark); + + try + { + var value = _helper.Get(null, requestUri); + return value; + } + catch (Exception ex) + { + throw ex; + } + } + + /// + /// ½ӿ + /// + /// Ӧókey. + /// û + /// + /// System.String. public static string Login(string appKey, string username, string pwd) { var requestUri = "/SSO/Login/Check"; @@ -53,12 +106,14 @@ namespace OpenAuth.App.SSO } } + /// + /// ע + /// public static bool Logout() { - var tokenCookie = HttpContext.Current.Request.Cookies["Token"]; - if (tokenCookie == null) return true; + var token = GetToken(); + if (string.IsNullOrEmpty(token)) return true; - string token = tokenCookie.Value; var requestUri = string.Format("/SSO/Login/Logout?token={0}&requestid={1}", token, ""); try diff --git a/OpenAuth.App/SSO/SSOController.cs b/OpenAuth.App/SSO/SSOController.cs new file mode 100644 index 00000000..3c16e60f --- /dev/null +++ b/OpenAuth.App/SSO/SSOController.cs @@ -0,0 +1,86 @@ +// *********************************************************************** +// Assembly : OpenAuth.Mvc +// Author : Administrator +// Created : 09-22-2015 +// +// Last Modified By : Administrator +// Last Modified On : 09-22-2015 +// *********************************************************************** +// +// Copyright (c) . All rights reserved. +// +// +// 基础控制器 +// 继承该控制器可以防止未登录查看 +// 继承该控制器后,如果想访问控制器中存在,但模块配置里面没有的Action(如:Home/Git),请使用AnonymousAttribute +// +// *********************************************************************** + +using System.Web; +using System.Web.Mvc; + +namespace OpenAuth.App.SSO +{ + public class SSOController : Controller + { + public const string Token = "Token"; + public const string SessionUserName = "SessionUserName"; + + protected override void OnActionExecuting(ActionExecutingContext filterContext) + { + var token = ""; + var cookieSessionUserName = ""; + + //Token by QueryString + var request = filterContext.HttpContext.Request; + if (request.QueryString[Token] != null) + { + token = request.QueryString[Token]; + filterContext.HttpContext.Response.Cookies.Add(new HttpCookie(Token, token)); + } + else if (request.Cookies[Token] != null) //从Cookie读取Token + { + token = request.Cookies[Token].Value; + } + + //SessionUserName by QueryString + if (request.QueryString[SessionUserName] != null) + { + cookieSessionUserName = request.QueryString[SessionUserName]; + filterContext.HttpContext.Response.Cookies.Add(new HttpCookie(SessionUserName, cookieSessionUserName)); + } + else if (request.Cookies[SessionUserName] != null) //从Cookie读取SessionUserName + { + cookieSessionUserName = request.Cookies[SessionUserName].Value; + } + + if (string.IsNullOrEmpty(token)) + { + //直接登录 + filterContext.Result = SsoLoginResult(cookieSessionUserName); + } + else + { + //验证 + if (AuthUtil.CheckLogin(token, request.RawUrl) == false) + { + //会话丢失,跳转到登录页面 + filterContext.Result = SsoLoginResult(cookieSessionUserName); + } + } + + base.OnActionExecuting(filterContext); + } + + private static ActionResult SsoLoginResult(string username) + { + //跳转到SSO站点登陆 + //return new RedirectResult(string.Format("{0}/sso/login?appkey={1}&username={2}", + // ConfigurationManager.AppSettings["SSOPassport"], + // ConfigurationManager.AppSettings["SSOAppKey"], + // username)); + + return new RedirectResult("/Login/Index"); + } + } +} \ No newline at end of file diff --git a/OpenAuth.App/SSO/UserAuthSession.cs b/OpenAuth.App/SSO/UserAuthSession.cs new file mode 100644 index 00000000..d3687eb3 --- /dev/null +++ b/OpenAuth.App/SSO/UserAuthSession.cs @@ -0,0 +1,20 @@ +using System; + +namespace OpenAuth.WebApi.Areas.SSO.Models +{ + [Serializable] + public class UserAuthSession + { + public string Token { get; set; } + + public string AppKey { get; set; } + + public string UserName { get; set; } + + public string IpAddress { get; set; } + + public DateTime InvalidTime { get; set; } + + public DateTime CreateTime { get; set; } + } +} \ No newline at end of file diff --git a/OpenAuth.App/ViewModel/LoginUserVM.cs b/OpenAuth.App/ViewModel/LoginUserVM.cs index 558c640b..7b216ab9 100644 --- a/OpenAuth.App/ViewModel/LoginUserVM.cs +++ b/OpenAuth.App/ViewModel/LoginUserVM.cs @@ -22,7 +22,6 @@ namespace OpenAuth.App.ViewModel /// public class LoginUserVM { - public string Token { get; set; } public User User { get; set; } /// /// 用户可以访问到的模块(包括所属角色与自己的所有模块) diff --git a/OpenAuth.Mvc/Controllers/BaseController.cs b/OpenAuth.Mvc/Controllers/BaseController.cs index e25ccd45..5817d765 100644 --- a/OpenAuth.Mvc/Controllers/BaseController.cs +++ b/OpenAuth.Mvc/Controllers/BaseController.cs @@ -24,21 +24,20 @@ using System.Reflection; using System.Web; using System.Web.Mvc; using OpenAuth.App; +using OpenAuth.App.SSO; namespace OpenAuth.Mvc.Controllers { - public class BaseController : Controller + public class BaseController : SSOController { protected BjuiResponse BjuiResponse = new BjuiResponse(); protected override void OnActionExecuting(ActionExecutingContext filterContext) { + base.OnActionExecuting(filterContext); + var loginUser = AutofacExt.GetFromFac().GetLoginUser(); - if (!User.Identity.IsAuthenticated) - { - filterContext.Result = new RedirectResult("/Login/Index"); - return; - } + var controllername = Request.RequestContext.RouteData.Values["controller"].ToString().ToLower(); var actionname = filterContext.ActionDescriptor.ActionName.ToLower(); @@ -69,7 +68,6 @@ namespace OpenAuth.Mvc.Controllers } } - base.OnActionExecuting(filterContext); } } } \ No newline at end of file diff --git a/OpenAuth.Mvc/Controllers/LoginController.cs b/OpenAuth.Mvc/Controllers/LoginController.cs index 81b0027d..cd08485c 100644 --- a/OpenAuth.Mvc/Controllers/LoginController.cs +++ b/OpenAuth.Mvc/Controllers/LoginController.cs @@ -1,10 +1,7 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; using System.Web.Mvc; -using System.Web.Security; using OpenAuth.App; +using OpenAuth.App.SSO; using OpenAuth.Mvc.Models; namespace OpenAuth.Mvc.Controllers @@ -28,8 +25,18 @@ namespace OpenAuth.Mvc.Controllers { try { - _app.Login(username, password); - return RedirectToAction("Index", "Home"); + var token = AuthUtil.Login("670b14728ad9902aecba32e22fa4f6bd", username, password); + if (!string.IsNullOrEmpty(token)) + return Redirect("/home/index?Token=" + token); + else + { + var response = new BjuiResponse + { + statusCode = "300", + message = "登陆失败" + }; + return View(response); + } } catch (Exception e) @@ -50,8 +57,14 @@ namespace OpenAuth.Mvc.Controllers { try { - _app.LoginByDev(); - return RedirectToAction("Index", "Home"); + var token = AuthUtil.Login("670b14728ad9902aecba32e22fa4f6bd", "System",""); + if (!string.IsNullOrEmpty(token)) + return Redirect("/home/index?Token=" + token); + else + { + return RedirectToAction("Index", "Login"); + + } } catch (Exception e) @@ -63,7 +76,7 @@ namespace OpenAuth.Mvc.Controllers public ActionResult Logout() { - FormsAuthentication.SignOut(); + AuthUtil.Logout(); return RedirectToAction("Index", "Login"); } } diff --git a/OpenAuth.Mvc/Global.asax.cs b/OpenAuth.Mvc/Global.asax.cs index 563e15b3..ae252c47 100644 --- a/OpenAuth.Mvc/Global.asax.cs +++ b/OpenAuth.Mvc/Global.asax.cs @@ -24,39 +24,39 @@ namespace OpenAuth.Mvc } - //protected void Application_Error(object sender, EventArgs e) - //{ - // var app = (MvcApplication)sender; - // var context = app.Context; - // var ex = app.Server.GetLastError(); - // LogHelper.Fatal(ex.Message); + protected void Application_Error(object sender, EventArgs e) + { + var app = (MvcApplication)sender; + var context = app.Context; + var ex = app.Server.GetLastError(); + LogHelper.Fatal(ex.Message); - // context.Response.Clear(); - // context.ClearError(); - // var httpException = ex as HttpException; - // var routeData = new RouteData(); - // routeData.Values["controller"] = "error"; - // routeData.Values["exception"] = ex; - // routeData.Values["action"] = "http500"; - // if (httpException != null) - // { + context.Response.Clear(); + context.ClearError(); + var httpException = ex as HttpException; + var routeData = new RouteData(); + routeData.Values["controller"] = "error"; + routeData.Values["exception"] = ex; + routeData.Values["action"] = "http500"; + if (httpException != null) + { - // switch (httpException.GetHttpCode()) - // { - // case 404: - // routeData.Values["action"] = "http404"; - // break; - // case 401: //没有登录 - // routeData.Values["action"] = "http401"; - // break; - // case 400: //演示版本,没有执行的权限 - // routeData.Values["action"] = "DemoError"; - // break; - // } - // } - // IController controller = new ErrorController(); - // controller.Execute(new RequestContext(new HttpContextWrapper(context), routeData)); - //} + switch (httpException.GetHttpCode()) + { + case 404: + routeData.Values["action"] = "http404"; + break; + case 401: //没有登录 + routeData.Values["action"] = "http401"; + break; + case 400: //演示版本,没有执行的权限 + routeData.Values["action"] = "DemoError"; + break; + } + } + IController controller = new ErrorController(); + controller.Execute(new RequestContext(new HttpContextWrapper(context), routeData)); + } } } diff --git a/OpenAuth.WebApi/Areas/SSO/Controllers/CheckController.cs b/OpenAuth.WebApi/Areas/SSO/Controllers/CheckController.cs new file mode 100644 index 00000000..2e8e94ba --- /dev/null +++ b/OpenAuth.WebApi/Areas/SSO/Controllers/CheckController.cs @@ -0,0 +1,38 @@ +using System.Web.Http; +using System.Web.Mvc; +using Infrastructure; +using OpenAuth.App; +using OpenAuth.WebApi.Areas.SSO.Models.Services; + +namespace OpenAuth.WebApi.Areas.SSO.Controllers +{ + public class CheckController : Controller + { + private LoginApp _app; + public CheckController() + { + _app = AutofacExt.GetFromFac(); + } + + public bool GetStatus(string token = "", string requestid = "") + { + if (new UserAuthSessionService().GetCache(token)) + { + return true; + } + + return false; + } + + public string GetUser(string token = "", string requestid = "") + { + var user = new UserAuthSessionService().Get(token); + if (user != null) + { + return JsonHelper.Instance.Serialize(_app.GetLoginUser(user.UserName)); + } + + return string.Empty; + } + } +} \ No newline at end of file diff --git a/OpenAuth.WebApi/Areas/SSO/Controllers/PassportController.cs b/OpenAuth.WebApi/Areas/SSO/Controllers/PassportController.cs deleted file mode 100644 index c5932bb8..00000000 --- a/OpenAuth.WebApi/Areas/SSO/Controllers/PassportController.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System.Web.Http; -using OpenAuth.WebApi.Areas.SSO.Models.Services; - -namespace OpenAuth.WebApi.Areas.SSO.Controllers -{ - public class PassportController : ApiController - { - public bool Get(string token = "", string requestid = "") - { - if (new UserAuthSessionService().GetCache(token)) - { - return true; - } - - return false; - } - } -} \ No newline at end of file diff --git a/OpenAuth.WebApi/Areas/SSO/Views/Login/Index.cshtml b/OpenAuth.WebApi/Areas/SSO/Views/Login/Index.cshtml index 54fa0f40..70d39d8f 100644 --- a/OpenAuth.WebApi/Areas/SSO/Views/Login/Index.cshtml +++ b/OpenAuth.WebApi/Areas/SSO/Views/Login/Index.cshtml @@ -1,5 +1,5 @@ @using OpenAuth.WebApi.Areas.SSO.Models -@model OpenAuth.WebApi.Areas.SSO.Models.PassportLoginRequest +@model PassportLoginRequest @{ ViewBag.Title = "用户授权应用登录"; diff --git a/OpenAuth.WebApi/OpenAuth.WebApi.csproj b/OpenAuth.WebApi/OpenAuth.WebApi.csproj index ec434ab9..d12ae22a 100644 --- a/OpenAuth.WebApi/OpenAuth.WebApi.csproj +++ b/OpenAuth.WebApi/OpenAuth.WebApi.csproj @@ -150,7 +150,7 @@ - + @@ -159,7 +159,6 @@ - diff --git a/OpenAuth.WebTest/Controllers/HomeController.cs b/OpenAuth.WebTest/Controllers/HomeController.cs index 912ae6f5..78b8180b 100644 --- a/OpenAuth.WebTest/Controllers/HomeController.cs +++ b/OpenAuth.WebTest/Controllers/HomeController.cs @@ -1,15 +1,24 @@ using System.Web.Mvc; +using OpenAuth.App; using OpenAuth.App.SSO; namespace OpenAuth.WebTest.Controllers { public class HomeController :Controller { + [SSOAuth] public ActionResult Index() { + var currentUser = AuthUtil.GetCurrentUser(); + ViewBag.CurrentUser = currentUser; return View(); } + + public ActionResult Admin() + { + return Redirect("http://localhost:56813?token=" + Request.Cookies["Token"].Value); + } } } \ No newline at end of file diff --git a/OpenAuth.WebTest/Controllers/LoginController.cs b/OpenAuth.WebTest/Controllers/LoginController.cs index 5b772e85..ce463487 100644 --- a/OpenAuth.WebTest/Controllers/LoginController.cs +++ b/OpenAuth.WebTest/Controllers/LoginController.cs @@ -18,7 +18,7 @@ namespace OpenAuth.WebTest.Controllers [HttpPost] public ActionResult Index(string username, string password) { - var token = AuthUtil.Login("670b14728ad9902aecba32e22fa4f6bd", username, "123"); + var token = AuthUtil.Login("670b14728ad9902aecba32e22fa4f6bd", username, password); if (!string.IsNullOrEmpty(token)) return Redirect("/home/index?Token=" + token); else @@ -26,5 +26,11 @@ namespace OpenAuth.WebTest.Controllers return View(); } } + + public ActionResult Logout() + { + AuthUtil.Logout(); + return Redirect("/Home/Index"); + } } } \ No newline at end of file diff --git a/OpenAuth.WebTest/Scripts/_references.js b/OpenAuth.WebTest/Scripts/_references.js index cbe7a470804985788af6cf4a4528208724d9f657..84aaa384d6e885573090e2785bd2b93b9046808c 100644 GIT binary patch delta 28 jcmcb?a)V_;-sD$|ev{=G&j2yc#4BDC^P(nOFev~4sM`v( delta 27 jcmcb?a)V_;-sF3XQ4{y@OrFB%HF3|GiFtmLEtnJlt)UB{ diff --git a/OpenAuth.WebTest/Views/Home/Index.cshtml b/OpenAuth.WebTest/Views/Home/Index.cshtml index 361b958f..e031d14f 100644 --- a/OpenAuth.WebTest/Views/Home/Index.cshtml +++ b/OpenAuth.WebTest/Views/Home/Index.cshtml @@ -1,62 +1,51 @@ @{ - ViewBag.Title = "Home Page"; + ViewBag.Title = "OpenAuth.net 测试页面"; }

OpenAuth.NET

这是OpenAuth.Net的测试站点,模拟一个第三方网站如何使用OpenAuth.net提供的权限功能!

-

Learn more » +

+ Learn more »

- -
-
-

登录

-

- @if (ViewBag.CurrentUser != null) - { - 当前登录用户:@ViewBag.CurrentUser.User.Account - 退出 - - } - else - { - 点击这里登陆 - } -

-
- -
-
- @if (ViewBag.CurrentUser != null) - { -

可访问的机构

-
    - @foreach (var org in ViewBag.CurrentUser.AccessedOrgs) + @if (ViewBag.CurrentUser != null) + { +
    +
    +

    @ViewBag.CurrentUser.User.Account ,您好!

    +

    因为使用了SSO,所以您可以直接进入OpenAuth.Net,而不用重复登陆

    +

    + 直接进入OpenAuth.Net + 注销 +

    +
    +
    + + } +
+
+ @if (ViewBag.CurrentUser != null) + { +

可访问的机构

+
    + @foreach (var org in ViewBag.CurrentUser.AccessedOrgs) { -
  • @org.Name
  • - } -
+
  • @org.Name
  • + } + -

    可访问的资源

    -
      - @foreach (var resource in ViewBag.CurrentUser.Resources) +

      可访问的资源

      +
        + @foreach (var resource in ViewBag.CurrentUser.Resources) { -
      • @resource.Name
      • - } -
      - } +
    • @resource.Name
    • + } +
    + }
    \ No newline at end of file diff --git a/OpenAuth.WebTest/Views/Login/Index.cshtml b/OpenAuth.WebTest/Views/Login/Index.cshtml index e41c6052..58f7c107 100644 --- a/OpenAuth.WebTest/Views/Login/Index.cshtml +++ b/OpenAuth.WebTest/Views/Login/Index.cshtml @@ -2,17 +2,17 @@ ViewBag.Title = "title"; } -

    Login

    +

    OpenAuth.net测试站点登陆

    - +
    - +
    @@ -22,7 +22,7 @@ - +