public void Ctor() {
			PolicyResponse resp = new PolicyResponse();
			Assert.IsNotNull(resp.ActualPolicies);
			Assert.AreEqual(0, resp.ActualPolicies.Count);
			Assert.IsNull(resp.AuthenticationTimeUtc);
			Assert.IsNull(resp.NistAssuranceLevel);
		}
		public void AuthenticationTimeUtcConvertsToUtc() {
			PolicyResponse resp = new PolicyResponse();
			resp.AuthenticationTimeUtc = someLocalTime;
			Assert.IsNotNull(resp.AuthenticationTimeUtc);
			Assert.AreEqual(DateTimeKind.Utc, resp.AuthenticationTimeUtc.Value.Kind);
			Assert.AreEqual(someLocalTime.ToUniversalTime(), resp.AuthenticationTimeUtc.Value);
		}
		public void AddPolicies() {
			PolicyResponse resp = new PolicyResponse();
			resp.ActualPolicies.Add(AuthenticationPolicies.MultiFactor);
			resp.ActualPolicies.Add(AuthenticationPolicies.PhishingResistant);
			Assert.AreEqual(2, resp.ActualPolicies.Count);
			Assert.AreEqual(AuthenticationPolicies.MultiFactor, resp.ActualPolicies[0]);
			Assert.AreEqual(AuthenticationPolicies.PhishingResistant, resp.ActualPolicies[1]);
		}
		public void AuthenticationTimeUtcSetNull() {
			PolicyResponse resp = new PolicyResponse();
			resp.AuthenticationTimeUtc = null;
			Assert.IsNull(resp.AuthenticationTimeUtc);
			resp.AuthenticationTimeUtc = someUtcTime;
			Assert.IsNotNull(resp.AuthenticationTimeUtc);
			resp.AuthenticationTimeUtc = null;
			Assert.IsNull(resp.AuthenticationTimeUtc);
		}
		public void AddPolicyMultipleTimes() {
			// Although this isn't really the desired behavior (we'd prefer to see an
			// exception thrown), since we're using a List<string> internally we can't
			// expect anything better (for now).  But if this is ever fixed, by all means
			// change this test to expect an exception or something else.
			PolicyResponse resp = new PolicyResponse();
			resp.ActualPolicies.Add(AuthenticationPolicies.MultiFactor);
			resp.ActualPolicies.Add(AuthenticationPolicies.MultiFactor);
			Assert.AreEqual(2, resp.ActualPolicies.Count);
		}
 public void AssuranceLevels()
 {
     PolicyResponse resp = new PolicyResponse();
     Assert.AreEqual(0, resp.AssuranceLevels.Count);
     resp.NistAssuranceLevel = NistAssuranceLevel.Level2;
     Assert.AreEqual(1, resp.AssuranceLevels.Count);
     Assert.AreEqual("2", resp.AssuranceLevels[Constants.AssuranceLevels.NistTypeUri]);
     resp.AssuranceLevels[Constants.AssuranceLevels.NistTypeUri] = "3";
     Assert.AreEqual(NistAssuranceLevel.Level3, resp.NistAssuranceLevel);
     resp.AssuranceLevels.Clear();
     Assert.IsNull(resp.NistAssuranceLevel);
 }
		public void Full() {
			var request = new PolicyRequest();
			request.MaximumAuthenticationAge = TimeSpan.FromMinutes(10);
			request.PreferredAuthLevelTypes.Add(Constants.AssuranceLevels.NistTypeUri);
			request.PreferredAuthLevelTypes.Add("customAuthLevel");
			request.PreferredPolicies.Add(AuthenticationPolicies.MultiFactor);
			request.PreferredPolicies.Add(AuthenticationPolicies.PhishingResistant);

			var response = new PolicyResponse();
			response.ActualPolicies.Add(AuthenticationPolicies.MultiFactor);
			response.ActualPolicies.Add(AuthenticationPolicies.PhishingResistant);
			response.AuthenticationTimeUtc = DateTime.UtcNow - TimeSpan.FromMinutes(5);
			response.AssuranceLevels[Constants.AssuranceLevels.NistTypeUri] = "1";
			response.AssuranceLevels["customlevel"] = "ABC";
			response.NistAssuranceLevel = NistAssuranceLevel.Level2;

			ExtensionTestUtilities.Roundtrip(Protocol.Default, new[] { request }, new[] { response });
		}
        /// <summary>
        /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
        /// </summary>
        /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param>
        /// <returns>
        /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
        /// </returns>
        /// <exception cref="T:System.NullReferenceException">
        /// The <paramref name="obj"/> parameter is null.
        /// </exception>
        public override bool Equals(object obj)
        {
            PolicyResponse other = obj as PolicyResponse;

            if (other == null)
            {
                return(false);
            }

            if (this.AuthenticationTimeUtc != other.AuthenticationTimeUtc)
            {
                return(false);
            }

            if (this.AssuranceLevels.Count != other.AssuranceLevels.Count)
            {
                return(false);
            }

            foreach (var pair in this.AssuranceLevels)
            {
                if (!other.AssuranceLevels.Contains(pair))
                {
                    return(false);
                }
            }

            if (this.ActualPolicies.Count != other.ActualPolicies.Count)
            {
                return(false);
            }

            foreach (string policy in this.ActualPolicies)
            {
                if (!other.ActualPolicies.Contains(policy))
                {
                    return(false);
                }
            }

            return(true);
        }
Example #9
0
        protected void Yes_Click(object sender, EventArgs e)
        {
            var sregRequest = ProviderEndpoint.PendingAuthenticationRequest.GetExtension<ClaimsRequest>();
            ClaimsResponse sregResponse = null;
            if (sregRequest != null) {
                sregResponse = this.profileFields.GetOpenIdProfileFields(sregRequest);
                ProviderEndpoint.PendingAuthenticationRequest.AddResponseExtension(sregResponse);
            }
            var papeRequest = ProviderEndpoint.PendingAuthenticationRequest.GetExtension<PolicyRequest>();
            PolicyResponse papeResponse = null;
            if (papeRequest != null) {
                papeResponse = new PolicyResponse();
                papeResponse.NistAssuranceLevel = NistAssuranceLevel.InsufficientForLevel1;
                ProviderEndpoint.PendingAuthenticationRequest.AddResponseExtension(papeResponse);
            }

            ProviderEndpoint.PendingAuthenticationRequest.IsAuthenticated = true;
            Debug.Assert(ProviderEndpoint.PendingAuthenticationRequest.IsResponseReady, "Setting authentication should be all that's necessary.");
            ProviderEndpoint.SendResponse();
        }
Example #10
0
		protected void Yes_Click(object sender, EventArgs e) {
			if (!Page.IsValid) {
				return;
			}

			if (this.OAuthPanel.Visible) {
				string grantedScope = null;
				if (this.oauthPermission.Checked) {
					// This SIMPLE sample merely uses the realm as the consumerKey,
					// but in a real app this will probably involve a database lookup to translate
					// the realm to a known consumerKey.
					grantedScope = string.Empty; // we don't scope individual access rights on this sample
				}

				OAuthHybrid.ServiceProvider.AttachAuthorizationResponse(ProviderEndpoint.PendingRequest, grantedScope);
			}

			var sregRequest = ProviderEndpoint.PendingRequest.GetExtension<ClaimsRequest>();
			ClaimsResponse sregResponse = null;
			if (sregRequest != null) {
				sregResponse = this.profileFields.GetOpenIdProfileFields(sregRequest);
				ProviderEndpoint.PendingRequest.AddResponseExtension(sregResponse);
			}
			var papeRequest = ProviderEndpoint.PendingRequest.GetExtension<PolicyRequest>();
			PolicyResponse papeResponse = null;
			if (papeRequest != null) {
				papeResponse = new PolicyResponse();
				papeResponse.NistAssuranceLevel = NistAssuranceLevel.InsufficientForLevel1;
				ProviderEndpoint.PendingRequest.AddResponseExtension(papeResponse);
			}

			if (ProviderEndpoint.PendingAuthenticationRequest != null) {
				ProviderEndpoint.PendingAuthenticationRequest.IsAuthenticated = true;
			} else {
				ProviderEndpoint.PendingAnonymousRequest.IsApproved = true;
			}
			Debug.Assert(ProviderEndpoint.PendingRequest.IsResponseReady, "Setting authentication should be all that's necessary.");
			ProviderEndpoint.SendResponse();
		}
		public void AuthenticationTimeUtcSetUnspecified() {
			PolicyResponse resp = new PolicyResponse();
			resp.AuthenticationTimeUtc = someUnspecifiedTime;
		}
		public void AuthenticationTimeUtcSetUtc() {
			PolicyResponse resp = new PolicyResponse();
			resp.AuthenticationTimeUtc = someUtcTime;
			Assert.AreEqual(someUtcTime, resp.AuthenticationTimeUtc);
		}
Example #13
0
		/// <summary>
		/// Called when the Provider is preparing to send a response to an authentication request.
		/// </summary>
		/// <param name="request">The request that is configured to generate the outgoing response.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <returns>
		/// 	<c>true</c> if this behavior owns this request and wants to stop other behaviors
		/// from handling it; <c>false</c> to allow other behaviors to process this request.
		/// </returns>
		async Task<bool> IProviderBehavior.OnOutgoingResponseAsync(Provider.IAuthenticationRequest request, CancellationToken cancellationToken) {
			bool result = false;

			// Nothing to do for negative assertions.
			if (!request.IsAuthenticated.Value) {
				return result;
			}

			var requestInternal = (Provider.AuthenticationRequest)request;
			var responseMessage = (IProtocolMessageWithExtensions)await requestInternal.GetResponseAsync(cancellationToken);

			// Only apply our special policies if the RP requested it.
			var papeRequest = request.GetExtension<PolicyRequest>();
			if (papeRequest != null) {
				var papeResponse = responseMessage.Extensions.OfType<PolicyResponse>().SingleOrDefault();
				if (papeResponse == null) {
					request.AddResponseExtension(papeResponse = new PolicyResponse());
				}

				if (papeRequest.PreferredPolicies.Contains(AuthenticationPolicies.USGovernmentTrustLevel1)) {
					result = true;
					if (!papeResponse.ActualPolicies.Contains(AuthenticationPolicies.USGovernmentTrustLevel1)) {
						papeResponse.ActualPolicies.Add(AuthenticationPolicies.USGovernmentTrustLevel1);
					}

					// The spec requires that the OP perform discovery and if that fails, it must either sternly
					// warn the user of a potential threat or just abort the authentication.
					// We can't verify that the OP displayed anything to the user at this level, but we can
					// at least verify that the OP performed the discovery on the realm and halt things if it didn't.
					ErrorUtilities.VerifyHost(requestInternal.HasRealmDiscoveryBeenPerformed, BehaviorStrings.RealmDiscoveryNotPerformed);
				}

				if (papeRequest.PreferredPolicies.Contains(AuthenticationPolicies.PrivatePersonalIdentifier)) {
					ErrorUtilities.VerifyProtocol(request.ClaimedIdentifier == request.LocalIdentifier, OpenIdStrings.DelegatingIdentifiersNotAllowed);

					// Mask the user's identity with a PPID.
					ErrorUtilities.VerifyHost(PpidIdentifierProvider != null, BehaviorStrings.PpidProviderNotGiven);
					Identifier ppidIdentifier = PpidIdentifierProvider.GetIdentifier(request.LocalIdentifier, request.Realm);
					requestInternal.ResetClaimedAndLocalIdentifiers(ppidIdentifier);

					// Indicate that the RP is receiving a PPID claimed_id
					if (!papeResponse.ActualPolicies.Contains(AuthenticationPolicies.PrivatePersonalIdentifier)) {
						papeResponse.ActualPolicies.Add(AuthenticationPolicies.PrivatePersonalIdentifier);
					}
				}

				if (papeRequest.PreferredPolicies.Contains(AuthenticationPolicies.NoPersonallyIdentifiableInformation)) {
					ErrorUtilities.VerifyProtocol(
						!responseMessage.Extensions.OfType<ClaimsResponse>().Any() &&
						!responseMessage.Extensions.OfType<FetchResponse>().Any(),
						BehaviorStrings.PiiIncludedWithNoPiiPolicy);

					// If no PII is given in extensions, and the claimed_id is a PPID, then we can state we issue no PII.
					if (papeResponse.ActualPolicies.Contains(AuthenticationPolicies.PrivatePersonalIdentifier)) {
						if (!papeResponse.ActualPolicies.Contains(AuthenticationPolicies.NoPersonallyIdentifiableInformation)) {
							papeResponse.ActualPolicies.Add(AuthenticationPolicies.NoPersonallyIdentifiableInformation);
						}
					}
				}

				Reporting.RecordEventOccurrence(this, "OP");
			}

			return result;
		}
Example #14
0
		/// <summary>
		/// Called when the Provider is preparing to send a response to an authentication request.
		/// </summary>
		/// <param name="request">The request that is configured to generate the outgoing response.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <returns>
		/// 	<c>true</c> if this behavior owns this request and wants to stop other behaviors
		/// from handling it; <c>false</c> to allow other behaviors to process this request.
		/// </returns>
		async Task<bool> IProviderBehavior.OnOutgoingResponseAsync(IAuthenticationRequest request, CancellationToken cancellationToken) {
			// Nothing to do for negative assertions.
			if (!request.IsAuthenticated.Value) {
				return false;
			}

			var requestInternal = (Provider.AuthenticationRequest)request;
			var responseMessage = (IProtocolMessageWithExtensions)await requestInternal.GetResponseAsync(cancellationToken);

			// Only apply our special policies if the RP requested it.
			var papeRequest = request.GetExtension<PolicyRequest>();
			if (papeRequest != null) {
				if (papeRequest.PreferredPolicies.Contains(AuthenticationPolicies.PrivatePersonalIdentifier)) {
					ErrorUtilities.VerifyProtocol(request.ClaimedIdentifier == request.LocalIdentifier, OpenIdStrings.DelegatingIdentifiersNotAllowed);

					if (PpidIdentifierProvider == null) {
						Logger.OpenId.Error(BehaviorStrings.PpidProviderNotGiven);
						return false;
					}

					// Mask the user's identity with a PPID.
					if (PpidIdentifierProvider.IsUserLocalIdentifier(request.LocalIdentifier)) {
						Identifier ppidIdentifier = PpidIdentifierProvider.GetIdentifier(request.LocalIdentifier, request.Realm);
						requestInternal.ResetClaimedAndLocalIdentifiers(ppidIdentifier);
					}

					// Indicate that the RP is receiving a PPID claimed_id
					var papeResponse = responseMessage.Extensions.OfType<PolicyResponse>().SingleOrDefault();
					if (papeResponse == null) {
						request.AddResponseExtension(papeResponse = new PolicyResponse());
					}

					if (!papeResponse.ActualPolicies.Contains(AuthenticationPolicies.PrivatePersonalIdentifier)) {
						papeResponse.ActualPolicies.Add(AuthenticationPolicies.PrivatePersonalIdentifier);
					}

					Reporting.RecordEventOccurrence(this, string.Empty);
				}
			}

			return false;
		}
Example #15
0
        /// <summary>
        /// Sends a positive or a negative assertion, based on how the pending request is currently marked.
        /// </summary>
        /// <returns>An MVC redirect result.</returns>
        public ActionResult SendAssertion()
        {
            var pendingRequest = ProviderEndpoint.PendingRequest;
            var authReq = pendingRequest as IAuthenticationRequest;
            var anonReq = pendingRequest as IAnonymousRequest;
            ProviderEndpoint.PendingRequest = null; // clear session static so we don't do this again
            if (pendingRequest == null)
            {
                throw new InvalidOperationException("There's no pending authentication request!");
            }

            // Set safe defaults if somehow the user ended up (perhaps through XSRF) here before electing to send data to the RP.
            if (anonReq != null && !anonReq.IsApproved.HasValue)
            {
                anonReq.IsApproved = false;
            }

            if (authReq != null && !authReq.IsAuthenticated.HasValue)
            {
                authReq.IsAuthenticated = false;
            }

            if (authReq != null && authReq.IsAuthenticated.Value)
            {
                if (authReq.IsDirectedIdentity)
                {
                    authReq.LocalIdentifier = Models.User.GetClaimedIdentifierForUser(User.Identity.Name);
                }

                if (!authReq.IsDelegatedIdentifier)
                {
                    authReq.ClaimedIdentifier = authReq.LocalIdentifier;
                }
            }

            // Respond to AX/sreg extension requests only on a positive result.
            if ((authReq != null && authReq.IsAuthenticated.Value) ||
                (anonReq != null && anonReq.IsApproved.Value))
            {
                // Look for a Simple Registration request.  When the AXFetchAsSregTransform behavior is turned on
                // in the web.config file as it is in this sample, AX requests will come in as SReg requests.
                var claimsRequest = pendingRequest.GetExtension<ClaimsRequest>();
                if (claimsRequest != null)
                {
                    var claimsResponse = claimsRequest.CreateResponse();

                    // This simple respond to a request check may be enhanced to only respond to an individual attribute
                    // request if the user consents to it explicitly, in which case this response extension creation can take
                    // place in the confirmation page action rather than here.
                    if (claimsRequest.Email != DemandLevel.NoRequest)
                    {
                        claimsResponse.Email = User.Identity.Name; // +"@dotnetopenauth.net";
                    }

                    pendingRequest.AddResponseExtension(claimsResponse);
                }

                // Look for PAPE requests.
                var papeRequest = pendingRequest.GetExtension<PolicyRequest>();
                if (papeRequest != null)
                {
                    var papeResponse = new PolicyResponse();
                    if (papeRequest.MaximumAuthenticationAge.HasValue)
                    {
                        papeResponse.AuthenticationTimeUtc = this.FormsAuth.SignedInTimestampUtc;
                    }

                    pendingRequest.AddResponseExtension(papeResponse);
                }
            }

            return OpenIdProvider.PrepareResponse(pendingRequest).AsActionResult();
        }
		public void Serialize() {
			PolicyResponse resp = new PolicyResponse();
			IMessageWithEvents respEvents = resp;

			var fields = this.MessageDescriptions.GetAccessor(resp);
			respEvents.OnSending();
			Assert.AreEqual(1, fields.Count);
			Assert.IsTrue(fields.ContainsKey("auth_policies"));
			Assert.AreEqual(AuthenticationPolicies.None, fields["auth_policies"]);

			resp.ActualPolicies.Add(AuthenticationPolicies.PhishingResistant);
			respEvents.OnSending();
			Assert.AreEqual(1, fields.Count);
			Assert.AreEqual(AuthenticationPolicies.PhishingResistant, fields["auth_policies"]);

			resp.ActualPolicies.Add(AuthenticationPolicies.PhysicalMultiFactor);
			respEvents.OnSending();
			Assert.AreEqual(1, fields.Count);
			Assert.AreEqual(
				AuthenticationPolicies.PhishingResistant + " " + AuthenticationPolicies.PhysicalMultiFactor,
				fields["auth_policies"]);

			resp.AuthenticationTimeUtc = DateTime.UtcNow;
			respEvents.OnSending();
			Assert.AreEqual(2, fields.Count);
			Assert.IsTrue(fields.ContainsKey("auth_time"));

			resp.NistAssuranceLevel = NistAssuranceLevel.Level3;
			respEvents.OnSending();
			Assert.AreEqual(4, fields.Count);
			Assert.IsTrue(fields.ContainsKey("auth_level.ns.nist"));
			Assert.AreEqual(Constants.AssuranceLevels.NistTypeUri, fields["auth_level.ns.nist"]);
			Assert.IsTrue(fields.ContainsKey("auth_level.nist"));
			Assert.AreEqual("3", fields["auth_level.nist"]);

			resp.AssuranceLevels.Add("custom", "CU");
			respEvents.OnSending();
			Assert.AreEqual(6, fields.Count);
			Assert.IsTrue(fields.ContainsKey("auth_level.ns.alias2"));
			Assert.AreEqual("custom", fields["auth_level.ns.alias2"]);
			Assert.IsTrue(fields.ContainsKey("auth_level.alias2"));
			Assert.AreEqual("CU", fields["auth_level.alias2"]);
			// and make sure the NIST is still there.
			Assert.IsTrue(fields.ContainsKey("auth_level.ns.nist"));
			Assert.AreEqual(Constants.AssuranceLevels.NistTypeUri, fields["auth_level.ns.nist"]);
			Assert.IsTrue(fields.ContainsKey("auth_level.nist"));
			Assert.AreEqual("3", fields["auth_level.nist"]);
		}
		public async Task Trivial() {
			var request = new PolicyRequest();
			var response = new PolicyResponse();
			await this.RoundtripAsync(Protocol.Default, new[] { request }, new[] { response });
		}
		public void Trivial() {
			var request = new PolicyRequest();
			var response = new PolicyResponse();
			ExtensionTestUtilities.Roundtrip(Protocol.Default, new[] { request }, new[] { response });
		}
		public void NistAssuranceLevelSetVarious() {
			PolicyResponse resp = new PolicyResponse();
			resp.NistAssuranceLevel = NistAssuranceLevel.Level1;
			Assert.AreEqual(NistAssuranceLevel.Level1, resp.NistAssuranceLevel);
			resp.NistAssuranceLevel = null;
			Assert.IsNull(resp.NistAssuranceLevel);
			resp.NistAssuranceLevel = NistAssuranceLevel.InsufficientForLevel1;
			Assert.AreEqual(NistAssuranceLevel.InsufficientForLevel1, resp.NistAssuranceLevel);
		}
		public void EqualsTest() {
			PolicyResponse resp = new PolicyResponse();
			PolicyResponse resp2 = new PolicyResponse();
			Assert.AreEqual(resp, resp2);
			Assert.AreNotEqual(resp, null);
			Assert.AreNotEqual(null, resp);

			// Test ActualPolicies list comparison
			resp.ActualPolicies.Add(AuthenticationPolicies.PhishingResistant);
			Assert.AreNotEqual(resp, resp2);
			resp2.ActualPolicies.Add(AuthenticationPolicies.MultiFactor);
			Assert.AreNotEqual(resp, resp2);
			resp2.ActualPolicies.Clear();
			resp2.ActualPolicies.Add(AuthenticationPolicies.PhishingResistant);
			Assert.AreEqual(resp, resp2);

			// Test ActualPolicies list comparison when that list is not in the same order.
			resp.ActualPolicies.Add(AuthenticationPolicies.MultiFactor);
			Assert.AreNotEqual(resp, resp2);
			resp2.ActualPolicies.Insert(0, AuthenticationPolicies.MultiFactor);
			Assert.AreEqual(resp, resp2);

			// Test AuthenticationTimeUtc comparison.
			resp.AuthenticationTimeUtc = DateTime.Now;
			Assert.AreNotEqual(resp, resp2);
			resp2.AuthenticationTimeUtc = resp.AuthenticationTimeUtc;
			Assert.AreEqual(resp, resp2);
			resp2.AuthenticationTimeUtc += TimeSpan.FromSeconds(1);
			Assert.AreNotEqual(resp, resp2);
			resp2.AuthenticationTimeUtc = resp.AuthenticationTimeUtc;
			Assert.AreEqual(resp, resp2);

			// Test NistAssuranceLevel comparison.
			resp.NistAssuranceLevel = NistAssuranceLevel.InsufficientForLevel1;
			Assert.AreNotEqual(resp, resp2);
			resp2.NistAssuranceLevel = NistAssuranceLevel.InsufficientForLevel1;
			Assert.AreEqual(resp, resp2);
			resp.NistAssuranceLevel = NistAssuranceLevel.Level2;
			Assert.AreNotEqual(resp, resp2);
			resp2.NistAssuranceLevel = NistAssuranceLevel.Level2;
			Assert.AreEqual(resp, resp2);

			// Test AssuranceLevels comparison.
			resp.AssuranceLevels.Add("custom", "b");
			Assert.AreNotEqual(resp, resp2);
			resp2.AssuranceLevels.Add("custom", "2");
			Assert.AreNotEqual(resp, resp2);
			resp2.AssuranceLevels["custom"] = "b";
			Assert.AreEqual(resp, resp2);
			resp.AssuranceLevels[Constants.AssuranceLevels.NistTypeUri] = "1";
			Assert.AreNotEqual(resp, resp2);
			resp2.AssuranceLevels[Constants.AssuranceLevels.NistTypeUri] = "1";
			Assert.AreEqual(resp, resp2);
		}