예제 #1
0
        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);
                }
            }
        }
예제 #2
0
        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);
        }
예제 #3
0
 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;
 }
        private static string GetFriendlyName(IAuthenticationResponse response)
        {
            var claimsResponse = response.GetExtension <ClaimsResponse>();

            if (claimsResponse != null)
            {
                if (!string.IsNullOrEmpty(claimsResponse.FullName))
                {
                    return(claimsResponse.FullName);
                }

                if (!string.IsNullOrEmpty(claimsResponse.Nickname))
                {
                    return(claimsResponse.Email);
                }

                if (!string.IsNullOrEmpty(claimsResponse.Email))
                {
                    return(claimsResponse.Email);
                }
            }

            var fetchResponse = response.GetExtension <FetchResponse>();

            if (fetchResponse != null)
            {
                var fullName = fetchResponse.GetAttributeValue(WellKnownAttributes.Name.FullName);

                if (!string.IsNullOrEmpty(fullName))
                {
                    return(fullName);
                }

                var firstName = fetchResponse.GetAttributeValue(WellKnownAttributes.Name.First);
                var lastName  = fetchResponse.GetAttributeValue(WellKnownAttributes.Name.Last);

                if (!string.IsNullOrEmpty(firstName) && !string.IsNullOrEmpty(lastName))
                {
                    return(fullName + " " + lastName);
                }

                var email = fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Email);

                if (!string.IsNullOrEmpty(email))
                {
                    return(email);
                }
            }

            return(response.FriendlyIdentifierForDisplay);
        }
		/// <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;
		}
		/// <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);
				}
			}
		}
 private void SetUserInformationGeneric(IAuthenticationResponse response)
 {
     var userdata = response.GetExtension<ClaimsResponse>();
     var email = userdata.Email;
     FullName = userdata.FullName;
     Email = email;
 }
        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);
        }
예제 #9
0
        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());
        }
예제 #10
0
        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);
        }
예제 #11
0
        /// <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);
        }
 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);
 }
예제 #13
0
 /// <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);
     }
 }
예제 #14
0
        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);
                }
            }
        }
예제 #15
0
        /// <summary>
        /// Called when an incoming positive assertion is received.
        /// </summary>
        /// <param name="assertion">The positive assertion.</param>
        void IRelyingPartyBehavior.OnIncomingPositiveAssertion(IAuthenticationResponse assertion)
        {
            PolicyResponse pape = assertion.GetExtension <PolicyResponse>();

            ErrorUtilities.VerifyProtocol(
                pape != null &&
                pape.ActualPolicies.Contains(AuthenticationPolicies.USGovernmentTrustLevel1) &&
                pape.ActualPolicies.Contains(AuthenticationPolicies.PrivatePersonalIdentifier),
                BehaviorStrings.PapeResponseOrRequiredPoliciesMissing);

            ErrorUtilities.VerifyProtocol(AllowPersonallyIdentifiableInformation || pape.ActualPolicies.Contains(AuthenticationPolicies.NoPersonallyIdentifiableInformation), BehaviorStrings.PapeResponseOrRequiredPoliciesMissing);

            if (pape.ActualPolicies.Contains(AuthenticationPolicies.NoPersonallyIdentifiableInformation))
            {
                ErrorUtilities.VerifyProtocol(
                    assertion.GetExtension <ClaimsResponse>() == null &&
                    assertion.GetExtension <FetchResponse>() == null,
                    BehaviorStrings.PiiIncludedWithNoPiiPolicy);
            }
        }
예제 #16
0
		/// <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;
		}
예제 #17
0
 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;
 }
예제 #18
0
        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;
        }
예제 #19
0
        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));
                extraData.AddItemIfNotEmpty(ClaimTypes.AuthenticationMethod, fetchResponse.GetAttributeValue(ClaimTypes.AuthenticationMethod));
                return(extraData);
            }
            return(null);
        }
예제 #20
0
        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 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);
        }
예제 #22
0
            public static OpenIdUserData CreateFromResponse(IAuthenticationResponse r)
            {
                var userData = new OpenIdUserData();

                var claimsResponse = r.GetExtension <ClaimsResponse>();

                if (claimsResponse != null)
                {
                    userData.Email       = claimsResponse.Email;
                    userData.DisplayName = claimsResponse.Nickname ?? claimsResponse.FullName;
                }

                return(userData);
            }
예제 #23
0
		/// <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();
        }
예제 #25
0
        /// <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.AddItemIfNotEmpty("email", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Email));
                extraData.AddItemIfNotEmpty("fullName", fetchResponse.GetAttributeValue(WellKnownAttributes.Name.FullName));

                return(extraData);
            }

            return(null);
        }
예제 #26
0
        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;
        }
예제 #27
0
        /// <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();
        }
        protected override Dictionary <string, string> GetExtraData(IAuthenticationResponse response)
        {
            var fetchResponse = response.GetExtension <FetchResponse>();

            if (fetchResponse == null)
            {
                return(null);
            }

            var result   = new Dictionary <string, string> ();
            var fullname = fetchResponse.GetAttributeValue(WellKnownAttributes.Name.First) + " " +
                           fetchResponse.GetAttributeValue(WellKnownAttributes.Name.Last);

            result.Add(FULLNAME_KEY, fullname);
            return(result);
        }
예제 #29
0
        private void ConsumeOpenIdResponse(IAuthenticationResponse response)
        {
            FetchResponse fetch = response.GetExtension <FetchResponse>();

            if (null != fetch)
            {
                Session["OpenIdResponse_trustScore"] = fetch.GetAttributeValue("http://schema.wave.com/endpoint/descriptor/trustScore");
                Session["OpenIdResponse_needsSetup"] = fetch.GetAttributeValue("http://schema.wave.com/endpoint/descriptor/needsSetup");
                Session["OpenIdResponse_setupURL"]   = fetch.GetAttributeValue("http://schema.wave.com/endpoint/descriptor/setupURL");
                // needsSetup and setupURL only returned if needed. Returned value is null otherwise.
            }
            Session["FriendlyIdentifier"] = response.FriendlyIdentifierForDisplay;
            FormsAuthentication.SetAuthCookie(response.ClaimedIdentifier, false);

            return;
        }
예제 #30
0
        /// <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);
        }
        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;
        }
예제 #32
0
        /// <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));

                return(extraData);
            }

            return(null);
        }
        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 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);
        }
예제 #35
0
        protected async void Page_Load(object sender, EventArgs e)
        {
            this.openIdBox.Focus();
            using (OpenIdRelyingParty rp = new OpenIdRelyingParty()) {
                IAuthenticationResponse response = await rp.GetResponseAsync(new HttpRequestWrapper(this.Request), this.Response.ClientDisconnectedToken);

                if (response != null)
                {
                    switch (response.Status)
                    {
                    case AuthenticationStatus.ExtensionsOnly:
                        this.ExtensionResponsesPanel.Visible = true;

                        // This is the "success" status we get when no authentication was requested.
                        var sreg = response.GetExtension <ClaimsResponse>();
                        if (sreg != null)
                        {
                            this.emailLabel.Text      = sreg.Email;
                            this.timeZoneLabel.Text   = sreg.TimeZone;
                            this.postalCodeLabel.Text = sreg.PostalCode;
                            this.countryLabel.Text    = sreg.Country;
                            if (sreg.Gender.HasValue)
                            {
                                this.genderLabel.Text = sreg.Gender.Value.ToString();
                            }
                        }
                        break;

                    case AuthenticationStatus.Canceled:
                        this.resultMessage.Text = "Canceled at OP.  This may be a sign that the OP doesn't support this message.";
                        break;

                    case AuthenticationStatus.Failed:
                        this.resultMessage.Text = "OP returned a failure: " + response.Exception;
                        break;

                    case AuthenticationStatus.SetupRequired:
                    case AuthenticationStatus.Authenticated:
                    default:
                        this.resultMessage.Text = "OP returned an unexpected response.";
                        break;
                    }
                }
            }
        }
예제 #36
0
        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;
        }
예제 #37
0
        private AWT2Demo.Domain.Entities.User CreateUserFromOpenIDResponse(IAuthenticationResponse response)
        {
            var    fetch     = response.GetExtension <FetchResponse>();
            string email     = String.Empty;
            string firstName = String.Empty;
            string lastName  = String.Empty;

            if (fetch != null)
            {
                email     = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);
                firstName = fetch.GetAttributeValue(WellKnownAttributes.Name.First);
                lastName  = fetch.GetAttributeValue(WellKnownAttributes.Name.Last);
            }
            return(_userRepo.AddUserForClaimedIdentifier(response.ClaimedIdentifier,
                                                         email,
                                                         firstName,
                                                         lastName));
        }
예제 #38
0
        private User EnsureUserExists(IAuthenticationResponse response)
        {
            var user = Users.Read().SingleOrDefault(u => u.identifier == response.ClaimedIdentifier.ToString());

            if (user == null)
            {
                var claim = response.GetExtension <ClaimsResponse>();

                user = new User
                {
                    identifier = response.ClaimedIdentifier.ToString(),
                    name       = claim.FullName,
                    email      = claim.Email
                };

                return(Users.Create(user));
            }
            return(user);
        }
예제 #39
0
        private IUser GetLoggedUser(IAuthenticationResponse authResponse)
        {
            var sregResponse = authResponse.GetExtension <ClaimsResponse>();
            var fullName     = sregResponse.IfNotNull(r => r.FullName.AsNullIfEmpty());
            var nickName     = sregResponse.IfNotNull(r => r.Nickname.AsNullIfEmpty());
            var email        = sregResponse.IfNotNull(r => r.Email.AsNullIfEmpty());

            var userToLogin = new User()
            {
                ClaimedIdentifier = authResponse.ClaimedIdentifier,
                Email             = email,
                FullName          = fullName,
                Nickname          = nickName
            };

            var loggedUser = LoginUser(userToLogin, false); //setting to true could result in lots of users creating their logins unnecessorily

            return(loggedUser);
        }
예제 #40
0
        protected void Page_Load(object sender, EventArgs e)
        {
            this.RegisterAsyncTask(
                new PageAsyncTask(
                    async ct => {
                if (!IsPostBack && string.Equals(Request.Url.Host, "localhost", StringComparison.OrdinalIgnoreCase))
                {
                    // Disable the button since the scenario won't work under localhost,
                    // and this will help encourage the user to read the the text above the button.
                    this.beginButton.Enabled = false;
                }

                IAuthenticationResponse authResponse =
                    await relyingParty.GetResponseAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
                if (authResponse != null)
                {
                    switch (authResponse.Status)
                    {
                    case AuthenticationStatus.Authenticated:
                        State.FetchResponse             = authResponse.GetExtension <FetchResponse>();
                        AccessTokenResponse accessToken =
                            await Global.GoogleWebConsumer.ProcessUserAuthorizationAsync(authResponse, Response.ClientDisconnectedToken);
                        if (accessToken != null)
                        {
                            State.GoogleAccessToken = accessToken.AccessToken;
                            FormsAuthentication.SetAuthCookie(authResponse.ClaimedIdentifier, false);
                            Response.Redirect("~/MembersOnly/DisplayGoogleContacts.aspx");
                        }
                        else
                        {
                            MultiView1.SetActiveView(AuthorizationDenied);
                        }
                        break;

                    case AuthenticationStatus.Canceled:
                    case AuthenticationStatus.Failed:
                    default:
                        this.MultiView1.SetActiveView(this.AuthenticationFailed);
                        break;
                    }
                }
            }));
        }
예제 #41
0
        protected virtual Dictionary <string, string> CreateAuthInfo(IAuthenticationResponse response)
        {
            // This is where you would look for any OpenID extension responses included
            // in the authentication assertion.
            var claimsResponse = response.GetExtension <ClaimsResponse>();
            var authInfo       = claimsResponse.ToDictionary();

            authInfo["user_id"] = response.ClaimedIdentifier; //a url

            // Store off the "friendly" username to display -- NOT for username lookup
            authInfo["openid_ref"] = response.FriendlyIdentifierForDisplay;

            var provided = GetAttributeEx(response);

            foreach (var entry in provided)
            {
                authInfo[entry.Key] = entry.Value;
            }

            return(authInfo);
        }
        /// <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;
        }
예제 #43
0
        /// <summary>
        /// Creates a Graywulf principal from the authentication response.
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        /// <remarks>
        /// The function also creates and initializer a registry user object by
        /// filling in the available information. The user is not save to the
        /// registry.
        /// </remarks>
        private GraywulfPrincipal CreatePrincipal(IAuthenticationResponse response)
        {
            var identity = new GraywulfIdentity()
            {
                Protocol        = this.Protocol,
                AuthorityName   = this.AuthorityName,
                AuthorityUri    = response.Provider.Uri.ToString(),
                Identifier      = response.ClaimedIdentifier,
                IsAuthenticated = false,
                User            = new User()
            };

            var fetch = response.GetExtension <FetchResponse>();

            if (fetch.Attributes.Contains(WellKnownAttributes.Contact.Email))
            {
                identity.User.Name = Util.EmailFormatter.ToUsername(fetch.Attributes[WellKnownAttributes.Contact.Email].Values[0]);
            }

            identity.User.Title      = fetch.Attributes.Contains(WellKnownAttributes.Name.Prefix) ? fetch.Attributes[WellKnownAttributes.Name.Prefix].Values[0] : "";
            identity.User.FirstName  = fetch.Attributes.Contains(WellKnownAttributes.Name.First) ? fetch.Attributes[WellKnownAttributes.Name.First].Values[0] : "";
            identity.User.MiddleName = fetch.Attributes.Contains(WellKnownAttributes.Name.Middle) ? fetch.Attributes[WellKnownAttributes.Name.Middle].Values[0] : "";
            identity.User.LastName   = fetch.Attributes.Contains(WellKnownAttributes.Name.Last) ? fetch.Attributes[WellKnownAttributes.Name.Last].Values[0] : "";
            // TODO identity.User.Gender = fetch.Attributes.Contains(WellKnownAttributes.Person.Gender) ?fetch.Attributes[WellKnownAttributes.Person.Gender].Values[0];
            identity.User.Email       = fetch.Attributes.Contains(WellKnownAttributes.Contact.Email) ? fetch.Attributes[WellKnownAttributes.Contact.Email].Values[0] : "";
            identity.User.DateOfBirth = fetch.Attributes.Contains(WellKnownAttributes.BirthDate.WholeBirthDate) ? DateTime.Parse(fetch.Attributes[WellKnownAttributes.BirthDate.WholeBirthDate].Values[0]) : new DateTime(1950, 1, 1);
            identity.User.Company     = fetch.Attributes.Contains(WellKnownAttributes.Company.CompanyName) ? fetch.Attributes[WellKnownAttributes.Company.CompanyName].Values[0] : "";
            identity.User.JobTitle    = fetch.Attributes.Contains(WellKnownAttributes.Company.JobTitle) ? fetch.Attributes[WellKnownAttributes.Company.JobTitle].Values[0] : "";
            identity.User.Address     = fetch.Attributes.Contains(WellKnownAttributes.Contact.WorkAddress.StreetAddressLine1) ? fetch.Attributes[WellKnownAttributes.Contact.WorkAddress.StreetAddressLine1].Values[0] : "";
            identity.User.Address2    = fetch.Attributes.Contains(WellKnownAttributes.Contact.WorkAddress.StreetAddressLine2) ? fetch.Attributes[WellKnownAttributes.Contact.WorkAddress.StreetAddressLine2].Values[0] : "";
            identity.User.State       = fetch.Attributes.Contains(WellKnownAttributes.Contact.WorkAddress.State) ? fetch.Attributes[WellKnownAttributes.Contact.WorkAddress.State].Values[0] : "";
            identity.User.City        = fetch.Attributes.Contains(WellKnownAttributes.Contact.WorkAddress.City) ? fetch.Attributes[WellKnownAttributes.Contact.WorkAddress.City].Values[0] : "";
            identity.User.Country     = fetch.Attributes.Contains(WellKnownAttributes.Contact.WorkAddress.Country) ? fetch.Attributes[WellKnownAttributes.Contact.WorkAddress.Country].Values[0] : "";
            identity.User.ZipCode     = fetch.Attributes.Contains(WellKnownAttributes.Contact.WorkAddress.PostalCode) ? fetch.Attributes[WellKnownAttributes.Contact.WorkAddress.PostalCode].Values[0] : "";
            identity.User.WorkPhone   = fetch.Attributes.Contains(WellKnownAttributes.Contact.Phone.Work) ? fetch.Attributes[WellKnownAttributes.Contact.Phone.Work].Values[0] : "";
            identity.User.HomePhone   = fetch.Attributes.Contains(WellKnownAttributes.Contact.Phone.Home) ? fetch.Attributes[WellKnownAttributes.Contact.Phone.Home].Values[0] : "";
            identity.User.CellPhone   = fetch.Attributes.Contains(WellKnownAttributes.Contact.Phone.Mobile) ? fetch.Attributes[WellKnownAttributes.Contact.Phone.Mobile].Values[0] : "";

            return(new GraywulfPrincipal(identity));
        }
예제 #44
0
        /// <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)
        {
            Contract.Requires <ArgumentNullException>(openIdAuthenticationResponse != null);
            Contract.Requires <InvalidOperationException>(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);
        }
예제 #45
0
        public ActionResult RsvpFinish()
        {
            IAuthenticationResponse response = relyingParty.GetResponse();

            if (response == null)
            {
                return(RedirectToAction("Index"));
            }

            if (response.Status == AuthenticationStatus.Authenticated)
            {
                var    dinnerRepository = new DinnerRepository();
                int    id     = int.Parse(response.GetUntrustedCallbackArgument("DinnerId"));
                Dinner dinner = dinnerRepository.GetDinner(id);

                // The alias we're getting here is NOT a secure identifier, but a friendly one,
                // which is all we need for this scenario.
                string alias = response.FriendlyIdentifierForDisplay;
                var    sreg  = response.GetExtension <ClaimsResponse>();
                if (sreg != null && sreg.MailAddress != null)
                {
                    alias = sreg.MailAddress.User;
                }

                // NOTE: The alias we've generated for this user isn't guaranteed to be unique.
                // Need to trim to 30 characters because that's the max for Attendee names.
                if (!dinner.IsUserRegistered(alias))
                {
                    RSVP rsvp = new RSVP();
                    rsvp.AttendeeName   = alias;
                    rsvp.AttendeeNameId = response.ClaimedIdentifier;

                    dinner.RSVPs.Add(rsvp);
                    dinnerRepository.Save();
                }
            }

            return(RedirectToAction("Details", "Dinners", new { id = response.GetUntrustedCallbackArgument("DinnerId") }));
        }
예제 #46
0
        /// <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>
        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));
                }
            }
        }
        protected override Dictionary<string, string> CreateAuthInfo(IAuthenticationResponse response)
        {
            // This is where you would look for any OpenID extension responses included
            // in the authentication assertion.
            var claimsResponse = response.GetExtension<ClaimsResponse>();

            claimsResponse.PatchCulture(); // Patch the Culture Object conversion issue

            var authInfo = claimsResponse.ToDictionary();

            authInfo["user_id"] = response.ClaimedIdentifier; //a url

            // Store off the "friendly" username to display -- NOT for username lookup
            authInfo["openid_ref"] = response.FriendlyIdentifierForDisplay;

            var provided = GetAttributeEx(response);
            foreach (var entry in provided)
            {
                authInfo[entry.Key] = entry.Value;
            }

            return authInfo;
        }
예제 #48
0
        public ActionResult LogOn()
        {
            IAuthenticationResponse response = openId.Response;

            if (response != null)
            {
                if ((response.Status == AuthenticationStatus.Failed) || (response.Status == AuthenticationStatus.Canceled))
                {
                    ModelState.AddModelError(ModelStateUserNameKey, TextMessages.UnableToLoginWithYourPreferredOpenIDProvider);
                }
                else if (response.Status == AuthenticationStatus.Authenticated)
                {
                    string         userName = response.ClaimedIdentifier;
                    ClaimsResponse fetch    = response.GetExtension <ClaimsResponse>();

                    // Some of the Provider does not return Email
                    // Such as Yahoo, Blogger, Bloglines etc, in that case email will be null
                    string email = (fetch != null) ? fetch.Email : null;

                    UserResult result = userService.Save(userName, email);
                    ModelState.Merge(result.RuleViolations);

                    if (ModelState.IsValid)
                    {
                        bool persistCookie = cookie.GetValue <bool>(CookieRememberMe);

                        formsAuthentication.SetAuthenticationCookie(userName, persistCookie);

                        string returnUrl = cookie.GetValue <string>(CookieReturnUrl);

                        return(Redirect(returnUrl ?? Url.Home()));
                    }
                }
            }

            return(View());
        }
예제 #49
0
        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();
        }
예제 #50
0
        /// <summary>
        /// Logs the user in or creates the user account if the user does not exist.
        /// Sets the logged user in the session.
        /// </summary>
        public static int OpenIdFinishLogin(IAuthenticationResponse response, SessionWrapper session, IUsersService service, bool enableClaimsRequest)
        {
            string externalId = response.ClaimedIdentifier.ToString();
            User user = service.GetByProviderId(AuthenticationProvider.OpenId, externalId);

            var claimsResponse = response.GetExtension<ClaimsResponse>();
            string name = enableClaimsRequest ? claimsResponse.Nickname : response.FriendlyIdentifierForDisplay;

            if (user == null)
            {
                user = new User(0, name);

                if (enableClaimsRequest)
                {
                    user.Email = claimsResponse.Email;
                    user.BirthDate = claimsResponse.BirthDate;
                }

                user = service.Add(user, AuthenticationProvider.OpenId, externalId);
            }
            else
            {
                if (enableClaimsRequest && !claimsResponse.Email.Equals(user.Email, StringComparison.CurrentCultureIgnoreCase))
                {
                    user.Email = claimsResponse.Email;
                    service.Edit(user);
                }
            }

            session.SetUser(user, AuthenticationProvider.OpenId);

            return user.Id;
        }
예제 #51
0
        private static User CreateUserModelFromOpenAuthReponse(IAuthenticationResponse response, string identifier)
        {
            var simpleReg = response.GetExtension<ClaimsResponse>();
            var model = new ExTracker.Core.DataModel.User();
            model.OpenId = identifier;

            if (!string.IsNullOrEmpty(simpleReg.Email)) model.EmailAddress = simpleReg.Email;
            if (!string.IsNullOrEmpty(simpleReg.FullName)) model.Name = simpleReg.FullName;
            if (!string.IsNullOrEmpty(simpleReg.Nickname)) model.UserName = simpleReg.Nickname;
            return model;
        }
예제 #52
0
        /// <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);
        }
예제 #53
0
		/// <summary>
		/// Called when an incoming positive assertion is received.
		/// </summary>
		/// <param name="assertion">The positive assertion.</param>
		void IRelyingPartyBehavior.OnIncomingPositiveAssertion(IAuthenticationResponse assertion) {
			PolicyResponse pape = assertion.GetExtension<PolicyResponse>();
			ErrorUtilities.VerifyProtocol(
				pape != null &&
				pape.ActualPolicies.Contains(AuthenticationPolicies.USGovernmentTrustLevel1) &&
				pape.ActualPolicies.Contains(AuthenticationPolicies.PrivatePersonalIdentifier),
				BehaviorStrings.PapeResponseOrRequiredPoliciesMissing);

			ErrorUtilities.VerifyProtocol(AllowPersonallyIdentifiableInformation || pape.ActualPolicies.Contains(AuthenticationPolicies.NoPersonallyIdentifiableInformation), BehaviorStrings.PapeResponseOrRequiredPoliciesMissing);

			if (pape.ActualPolicies.Contains(AuthenticationPolicies.NoPersonallyIdentifiableInformation)) {
				ErrorUtilities.VerifyProtocol(
					assertion.GetExtension<ClaimsResponse>() == null &&
					assertion.GetExtension<FetchResponse>() == null,
					BehaviorStrings.PiiIncludedWithNoPiiPolicy);
			}
		}
예제 #54
0
        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;
        }
예제 #55
0
        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;
        }
예제 #56
0
 private AWT2Demo.Domain.Entities.User CreateUserFromOpenIDResponse(IAuthenticationResponse response)
 {
     var fetch = response.GetExtension<FetchResponse>();
     string email = String.Empty;
     string firstName = String.Empty;
     string lastName = String.Empty;
     if (fetch != null)
     {
         email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);
         firstName = fetch.GetAttributeValue(WellKnownAttributes.Name.First);
         lastName = fetch.GetAttributeValue(WellKnownAttributes.Name.Last);
     }
     return _userRepo.AddUserForClaimedIdentifier(response.ClaimedIdentifier,
                         email,
                         firstName,
                         lastName);
 }
예제 #57
0
		/// <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);
			}
		}
        /// <summary>
        /// Creates a Graywulf principal from the authentication response.
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        /// <remarks>
        /// The function also creates and initializes a registry user object by
        /// filling in the available information. The user is not saved to the
        /// registry.
        /// </remarks>
        private GraywulfPrincipal CreatePrincipal(IAuthenticationResponse response)
        {
            var principal = base.CreatePrincipal();
            var identity = principal.Identity;

            // Read response from OpenID provider
            var fetch = response.GetExtension<FetchResponse>();

            // Fill in identity details based on the response
            identity.AuthorityUri = response.Provider.Uri.ToString();
            identity.Identifier = response.ClaimedIdentifier;

            identity.User = new User();

            // Fill in user details
            // TODO: how to generate user name from OpenID?
            identity.User.Name = fetch.Attributes.Contains(WellKnownAttributes.Contact.Email) ? Jhu.Graywulf.Util.EmailFormatter.ToUsername(fetch.Attributes[WellKnownAttributes.Contact.Email].Values[0]) : "";
            identity.User.Title = fetch.Attributes.Contains(WellKnownAttributes.Name.Prefix) ? fetch.Attributes[WellKnownAttributes.Name.Prefix].Values[0] : "";
            identity.User.FirstName = fetch.Attributes.Contains(WellKnownAttributes.Name.First) ? fetch.Attributes[WellKnownAttributes.Name.First].Values[0] : "";
            identity.User.MiddleName = fetch.Attributes.Contains(WellKnownAttributes.Name.Middle) ? fetch.Attributes[WellKnownAttributes.Name.Middle].Values[0] : "";
            identity.User.LastName = fetch.Attributes.Contains(WellKnownAttributes.Name.Last) ? fetch.Attributes[WellKnownAttributes.Name.Last].Values[0] : "";
            // TODO identity.User.Gender = fetch.Attributes.Contains(WellKnownAttributes.Person.Gender) ?fetch.Attributes[WellKnownAttributes.Person.Gender].Values[0];
            identity.User.Email = fetch.Attributes.Contains(WellKnownAttributes.Contact.Email) ? fetch.Attributes[WellKnownAttributes.Contact.Email].Values[0] : "";
            identity.User.DateOfBirth = fetch.Attributes.Contains(WellKnownAttributes.BirthDate.WholeBirthDate) ? DateTime.Parse(fetch.Attributes[WellKnownAttributes.BirthDate.WholeBirthDate].Values[0]) : new DateTime(1950, 1, 1);
            identity.User.Company = fetch.Attributes.Contains(WellKnownAttributes.Company.CompanyName) ? fetch.Attributes[WellKnownAttributes.Company.CompanyName].Values[0] : "";
            identity.User.JobTitle = fetch.Attributes.Contains(WellKnownAttributes.Company.JobTitle) ? fetch.Attributes[WellKnownAttributes.Company.JobTitle].Values[0] : "";
            identity.User.Address = fetch.Attributes.Contains(WellKnownAttributes.Contact.WorkAddress.StreetAddressLine1) ? fetch.Attributes[WellKnownAttributes.Contact.WorkAddress.StreetAddressLine1].Values[0] : "";
            identity.User.Address2 = fetch.Attributes.Contains(WellKnownAttributes.Contact.WorkAddress.StreetAddressLine2) ? fetch.Attributes[WellKnownAttributes.Contact.WorkAddress.StreetAddressLine2].Values[0] : "";
            identity.User.State = fetch.Attributes.Contains(WellKnownAttributes.Contact.WorkAddress.State) ? fetch.Attributes[WellKnownAttributes.Contact.WorkAddress.State].Values[0] : "";
            identity.User.City = fetch.Attributes.Contains(WellKnownAttributes.Contact.WorkAddress.City) ? fetch.Attributes[WellKnownAttributes.Contact.WorkAddress.City].Values[0] : "";
            identity.User.Country = fetch.Attributes.Contains(WellKnownAttributes.Contact.WorkAddress.Country) ? fetch.Attributes[WellKnownAttributes.Contact.WorkAddress.Country].Values[0] : "";
            identity.User.ZipCode = fetch.Attributes.Contains(WellKnownAttributes.Contact.WorkAddress.PostalCode) ? fetch.Attributes[WellKnownAttributes.Contact.WorkAddress.PostalCode].Values[0] : "";
            identity.User.WorkPhone = fetch.Attributes.Contains(WellKnownAttributes.Contact.Phone.Work) ? fetch.Attributes[WellKnownAttributes.Contact.Phone.Work].Values[0] : "";
            identity.User.HomePhone = fetch.Attributes.Contains(WellKnownAttributes.Contact.Phone.Home) ? fetch.Attributes[WellKnownAttributes.Contact.Phone.Home].Values[0] : "";
            identity.User.CellPhone = fetch.Attributes.Contains(WellKnownAttributes.Contact.Phone.Mobile) ? fetch.Attributes[WellKnownAttributes.Contact.Phone.Mobile].Values[0] : "";

            return principal;
        }
예제 #59
0
        public UserModel GetOrCreateUser(IAuthenticationResponse openIdResponse)
        {
            var ipUriString = openIdResponse.Provider.Uri.ToString();
            var upn = openIdResponse.ClaimedIdentifier.ToString();

            var dbUser = (from i in BlogDb.IdentityProviders
                          from u in i.Users
                          where i.Uri == ipUriString
                            && u.Upn == upn
                          select u).FirstOrDefault();

            if (dbUser == null)
            {
                var identityProvider = getIdentityProvider(ipUriString);
                if (identityProvider == null)
                {
                    identityProvider = createIdentityProvider(ipUriString);
                }

                var details = openIdResponse.GetExtension<ClaimsResponse>();
                string nickname = null, email = null;
                if (details != null)
                {
                    nickname = details.Nickname;
                    email = details.Email;
                    if (string.IsNullOrEmpty(nickname))
                    {
                        nickname = openIdResponse.FriendlyIdentifierForDisplay;
                    }
                }
                dbUser = createUser(identityProvider.IdentityProviderId, upn, email, nickname);
            }

            return GetUser(dbUser.UserId);
        }
예제 #60
0
        public void Login()
        {
            response = new OpenIdRelyingParty().GetResponse();

            if (response == null)
            {
                var request = new OpenIdRelyingParty().CreateRequest(Url);

                request.AddExtension
                (
                    new ClaimsRequest()
                    {
                        Email = DemandLevel.Require,
                        Language = DemandLevel.Require,
                        TimeZone = DemandLevel.Require,
                        Country = DemandLevel.Require,
                        BirthDate = DemandLevel.Require,
                        PostalCode = DemandLevel.Require,
                        Gender = DemandLevel.Require,
                        Nickname = DemandLevel.Require,
                        FullName = DemandLevel.Require
                    }
                );
                request.RedirectToProvider();

            } else if (response != null && response.Status == AuthenticationStatus.Authenticated)
            {
                IsAuthenticated = true;
                //基本
                var claimResponse = response.GetExtension<ClaimsResponse>();

                User = new NTPCLibrary.User();
                User.Identity = response.ClaimedIdentifier.ToString().Split('/').Last();

                User.Departments = new List<Department>();
                if (claimResponse != null)
                {
                    User.ID = claimResponse.PostalCode;
                    User.FullName = claimResponse.FullName;
                    User.NickName = claimResponse.Nickname;
                    User.Email = claimResponse.Email;
                    User.Gender = claimResponse != null ? (claimResponse.Gender.Equals(Gender.Male) ? "男" : "女") : string.Empty;
                    User.BirthDate = claimResponse.BirthDate;
                    User.SchoolName = claimResponse.Country;
                    User.ClassRoom = claimResponse.Language;
                    User.Departments = JsonConvert.DeserializeObject<List<Department>>(claimResponse.TimeZone);
                }

                //延伸
                FetchResponse fetchResponse = response.GetExtension<FetchResponse>();

                User.AXExtension = fetchResponse != null ? GetAx(fetchResponse) : "無";

                //寫入Cookie
                Util.SetCookie<User>(OPENID_COOKIE, User, CookieDomain, true);
            }
        }