/// <summary> /// 异步通知 /// </summary> /// <param name="isOut"></param> /// <param name="id"></param> private static void NotifyDomains(bool isOut, SSOIdentity id) { TaskHelper.Factory.StartNew(() => { var client = new HttpClient(); foreach (var domain in Domains) { client.SetRequest(new Uri(domain.ClientHandlerUrl)); client.Form["_SID"] = id.SessionID; client.Form["Action"] = Convert.ToUInt32(isOut).ToString(); client.Form["Token"] = id.Token; App.Retry(() => { try { string text = client.GetResponse().GetResponseText(); return(text == "1"); } catch (System.Net.WebException ex) { App.LogError(ex, "SSOServiceNotify"); return(false); } }, 3); } }); }
public SSOIdentity SignIn(SignInParameter param) { SSOIdentity id = mgr.SignIn(param); if (id.IsAuthenticated) { this.SetSignIn(id); } return(id); }
/// <summary> /// Returns an instance of a SSOIdentity class, /// given an encrypted authentication string obtained from an HTTP cookie. /// </summary> /// <param name="encryptedInput">Encrypted string conataining User Identity</param> /// <returns>SSOIdentity object</returns> public static SSOIdentity Decrypt(string encryptedInput) { SSOIdentity identity = null; try { string decryptedString = SSOEncryption.Decrypt(encryptedInput); identity = JsonConvert.DeserializeObject <SSOIdentity>(decryptedString); } catch (Exception e) { string str = e.Message; throw; } return(identity); }
//const string LOGINURL_KEY = "SSO.LoginUrl"; //const string AUTHENTICATION_COOKIE_KEY = "SSO.Cookie.Name"; //const string CLIENTID_KEY = "SSO.ClientID"; //const string CLIENTSECRET_KEY = "SSO.ClientSecret"; //const string TENANTID_KEY = "SSO.TenantID"; //const string SCOPE_KEY = "SSO.Scope"; #region static methods /// <summary> /// Produces a string containing an encrypted string for an authenticated User Identity /// suitable for use in an HTTP cookie given a SSOIdentity /// </summary> /// <param name="identity">SSOIdentity class for the authenticated user</param> /// <returns>Encrypted string</returns> public static string Encrypt(SSOIdentity identity) { string encryptedString = String.Empty; try { var str = JsonConvert.SerializeObject(identity); encryptedString = SSOEncryption.Encrypt(str); } catch (Exception e) { string str = e.Message; throw; } return(encryptedString); }
/// <summary> /// Redirects an authenticated user back to the originally requested URL. /// </summary> /// <param name="identity">SSOIdentity of an authenticated user</param> public static void RedirectFromLoginPage(SSOIdentity identity, int tokenExpirationTime = 3600) { string cookieName = ".SSO_AUTH"; // ConfigurationManager.AppSettings[AUTHENTICATION_COOKIE_KEY]; if (cookieName == null || cookieName.Trim() == String.Empty) { throw new Exception("There are some issues in setting SSO at the moment. please contact maintainence."); } FormsAuthentication.SetAuthCookie(identity.UserName, false); HttpRequest request = HttpContext.Current.Request; HttpResponse response = HttpContext.Current.Response; string encryptedUserDetails = Encrypt(identity); HttpCookie userCookie = new HttpCookie(cookieName.ToUpper(), encryptedUserDetails); userCookie.Expires = DateTime.Now.AddSeconds(tokenExpirationTime); response.Cookies.Add(userCookie); string returnUrl = request["ReturnUrl"]; string state = request.QueryString.Get("state"); if (!string.IsNullOrEmpty(state) && state != null) { var stateBytes = Convert.FromBase64String(state); returnUrl = Encoding.UTF8.GetString(stateBytes); } if (returnUrl != null && returnUrl.Trim() != String.Empty) { response.Redirect(returnUrl); } else { response.Redirect("/"); } }
/// <summary> /// 把Identity写入内存,仅供上层调用不作对外服务 /// </summary> /// <param name="identity"></param> public void SetSignIn(SSOIdentity identity, DateTime?expiresDate = null) { var newToken = Guid.NewGuid(); var policy = new CacheItemPolicy() { Priority = CacheItemPriority.NotRemovable, SlidingExpiration = TimeSpan.FromMinutes(ExpireMinutes) }; if (expiresDate.HasValue) { if (identity.Token != null) { mgr.CreatePersistentIdentity(identity, expiresDate.Value, newToken); } policy.RemovedCallback = arguments => { if (arguments.RemovedReason == CacheEntryRemovedReason.Removed) { return; } var id = (SSOIdentity)arguments.CacheItem.Value; id.IsAuthenticated = false; mgr.CreatePersistentIdentity(id, expiresDate.Value); NotifyDomains(true, id); }; } if (identity.Token != null) { _cache.Remove(identity.Token); } //颁发新token,确保token随会话更新 identity.Token = newToken.ToString("N"); identity.IssueDate = DateTime.Now; identity.IsAuthenticated = true; _cache.Set(identity.Token, identity, policy); NotifyDomains(false, identity); }
/// <summary> /// 创建持久Identity /// </summary> /// <param name="id"></param> /// <param name="expiresDate"></param> /// <param name="newToken"></param> public void CreatePersistentIdentity(SSOIdentity id, DateTime expiresDate, Guid?newToken = null) { Guid token = Guid.ParseExact(id.Token, "N"); using (var context = base.CreateUserContext()) { if (newToken == null) { var dataObj = new PersistentSession() { Token = token, UserID = id.UserID, ExpiresDate = expiresDate }; context.PersistentSessions.Add(dataObj); } else { var dataObj = context.PersistentSessions.Where(t => t.Token == token).Single(); dataObj.Token = newToken.Value; } context.SaveChanges(); } }
internal SSOIdentityVariables(SSOIdentity identity) { this.identity = identity; }
void OnAuthenticate(object sender, EventArgs e) { app = (HttpApplication)sender; HttpRequest req = app.Request; HttpResponse res = app.Response; Debug.Write(req.IsAuthenticated); string cookieName = ".SSO_AUTH"; //ConfigurationManager.AppSettings[AUTHENTICATION_COOKIE_KEY]; if (cookieName == null || cookieName.Trim() == String.Empty) { throw new Exception(" SSOAuthentication.Cookie.Name entry not found in appSettings section section of Web.config"); } if (req.Cookies.Count > 0 && req.Cookies[".ASPXAUTH"] != null && req.Cookies[cookieName.ToUpper()] != null) { HttpCookie authCookie = req.Cookies[".ASPXAUTH"]; if (authCookie != null) { HttpCookie cookie = req.Cookies[cookieName.ToUpper()]; if (cookie != null) { string str = cookie.Value; SSOIdentity userIdentity = SSOAuthentication.Decrypt(str); string[] roles = userIdentity.UserRoles.Split(new char[] { '|' }); ArrayList arrRoles = new ArrayList(); arrRoles.InsertRange(0, roles); SSOPrincipal principal = new SSOPrincipal(userIdentity, arrRoles); app.Context.User = principal; Thread.CurrentPrincipal = principal; } return; } } string loginUrl = ConfigurationManager.AppSettings[LOGINURL_KEY]; string clientID = ConfigurationManager.AppSettings[CLIENTID_KEY]; string tenantID = ConfigurationManager.AppSettings[TENANTID_KEY]; string scopes = ConfigurationManager.AppSettings[SCOPE_KEY]; string clientSecret = ConfigurationManager.AppSettings[CLIENT_SECRET_KEY]; string redirectUri = ConfigurationManager.AppSettings[REDIRECT_URI_KEY]; string tokenUri = ConfigurationManager.AppSettings[TOKEN_URI_KEY]; if (loginUrl == null || loginUrl.Trim() == String.Empty) { throw new Exception(" SSOAuthentication.LoginUrl entry not found in appSettings section of Web.config"); } loginUrl += $"/{tenantID}/oauth2/v2.0/authorize/?client_id={clientID}&response_type=code&scope={scopes}"; if (req.QueryString.HasKeys() && req.QueryString.GetValues("code").Length > 0) { string code = req.QueryString.GetValues("code")[0]; WebClient wc = new WebClient(); var reqparm = new NameValueCollection(); reqparm.Add("client_id", clientID); reqparm.Add("scope", scopes); reqparm.Add("code", code); reqparm.Add("redirect_uri", redirectUri); reqparm.Add("grant_type", "authorization_code"); reqparm.Add("client_secret", clientSecret); string reirUrl = tokenUri; HttpWebResponse httpResponse = null; string response = WebServiceRedirect(req, "application/x-www-form-urlencoded", "POST", reirUrl, reqparm, out httpResponse); ErrorInformation errors = JsonConvert.DeserializeObject <ErrorInformation>(response); if (errors != null && !string.IsNullOrEmpty(errors.Error) && errors.Error != null) { //JsonConvert.SerializeObject(errors); throw new Exception(JsonConvert.SerializeObject(errors)); } SSOInformation tokeninfo = JsonConvert.DeserializeObject <SSOInformation>(response); if (tokeninfo != null) { var accessTokenArr = tokeninfo.AccessToken.Split('.'); if (accessTokenArr.Length == 3) { var actualAccessToken = accessTokenArr[1]; string decodedTokenValue = GetTokenDetails(actualAccessToken); Dictionary <string, object> tokenDict = JsonConvert.DeserializeObject <Dictionary <string, object> >(decodedTokenValue); object userID, upk, email; tokenDict.TryGetValue("upn", out userID); tokenDict.TryGetValue("unique_name", out upk); tokenDict.TryGetValue("email", out email); SSOIdentity userIdentity = new SSOIdentity((string)userID, 0, true, false, "", (string)email, ""); SSOPrincipal principal = new SSOPrincipal(userIdentity, null); app.Context.User = principal; Thread.CurrentPrincipal = principal; SSOAuthentication.RedirectFromLoginPage(userIdentity, tokeninfo.ExpiresIn); } else { res.Redirect(loginUrl, true); } } } else { var b = Encoding.UTF8.GetBytes(req.Path); var str = Convert.ToBase64String(b); loginUrl += $"&state={str}"; res.Redirect(loginUrl, true); } }