In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is about a sample analysis of ASP.NET MVC SSO single sign-on. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Experimental environment configuration
The HOST file is configured as follows:
127.0.0.1 app.com
127.0.0.1 sso.com
The IIS configuration is as follows:
The application pool uses .net Framework 4.0.
Notice the domain name bound by IIS, two completely different domain names.
The app.com website is configured as follows:
The sso.com website is configured as follows:
Memcached cache:
Database configuration:
The database uses EntityFramework 6.0.0, and the corresponding database and table structure are automatically created when it is run for the first time.
The authorization verification process demonstrates:
Visit: http://app.com in the browser address bar. If the user has not logged in, the website will be automatically redirected to: http://sso.com/passport, and the corresponding AppKey application ID will be passed by passing parameters through QueryString. The screenshot is as follows:
URL address: http://sso.com/passport?appkey=670b14728ad9902aecba32e22fa4f6bd&username=
After entering the correct login account and password, click the login button to redirect the system to the application automatically 301, which will drop the home page. After destroying it successfully, it is as follows:
Because the SSO authorization login is carried out in different domains, the authorization ID is returned by QueryString. Cookie can be used under the same domain website. Because the 301 redirect request is sent by the browser, it will be lost when the browser redirects if the authorization ID is placed in the Handers. After the redirection is successful, the program automatically writes the authorization logo to the Cookie. When you click on another page address, the authorization mark information will no longer be seen in the URL address bar. The Cookie settings are as follows:
Subsequent authorization verification after successful login (visit other pages that require authorization):
Check address: http://sso.com/api/passport?sessionkey=xxxxxx&remark=xxxxxx
Returned result: true,false
According to the actual business situation, the client can choose to remind the user that the authorization has been lost and needs to be re-authorized. By default, it is automatically redirected to the SSO landing page, that is, the email address text box of the http://sso.com/passport?appkey=670b14728ad9902aecba32e22fa4f6bd&username=seo@ljja.cn landing page will customize and complete the user's login account. Users only need to enter the login password, and the session validity period will be automatically extended for one year after successful authorization.
SSO Database Verification Log:
User authorization verification log:
User Authorization session Session:
Database user account and application information:
The core code of the application authorization login verification page:
/ Public key: AppKey / Private key: AppSecret / session: SessionKey / public class PassportController: Controller {private readonly IAppInfoService _ appInfoService = new AppInfoService (); private readonly IAppUserService _ appUserService = new AppUserService (); private readonly IUserAuthSessionService _ authSessionService = new UserAuthSessionService (); private readonly IUserAuthOperateService _ userAuthOperateService = new UserAuthOperateService (); private const string AppInfo = "AppInfo"; private const string SessionKey = "SessionKey"; private const string SessionUserName = "SessionUserName" / / default login interface public ActionResult Index (string appKey = "", string username = "") {TempData [AppInfo] = _ appInfoService.Get (appKey); var viewModel = new PassportLoginRequest {AppKey = appKey, UserName = username}; return View (viewModel) } / / authorized login [HttpPost] public ActionResult Index (PassportLoginRequest model) {/ / get application information var appInfo = _ appInfoService.Get (model.AppKey); if (appInfo = = null) {/ / Application does not exist return View (model);} TempData [AppInfo] = appInfo If (ModelState.IsValid = = false) {/ / entity authentication failed return View (model);} / / filter field invalid characters model.Trim (); / / get user information var userInfo = _ appUserService.Get (model.UserName); if (userInfo = = null) {/ / user does not exist return View (model) } if (userInfo.UserPwd! = model.Password.ToMd5 ()) {/ / incorrect password return View (model);} / / get the current unexpired Session var currentSession = _ authSessionService.ExistsByValid (appInfo.AppKey, userInfo.UserName) If (currentSession = = null) {/ / build Session currentSession = new UserAuthSession {AppKey = appInfo.AppKey, CreateTime = DateTime.Now, InvalidTime = DateTime.Now.AddYears (1), IpAddress = Request.UserHostAddress, SessionKey = Guid.NewGuid (). ToMd5 (), UserName = userInfo.UserName} / / create Session _ authSessionService.Create (currentSession);} else {/ / extend the validity period. Default is one year _ authSessionService.ExtendValid (currentSession.SessionKey). } / / record user authorization log _ userAuthOperateService.Create (new UserAuthOperate {CreateTime = DateTime.Now, IpAddress = Request.UserHostAddress, Remark = string.Format ("{0} login {1} authorization succeeded", currentSession.UserName, appInfo.Title), SessionKey = currentSession.SessionKey}) Var redirectUrl = string.Format ("{0}? SessionKey= {1} & SessionUserName= {2}", appInfo.ReturnUrl, currentSession.SessionKey, userInfo.UserName); / / Hop default callback page return Redirect (redirectUrl);}} Memcached session identity verification core code: public class PassportController: ApiController {private readonly IUserAuthSessionService _ authSessionService = new UserAuthSessionService (); private readonly IUserAuthOperateService _ userAuthOperateService = new UserAuthOperateService () Public bool Get (string sessionKey = "", string remark = "") {if (_ authSessionService.GetCache (sessionKey)) {_ userAuthOperateService.Create (new UserAuthOperate {CreateTime = DateTime.Now, IpAddress = Request.RequestUri.Host, Remark = string.Format ("Verification succeeded-{0}", remark), SessionKey = sessionKey}); return true } _ userAuthOperateService.Create (new UserAuthOperate {CreateTime = DateTime.Now, IpAddress = Request.RequestUri.Host, Remark = string.Format ("Verification failed-{0}", remark), SessionKey = sessionKey}); return false;}}
Client Authorization Verification Filters Attribute
Public class SSOAuthAttribute: ActionFilterAttribute {public const string SessionKey = "SessionKey"; public const string SessionUserName = "SessionUserName"; public override void OnActionExecuting (ActionExecutingContext filterContext) {var cookieSessionkey = ""; var cookieSessionUserName = ""; / / SessionKey by QueryString if (filterContext.HttpContext.Request.QueryString [SessionKey]! = null) {cookieSessionkey = filterContext.HttpContext.Request.QueryString [SessionKey]; filterContext.HttpContext.Response.Cookies.Add (new HttpCookie (SessionKey, cookieSessionkey)) } / / SessionUserName by QueryString if (filterContext.HttpContext.Request.QueryString [SessionUserName]! = null) {cookieSessionUserName = filterContext.HttpContext.Request.QueryString [SessionUserName]; filterContext.HttpContext.Response.Cookies.Add (new HttpCookie (SessionUserName, cookieSessionUserName));} / / read SessionKey if from Cookie (filterContext.HttpContext.Request.Cookies [SessionKey]! = null) {cookieSessionkey = filterContext.HttpContext.Request.Cookies [SessionKey] .value } / / read SessionUserName if from Cookie (filterContext.HttpContext.Request.Cookies [SessionUserName]! = null) {cookieSessionUserName = filterContext.HttpContext.Request.Cookes [SessionUserName] .value;} if (string.IsNullOrEmpty (cookieSessionkey) | | string.IsNullOrEmpty (cookieSessionUserName)) {/ / login directly to filterContext.Result = SsoLoginResult (cookieSessionUserName) } else {/ / verify if (CheckLogin (cookieSessionkey, filterContext.HttpContext.Request.RawUrl) = = false) {/ / session lost, jump to login page filterContext.Result = SsoLoginResult (cookieSessionUserName);}} base.OnActionExecuting (filterContext) } public static bool CheckLogin (string sessionKey, string remark= "") {var httpClient = new HttpClient {BaseAddress = new Uri (ConfigurationManager.AppSettings ["SSOPassport"])}; var requestUri = string.Format ("api/Passport?sessionKey= {0} & remark= {1}", sessionKey, remark); try {var resp = httpClient.GetAsync (requestUri) .Result; resp.EnsureSuccessStatusCode () Return resp.Content.ReadAsAsync () .Result;} catch (Exception ex) {throw ex;}} private static ActionResult SsoLoginResult (string username) {return new RedirectResult (string.Format ("{0} / passport?appkey= {1} & username= {2}", ConfigurationManager.AppSettings ["SSOPassport"], ConfigurationManager.AppSettings ["SSOAppKey"], username);}}
The example SSO verification feature is used:
[SSOAuth] public class HomeController: Controller {public ActionResult Index () {return View ();} public ActionResult About () {ViewBag.Message = "Your application description page."; return View ();} public ActionResult Contact () {ViewBag.Message = "Your contact page."; return View ();}} Thank you for reading! This is the end of this article on "sample Analysis of ASP.NET MVC SSO single sign-on". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.