private ActionResult HandleSignInResponse(string contextId) { var ctxCookie = this.Request.Cookies[contextId]; if (ctxCookie == null) { throw new InvalidOperationException("Context cookie not found"); } var originalRequestUri = new Uri(ctxCookie.Value); this.DeleteContextCookie(contextId); SignInRequestMessage requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(originalRequestUri); SecurityTokenService sts = new FederationSecurityTokenService(SecurityTokenServiceConfiguration <FederationSecurityTokenService> .Current); SignInResponseMessage responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, User, sts); FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(responseMessage, this.HttpContext.ApplicationInstance.Response); return(this.Content(responseMessage.WriteFormPost())); }
protected override void OnLoad(EventArgs e) { string action = this.Request.QueryString[WSFederationConstants.Parameters.Action]; if (action == WSFederationConstants.Actions.SignIn) { // Process signin request. if (SimulatedWindowsAuthenticationOperations.TryToAuthenticateUser(this.Context, this.Request, this.Response)) { //This is the second time through SecurityTokenService sts = new IdentityProviderSecurityTokenService(IdentityProviderSecurityTokenServiceConfiguration.Current); var requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(this.Request.Url); SignInResponseMessage responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, this.User, sts); //responseMessage = getMessage(); FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(responseMessage, this.Response); var response = this.Response; } } else if (action == WSFederationConstants.Actions.SignOut || action == WSFederationConstants.Actions.SignOutCleanup) { // Process signout request in the SignOut page. We do this because we have different styling for signout vs signin this.Response.Redirect("~/SignOut.aspx?" + this.Request.QueryString, false); } else { throw new InvalidOperationException( String.Format( CultureInfo.InvariantCulture, "The action '{0}' (Request.QueryString['{1}']) is unexpected. Expected actions are: '{2}' or '{3}'.", String.IsNullOrEmpty(action) ? "<EMPTY>" : action, WSFederationConstants.Parameters.Action, WSFederationConstants.Actions.SignIn, WSFederationConstants.Actions.SignOut)); } base.OnLoad(e); }
public ActionResult GetAccessToken(string code) { var query = new Dictionary <string, string>(); query.Add("client_id", Constants.GITHUB_CLIENT_ID); query.Add("client_secret", Constants.GITHUB_CLIENT_SEC); query.Add("code", code); query.Add("state", Constants.GITHUB_OAUTH_STATE); // send request JObject resp = Utility.MakeJsonHttpRequest(Constants.GITHUB_AK_URL, query); string accessToken = (string)resp["access_token"]; // call sts and return // build cliam var claim = new ClaimsPrincipal(); var id = new ClaimsIdentity(); id.AddClaim(new Claim(Constants.CLAIM_TYPE_GITHUB_AK, accessToken)); claim.AddIdentity(id); // send claim var sigingCredentials = new X509SigningCredentials(Utility.GetCertificate(Constants.CERTIFICATE_NAME)); var config = new SecurityTokenServiceConfiguration(Constants.ISSUER_NAME, sigingCredentials); var sts = new CustomSecurityTokenService(config); var requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(Request.Url); var responesMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, claim, sts); var formData = responesMessage.WriteFormPost(); return(new ContentResult() { Content = formData, ContentType = "text/html" }); }
protected override void OnPreRender(EventArgs e) { string action = Request.QueryString[WSFederationConstants.Parameters.Action]; try { if (action == WSFederationConstants.Actions.SignIn) { // Process signin request. string endpointAddress = "~/SimulatedWindowsAuthentication.aspx"; this.Response.Redirect(endpointAddress + "?" + Request.QueryString, false); } else if (action == WSFederationConstants.Actions.SignOut) { // Process signout request. SimulatedWindowsAuthenticationOperations.LogOutUser(this.Request, this.Response); SignOutRequestMessage requestMessage = (SignOutRequestMessage)WSFederationMessage.CreateFromUri(Request.Url); FederatedPassiveSecurityTokenServiceOperations.ProcessSignOutRequest(requestMessage, this.User, null, this.Response); this.ActionExplanationLabel.Text = "Sign out from the issuer has been requested."; } else { throw new InvalidOperationException( string.Format( CultureInfo.InvariantCulture, "The action '{0}' (Request.QueryString['{1}']) is unexpected. Expected actions are: '{2}' or '{3}'.", string.IsNullOrEmpty(action) ? "<EMPTY>" : action, WSFederationConstants.Parameters.Action, WSFederationConstants.Actions.SignIn, WSFederationConstants.Actions.SignOut)); } } catch (Exception exception) { throw new Exception("An unexpected error occurred when processing the request. See inner exception for details.", exception); } }
private void HandleSignInResponse(WSFederationMessage responseMessageFromIssuer) { var contextId = responseMessageFromIssuer.Context; var ctxCookie = this.Request.Cookies[contextId]; if (ctxCookie == null) { throw new InvalidOperationException("Context cookie not found"); } var originalRequestUri = new Uri(ctxCookie.Value); this.DeleteContextCookie(contextId); var requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(originalRequestUri); SecurityTokenService sts = new FederationSecurityTokenService(FederationSecurityTokenServiceConfiguration.Current); SignInResponseMessage responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, this.User, sts); FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(responseMessage, this.Response); }
public ActionResult Issue() { Tracing.Verbose("HRD endpoint called."); var message = WSFederationMessage.CreateFromUri(HttpContext.Request.Url); // sign in var signinMessage = message as SignInRequestMessage; if (signinMessage != null) { return(ProcessSignInRequest(signinMessage)); } // sign out var signoutMessage = message as SignOutRequestMessage; if (signoutMessage != null) { return(ProcessSignOut(signoutMessage)); } return(View("Error")); }
protected void Page_Load() { string action = Request.QueryString[WSFederationConstants.Parameters.Action]; try { if (action == WSFederationConstants.Actions.SignIn) { // Process signin request. if (SimulatedWindowsAuthenticationOperations.TryToAuthenticateUser(this.Context, this.Request, this.Response)) { SecurityTokenService sts = new IdentityProviderSecurityTokenService(IdentityProviderSecurityTokenServiceConfiguration.Current); SignInRequestMessage requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(Request.Url); SignInResponseMessage responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, User, sts); FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(responseMessage, this.Response); } } else if (action == WSFederationConstants.Actions.SignOut) { // Process signout request in the default page. this.Response.Redirect("~/?" + Request.QueryString, false); } else { throw new InvalidOperationException( string.Format( CultureInfo.InvariantCulture, "The action '{0}' (Request.QueryString['{1}']) is unexpected. Expected actions are: '{2}' or '{3}'.", string.IsNullOrEmpty(action) ? "<EMPTY>" : action, WSFederationConstants.Parameters.Action, WSFederationConstants.Actions.SignIn, WSFederationConstants.Actions.SignOut)); } } catch (Exception exception) { throw new Exception("An unexpected error occurred when processing the request. See inner exception for details.", exception); } }
/// <summary> /// Performs WS-Federation Passive Protocol processing. /// </summary> protected void Page_PreRender(object sender, EventArgs e) { string action = Request.QueryString[WSFederationConstants.Parameters.Action]; try { if (action == WSFederationConstants.Actions.SignIn) { // Process signin request. SignInRequestMessage requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(Request.Url); if (User != null && User.Identity != null && User.Identity.IsAuthenticated) { SecurityTokenService sts = new CustomSecurityTokenService(CustomSecurityTokenServiceConfiguration.Current); SignInResponseMessage responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, User, sts); FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(responseMessage, Response); } else { throw new UnauthorizedAccessException(); } } else if (action == WSFederationConstants.Actions.SignOut) { // Process signout request. SignOutRequestMessage requestMessage = (SignOutRequestMessage)WSFederationMessage.CreateFromUri(Request.Url); FederatedPassiveSecurityTokenServiceOperations.ProcessSignOutRequest(requestMessage, User, requestMessage.Reply, Response); } else if (action == null && SocialAuthUser.IsLoggedIn()) { string originalUrl = SocialAuthUser.GetCurrentUser().GetConnection(SocialAuthUser.CurrentProvider).GetConnectionToken().UserReturnURL; //replace ru value int wctxBeginsFrom = originalUrl.IndexOf("wctx="); int wctxEndsAt = originalUrl.IndexOf("&wct="); string wctxContent = originalUrl.Substring(wctxBeginsFrom + 5, wctxEndsAt - (wctxBeginsFrom + 5)); originalUrl = originalUrl.Replace(wctxContent, Server.UrlEncode(wctxContent)); //replace wtrealm value int wtrealmBeginsFrom = originalUrl.IndexOf("wtrealm="); int wtrealmEndsAt = originalUrl.IndexOf("&", wtrealmBeginsFrom); string wtrealmContent = originalUrl.Substring(wtrealmBeginsFrom + 8, wtrealmEndsAt - (wtrealmBeginsFrom + 8)); originalUrl = originalUrl.Replace(wtrealmContent, Server.UrlEncode(wtrealmContent)); SignInRequestMessage requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(new Uri(originalUrl)); if (User != null && User.Identity != null && User.Identity.IsAuthenticated) { SecurityTokenService sts = new CustomSecurityTokenService(CustomSecurityTokenServiceConfiguration.Current); SignInResponseMessage responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, User, sts); FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(responseMessage, Response); } } else { throw new InvalidOperationException( String.Format(CultureInfo.InvariantCulture, "The action '{0}' (Request.QueryString['{1}']) is unexpected. Expected actions are: '{2}' or '{3}'.", String.IsNullOrEmpty(action) ? "<EMPTY>" : action, WSFederationConstants.Parameters.Action, WSFederationConstants.Actions.SignIn, WSFederationConstants.Actions.SignOut)); } } catch (Exception exception) { throw new Exception("An unexpected error occurred when processing the request. See inner exception for details.", exception); } }
public ActionResult ProcessFederationRequest() { Logger.Info("ProcessFederationRequest"); var action = Request.QueryString[WSFederationConstants.Parameters.Action]; switch (action) { case WSFederationConstants.Actions.SignIn: { var requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(Request.UrlConsideringLoadBalancerHeaders()); if (User?.Identity != null && User.Identity.IsAuthenticated) { try { var sts = new MultiProtocolSecurityTokenService(MultiProtocolSecurityTokenServiceConfiguration.Current); if (Logger.IsInfoEnabled) { var user = User.Identity as ClaimsIdentity; if (user?.Claims != null) { foreach (var claim in user.Claims) { Logger.InfoFormat( "claim, Issuer: {0}, OriginalIssuer: {1}, Type:{2}, Subject:{3}, Value: {4}, ValueType: {5}", claim.Issuer, claim.OriginalIssuer, claim.Type, claim.Subject, claim.Value, claim.ValueType); } } Logger.InfoFormat("Reply: {0}", requestMessage.Reply); Logger.InfoFormat("Before ProcessSignInRequest"); } var responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, new ClaimsPrincipal(User), sts); responseMessage.Write(Response.Output); } finally { FederatedAuthentication.SessionAuthenticationModule.DeleteSessionTokenCookie(); } Response.Flush(); Response.End(); HttpContext.ApplicationInstance.CompleteRequest(); } else { // user not authenticated yet, look for whr, if not there go to HomeRealmDiscovery page Logger.InfoFormat("User is not authenticated yet, redirecting to given realm."); CreateFederationContext(); if (string.IsNullOrEmpty(Request.QueryString[WSFederationConstants.Parameters.HomeRealm])) { return(HomeRealmDiscovery(HttpUtility.HtmlEncode(HttpUtility.ParseQueryString(requestMessage.Context).Get("em")))); } return(Authenticate()); } } break; case WSFederationConstants.Actions.SignOut: { var requestMessage = (SignOutRequestMessage)WSFederationMessage.CreateFromUri(Request.UrlConsideringLoadBalancerHeaders()); var replyTo = requestMessage.Reply; if (!string.IsNullOrEmpty(replyTo) && ConfigurationManager.AppSettings.GetBoolSetting("UseRelativeConfiguration")) { var uri = new Uri(replyTo); if (uri.IsAbsoluteUri) { replyTo = "/" + new Uri(uri.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped)).MakeRelativeUri(uri); } } FederatedPassiveSecurityTokenServiceOperations.ProcessSignOutRequest(requestMessage, new ClaimsPrincipal(User), replyTo, HttpContext.ApplicationInstance.Response); } break; default: Response.AddHeader("X-XRDS-Location", new Uri(Request.UrlConsideringLoadBalancerHeaders(), Response.ApplyAppPathModifier("~/xrds.aspx")).AbsoluteUri); return(new EmptyResult()); } return(null); }
public ActionResult ProcessFederationRequest() { var action = Request.QueryString[WSFederationConstants.Parameters.Action]; try { switch (action) { case WSFederationConstants.Actions.SignIn: { var requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(Request.Url); if (User != null && User.Identity != null && User.Identity.IsAuthenticated) { var sts = new MultiProtocolSecurityTokenService(MultiProtocolSecurityTokenServiceConfiguration.Current); var responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, User, sts); responseMessage.Write(Response.Output); Response.Flush(); Response.End(); HttpContext.ApplicationInstance.CompleteRequest(); } else { // user not authenticated yet, look for whr, if not there go to HomeRealmDiscovery page this.CreateFederationContext(); if (string.IsNullOrEmpty(this.Request.QueryString[WSFederationConstants.Parameters.HomeRealm])) { return(this.RedirectToAction("HomeRealmDiscovery")); } else { return(this.Authenticate()); } } } break; case WSFederationConstants.Actions.SignOut: { var requestMessage = (SignOutRequestMessage)WSFederationMessage.CreateFromUri(Request.Url); FederatedPassiveSecurityTokenServiceOperations.ProcessSignOutRequest(requestMessage, User, requestMessage.Reply, HttpContext.ApplicationInstance.Response); } break; default: throw new InvalidOperationException( String.Format( CultureInfo.InvariantCulture, "The action '{0}' (Request.QueryString['{1}']) is unexpected. Expected actions are: '{2}' or '{3}'.", String.IsNullOrEmpty(action) ? "<EMPTY>" : action, WSFederationConstants.Parameters.Action, WSFederationConstants.Actions.SignIn, WSFederationConstants.Actions.SignOut)); } } catch (Exception exception) { throw new Exception("An unexpected error occurred when processing the request. See inner exception for details.", exception); } return(null); }
public async Task <ActionResult> Login(LoginModel login) { if (login.UserName.IndexOf('@') < 0) { //incorrect format Session["Error"] = @"Enter your user ID in the format ""domain\user"" or ""user @domain"". "; return(RedirectToAction("Index", new { Request.Url.Query })); } string domain = login.UserName.Split('@')[1]; InitSTS(domain); ValidationResponse user; try { //validate identity user = await LoginValidate.ValidateAsync(login, HttpRuntime.Cache); if (!user.IsValid) { Session["Error"] = "Incorrect user ID or password. Type the correct user ID and password, and try again."; return(RedirectToAction("Index", new { Request.Url.Query })); } } catch (Exception ex) { Common.Utils.AddLogEntry("Error during user authentication", System.Diagnostics.EventLogEntryType.Error, 0, ex); Session["Error"] = string.Format("An error occured during authentication ({0})", ex.Message); return(RedirectToAction("Index", new { Request.Url.Query })); } //identity validated string fullRequest = String.Format("{0}{1}{2}?{3}", Settings.HttpLocalhost, Settings.Port, Settings.WSFedStsIssue, Request.Url.Query ); //todo: var immutableId = user.UserProperties.MasterGuid; //var immutableId = user.UserProperties.LocalGuid; SignInRequestMessage requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(new Uri(fullRequest)); //todo: requestMessage.Reply = string.Format("https://login.microsoftonline.com:443/login.srf?client-request-id={0}", Request.QueryString["client-request-id"]); ClaimsIdentity identity = new ClaimsIdentity(AuthenticationTypes.Federation); identity.AddClaim(new Claim("http://schemas.microsoft.com/LiveID/Federation/2008/05/ImmutableID", immutableId)); identity.AddClaim(new Claim("http://schemas.xmlsoap.org/claims/UPN", user.UserProperties.Upn)); //TODO: verify the source of this flag in ADFS //identity.AddClaim(new Claim("http://schemas.microsoft.com/ws/2012/01/insidecorporatenetwork", "true", typeof(bool).ToString())); ClaimsPrincipal principal = new ClaimsPrincipal(identity); SignInResponseMessage responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, principal, this.securityTokenService); MemoryStream stream = new MemoryStream(); StreamWriter writer = new StreamWriter(stream, Encoding.UTF8); responseMessage.Write(writer); writer.Flush(); stream.Position = 0; var res = new ContentResult() { ContentType = "text/html", ContentEncoding = Encoding.UTF8, Content = Encoding.UTF8.GetString(stream.ToArray()) }; return(res); }
private static void ProcessSignOut(Uri url, ClaimsPrincipal user) { var requestMessage = (SignOutRequestMessage)WSFederationMessage.CreateFromUri(url); FederatedPassiveSecurityTokenServiceOperations.ProcessSignOutRequest(requestMessage, user, requestMessage.Reply, System.Web.HttpContext.Current.Response); }
public async Task <IHttpActionResult> Login(string relyingPartyName) { if (string.IsNullOrWhiteSpace(relyingPartyName)) { return(BadRequest("No relying party id provided")); } string action; NameValueCollection content = null; NameValueCollection qs = Request.RequestUri.ParseQueryString(); action = qs.Get(WSFederationConstants.Parameters.Action); if (string.IsNullOrWhiteSpace(action)) { content = await Request.Content.ReadAsFormDataAsync(); action = content.Get(WSFederationConstants.Parameters.Action); } if (action == WSFederationConstants.Actions.SignIn) { IRelyingParty rp = STSConfiguration <RelyingParty> .Current.RelyingParties.FindByName(relyingPartyName); if (this.User != null && this.User.Identity.IsAuthenticated) { if (content == null) { content = await Request.Content.ReadAsFormDataAsync(); } WSFederationMessage responseMessageFromIssuer = WSFederationMessage.CreateFromNameValueCollection(Request.RequestUri, content); var contextId = responseMessageFromIssuer.Context; var ctxCookie = System.Web.HttpContext.Current.Request.Cookies[contextId]; if (ctxCookie == null) { throw new InvalidOperationException("Context cookie not found"); } var originalRequestUri = new Uri(ctxCookie.Value); HttpCookie cookie = DeleteContextCookie(contextId); System.Web.HttpContext.Current.Response.Cookies.Add(cookie); var requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(originalRequestUri); var sts = new SimpleSts(rp.GetStsConfiguration()); SignInResponseMessage rm = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, User as ClaimsPrincipal, sts); //WSTrustSerializationContext context = new WSTrustSerializationContext(FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlerCollectionManager); //WSFederationSerializer fedSer = new WSFederationSerializer(); //RequestSecurityTokenResponse token = fedSer.CreateResponse(rm, context); //token.RequestedSecurityToken.SecurityToken. FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(rm, System.Web.HttpContext.Current.Response); return(StatusCode(HttpStatusCode.NoContent)); } else { var contextId = Guid.NewGuid().ToString(); HttpCookie cookie = CreateContextCookie(contextId, HttpUtility.UrlDecode(this.Request.RequestUri.AbsoluteUri)); System.Web.HttpContext.Current.Response.Cookies.Add(cookie); var message = new SignInRequestMessage(new Uri(rp.AuthenticationUrl), FederatedAuthentication.WSFederationAuthenticationModule.Realm) { CurrentTime = DateTime.UtcNow.ToString("s", CultureInfo.InvariantCulture) + "Z", HomeRealm = rp.Realm, Context = contextId, Reply = Url.Link("Login", new { relyingPartyName = relyingPartyName }) }; message.Parameters.Add(new KeyValuePair <string, string>("originalRequest", Request.RequestUri.ToString())); return(Redirect(message.RequestUrl)); } } else { return(BadRequest(String.Format( CultureInfo.InvariantCulture, "The action '{0}' (Request.QueryString['{1}']) is unexpected. Expected actions are: '{2}' or '{3}'.", String.IsNullOrEmpty(action) ? "<EMPTY>" : action, WSFederationConstants.Parameters.Action, WSFederationConstants.Actions.SignIn, WSFederationConstants.Actions.SignOut))); } }