protected void OpenIdLogin1_LoggedIn(object sender, OpenIdEventArgs e) { if (sender == null) return; if (e == null) return; // this prevents another login from happening e.Cancel = true; if (siteUser != null) { string oiduri = e.ClaimedIdentifier.ToString(); Guid foundUserGuid = SiteUser.GetUserGuidFromOpenId( siteSettings.SiteId, oiduri); if ( (foundUserGuid == Guid.Empty) || (foundUserGuid == siteUser.UserGuid) ) { siteUser.OpenIdUri = e.ClaimedIdentifier.ToString(); siteUser.Save(); } } WebUtils.SetupRedirect(this, "UserProfile.aspx"); }
protected void OpenIdLogin1_LoggedIn(object sender, OpenIdEventArgs e) { Session["OpenId"] = e.ClaimedIdentifier.ToString(); FormsAuthentication.SetAuthCookie(e.ClaimedIdentifier.ToString(), false); Response.Redirect(Url.Action("Index", "Home")); }
protected void identifierBox_LoggedIn(object sender, OpenIdEventArgs e) { this.RegisterAsyncTask( new PageAsyncTask( async ct => { State.FetchResponse = e.Response.GetExtension<FetchResponse>(); var serviceDescription = new ServiceProviderDescription { TokenRequestEndpoint = new Uri(e.Response.Provider.Uri, "/access_token.ashx"), }; var consumer = CreateConsumer(); consumer.ServiceProvider = serviceDescription; AccessTokenResponse accessToken = await consumer.ProcessUserAuthorizationAsync(e.Response); if (accessToken != null) { this.MultiView1.SetActiveView(this.AuthorizationGiven); // At this point, the access token would be somehow associated with the user // account at the RP. ////Database.Associate(e.Response.ClaimedIdentifier, accessToken.AccessToken); } else { this.MultiView1.SetActiveView(this.AuthorizationDenied); } // Avoid the redirect e.Cancel = true; })); }
protected void identifierBox_LoggingIn(object sender, OpenIdEventArgs e) { ServiceProviderDescription serviceDescription = new ServiceProviderDescription { TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() }, }; var consumer = new WebConsumerOpenIdRelyingParty(serviceDescription, Global.OwnSampleOPHybridTokenManager); consumer.AttachAuthorizationRequest(e.Request, "http://tempuri.org/IDataApi/GetName"); }
protected void OpenIdAjaxTextBox1_LoggedIn(object sender, OpenIdEventArgs e) { Label label = (Label)this.commentSubmitted.FindControl("emailLabel"); label.Text = e.Response.FriendlyIdentifierForDisplay; // We COULD get the sreg extension response here for the email, but since we let the user // potentially change the email in the HTML form, we'll use that instead. ////var claims = OpenIdAjaxTextBox1.AuthenticationResponse.GetExtension<ClaimsResponse>(); if (this.emailAddressBox.Text.Length > 0) { label.Text += " (" + this.emailAddressBox.Text + ")"; } }
protected void OpenIdLogin_OnLoggingIn(object sender, OpenIdEventArgs e) { var users = new LokadCloudUserRoles(); var isAdmin = users.GetAdministrators().Exists( user => user.Credential == e.ClaimedIdentifier); // if the user isn't listed as an administrator, cancel the login if (!isAdmin) { e.Cancel = true; } }
protected void btnOpenIdLogin_LoggedIn(object sender, OpenIdEventArgs e) { e.Cancel = true; if(e.Response.Status == AuthenticationStatus.Authenticated && SecurityHelper.Authenticate(e.ClaimedIdentifier, btnOpenIdLogin.RememberMe)) { ReturnToUrl(AdminUrl.Home()); } else { openIdMessage.Text = Resources.Login_AuthenticationFailed; } }
protected void OpenIdLogin_LoggingIn(object sender, OpenIdEventArgs e) { e.Request.AddExtension(new ClaimsRequest { BirthDate = DemandLevel.Require, Country = DemandLevel.Require, Email = DemandLevel.Require, FullName = DemandLevel.Require, Gender = DemandLevel.Require, PostalCode = DemandLevel.Require, TimeZone = DemandLevel.Require, Language = DemandLevel.Require, Nickname = DemandLevel.Require }); }
protected void openidLogin_LoggingIn(object sender, OpenIdEventArgs e) { // We don't actually want to log in... we just want the claimed identifier. e.Cancel = true; if (e.IsDirectedIdentity) { this.noOPIdentifierLabel.Visible = true; } else if (!this.databaseCreated) { Utilities.CreateDatabase(e.ClaimedIdentifier, this.openidLogin.Text, "MvcRelyingParty"); this.MultiView1.ActiveViewIndex = 1; // indicate we have already created the database so that if the // identifier the user gave has multiple service endpoints, // we won't try to recreate the database as the next one is considered. this.databaseCreated = true; } }
protected void identifierBox_LoggedIn(object sender, OpenIdEventArgs e) { State.FetchResponse = e.Response.GetExtension<FetchResponse>(); ServiceProviderDescription serviceDescription = new ServiceProviderDescription { AccessTokenEndpoint = new MessageReceivingEndpoint(new Uri(e.Response.Provider.Uri, "/access_token.ashx"), HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest), TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() }, }; var consumer = new WebConsumerOpenIdRelyingParty(serviceDescription, Global.OwnSampleOPHybridTokenManager); AuthorizedTokenResponse accessToken = consumer.ProcessUserAuthorization(e.Response); if (accessToken != null) { this.MultiView1.SetActiveView(this.AuthorizationGiven); // At this point, the access token would be somehow associated with the user // account at the RP. ////Database.Associate(e.Response.ClaimedIdentifier, accessToken.AccessToken); } else { this.MultiView1.SetActiveView(this.AuthorizationDenied); } // Avoid the redirect e.Cancel = true; }
/// <summary> /// Fires the <see cref="LoggingIn"/> event. /// </summary> /// <returns> /// Returns whether the login should proceed. False if some event handler canceled the request. /// </returns> protected virtual bool OnLoggingIn() { EventHandler <OpenIdEventArgs> loggingIn = this.LoggingIn; if (this.Request == null) { this.CreateRequest(); } if (this.Request != null) { OpenIdEventArgs args = new OpenIdEventArgs(this.Request); if (loggingIn != null) { loggingIn(this, args); } return(!args.Cancel); } else { return(false); } }
protected void OpenIdLogin1_LoggingIn(object sender, OpenIdEventArgs e) { // Allow us to "remember" that we are preforming an OpenID login Session["isDoingOpenIDLogin"] = "******"; }
/// <summary> /// Fires the <see cref="LoggingIn"/> event. /// </summary> /// <param name="request">The request.</param> /// <returns> /// Returns whether the login should proceed. False if some event handler canceled the request. /// </returns> protected virtual bool OnLoggingIn(IAuthenticationRequest request) { Contract.Requires<ArgumentNullException>(request != null); EventHandler<OpenIdEventArgs> loggingIn = this.LoggingIn; OpenIdEventArgs args = new OpenIdEventArgs(request); if (loggingIn != null) { loggingIn(this, args); } return !args.Cancel; }
/// <summary> /// Fired upon login. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="DotNetOpenAuth.OpenId.RelyingParty.OpenIdEventArgs"/> instance containing the event data.</param> /// <remarks> /// Note, that straight after login, forms auth will redirect the user /// to their original page. So this page may never be rendererd. /// </remarks> protected void OpenIdLogin1_LoggedIn(object sender, OpenIdEventArgs e) { State.FriendlyLoginName = e.Response.FriendlyIdentifierForDisplay; State.ProfileFields = e.Response.GetExtension<ClaimsResponse>(); State.PapePolicies = e.Response.GetExtension<PolicyResponse>(); }
void OpenIdLogin1_Failed(object sender, OpenIdEventArgs e) { lblLoginFailed.Visible = true; if (e.Response.Exception is System.Net.WebException) { lblError.Text = Resource.OpenIDServerConnectionErrorMessage; } else log.Error(e.Response.Exception); }
private bool IsValidForUserCreation(OpenIdEventArgs e, ClaimsResponse claim) { bool result = true; if (claim == null) { return false; } if (String.IsNullOrEmpty(claim.Email)) { return false; } if (String.IsNullOrEmpty(claim.FullName)) { return false; } if (!Email.IsValidEmailAddressSyntax(claim.Email)) { return false; } mojoProfileConfiguration profileConfig = mojoProfileConfiguration.GetConfig(); if (profileConfig.HasRequiredCustomProperties()) { result = false; } return result; }
private void DisplayResults(OpenIdEventArgs e, ClaimsResponse claim) { litResult.Text = "uri: " + e.ClaimedIdentifier.ToString() + "<br />" + "Full Name: " + claim.FullName + "<br />" + "Nickname: " + claim.Nickname + "<br />" + "Birthdate: " + claim.BirthDate.ToString() + "<br />" + "Country: " + claim.Country + "<br />" + "Culture: " + claim.Culture.ToString() + "<br />" + "Gender: " + claim.Gender + "<br />" + "Language: " + claim.Language + "<br />" + "MailAddress: " + claim.MailAddress + "<br />" + "Postal Code: " + claim.PostalCode + " <br />" + "Email: " + claim.Email + "<br />" + "TimeZone: " + claim.TimeZone + "<br />"; }
/// <summary> /// Fires the <see cref="LoggingIn"/> event. /// </summary> /// <param name="request">The request.</param> /// <returns> /// Returns whether the login should proceed. False if some event handler canceled the request. /// </returns> protected virtual bool OnLoggingIn(IAuthenticationRequest request) { Requires.NotNull(request, "request"); EventHandler<OpenIdEventArgs> loggingIn = this.LoggingIn; OpenIdEventArgs args = new OpenIdEventArgs(request); if (loggingIn != null) { loggingIn(this, args); } return !args.Cancel; }
/// <summary> /// Handles the LoggedIn event of the OpenIdLogin1 control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="DotNetOpenAuth.OpenId.RelyingParty.OpenIdEventArgs"/> instance containing the event data.</param> protected void OpenIdLogin1_LoggedIn(object sender, OpenIdEventArgs e) { try { // Clear previously remembered OpenID state Session["isDoingOpenIDLogin"] = ""; // May 30 2010 // BGN-1356 // // Added by smoss for security. // User shouldnt be able to use this method if OpenID is off. if (!HostSettingManager.Get(HostSettingNames.OpenIdAuthentication, false)) { throw new UnauthorizedAccessException(); } if (e.Response != null) { switch (e.Response.Status) { case AuthenticationStatus.Authenticated: // This is where you would look for any OpenID extension responses included // in the authentication assertion. // var extension = openid.Response.GetExtension<someextensionresponsetype>(); // TODO : check for linked account via user profile settings if Desired // May 31 2010 // WARNING: There is no logging in this method! string email = string.Empty; string alias = string.Empty; string fullname = string.Empty; ClaimsResponse fetch = e.Response.GetExtension(typeof(ClaimsResponse)) as ClaimsResponse; if (fetch != null) { alias = fetch.Nickname; // set size limits email = fetch.Email; // no validation of email fullname = fetch.FullName; // set size limits } if (string.IsNullOrEmpty(alias)) alias = e.Response.ClaimedIdentifier; // Warning: Invalid email address if (string.IsNullOrEmpty(email)) email = e.Response.ClaimedIdentifier; if (string.IsNullOrEmpty(fullname)) fullname = e.Response.ClaimedIdentifier; //Now see if the user already exists, if not create them MembershipUser TestUser = Membership.GetUser(e.Response.ClaimedIdentifier); if (TestUser != null) { // BGN-1867 // Banned users are not allowed to login via OpenID // See if this user is allowed on the system. Also dont allow users // who are still logged in to try and login. if ((!TestUser.IsApproved) || (TestUser.IsLockedOut) || (TestUser.IsOnline)) { loginFailedLabel.Text += " " + GetLocalResourceObject("NotAuthorized.Text").ToString(); loginFailedLabel.Visible = true; e.Cancel = true; break; } } else { // Part of BGN-1860 if (Convert.ToInt32(HostSettingManager.Get(HostSettingNames.UserRegistration)) == (int)Globals.UserRegistration.None) { loginFailedLabel.Text += GetLocalResourceObject("RegistrationDisabled").ToString(); loginFailedLabel.Visible = true; e.Cancel = true; break; // unsecure break should be a return } MembershipCreateStatus membershipCreateStatus; MembershipUser user = Membership.CreateUser(e.Response.ClaimedIdentifier, Membership.GeneratePassword(7, 2), email, GetLocalResourceObject("OpenIDPasswordQuestion").ToString(), Membership.GeneratePassword(12, 4), true, out membershipCreateStatus); if (membershipCreateStatus != MembershipCreateStatus.Success) { loginFailedLabel.Text += GetLocalResourceObject("CreateAccountFailed").ToString() + membershipCreateStatus.ToString(); loginFailedLabel.Visible = true; e.Cancel = true; break;// unsecure break should be a return } //save profile info WebProfile Profile = new WebProfile().GetProfile(user.UserName); Profile.DisplayName = fullname; Profile.Save(); user.Comment = alias; Membership.UpdateUser(user); //auto assign user to roles List<Role> roles = RoleManager.GetAll(); foreach (Role r in roles) { if (r.AutoAssign) RoleManager.AddUser(user.UserName, r.Id); } //send notification this user was created UserManager.SendUserRegisteredNotification(user.UserName); } // NB NB Only do the redirect when e.Cancel != true // There is a very very slim chance this code will be reached with // e.Cancel == true if (e.Cancel == false) { // Use FormsAuthentication to tell ASP.NET that the user is now logged in, // with the OpenID Claimed Identifier as their username. FormsAuthentication.RedirectFromLoginPage(e.Response.ClaimedIdentifier, false); } break; case AuthenticationStatus.Canceled: loginCanceledLabel.Visible = true; e.Cancel = true; break; // unsecure break should be a return // extra enums detected and force a default case // They all mean failures case AuthenticationStatus.Failed: case AuthenticationStatus.ExtensionsOnly: case AuthenticationStatus.SetupRequired: default: loginFailedLabel.Visible = true; e.Cancel = true; break; // unsecure break should be a return } } else { // response is null } } finally { // This finally block covers all the code if (e.Cancel) { // make sure we stay focused on the openid control Session["isDoingOpenIDLogin"] = "******"; } } }
/// <summary> /// Fires the <see cref="LoggedIn"/> event. /// </summary> /// <param name="response">The response.</param> protected virtual void OnLoggedIn(IAuthenticationResponse response) { Requires.NotNull(response, "response"); Requires.That(response.Status == AuthenticationStatus.Authenticated, "response", "response not authenticatedl"); var loggedIn = this.LoggedIn; OpenIdEventArgs args = new OpenIdEventArgs(response); if (loggedIn != null) { loggedIn(this, args); } if (!args.Cancel) { if (this.UsePersistentCookie == LogOnPersistence.SessionAndPersistentIdentifier) { Page.Response.SetCookie(CreateIdentifierPersistingCookie(response)); } switch (this.LogOnMode) { case LogOnSiteNotification.FormsAuthentication: FormsAuthentication.RedirectFromLoginPage(response.ClaimedIdentifier, this.UsePersistentCookie == LogOnPersistence.PersistentAuthentication); break; case LogOnSiteNotification.None: default: break; } } }
protected void OpenIdAjaxTextBox1_UnconfirmedPositiveAssertion(object sender, OpenIdEventArgs e) { // This is where we register extensions that we want to have available in javascript // on the browser. this.OpenIdAjaxTextBox1.RegisterClientScriptExtension<ClaimsResponse>("sreg"); }
/// <summary> /// Fires the <see cref="LoggedIn"/> event. /// </summary> /// <param name="response">The response.</param> protected virtual void OnLoggedIn(IAuthenticationResponse response) { Requires.NotNull(response, "response"); ErrorUtilities.VerifyInternal(response.Status == AuthenticationStatus.Authenticated, "Firing OnLoggedIn event without an authenticated response."); var loggedIn = this.LoggedIn; OpenIdEventArgs args = new OpenIdEventArgs(response); if (loggedIn != null) { loggedIn(this, args); } if (!args.Cancel) { FormsAuthentication.RedirectFromLoginPage(response.ClaimedIdentifier, this.UsePersistentCookie); } }
/// <summary> /// This event fires upon successfull authentication from /// open id provider. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void OpenIdLogin1_LoggedIn(object sender, OpenIdEventArgs e) { // prevent the base control from // setting forms auth cookie for us // we'll login after further verification e.Cancel = true; Guid userGuid = SiteUser.GetUserGuidFromOpenId( siteSettings.SiteId, e.ClaimedIdentifier.ToString()); if (userGuid == Guid.Empty) { // this is expected result for new users // user not found in db by open id DoNewUserLogic(e); } else { // user found so just login DoExistingUserLogic(userGuid); } }
private void DoNewUserLogic(OpenIdEventArgs e) { if (e == null) { return; } ClaimsResponse claim = e.Response.GetExtension<ClaimsResponse>(); if (claim == null) { return; } if (IsValidForUserCreation(e, claim)) { if (SiteUser.EmailExistsInDB(siteSettings.SiteId, claim.Email)) { // show message that user should login and associate // their open id account on their profile page. lblError.Text = Resource.OpenIDRegisterUserEmailExistsMessage; return; } else { // create user automagically since we have all // the needed data SiteUser newUser = new SiteUser(siteSettings); newUser.Email = claim.Email; newUser.Name = claim.FullName; string loginName = newUser.Name.Replace(" ", ".").ToLower(); if (loginName.Length > 50) loginName = loginName.Substring(0, 50); if (SiteUser.LoginExistsInDB( siteSettings.SiteId, loginName)) { loginName = e.ClaimedIdentifier.ToString().Replace("http://", string.Empty).Replace("https://", string.Empty).Replace("/", string.Empty); if (loginName.Length > 50) loginName = loginName.Substring(0, 50); int i = 1; while (SiteUser.LoginExistsInDB( siteSettings.SiteId, loginName)) { loginName += i.ToString(); if (loginName.Length > 50) loginName = loginName.Remove(40, 1); i++; } } newUser.LoginName = loginName; newUser.Password = SiteUser.CreateRandomPassword(7, WebConfigSettings.PasswordGeneratorChars); newUser.PasswordQuestion = Resource.ManageUsersDefaultSecurityQuestion; newUser.PasswordAnswer = Resource.ManageUsersDefaultSecurityAnswer; newUser.OpenIdUri = e.ClaimedIdentifier.ToString(); newUser.Save(); if (siteSettings.UseSecureRegistration) { newUser.SetRegistrationConfirmationGuid(Guid.NewGuid()); } // track user ip address UserLocation userLocation = new UserLocation(newUser.UserGuid, SiteUtils.GetIP4Address()); userLocation.SiteGuid = siteSettings.SiteGuid; userLocation.Hostname = Page.Request.UserHostName; userLocation.Save(); if ( (siteSettings.UseSecureRegistration) && (newUser.RegisterConfirmGuid != Guid.Empty) ) { Notification.SendRegistrationConfirmationLink( SiteUtils.GetSmtpSettings(), ResourceHelper.GetMessageTemplate("RegisterConfirmEmailMessage.config"), siteSettings.DefaultEmailFromAddress, siteSettings.DefaultFromEmailAlias, newUser.Email, siteSettings.SiteName, WebUtils.GetSiteRoot() + "/ConfirmRegistration.aspx?ticket=" + newUser.RegisterConfirmGuid.ToString()); lblError.Text = Resource.LoginUnconfirmedEmailMessage; log.Info("Automatically created User " + newUser.Name + " on login from open id. Tried to login but email address is not confirmed."); return; } if (siteSettings.UseEmailForLogin) { FormsAuthentication.SetAuthCookie( newUser.Email, true); } else { FormsAuthentication.SetAuthCookie( newUser.LoginName, true); } if (WebConfigSettings.UseFoldersInsteadOfHostnamesForMultipleSites) { string cookieName = "siteguid" + siteSettings.SiteGuid; CookieHelper.SetCookie(cookieName, newUser.UserGuid.ToString(), true); } newUser.UpdateLastLoginTime(); string redirectUrl = GetRedirectPath(); CookieHelper.ExpireCookie(returnUrlCookieName); WebUtils.SetupRedirect(this, redirectUrl); return; } } else { // user not found // required fields not available from open id // redirect to register page? // Or show message with Link to // register page string registerLinkHref = siteRoot + "/Secure/RegisterWithOpenID.aspx"; litNotRegisteredYetMessage.Text = string.Format( Resource.OpenIDMustRegisterBeforeLoginMesage, registerLinkHref); } }
private void DoNewUserLogic(OpenIdEventArgs e) { if (e == null) { return; } ClaimsResponse claim = e.Response.GetExtension<ClaimsResponse>(); if (claim == null) { return; } if (IsValidForUserCreation(e, claim)) { if (SiteUser.EmailExistsInDB(siteSettings.SiteId, claim.Email)) { // show message that user should login and associate // their open id account on their profile page. lblError.Text = Resource.OpenIDRegisterUserEmailExistsMessage; } else { // create user automagically since we have all // the needed data string loginName = SecurityHelper.RemoveMarkup(e.ClaimedIdentifier.ToString().Replace("http://", string.Empty).Replace("https://", string.Empty).Replace("/", string.Empty)); CreateUser( e.ClaimedIdentifier.ToString(), claim.Email, loginName, SecurityHelper.RemoveMarkup(claim.FullName)); return; } } else { // prompt user to enter needed fields CookieHelper.SetSecureCookie(openidCookieName, e.ClaimedIdentifier.ToString()); if ( (claim != null) &&(claim.Email != null) && (claim.Email.Length > 3) && (Email.IsValidEmailAddressSyntax(claim.Email)) ) { CookieHelper.SetSecureCookie(openIdEmailCookieName, claim.Email); divEmailInput.Visible = false; divEmailDisplay.Visible = true; litEmail.Text = claim.Email; } else { divEmailInput.Visible = true; divEmailDisplay.Visible = false; } if ( (claim != null) && (claim.FullName != null) && (claim.FullName.Length > 0) ) { CookieHelper.SetSecureCookie(openIdFullNameCookieName, SecurityHelper.RemoveMarkup(claim.FullName)); } pnlNeededProfileProperties.Visible = true; pnlOpenID.Visible = false; if (e.ClaimedIdentifier != null) { litOpenIDURI.Text = e.ClaimedIdentifier.ToString(); } //PopulateRequiredProfileControls(); //DisplayResults(e); litInfoNeededMessage.Text = Resource.OpenIDAdditionalInfoNeededMessage; } }
void OpenIdLogin1_Canceled(object sender, OpenIdEventArgs e) { lblLoginCanceled.Visible = true; }
private bool IsValidForUserCreation(OpenIdEventArgs e, ClaimsResponse claim) { if (e == null) return false; if (claim == null) return false; if (e.ClaimedIdentifier == null) { return false; } if (String.IsNullOrEmpty(claim.Email)) { return false; } if (String.IsNullOrEmpty(claim.FullName)) { return false; } if (!Email.IsValidEmailAddressSyntax(claim.Email)) return false; // if custom profile fields are required // must pass them on to registration page mojoProfileConfiguration profileConfig = mojoProfileConfiguration.GetConfig(); if (profileConfig != null) { if (profileConfig.HasRequiredCustomProperties()) return false; } return true; }
protected void OpenIdLogin1_LoggedIn(object sender, OpenIdEventArgs e) { // prevent the base control from doing forms auth for us e.Cancel = true; Guid userGuid = SiteUser.GetUserGuidFromOpenId( siteSettings.SiteId, e.ClaimedIdentifier.ToString()); if (userGuid == Guid.Empty) { // if enough info is available auto create user DoNewUserLogic(e); } else { DoExistingUserLogic(userGuid); } }
protected void OpenIdLogin1_LoggedIn(object sender, OpenIdEventArgs e) { State.FriendlyLoginName = e.Response.FriendlyIdentifierForDisplay; }
protected void btnOpenIdLogin_LoggingIn(object sender, OpenIdEventArgs e) { if(btnOpenIdLogin.RememberMe) { var openIdCookie = new HttpCookie("__OpenIdUrl__", btnOpenIdLogin.Text) {Expires = DateTime.Now.AddDays(14)}; Response.Cookies.Add(openIdCookie); } }
protected void OpenIdLogin1_LoggingIn(object sender, OpenIdEventArgs e) { this.prepareRequest(e.Request); }