public string CreateRequest(string userSuppliedIdentifier, string realm, string returnToUrl) { var request = relyingParty.CreateRequestAsync(userSuppliedIdentifier, realm, new Uri(returnToUrl)).Result; var response = request.GetRedirectingResponseAsync(CancellationToken.None).Result; return(response.GetDirectUriRequest().AbsoluteUri); }
public async Task <ActionResult> LogOn(LogOnModel model, string returnUrl) { if (ModelState.IsValid) { var rp = new OpenIdRelyingParty(); var request = await rp.CreateRequestAsync(model.UserSuppliedIdentifier, Realm.AutoDetect, new Uri(Request.Url, Url.Action("Authenticate"))); if (request != null) { if (returnUrl != null) { request.AddCallbackArguments("returnUrl", returnUrl); } var response = await request.GetRedirectingResponseAsync(); return(response.AsActionResult()); } else { ModelState.AddModelError(string.Empty, "The identifier you supplied is not recognized as a valid OpenID Identifier."); } } // If we got this far, something failed, redisplay form return(View(model)); }
private async Task <IAuthenticationRequest> GetGoogleRequestAsync() { // Google requires that the realm and consumer key be equal, // so we constrain the realm to match the realm in the web.config file. // This does mean that the return_to URL must also fall under the key, // which means this sample will only work on a public web site // that is properly registered with Google. // We will customize the realm to use http or https based on what the // return_to URL will be (which will be this page). Realm realm = Request.Url.Scheme + Uri.SchemeDelimiter + (new GoogleConsumer()).ConsumerKey + "/"; IAuthenticationRequest authReq = await relyingParty.CreateRequestAsync(GoogleOPIdentifier, realm, cancellationToken : Response.ClientDisconnectedToken); // Prepare the OAuth extension string scope = GoogleConsumer.GetScopeUri(GoogleConsumer.Applications.Contacts); Global.GoogleWebConsumer.AttachAuthorizationRequest(authReq, scope); // We also want the user's email address var fetch = new FetchRequest(); fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email); authReq.AddExtension(fetch); return(authReq); }
public async Task <ActionResult> Authenticate(string returnUrl) { var response = await openid.GetResponseAsync(this.Request, this.Response.ClientDisconnectedToken); if (response == null) { // Stage 2: user submitting Identifier Identifier id; if (Identifier.TryParse(Request.Form["openid_identifier"], out id)) { try { var request = await openid.CreateRequestAsync(Request.Form["openid_identifier"]); var redirectingResponse = await request.GetRedirectingResponseAsync(this.Response.ClientDisconnectedToken); Response.ContentType = redirectingResponse.Content.Headers.ContentType.ToString(); return(redirectingResponse.AsActionResult()); } catch (ProtocolException ex) { ViewData["Message"] = ex.Message; return(View("Login")); } } else { ViewData["Message"] = "Invalid identifier"; return(View("Login")); } } else { // Stage 3: OpenID Provider sending assertion response switch (response.Status) { case AuthenticationStatus.Authenticated: Session["FriendlyIdentifier"] = response.FriendlyIdentifierForDisplay; var cookie = FormsAuthentication.GetAuthCookie(response.ClaimedIdentifier, false); Response.SetCookie(cookie); if (!string.IsNullOrEmpty(returnUrl)) { return(Redirect(returnUrl)); } else { return(RedirectToAction("Index", "Home")); } case AuthenticationStatus.Canceled: ViewData["Message"] = "Canceled at provider"; return(View("Login")); case AuthenticationStatus.Failed: ViewData["Message"] = response.Exception.Message; return(View("Login")); } } return(new EmptyResult()); }
public virtual async Task RequestAuthenticationAsync(HttpContextBase context, Uri returnUrl, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(returnUrl, "returnUrl"); var realm = new Realm(returnUrl.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped)); IAuthenticationRequest request = await RelyingParty.CreateRequestAsync(this.providerIdentifier, realm, returnUrl, cancellationToken); // give subclasses a chance to modify request message, e.g. add extension attributes, etc. this.OnBeforeSendingAuthenticationRequest(request); await request.RedirectToProviderAsync(context); }
public async Task <ActionResult> LogOn() { var response = await RP.GetResponseAsync(this.Request, this.Response.ClientDisconnectedToken); if (response == null) { Session["customidentity"] = null; var request = await RP.CreateRequestAsync(EndPoint); StoreRequest store = new StoreRequest(); store.Attributes.Add(new AttributeValues(Util.GetRootedUri("").ToString(), new[] { Session.SessionID })); request.AddExtension(store); var redirecting = await request.GetRedirectingResponseAsync(this.Response.ClientDisconnectedToken); //设置本地响应头部信息 Response.ContentType = redirecting.Content.Headers.ContentType.ToString(); return(redirecting.AsActionResult()); } switch (response.Status) { case AuthenticationStatus.Authenticated: var fetch = response.GetExtension <FetchResponse>(); var dic = fetch.Attributes.Where(obj => { return(obj.TypeUri.IndexOf(EndPoint) == 0); }).Select(obj => new { name = obj.TypeUri.Replace(EndPoint, ""), value = obj.Values[0] }) .ToLookup(obj => obj.name).ToDictionary(obj => obj.Key, obj => obj.First().value); UserModel user = null; if (!dic.Any(obj => string.IsNullOrEmpty(obj.Value))) { user = new UserModel { UserName = dic["username"], Email = dic["email"], Gender = dic["gender"][0] }; } this._formsAuth.SignIn(user); return(this.RedirectToAction("index", "home")); case AuthenticationStatus.Canceled: break; case AuthenticationStatus.Failed: break; } return(new EmptyResult()); }
protected void Page_Load(object sender, EventArgs e) { this.RegisterAsyncTask( new PageAsyncTask( async ct => { using (var openid = new OpenIdRelyingParty()) { // In order to receive the UIRequest as a response, we must register a custom extension factory. openid.ExtensionFactories.Add(new UIRequestAtRelyingPartyFactory()); var response = await openid.GetResponseAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken); if (response == null) { // Submit an OpenID request which Google must reply to immediately. // If the user hasn't established a trust relationship with this site yet, // Google will not give us the user identity, but they will tell us whether the user // at least has an active login session with them so we know whether to promote the // "Log in with Google" button. IAuthenticationRequest request = await openid.CreateRequestAsync( "https://www.google.com/accounts/o8/id", new HttpRequestWrapper(Request), Response.ClientDisconnectedToken); request.AddExtension(new UIRequest { Mode = UIModeDetectSession }); request.Mode = AuthenticationRequestMode.Immediate; await request.RedirectToProviderAsync(new HttpContextWrapper(this.Context), Response.ClientDisconnectedToken); } else { if (response.Status == AuthenticationStatus.Authenticated) { this.YouTrustUsLabel.Visible = true; } else if (response.Status == AuthenticationStatus.SetupRequired) { // Google refused to authenticate the user without user interaction. // This is either because Google doesn't know who the user is yet, // or because the user hasn't indicated to Google to trust this site. // Google uniquely offers the RP a tip as to which of the above situations is true. // Figure out which it is. In a real app, you might use this value to promote a // Google login button on your site if you detect that a Google session exists. var ext = response.GetUntrustedExtension <UIRequest>(); this.YouAreLoggedInLabel.Visible = ext != null && ext.Mode == UIModeDetectSession; this.YouAreNotLoggedInLabel.Visible = !this.YouAreLoggedInLabel.Visible; } } } })); }
public async Task <ActionResult> OpenId(LoginModel model) { Identifier id; if (Identifier.TryParse(model.OpenID_Identifier, out id)) { try { var openId = new OpenIdRelyingParty(); var returnToUrl = new Uri(Url.Action("OpenIdCallback", "Authentication", new { ReturnUrl = model.ReturnUrl }, Request.Url.Scheme), UriKind.Absolute); var requestTask = openId.CreateRequestAsync(id, Realm.AutoDetect, returnToUrl); await requestTask; var request = requestTask.Result; // add request for name and email using sreg (OpenID Simple Registration // Extension) request.AddExtension(new ClaimsRequest { Email = DemandLevel.Require, FullName = DemandLevel.Require, Nickname = DemandLevel.Require }); // also add AX request var axRequest = new FetchRequest(); axRequest.Attributes.AddRequired(WellKnownAttributes.Name.FullName); axRequest.Attributes.AddRequired(WellKnownAttributes.Name.First); axRequest.Attributes.AddRequired(WellKnownAttributes.Name.Last); axRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Email); request.AddExtension(axRequest); var redirectingResponseTask = request.GetRedirectingResponseAsync(); await redirectingResponseTask; return(redirectingResponseTask.Result.AsActionResult()); } catch (ProtocolException ex) { model.Message = ex.Message; return(View("Login", model)); } } else { model.Message = "Invalid identifier"; return(View("Login", model)); } }
public async Task <ActionResult> Login(string returnUrl) { var rp = new OpenIdRelyingParty(null); Realm officialWebSiteHome = Realm.AutoDetect; Uri returnTo = new Uri(this.Request.Url, this.Url.Action("Authenticate")); var request = await rp.CreateRequestAsync(WellKnownProviders.Google, officialWebSiteHome, returnTo); if (returnUrl != null) { request.SetUntrustedCallbackArgument("returnUrl", returnUrl); } var redirectingResponse = await request.GetRedirectingResponseAsync(); return(redirectingResponse.AsActionResult()); }
protected void loginButton_Click(object sender, EventArgs e) { this.RegisterAsyncTask( new PageAsyncTask( async ct => { if (!this.Page.IsValid) { return; // don't login if custom validation failed. } try { using (OpenIdRelyingParty openid = this.createRelyingParty()) { IAuthenticationRequest request = await openid.CreateRequestAsync( this.openIdBox.Text, new HttpRequestWrapper(Request), Response.ClientDisconnectedToken); // This is where you would add any OpenID extensions you wanted // to include in the authentication request. request.AddExtension( new ClaimsRequest { Country = DemandLevel.Request, Email = DemandLevel.Request, Gender = DemandLevel.Require, PostalCode = DemandLevel.Require, TimeZone = DemandLevel.Require, }); // Send your visitor to their Provider for authentication. await request.RedirectToProviderAsync(new HttpContextWrapper(Context), Response.ClientDisconnectedToken); } } catch (ProtocolException ex) { // The user probably entered an Identifier that // was not a valid OpenID endpoint. this.openidValidator.Text = ex.Message; this.openidValidator.IsValid = false; } })); }
protected void Page_Load(object sender, EventArgs e) { this.RegisterAsyncTask( new PageAsyncTask( async ct => { UriBuilder returnToBuilder = new UriBuilder(Request.Url); returnToBuilder.Path = "/login.aspx"; returnToBuilder.Query = null; returnToBuilder.Fragment = null; Uri returnTo = returnToBuilder.Uri; returnToBuilder.Path = "/"; Realm realm = returnToBuilder.Uri; var response = await relyingParty.GetResponseAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken); if (response == null) { if (Request.QueryString["ReturnUrl"] != null && User.Identity.IsAuthenticated) { // The user must have been directed here because he has insufficient // permissions to access something. this.MultiView1.ActiveViewIndex = 1; } else { // Because this is a sample of a controlled SSO environment, // we don't ask the user which Provider to use... we just send // them straight off to the one Provider we trust. var request = await relyingParty.CreateRequestAsync( ConfigurationManager.AppSettings["SsoProviderOPIdentifier"], realm, returnTo, Response.ClientDisconnectedToken); var fetchRequest = new FetchRequest(); fetchRequest.Attributes.AddOptional(RolesAttribute); request.AddExtension(fetchRequest); await request.RedirectToProviderAsync(new HttpContextWrapper(Context), Response.ClientDisconnectedToken); } } else { switch (response.Status) { case AuthenticationStatus.Canceled: this.errorLabel.Text = "Login canceled."; break; case AuthenticationStatus.Failed: this.errorLabel.Text = HttpUtility.HtmlEncode(response.Exception.Message); break; case AuthenticationStatus.Authenticated: IList <string> roles = null; var fetchResponse = response.GetExtension <FetchResponse>(); if (fetchResponse != null) { if (fetchResponse.Attributes.Contains(RolesAttribute)) { roles = fetchResponse.Attributes[RolesAttribute].Values; } } if (roles == null) { roles = new List <string>(0); } // Apply the roles to this auth ticket const int TimeoutInMinutes = 100; // TODO: look up the right value from the web.config file var ticket = new FormsAuthenticationTicket( 2, response.ClaimedIdentifier, DateTime.Now, DateTime.Now.AddMinutes(TimeoutInMinutes), false, // non-persistent, since login is automatic and we wanted updated roles string.Join(";", roles.ToArray())); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)); Response.SetCookie(cookie); Response.Redirect(Request.QueryString["ReturnUrl"] ?? FormsAuthentication.DefaultUrl); break; default: break; } } })); }
public async Task <ActionResult> Authenticate(string returnUrl) { HttpRequestMessage req = this.Request.AsHttpRequestMessage(); Dictionary <string, string> fields = new Dictionary <string, string>(); fields.AddRange(await ParseUrlEncodedFormContentAsync(req)); if (fields.Count == 0 && req.Method.Method != "POST") { // OpenID 2.0 section 4.1.2 fields.AddRange(HttpUtility.ParseQueryString(req.RequestUri.Query).AsKeyValuePairs()); } string mode; if (fields.TryGetValue("openid.mode", out mode)) { string symVal = ""; fields.TryGetValue("openid.symval", out symVal); //first, we add RP's code onto our symval string hash_rp = PositiveAssertionResponse.code_to_hash(PositiveAuthenticationResponse.SourceCode_RP); //((AuthenticationRequest)request).ProviderEndpoint.Authority + "[[" + PositiveAssertionResponse.hashvalue_op + "()]"; symVal = this.Request.Url.Authority + "[[" + hash_rp + "(" + symVal + ")]]"; generate_cs_file_from_symval(symVal, fields); TimeSpan t1 = (DateTime.UtcNow - new DateTime(1970, 1, 1)); TimeSpan t2 = (DateTime.UtcNow - new DateTime(1970, 1, 1)); int num = (int)(t2.TotalMilliseconds - t1.TotalMilliseconds); HttpRequestMessage request = this.Request.AsHttpRequestMessage(); MessageReceivingEndpoint recipient; recipient = request.GetRecipient(); IProtocolMessage message = openid.Channel.MessageFactory.GetNewRequestMessage(recipient, fields); // If there was no data, or we couldn't recognize it as a message, abort. if (message == null) { return(null); } // We have a message! Assemble it. var messageAccessor = openid.Channel.MessageDescriptions.GetAccessor(message); messageAccessor.Deserialize(fields); //IDirectedProtocolMessage message = await openid.Channel.ReadFromRequestAsync_ccp(fields, request, this.Response.ClientDisconnectedToken); //only the final response will be here var response_ccp = await openid.GetResponseAsync_ccp(message, this.Response.ClientDisconnectedToken); //var response_ccp = await openid.GetResponseAsync(req, this.Response.ClientDisconnectedToken); // Stage 3: OpenID Provider sending assertion response if (!checkLogicProperty()) { return(new EmptyResult()); } switch (response_ccp.Status) { case AuthenticationStatus.Authenticated: Session["FriendlyIdentifier"] = response_ccp.FriendlyIdentifierForDisplay; var cookie = FormsAuthentication.GetAuthCookie(response_ccp.ClaimedIdentifier, false); Response.SetCookie(cookie); if (!string.IsNullOrEmpty(returnUrl)) { return(Redirect(returnUrl)); } else { return(RedirectToAction("Index", "Home")); } case AuthenticationStatus.Canceled: ViewData["Message"] = "Canceled at provider"; return(View("Login")); case AuthenticationStatus.Failed: ViewData["Message"] = response_ccp.Exception.Message; return(View("Login")); } return(new EmptyResult()); } else { var response = await openid.GetResponseAsync(this.Request, this.Response.ClientDisconnectedToken); if (response == null) { // Stage 2: user submitting Identifier Identifier id; if (Identifier.TryParse(Request.Form["openid_identifier"], out id)) { try { var request = await openid.CreateRequestAsync(Request.Form["openid_identifier"]); //Eric - add extension var sregRequest = new ClaimsRequest(); sregRequest.Email = DemandLevel.Require; request.AddExtension(sregRequest); var redirectingResponse = await request.GetRedirectingResponseAsync(this.Response.ClientDisconnectedToken); // this code is handled by HttpResponseMessageActionResult :: ExecuteResult(ControllerContext context) return(redirectingResponse.AsActionResult()); } catch (ProtocolException ex) { ViewData["Message"] = ex.Message; return(View("Login")); } } else { ViewData["Message"] = "Invalid identifier"; return(View("Login")); } } return(new EmptyResult()); } //ERIC'S CODE - end }
public async Task <ActionResult> Authenticate(string redirect) { var response = await openid.GetResponseAsync(this.Request); if (response == null) { // Stage 2: user submitting Identifier Identifier id; if (Identifier.TryParse(c_STEAM_PROVIDER, out id)) { try { var request = await openid.CreateRequestAsync(c_STEAM_PROVIDER); var redirectingResponse = await request.GetRedirectingResponseAsync(); return(redirectingResponse.AsActionResult()); } catch (ProtocolException ex) { ViewData["message"] = ex.Message; return(View("login")); } } else { ViewData["message"] = "Invalid identifier"; return(View("login")); } } else { // Stage 3: OpenID Provider sending assertion response switch (response.Status) { case AuthenticationStatus.Authenticated: //authenticate user Session["FriendlyIdentifier"] = response.FriendlyIdentifierForDisplay; var cookie = FormsAuthentication.GetAuthCookie(response.ClaimedIdentifier, true); cookie.Expires = DateTime.Now.Add(new TimeSpan(7, 0, 0, 0)); Response.SetCookie(cookie); if (!string.IsNullOrEmpty(redirect)) { return(Redirect(redirect)); } else { return(RedirectToAction("index", "home")); } case AuthenticationStatus.Canceled: ViewData["message"] = "Canceled at provider"; return(View("login")); case AuthenticationStatus.Failed: ViewData["message"] = response.Exception.Message; return(View("login")); } } return(new EmptyResult()); }