bool IExtensionResponse.Deserialize(IDictionary <string, string> fields, IAuthenticationResponse response, string typeUri) { if (fields == null) { return(false); } string mode; fields.TryGetValue("mode", out mode); if (mode != Mode) { return(false); } string updateUrl; fields.TryGetValue("update_url", out updateUrl); Uri updateUri; if (Uri.TryCreate(updateUrl, UriKind.Absolute, out updateUri)) { UpdateUrl = updateUri; } foreach (var att in DeserializeAttributes(fields)) { AddAttribute(att); } return(true); }
private ActionResult CreateHltbsRedirectionResponse(IAuthenticationResponse response) { if (response.Status != AuthenticationStatus.Authenticated) { SiteEventSource.Log.SteamAuthenticationFailed(response.Status); return(CreateSiteRedirection()); } long steam64Id; try { steam64Id = Int64.Parse(GetSteam64IdFromClaimedId(response.ClaimedIdentifier), CultureInfo.InvariantCulture); } catch (FormatException e) { SiteEventSource.Log.MalformedSteamClaimedIdProvided(response.ClaimedIdentifier, e.Message); return(CreateSiteRedirection()); } catch (OverflowException e) { SiteEventSource.Log.MalformedSteamClaimedIdProvided(response.ClaimedIdentifier, e.Message); return(CreateSiteRedirection()); } SiteEventSource.Log.SteamAuthenticationSucceeded(response.FriendlyIdentifierForDisplay); return(CreateSiteRedirection(steam64Id)); }
/// <summary> /// Processes an incoming authorization-granted message from an SP and obtains an access token. /// </summary> /// <param name="openIdAuthenticationResponse">The OpenID authentication response that may be carrying an authorized request token.</param> /// <returns> /// The access token, or null if OAuth authorization was denied by the user or service provider. /// </returns> /// <remarks> /// The access token, if granted, is automatically stored in the <see cref="ConsumerBase.TokenManager"/>. /// The token manager instance must implement <see cref="IOpenIdOAuthTokenManager"/>. /// </remarks> public AuthorizedTokenResponse ProcessUserAuthorization(IAuthenticationResponse openIdAuthenticationResponse) { Requires.NotNull(openIdAuthenticationResponse, "openIdAuthenticationResponse"); Requires.ValidState(this.TokenManager is IOpenIdOAuthTokenManager); var openidTokenManager = this.TokenManager as IOpenIdOAuthTokenManager; ErrorUtilities.VerifyOperation(openidTokenManager != null, OAuthStrings.OpenIdOAuthExtensionRequiresSpecialTokenManagerInterface, typeof(IOpenIdOAuthTokenManager).FullName); // The OAuth extension is only expected in positive assertion responses. if (openIdAuthenticationResponse.Status != AuthenticationStatus.Authenticated) { return null; } // Retrieve the OAuth extension var positiveAuthorization = openIdAuthenticationResponse.GetExtension<AuthorizationApprovedResponse>(); if (positiveAuthorization == null) { return null; } // Prepare a message to exchange the request token for an access token. // We are careful to use a v1.0 message version so that the oauth_verifier is not required. var requestAccess = new AuthorizedTokenRequest(this.ServiceProvider.AccessTokenEndpoint, Protocol.V10.Version) { RequestToken = positiveAuthorization.RequestToken, ConsumerKey = this.ConsumerKey, }; // Retrieve the access token and store it in the token manager. openidTokenManager.StoreOpenIdAuthorizedRequestToken(this.ConsumerKey, positiveAuthorization); var grantAccess = this.Channel.Request<AuthorizedTokenResponse>(requestAccess); this.TokenManager.ExpireRequestTokenAndStoreNewAccessToken(this.ConsumerKey, positiveAuthorization.RequestToken, grantAccess.AccessToken, grantAccess.TokenSecret); // Provide the caller with the access token so it may be associated with the user // that is logging in. return grantAccess; }
private string GetFriendlyName(IAuthenticationResponse authResponse) { string friendlyName = ""; var sregResponse = authResponse.GetExtension <ClaimsResponse>(); var axResponse = authResponse.GetExtension <FetchResponse>(); if (sregResponse != null) { friendlyName = sregResponse.FullName.AsNullIfEmpty() ?? sregResponse.Nickname.AsNullIfEmpty() ?? sregResponse.Email; } else if (axResponse != null) { var fullName = axResponse.GetAttributeValue(WellKnownAttributes.Name.FullName); var firstName = axResponse.GetAttributeValue(WellKnownAttributes.Name.First); var lastName = axResponse.GetAttributeValue(WellKnownAttributes.Name.Last); var email = axResponse.GetAttributeValue(WellKnownAttributes.Contact.Email); friendlyName = fullName.AsNullIfEmpty() ?? ((!string.IsNullOrEmpty(firstName) && !string.IsNullOrEmpty(lastName)) ? firstName + " " + lastName : null) ?? email; } if (string.IsNullOrEmpty(friendlyName)) { friendlyName = authResponse.FriendlyIdentifierForDisplay; } return(friendlyName); }
public override void SetUp() { base.SetUp(); IndirectSignedResponse responseMessage = new IndirectSignedResponse(Protocol.Default.Version, RPUri); this.extensions = responseMessage.Extensions; this.response = new DotNetOpenAuth.OpenId.RelyingParty.PositiveAnonymousResponse(responseMessage); }
public MockRelyingParty() { var mock = new Mock <IAuthenticationResponse>(); mock.SetupGet(r => r.Status).Returns(AuthenticationStatus.Authenticated); this.response = mock.Object; }
public async Task UnsolicitedAssertion() { var opStore = new MemoryCryptoKeyAndNonceStore(); Handle(RPUri).By( async req => { var rp = new OpenIdRelyingParty(new MemoryCryptoKeyAndNonceStore(), this.HostFactories); IAuthenticationResponse response = await rp.GetResponseAsync(req); Assert.That(response, Is.Not.Null); Assert.AreEqual(AuthenticationStatus.Authenticated, response.Status); return(new HttpResponseMessage()); }); Handle(OPUri).By( async(req, ct) => { var op = new OpenIdProvider(opStore, this.HostFactories); return(await this.AutoProviderActionAsync(op, req, ct)); }); this.RegisterMockRPDiscovery(ssl: false); { var op = new OpenIdProvider(opStore, this.HostFactories); Identifier id = GetMockIdentifier(ProtocolVersion.V20); var assertion = await op.PrepareUnsolicitedAssertionAsync(OPUri, RPRealmUri, id, OPLocalIdentifiers[0]); using (var httpClient = this.HostFactories.CreateHttpClient()) { using (var response = await httpClient.GetAsync(assertion.Headers.Location)) { response.EnsureSuccessStatusCode(); } } } }
/// <summary> /// Check if authentication succeeded after user is redirected back from the service provider. /// </summary> /// <param name="context"> /// The context of the current request. /// </param> /// <returns> /// An instance of <see cref="AuthenticationResult"/> containing authentication result. /// </returns> public virtual AuthenticationResult VerifyAuthentication(HttpContextBase context) { IAuthenticationResponse response = RelyingParty.GetResponse(); if (response == null) { throw new InvalidOperationException(WebResources.OpenIDFailedToGetResponse); } if (response.Status == AuthenticationStatus.Authenticated) { string id = response.ClaimedIdentifier; string username; Dictionary <string, string> extraData = this.GetExtraData(response) ?? new Dictionary <string, string>(); // try to look up username from the 'username' or 'email' property. If not found, fall back to 'friendly id' if (!extraData.TryGetValue("username", out username) && !extraData.TryGetValue("email", out username)) { username = response.FriendlyIdentifierForDisplay; } return(new AuthenticationResult(true, this.ProviderName, id, username, extraData)); } return(AuthenticationResult.Failed); }
public ActionResult LogOn() { var openid = new OpenIdRelyingParty(); IAuthenticationResponse response = openid.GetResponse(); if (response != null) { switch (response.Status) { case AuthenticationStatus.Authenticated: var user = _userRepo.FindUserByClaimedIdentifier(response.ClaimedIdentifier); if (null == user) { user = CreateUserFromOpenIDResponse(response); } FormsAuthentication.RedirectFromLoginPage(user.FriendlyIdentifier, false); break; case AuthenticationStatus.Canceled: ModelState.AddModelError("loginIdentifier", "Login was cancelled at the provider"); break; case AuthenticationStatus.Failed: ModelState.AddModelError("loginIdentifier", "Login failed using the provided OpenID identifier"); break; } } return(View()); }
public ActionResult Login() { var openid = new OpenIdRelyingParty(); IAuthenticationResponse response = openid.GetResponse(); if (response != null) { switch (response.Status) { case AuthenticationStatus.Authenticated: var user = EnsureUserExists(response); FormsAuthentication.RedirectFromLoginPage( user.email, false); break; case AuthenticationStatus.Canceled: ModelState.AddModelError("loginIdentifier", "Login was cancelled at the provider"); break; case AuthenticationStatus.Failed: ModelState.AddModelError("loginIdentifier", "Login failed using the provided OpenID identifier"); break; } } return(View()); }
private void SetUserInformationGeneric(IAuthenticationResponse response) { var userdata = response.GetExtension<ClaimsResponse>(); var email = userdata.Email; FullName = userdata.FullName; Email = email; }
/// <summary> /// The PreparePolicyInfo /// </summary> /// <param name="authenticationResponse">The verifyFactorsList<see cref="IAuthenticationResponse"/></param> private PolicyInfo PreparePolicyInfo(IAuthenticationResponse authenticationResponse) { var policyResponse = JsonConvert.SerializeObject(authenticationResponse.Embedded["policy"]); PolicyInfo policyObj = JsonConvert.DeserializeObject <PolicyInfo>(policyResponse); return(policyObj); }
public ActionResult OpenIdLogin(IAuthenticationResponse response) { switch (response.Status) { case AuthenticationStatus.Authenticated: var claimsResponse = response.GetExtension <ClaimsResponse>(); if (claimsResponse.Email == _adminEmail) { FormsAuthentication.SetAuthCookie(response.ClaimedIdentifier, false); return(RedirectToAction("Index", "Dashboard", new { area = "Admin" })); } break; case AuthenticationStatus.Canceled: ModelState.AddModelError("loginIdentifier", "Login was cancelled at the provider"); break; case AuthenticationStatus.Failed: ModelState.AddModelError("loginIdentifier", "Login failed using the provided OpenID identifier"); break; } return(new EmptyResult()); }
private List <IEnrollFactor> PrepareEnrollFactors(IAuthenticationResponse authenticationResponse) { List <IEnrollFactor> enrollFactorsList = new List <IEnrollFactor>(); if (authenticationResponse.Embedded.GetData().ContainsKey("factors")) { string stringResponse = JsonConvert.SerializeObject(authenticationResponse.Embedded.GetData()["factors"]); List <object> factorsList = JsonConvert.DeserializeObject <List <object> >(stringResponse); this.OktaFactorCount = factorsList.Count; foreach (var factor in factorsList) { string factorStringResponse = JsonConvert.SerializeObject(factor); FactorInfo factorObj = JsonConvert.DeserializeObject <FactorInfo>(factorStringResponse); string factorKey = GetFactorKey(factorObj); string isFactorRequired = IsFactorRequired(factorObj); string factorEnrollmentStatus = GetFactorEnrollStatus(factorObj); string factorId = GetEnrollFactorId(factorObj.FactorType); factorObj.FactorKey = factorKey; string[] supportedFactors = { "sms:OKTA" }; if (supportedFactors.Contains(factorKey) && isFactorRequired == "REQUIRED" && factorEnrollmentStatus == "NOT_SETUP") { IEnrollFactor enrollFactor = this.CreateEnrollFactorObject(factorObj); enrollFactorsList.Add(enrollFactor); } } } return(enrollFactorsList); }
/// <summary> /// Initializes a new instance of the <see cref="OpenIdEventArgs"/> class /// with information on a completed authentication attempt /// (whether that attempt was successful or not). /// </summary> /// <param name="response">The incoming authentication response.</param> internal OpenIdEventArgs(IAuthenticationResponse response) { ErrorUtilities.VerifyArgumentNotNull(response, "response"); this.Response = response; this.ClaimedIdentifier = response.ClaimedIdentifier; }
/// <summary> /// Gets the extra data obtained from the response message when authentication is successful. /// </summary> /// <param name="response"> /// The response message. /// </param> /// <returns>A dictionary of profile data; or null if no data is available.</returns> protected override Dictionary <string, string> GetExtraData(IAuthenticationResponse response) { FetchResponse fetchResponse = response.GetExtension <FetchResponse>(); if (fetchResponse != null) { var extraData = new Dictionary <string, string>(); extraData.Add("email", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Email)); extraData.Add("country", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.HomeAddress.Country)); extraData.Add("firstName", fetchResponse.GetAttributeValue(WellKnownAttributes.Name.First)); extraData.Add("lastName", fetchResponse.GetAttributeValue(WellKnownAttributes.Name.Last)); //extraData.Add("city", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.HomeAddress.City)); //extraData.Add("postalcode", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.HomeAddress.PostalCode)); //extraData.Add("state", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.HomeAddress.State)); //extraData.Add("addressone", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.HomeAddress.StreetAddressLine1)); //extraData.Add("addresstwo", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.HomeAddress.StreetAddressLine2)); //extraData.Add("birthdate", fetchResponse.GetAttributeValue(WellKnownAttributes.BirthDate.WholeBirthDate)); //extraData.Add("companyname", fetchResponse.GetAttributeValue(WellKnownAttributes.Company.CompanyName)); //extraData.Add("jobtitle", fetchResponse.GetAttributeValue(WellKnownAttributes.Company.JobTitle)); //extraData.Add("gender", fetchResponse.GetAttributeValue(WellKnownAttributes.Person.Gender)); //extraData.Add("fullname", fetchResponse.GetAttributeValue(WellKnownAttributes.Name.FullName)); //extraData.Add("mobile", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Phone.Mobile)); //extraData.Add("homepage", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Web.Homepage)); return(extraData); } return(null); }
public async Task <IAuthenticationResponse> LogIn(object userData, string key) { var authData = JsonConvert.DeserializeObject <AuthData>(userData.ToString()); //if (authData.SystemCode == 0) throw new Exception("Código do sistema não informado"); if (authData.UserIdentity == null) { throw new ArgumentNullException(nameof(IAuthData.UserIdentity)); } if (authData.KeyContent == null) { throw new ArgumentNullException(nameof(IAuthData.KeyContent)); } IAuthenticationResponse response = null; IAuthData data = null; switch (authData.LoginType) { default: case enumLoginType.PassPhrase: data = JsonConvert.DeserializeObject <AuthDataFromPassPhrase>(userData.ToString()); response = await AuthWithLogin(data, key); break; } return(response); }
public static UserToken Login(IAuthenticationResponse resp) { if (resp == null) { return(null); } UserToken token = null; if (resp.Status == AuthenticationStatus.Authenticated) { ClaimsResponse ProfileFields = resp.GetExtension <ClaimsResponse>(); User user = GetUserByOpenIDIdentifier(resp.ClaimedIdentifier); if (user != null && user.Active) { token = user.ToToken(); } } Login(token, resp.ClaimedIdentifier); return(token); }
private static void SetCommenterValuesFromOpenIdResponse(IAuthenticationResponse response, Commenter commenter) { var claimsResponse = response.GetExtension<ClaimsResponse>(); if (claimsResponse != null) { if (string.IsNullOrWhiteSpace(commenter.Name) && string.IsNullOrWhiteSpace(claimsResponse.Nickname) == false) commenter.Name = claimsResponse.Nickname; else if (string.IsNullOrWhiteSpace(commenter.Name) && string.IsNullOrWhiteSpace(claimsResponse.FullName) == false) commenter.Name = claimsResponse.FullName; if (string.IsNullOrWhiteSpace(commenter.Email) && string.IsNullOrWhiteSpace(claimsResponse.Email) == false) commenter.Email = claimsResponse.Email; } var fetchResponse = response.GetExtension<FetchResponse>(); if (fetchResponse != null) // let us try from the attributes { if (string.IsNullOrWhiteSpace(commenter.Email)) commenter.Email = fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Email); if (string.IsNullOrWhiteSpace(commenter.Name)) { commenter.Name = fetchResponse.GetAttributeValue(WellKnownAttributes.Name.FullName) ?? fetchResponse.GetAttributeValue(WellKnownAttributes.Name.First) + " " + fetchResponse.GetAttributeValue(WellKnownAttributes.Name.Last); } if (string.IsNullOrWhiteSpace(commenter.Url)) { commenter.Url = fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Web.Blog) ?? fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Web.Homepage); } } }
/// <summary> /// Initializes a new instance of the <see cref="OpenIdEventArgs"/> class /// with information on a completed authentication attempt /// (whether that attempt was successful or not). /// </summary> /// <param name="response">The incoming authentication response.</param> internal OpenIdEventArgs(IAuthenticationResponse response) { Requires.NotNull(response, "response"); this.Response = response; this.ClaimedIdentifier = response.ClaimedIdentifier; }
/// <summary> /// Initializes a new instance of the <see cref="OpenIdEventArgs"/> class /// with information on a completed authentication attempt /// (whether that attempt was successful or not). /// </summary> /// <param name="response">The incoming authentication response.</param> internal OpenIdEventArgs(IAuthenticationResponse response) { Contract.Requires <ArgumentNullException>(response != null); this.Response = response; this.ClaimedIdentifier = response.ClaimedIdentifier; }
public virtual UserClaim GetUserClaim(IAuthenticationResponse response) { if (response == null) return null; switch (response.Status) { case AuthenticationStatus.Authenticated: var claimsResponse = response.GetExtension<ClaimsResponse>(); if (claimsResponse != null) { return new UserClaim { Username = claimsResponse.Nickname, Email = claimsResponse.Email, Name = claimsResponse.FullName, Identifier = response.FriendlyIdentifierForDisplay }; } return null; case AuthenticationStatus.Canceled: case AuthenticationStatus.Failed: return null; } return null; }
private void ProcessOpenIdResponse(IAuthenticationResponse response) { switch (response.Status) { case AuthenticationStatus.Authenticated: string openId = response.ClaimedIdentifier; int userId; string userName; GetUserByOpenId(openId, out userId, out userName); //int userId = BusinessLayer.User.GetUserIDByOpenIdUsername(response.ClaimedIdentifier); if (userId != 0) { Utils.User.Login(userId, userName); Response.Redirect("default.aspx"); } else //we have to add a new user { Session["OpenIdUserName"] = openId; divLogin.Visible = false; divPickLogin.Visible = true; lblOpenId.Text = openId; lblOpenId2.Text = openId; } break; } }
/// <summary> /// The PrepareVerifyFactors /// </summary> /// <param name="authenticationResponse">The authenticationResponse<see cref="IAuthenticationResponse"/></param> /// <returns>The <see cref="List{IVerifyFactor}"/></returns> private List <IVerifyFactor> PrepareVerifyFactors(IAuthenticationResponse authenticationResponse) { List <IVerifyFactor> verifyFactorsList = new List <IVerifyFactor>(); //this.logger.Debug("ProcessAuthnResponse stateToken: " + authenticationResponse.StateToken); if (authenticationResponse.Embedded.GetData().ContainsKey("factors")) { string stringResponse = JsonConvert.SerializeObject(authenticationResponse.Embedded.GetData()["factors"]); List <object> factorsList = JsonConvert.DeserializeObject <List <object> >(stringResponse); this.OktaFactorCount = factorsList.Count; foreach (var factor in factorsList) { string factorStringResponse = JsonConvert.SerializeObject(factor); FactorInfo factorObj = JsonConvert.DeserializeObject <FactorInfo>(factorStringResponse); string factorKey = GetFactorKey(factorObj); factorObj.FactorKey = factorKey; string[] supportedFactors = { "sms:OKTA", "email:OKTA" }; if (supportedFactors.Contains(factorKey)) { IVerifyFactor verifyFactor = this.CreateFactorObject(factorObj); verifyFactorsList.Add(verifyFactor); } else { this.OktaFactorCount -= 1; } } } return(verifyFactorsList); }
private ActionResult OpenIdResponse(IAuthenticationResponse response) { Logger.Trace("Received response from open id provider"); // Step 2: OpenID Provider sending assertion response switch (response.Status) { case AuthenticationStatus.Authenticated: Logger.Info("User succesfully authenticated"); var userId = OpenIdService.ParseResponse(response); var loginResult = this.PerformLoginProcedure(userId); if (!loginResult) { this.ViewBag.Error = "Authentication failed"; return(this.View("Login")); } Logger.Info("Authentication procedure succesfull redirecting to Home/Index"); return(this.RedirectToAction("Index", "Home")); case AuthenticationStatus.Canceled: case AuthenticationStatus.Failed: Logger.Error("Authentication failed : {0}", response.Exception.Message); this.ViewBag.Error = "Authentication failed"; return(this.View("Login")); } return(new EmptyResult()); }
/// <summary> /// Processes an incoming authorization-granted message from an SP and obtains an access token. /// </summary> /// <param name="openIdAuthenticationResponse">The OpenID authentication response that may be carrying an authorized request token.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The access token, or null if OAuth authorization was denied by the user or service provider. /// </returns> /// <remarks> /// The access token, if granted, is automatically stored in the <see cref="ConsumerBase.TokenManager" />. /// The token manager instance must implement <see cref="IOpenIdOAuthTokenManager" />. /// </remarks> public async Task<AccessTokenResponse> ProcessUserAuthorizationAsync(IAuthenticationResponse openIdAuthenticationResponse, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(openIdAuthenticationResponse, "openIdAuthenticationResponse"); // The OAuth extension is only expected in positive assertion responses. if (openIdAuthenticationResponse.Status != AuthenticationStatus.Authenticated) { return null; } // Retrieve the OAuth extension var positiveAuthorization = openIdAuthenticationResponse.GetExtension<AuthorizationApprovedResponse>(); if (positiveAuthorization == null) { return null; } using (var client = this.CreateHttpClient(new AccessToken(positiveAuthorization.RequestToken, string.Empty))) { var request = new HttpRequestMessage(this.ServiceProvider.TokenRequestEndpointMethod, this.ServiceProvider.TokenRequestEndpoint); using (var response = await client.SendAsync(request, cancellationToken)) { response.EnsureSuccessStatusCode(); // Parse the response and ensure that it meets the requirements of the OAuth 1.0 spec. string content = await response.Content.ReadAsStringAsync(); var responseData = HttpUtility.ParseQueryString(content); string accessToken = responseData[Protocol.TokenParameter]; string tokenSecret = responseData[Protocol.TokenSecretParameter]; ErrorUtilities.VerifyProtocol(!string.IsNullOrEmpty(accessToken), MessagingStrings.RequiredParametersMissing, typeof(AuthorizedTokenResponse).Name, Protocol.TokenParameter); ErrorUtilities.VerifyProtocol(tokenSecret != null, MessagingStrings.RequiredParametersMissing, typeof(AuthorizedTokenResponse).Name, Protocol.TokenSecretParameter); responseData.Remove(Protocol.TokenParameter); responseData.Remove(Protocol.TokenSecretParameter); return new AccessTokenResponse(accessToken, tokenSecret, responseData); } } }
/// <summary> /// Initializes a new instance of the <see cref="AuthenticationResponseShim"/> class. /// </summary> /// <param name="response">The response.</param> internal AuthenticationResponseShim(IAuthenticationResponse response) { if (response == null) { throw new ArgumentNullException("response"); } this.response = response; }
private void SetUserInformationFromGoogle(IAuthenticationResponse response) { var userdata = response.GetExtension<FetchResponse>(); var firstname = userdata.GetAttributeValue(WellKnownAttributes.Name.First); var lastname = userdata.GetAttributeValue(WellKnownAttributes.Name.Last); FullName = firstname + " " + lastname; Email = userdata.GetAttributeValue(WellKnownAttributes.Contact.Email); }
/// <summary> /// Called when an incoming positive assertion is received. /// </summary> /// <param name="assertion">The positive assertion.</param> void IRelyingPartyBehavior.OnIncomingPositiveAssertion(IAuthenticationResponse assertion) { if (assertion.GetExtension <ClaimsResponse>() == null) { ClaimsResponse sreg = assertion.UnifyExtensionsAsSreg(true); ((PositiveAnonymousResponse)assertion).Response.Extensions.Add(sreg); } }
protected override string HandleUnknownUser(IAuthenticationResponse response) { string username = response.ClaimedIdentifier.ToString(); string email = response.ClaimedIdentifier.ToString(); string comment = null; var sreg = response.GetExtension<DotNetOpenAuth.OpenId.Extensions.SimpleRegistration.ClaimsResponse>(); if (sreg != null) { if (sreg.Nickname != null) { comment = sreg.Nickname; } if (sreg.Email != null) { email = sreg.Email; } } var ax = response.GetExtension<DotNetOpenAuth.OpenId.Extensions.AttributeExchange.FetchResponse>(); if (ax != null) { if (ax.Attributes.Contains(WellKnownAttributes.Contact.Email)) { IList<string> emailAddresses = ax.Attributes[WellKnownAttributes.Contact.Email].Values; email = emailAddresses.Count > 0 ? emailAddresses[0] : email; } if (ax.Attributes.Contains(WellKnownAttributes.Name.Alias)) { IList<string> aliasNames = ax.Attributes[WellKnownAttributes.Name.Alias].Values; comment = aliasNames.Count > 0 ? aliasNames[0] : comment; } } try { var user = Membership.CreateUser(username, Guid.NewGuid().ToString(), email); NHOpenIDMembershipProvider idprov = Provider as NHOpenIDMembershipProvider; MembershipCreateStatus status; idprov.AddIdToUser(user, response.ClaimedIdentifier, out status); if (status == MembershipCreateStatus.Success) { if (String.IsNullOrEmpty(comment)) { user.Comment = email; } else { user.Comment = comment; } Provider.UpdateUser(user); return user.UserName; } else { Provider.DeleteUser(user.UserName, true); } } catch (MembershipCreateUserException) { return null; } return null; }
internal static string SignIn(Guid userDetailsPageId) { string errorMessage = string.Empty; using (var openid = new OpenIdRelyingParty()) { //fix wrong URI, add PathInfo HttpContext.Current.RewritePath(HttpContext.Current.Request.RawUrl); IAuthenticationResponse response = openid.GetResponse(); if (response == null) { //request string openIDIdentifier = HttpContext.Current.Request.Form["openid_identifier"]; if (!string.IsNullOrEmpty(openIDIdentifier)) { IAuthenticationRequest request = openid.CreateRequest(openIDIdentifier); var claims = new ClaimsRequest(); claims.Email = DemandLevel.Require; claims.Nickname = DemandLevel.Require; claims.FullName = DemandLevel.Require; claims.Country = DemandLevel.Require; request.AddExtension(claims); //small fix for request.RedirectToProvider(); string location = request.RedirectingResponse.Headers["Location"]; HttpContext.Current.Response.Redirect(location, false); } } else { //response switch (response.Status) { case AuthenticationStatus.Authenticated: HandleSuccessfulSignIn(response, userDetailsPageId); break; case AuthenticationStatus.Canceled: errorMessage = "Login was cancelled at the provider."; break; case AuthenticationStatus.Failed: errorMessage = "Login failed at the provider."; break; case AuthenticationStatus.SetupRequired: errorMessage = "The provider requires setup."; break; default: errorMessage = "Login failed."; break; } } } return(errorMessage); }
public override bool TryGetOpenIdResponse(out IAuthenticationResponse openIdResponse) { openIdResponse = openIdRelyingParty.GetResponse(); if (openIdResponse.IsNull()) { return false; } return true; }
private PolicyComplexity PreparePolicyComplexityObject(IAuthenticationResponse authenticationResponse) { var policyResponseObject = JsonConvert.SerializeObject(authenticationResponse.Embedded["policy"]); dynamic policyComplexityObj = JsonConvert.DeserializeObject <dynamic>(policyResponseObject).complexity; string passwordComplexityString = JsonConvert.SerializeObject(policyComplexityObj); PolicyComplexity passwordComplexityObj = JsonConvert.DeserializeObject <PolicyComplexity>(passwordComplexityString); return(passwordComplexityObj); }
private PolicyAge PreparePolicyAgeObject(IAuthenticationResponse authenticationResponse) { var policyResponseObject = JsonConvert.SerializeObject(authenticationResponse.Embedded["policy"]); dynamic policyAgeObj = JsonConvert.DeserializeObject <dynamic>(policyResponseObject).age; string policyAgeString = JsonConvert.SerializeObject(policyAgeObj); PolicyAge policyAge = JsonConvert.DeserializeObject <PolicyAge>(policyAgeString); return(policyAge); }
/// <summary> /// Initializes a new instance of the <see cref="AuthenticationResponseSnapshot"/> class. /// </summary> /// <param name="copyFrom">The authentication response to copy from.</param> internal AuthenticationResponseSnapshot(IAuthenticationResponse copyFrom) { ErrorUtilities.VerifyArgumentNotNull(copyFrom, "copyFrom"); this.ClaimedIdentifier = copyFrom.ClaimedIdentifier; this.FriendlyIdentifierForDisplay = copyFrom.FriendlyIdentifierForDisplay; this.Status = copyFrom.Status; this.callbackArguments = copyFrom.GetCallbackArguments(); }
private PolicyExpiration PreparePolicyExpirationObject(IAuthenticationResponse authenticationResponse) { var policyResponseObject = JsonConvert.SerializeObject(authenticationResponse.Embedded["policy"]); dynamic policyExpirationObj = JsonConvert.DeserializeObject <dynamic>(policyResponseObject).expiration; string policyExpirationString = JsonConvert.SerializeObject(policyExpirationObj); PolicyExpiration policyExpiration = JsonConvert.DeserializeObject <PolicyExpiration>(policyExpirationString); return(policyExpiration); }
/// <summary> /// Initializes a new instance of the <see cref="AuthenticationResponseShim"/> class. /// </summary> /// <param name="response">The response.</param> internal AuthenticationResponseShim(IAuthenticationResponse response) { Requires.NotNull(response, "response"); this.response = response; var claimsResponse = this.response.GetExtension<ClaimsResponse>(); if (claimsResponse != null) { this.ClaimsResponse = new ClaimsResponseShim(claimsResponse); } }
/// <summary> /// Initializes a new instance of the <see cref="AuthenticationResponseShim"/> class. /// </summary> /// <param name="response">The response.</param> internal AuthenticationResponseShim(IAuthenticationResponse response) { Contract.Requires<ArgumentNullException>(response != null); this.response = response; var claimsResponse = this.response.GetExtension<ClaimsResponse>(); if (claimsResponse != null) { this.ClaimsResponse = new ClaimsResponseShim(claimsResponse); } }
public override void SetUp() { base.SetUp(); IndirectSignedResponse responseMessage = new IndirectSignedResponse(Protocol.Default.Version, RPUri); this.extensions = responseMessage.Extensions; this.response = new DotNetOpenAuth.OpenId.RelyingParty.PositiveAnonymousResponse(responseMessage); }
/// <summary> /// Adds authentication cancellation behavior to display a message to the user. /// </summary> /// <param name="response">The response.</param> protected override void OnCanceled(IAuthenticationResponse response) { base.OnCanceled(response); if (!string.IsNullOrEmpty(this.CanceledText)) { this.errorLabel.Text = this.CanceledText; this.errorLabel.Visible = true; } }
/// <summary> /// Adds failure handling to display an error message to the user. /// </summary> /// <param name="response">The response.</param> protected override void OnFailed(IAuthenticationResponse response) { base.OnFailed(response); if (!string.IsNullOrEmpty(this.FailedMessageText)) { this.errorLabel.Text = string.Format(CultureInfo.CurrentCulture, this.FailedMessageText, response.Exception.ToStringDescriptive()); this.errorLabel.Visible = true; } }
/// <summary> /// Initializes a new instance of the <see cref="AuthenticationResponseShim"/> class. /// </summary> /// <param name="response">The response.</param> internal AuthenticationResponseShim(IAuthenticationResponse response) { Contract.Requires(response != null); ErrorUtilities.VerifyArgumentNotNull(response, "response"); this.response = response; var claimsResponse = this.response.GetExtension<ClaimsResponse>(); if (claimsResponse != null) { this.ClaimsResponse = new ClaimsResponseShim(claimsResponse); } }
public OpenIdentity ProcessOpenId(string openId) { _response = _openIdRelyingParty.GetResponse(); if (_response == null) { Authenticate(openId); return null; } return Verify(); }
protected override Dictionary<string, string> GetExtraData(IAuthenticationResponse response) { var fetchResponse = response.GetExtension<FetchResponse>(); if (fetchResponse != null) { var extraData = new Dictionary<string, string>(); extraData.AddItemIfNotEmpty(ClaimTypes.IsPersistent, fetchResponse.GetAttributeValue(ClaimTypes.IsPersistent)); return extraData; } return null; }
/// <summary> /// This authenticates a user based on a response from an openid provider. /// </summary> /// <param name="response"></param> private void AuthenticateUser(IAuthenticationResponse response) { if (response.Status != AuthenticationStatus.Authenticated) throw new ArgumentException("The response status must be 'Authenticated'. (" + response.Status.ToString() + ")", "response"); Identifier identifier = response.ClaimedIdentifier; if (identifier == null) { lblError.Text = "Oops! We lost the ID you tried to log in with. Can you try again?"; } else { using (SqlConnection cn = new SqlConnection(Database.TadMapConnection)) { cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "GetUserId"; cm.Parameters.AddWithValue("@OpenIdUrl", identifier.ToString()); using (SqlDataReader dr = cm.ExecuteReader()) { if (dr.Read()) { // a record was found so the user already exists // in the future we can use this to populate the identity // with display name and image... } else { // no user was found so we create it now. CreateNewUser(identifier.ToString()); } } } } // somehow we need to put the response.FriendlyIdentifierForDisplay // into the identity/principal if (Request.QueryString["ReturnUrl"] != null) { FormsAuthentication.RedirectFromLoginPage(identifier.ToString(), false); } else { FormsAuthentication.SetAuthCookie(identifier.ToString(), false); Response.Redirect("MyImages.aspx", false); } } }
/// <summary> /// Gets the extra data obtained from the response message when authentication is successful. /// </summary> /// <param name="response"> /// The response message. /// </param> /// <returns> /// </returns> protected override Dictionary<string, string> GetExtraData(IAuthenticationResponse response) { FetchResponse fetchResponse = response.GetExtension<FetchResponse>(); if (fetchResponse != null) { var extraData = new Dictionary<string, string>(); extraData.AddItemIfNotEmpty("email", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Email)); extraData.AddItemIfNotEmpty("fullName", fetchResponse.GetAttributeValue(WellKnownAttributes.Name.FullName)); return extraData; } return null; }
protected override Dictionary<string, string> GetExtraData(IAuthenticationResponse response) { FetchResponse extension = response.GetExtension<FetchResponse>(); if (extension != null) { Dictionary<string, string> dictionary = new Dictionary<string, string>(); dictionary.Add("email", extension.GetAttributeValue("http://axschema.org/contact/email")); dictionary.Add("name", extension.GetAttributeValue("http://axschema.org/namePerson/first") + " " + extension.GetAttributeValue("http://axschema.org/namePerson/last")); return dictionary; } return null; }
public static string GetFriendlyOpenId(IAuthenticationResponse response, string email) { if (response.ClaimedIdentifier.ToString().Contains(WellKnownProviders.Google)) { return "Google(" + email + ")"; } if (response.ClaimedIdentifier.ToString().Contains(WellKnownProviders.Yahoo)) { return "Yahoo(" + email + ")"; } return response.FriendlyIdentifierForDisplay; }
internal AuthenticationResult ProcessOpenIdResponse(IAuthenticationResponse response) { switch (response.Status) { default: { return AbortedAuthentication(Common.Resources.Authentication.InvalidOpenAuthenticationStatus); } case AuthenticationStatus.Canceled: { return AbortedAuthentication(Common.Resources.Authentication.CanceledAtProvider, ConnectionStatus.Canceled); } case AuthenticationStatus.Failed: { return AuthenticationException(response.Exception); } case AuthenticationStatus.Authenticated: { string openId = response.ClaimedIdentifier; User user = userService.GetByOpenId(openId); bool isNewUser = false; bool isNewConnection = false; if (user == null) { isNewConnection = true; string email = null; string displayName = null; var fetch = response.GetExtension<FetchResponse>(); if (fetch != null) { email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email); displayName = fetch.GetAttributeValue(WellKnownAttributes.Name.FullName); } if (!email.NullOrEmpty()) // maybe they already have an account. { user = userService.GetByEmail(email); } if (user == null) // create a brand new account. { user = userService.CreateWithOpenId(openId, email, displayName); isNewUser = true; } else // just connect the existing account to their OpenId account. { userService.AddOpenIdConnection(user, openId); } } return SuccessfulAuthentication(user, isNewUser, isNewConnection); } } }
public UserInformation(IAuthenticationResponse response) { Response = response; ClaimedIdentifier = response.ClaimedIdentifier.ToString(); if (response.Provider.Uri.Host == OpenIdHelper.Google) { SetUserInformationFromGoogle(response); } else { SetUserInformationGeneric(response); } }
private Interfaces.IAuthenticationResponse GetUserIdentity(IAuthenticationResponse response) { var identifier = response.ClaimedIdentifier; var fetch = response.GetExtension<FetchResponse>(); Interfaces.IUserIdentity userIdentity = (fetch == null) ? null : Factory.GetUserIdentity(response.ClaimedIdentifier.ToString(), fetch.GetAttributeValue(WellKnownAttributes.Name.First), fetch.GetAttributeValue(WellKnownAttributes.Name.Last), fetch.GetAttributeValue(WellKnownAttributes.Contact.Email)); return Factory.AuthenticationResponse(userIdentity); }
/// <summary> /// Gets the extra data obtained from the response message when authentication is successful. /// </summary> /// <param name="response"> /// The response message. /// </param> /// <returns>A dictionary of profile data; or null if no data is available.</returns> protected override NameValueCollection GetExtraData(IAuthenticationResponse response) { FetchResponse fetchResponse = response.GetExtension<FetchResponse>(); if (fetchResponse != null) { var extraData = new NameValueCollection(); extraData.AddItemIfNotEmpty("email", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Email)); extraData.AddItemIfNotEmpty("country", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.HomeAddress.Country)); extraData.AddItemIfNotEmpty("firstName", fetchResponse.GetAttributeValue(WellKnownAttributes.Name.First)); extraData.AddItemIfNotEmpty("lastName", fetchResponse.GetAttributeValue(WellKnownAttributes.Name.Last)); return extraData; } return null; }
/// <summary> /// Log member in from response informations. /// </summary> /// <param name="response">A successfull response from the relying party</param> public void LogInMember(IAuthenticationResponse response) { var fetch = response.GetExtension(typeof(ClaimsResponse)) as ClaimsResponse; string email = null; if (fetch != null) { email = fetch.Email; } Member connectedMember = email == null ? _membershipService.LogIn(response.ClaimedIdentifier.ToString()) : _membershipService.LogIn(response.ClaimedIdentifier.ToString(), email); _sessionRegistry.MemberInformations.UserName = connectedMember.UserName; _sessionRegistry.MemberInformations.OpenId = response.ClaimedIdentifier.ToString(); }
public OpenIdUser ResponseIntoUser(IAuthenticationResponse response) { var claimResponseUntrusted = response.GetUntrustedExtension<ClaimsResponse>(); var claimResponse = response.GetExtension<ClaimsResponse>(); if (claimResponse != null) { return new OpenIdUser(claimResponse, response.ClaimedIdentifier); } if (claimResponseUntrusted != null) { return new OpenIdUser(claimResponseUntrusted, response.ClaimedIdentifier); } return null; }
public OpenIdAuthenticationParameters(IAuthenticationResponse authenticationResponse) { ExternalIdentifier = authenticationResponse.ClaimedIdentifier; ExternalDisplayIdentifier = authenticationResponse.FriendlyIdentifierForDisplay; _claims = new List<UserClaims>(); var claimsResponseTranslator = new OpenIdClaimsResponseClaimsTranslator(); var claims1 = claimsResponseTranslator.Translate(authenticationResponse.GetExtension<ClaimsResponse>()); if (claims1 != null) UserClaims.Add(claims1); var fetchResponseTranslator = new OpenIdFetchResponseClaimsTranslator(); var claims2 = fetchResponseTranslator.Translate(authenticationResponse.GetExtension<FetchResponse>()); if (claims2 != null) UserClaims.Add(claims2); }
private OpenIdUser ResponseIntoUser(IAuthenticationResponse response) { OpenIdUser user = null; var claimResponseUntrusted = response.GetUntrustedExtension<FetchResponse>(); var claimResponse = response.GetExtension<FetchResponse>(); if (claimResponse != null) { user = new OpenIdUser(claimResponse, response.ClaimedIdentifier); } else if (claimResponseUntrusted != null) { user = new OpenIdUser(claimResponseUntrusted, response.ClaimedIdentifier); } return user; }
private static string FetchEmail(IAuthenticationResponse response) { var fetch = response.GetExtension<FetchResponse>(); string email = string.Empty; if (fetch != null) { email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email); } if (string.IsNullOrEmpty(email)) { throw new InvalidOperationException("Email is required, but was not supplied by the OpenID provider."); } return email; }
public override OpenIdData ParseOpenIdResponse(IAuthenticationResponse openIdResponse) { if (openIdResponse.IsNull()) { throw new ArgumentException("Invalid open id response"); } //Let us check the response switch (openIdResponse.Status) { case AuthenticationStatus.Authenticated: var openId = openIdResponse.ClaimedIdentifier; var friendlyName = openIdResponse.FriendlyIdentifierForDisplay; return new OpenIdData() {FriendlyName = friendlyName, OpenId = openId}; break; default: throw new ArgumentException("Invalid open id"); } }
protected override Dictionary<string, string> GetExtraData(IAuthenticationResponse response) { var fetchResponse = response.GetExtension<FetchResponse>(); if (fetchResponse != null) { var extraData = new Dictionary<string, string> { {"email", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Email)}, {"country", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.HomeAddress.Country)}, {"firstName", fetchResponse.GetAttributeValue(WellKnownAttributes.Name.First)}, {"lastName", fetchResponse.GetAttributeValue(WellKnownAttributes.Name.Last)} }; return extraData; } return null; }
/// <summary> /// Extracts an Attribute Exchange response, if one exists /// </summary> private Dictionary<string, string> GetAttributeEx(IAuthenticationResponse response) { var ret = new Dictionary<string, string>(); var fetchResponse = response.GetExtension<FetchResponse>(); if (fetchResponse == null) return ret; var names = new List<string>(); var emails = new List<string>(); if (fetchResponse.Attributes.Contains("http://schema.openid.net/namePerson")) names.AddRange(fetchResponse.Attributes["http://schema.openid.net/namePerson"].Values); if (fetchResponse.Attributes.Contains(WellKnownAttributes.Name.FullName)) names.AddRange(fetchResponse.Attributes[WellKnownAttributes.Name.FullName].Values); if (fetchResponse.Attributes.Contains(WellKnownAttributes.Name.Alias)) names.AddRange(fetchResponse.Attributes[WellKnownAttributes.Name.Alias].Values); if (fetchResponse.Attributes.Contains(WellKnownAttributes.Name.First)) names.AddRange(fetchResponse.Attributes[WellKnownAttributes.Name.First].Values); if (fetchResponse.Attributes.Contains(WellKnownAttributes.Name.Last)) names.AddRange(fetchResponse.Attributes[WellKnownAttributes.Name.Last].Values); if (fetchResponse.Attributes.Contains("http://schema.openid.net/contact/email")) emails.AddRange(fetchResponse.Attributes["http://schema.openid.net/contact/email"].Values); if (fetchResponse.Attributes.Contains(WellKnownAttributes.Contact.Email)) emails.AddRange(fetchResponse.Attributes[WellKnownAttributes.Contact.Email].Values); if (names.Count > 0) ret["FullName"] = names[0]; if (emails.Count > 0) ret["Email"] = emails[0]; return ret; }