protected override bool AuthorizeCore(HttpContextBase httpContext) { bool isAuthenticated = false; 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]; var request = httpContext.Request; var response = httpContext.Response; 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 (request.Cookies.Count > 0 && request.Cookies[".ASPXAUTH"] != null && request.Cookies[cookieName.ToUpper()] != null) { HttpCookie authCookie = request.Cookies[".ASPXAUTH"]; if (authCookie != null) { HttpCookie cookie = request.Cookies[cookieName.ToUpper()]; if (cookie != null) { string str = cookie.Value; SSOIdentity userIdentity = SSOAuthentication.Decrypt(str); string[] roles = userIdentity.UserRoles.Split(new char[] { '|' }); var claims = userIdentity.Claims; ArrayList arrRoles = new ArrayList(); arrRoles.InsertRange(0, roles); SSOPrincipal principal = new SSOPrincipal(userIdentity, arrRoles, claims); httpContext.User = principal; Thread.CurrentPrincipal = principal; isAuthenticated = userIdentity.IsAuthenticated; } } } 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 (!isAuthenticated && request.QueryString.HasKeys() && request.QueryString.GetValues("code").Length > 0) { string code = request.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 serviceResponse = WebServiceRedirect(request, "application/x-www-form-urlencoded", "POST", reirUrl, reqparm, out httpResponse); ErrorInformation errors = JsonConvert.DeserializeObject <ErrorInformation>(serviceResponse); if (errors != null && !string.IsNullOrEmpty(errors.Error) && errors.Error != null) { throw new Exception(JsonConvert.SerializeObject(errors)); } SSOInformation tokeninfo = JsonConvert.DeserializeObject <SSOInformation>(serviceResponse); if (tokeninfo != null) { var token = DecodeJWT(tokeninfo.AccessToken); if (token != null) { object userID, upk, email; token.TryGetValue("upn", out userID); token.TryGetValue("unique_name", out upk); token.TryGetValue("email", out email); SSOIdentity userIdentity = new SSOIdentity((string)userID, 0, true, false, "", (string)email, "", token); SSOPrincipal principal = new SSOPrincipal(userIdentity, null, token); httpContext.User = principal; Thread.CurrentPrincipal = principal; isAuthenticated = SSOAuthentication.RedirectFromLoginPage(userIdentity, redirectUri, tokeninfo.ExpiresIn); } else { isAuthenticated = false; } } } if (!isAuthenticated) { response.RedirectPermanent(loginUrl); } return(isAuthenticated); }
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); } }