Example #1
0
        public static ProviderSession CreateSession(OpenIdProvider provider)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }
            Protocol protocol     = provider.Protocol;
            string   session_type = protocol.Version.Major >= 2 ?
                                    Util.GetRequiredArg(provider.Query, protocol.openid.session_type) :
                                    (Util.GetOptionalArg(provider.Query, protocol.openid.session_type) ?? "");

            if (protocol.Args.SessionType.NoEncryption.Equals(session_type, StringComparison.Ordinal))
            {
                return(new PlainTextProviderSession(provider));
            }
            else if (Array.IndexOf(protocol.Args.SessionType.AllDiffieHellman, session_type) >= 0)
            {
                return(new DiffieHellmanProviderSession(provider));
            }
            else
            {
                throw new OpenIdException(string.Format(CultureInfo.CurrentCulture,
                                                        Strings.InvalidOpenIdQueryParameterValue,
                                                        protocol.openid.session_type, session_type), provider.Query)
                      {
                          ExtraArgsToReturn = AssociateRequest.CreateAssociationTypeHints(provider),
                      };
            }
        }
        public static void CreatePositiveAssertion(EncodableResponse message,
                                                   OpenIdProvider provider, Identifier localIdentifier, Identifier claimedIdentifier)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }
            Protocol protocol = message.Protocol;

            message.Fields[protocol.openidnp.mode]     = protocol.Args.Mode.id_res;
            message.Fields[protocol.openidnp.identity] = localIdentifier;
            // We use OriginalString for the return_to to help protect against interop
            // problems with RPs that require an explicit port, or who knows what else.
            message.Fields[protocol.openidnp.return_to] = message.RedirectUrl.OriginalString;
            message.Signed.AddRange(new[] {
                protocol.openidnp.return_to,
                protocol.openidnp.identity,
            });
            if (protocol.Version.Major >= 2)
            {
                message.Fields[protocol.openidnp.claimed_id]     = claimedIdentifier;
                message.Fields[protocol.openidnp.op_endpoint]    = provider.Endpoint.AbsoluteUri;
                message.Fields[protocol.openidnp.response_nonce] = new Nonce().Code;
                message.Signed.AddRange(new[] {
                    protocol.openidnp.claimed_id,
                    protocol.openidnp.op_endpoint,
                    protocol.openidnp.response_nonce,
                });
            }

            Debug.Assert(!message.Signed.Contains(protocol.openidnp.mode), "openid.mode must not be signed because it changes in check_authentication requests.");
            // The assoc_handle, signed, sig and invalidate_handle fields are added
            // as appropriate by the Signatory.Sign method.
        }
Example #3
0
        public static void CreatePositiveAssertion(EncodableResponse message,
            OpenIdProvider provider, Identifier localIdentifier, Identifier claimedIdentifier)
        {
            if (message == null) throw new ArgumentNullException("message");
            Protocol protocol = message.Protocol;

            message.Fields[protocol.openidnp.mode] = protocol.Args.Mode.id_res;
            message.Fields[protocol.openidnp.identity] = localIdentifier;
            // We use OriginalString for the return_to to help protect against interop
            // problems with RPs that require an explicit port, or who knows what else.
            message.Fields[protocol.openidnp.return_to] = message.RedirectUrl.OriginalString;
            message.Signed.AddRange(new[]{
                    protocol.openidnp.return_to,
                    protocol.openidnp.identity,
                });
            if (protocol.Version.Major >= 2) {
                message.Fields[protocol.openidnp.claimed_id] = claimedIdentifier;
                message.Fields[protocol.openidnp.op_endpoint] = provider.Endpoint.AbsoluteUri;
                message.Fields[protocol.openidnp.response_nonce] = new Nonce().Code;
                message.Signed.AddRange(new[]{
                        protocol.openidnp.claimed_id,
                        protocol.openidnp.op_endpoint,
                        protocol.openidnp.response_nonce,
                    });
            }

            Debug.Assert(!message.Signed.Contains(protocol.openidnp.mode), "openid.mode must not be signed because it changes in check_authentication requests.");
            // The assoc_handle, signed, sig and invalidate_handle fields are added
            // as appropriate by the Signatory.Sign method.
        }
Example #4
0
		public void ProcessRequest(HttpContext context) {
			OpenIdProvider provider = new OpenIdProvider();
			if (provider.Request != null) {
				// Some OpenID requests are automatable and can be responded to immediately.
				if (!provider.Request.IsResponseReady) {
					// But authentication requests cannot be responded to until something on
					// this site decides whether to approve or disapprove the authentication.
					var idrequest = (IAuthenticationRequest)provider.Request;
					// We store the authentication request in the user's session so that
					// redirects and user prompts can appear and eventually some page can decide
					// to respond to the OpenID authentication request either affirmatively or
					// negatively.
					ProviderEndpoint.PendingAuthenticationRequest = idrequest;
					// We delegate that approval process to our utility method that we share
					// with our other Provider sample page server.aspx.
					Util.ProcessAuthenticationChallenge(idrequest);
					// As part of authentication approval, the user may need to authenticate
					// to this Provider and/or decide whether to allow the requesting RP site
					// to log this user in.  If any UI needs to be presented to the user, 
					// the previous call to ProcessAuthenticationChallenge MAY not return
					// due to a redirect to some ASPX page.
				} else {
					// Some other automatable OpenID request is coming down, so clear
					// any previously session stored authentication request that might be
					// stored for this user.
					ProviderEndpoint.PendingAuthenticationRequest = null;
				}
				// Whether this was an automated message or an authentication message,
				// if there is a response ready to send back immediately, do so.
				if (provider.Request.IsResponseReady) {
					provider.Request.Response.Send();
					ProviderEndpoint.PendingAuthenticationRequest = null;
				}
			}
		}
        /// <summary>
        /// Creates a message that can be sent to a user agent to redirect them to a
        /// relying party web site complete with authentication information to
        /// automatically log them into that web site.
        /// </summary>
        public static IResponse CreateUnsolicitedAssertion(OpenIdProvider provider,
                                                           Realm relyingParty, Identifier claimedIdentifier, Identifier localIdentifier)
        {
            if (relyingParty == null)
            {
                throw new ArgumentNullException("relyingParty");
            }
            if (claimedIdentifier == null)
            {
                throw new ArgumentNullException("claimedIdentifier");
            }
            if (localIdentifier == null)
            {
                throw new ArgumentNullException("localIdentifier");
            }

            var discoveredEndpoints = new List <RelyingPartyReceivingEndpoint>(relyingParty.Discover(true));

            if (discoveredEndpoints.Count == 0)
            {
                throw new OpenIdException(
                          string.Format(CultureInfo.CurrentCulture, Strings.NoRelyingPartyEndpointDiscovered,
                                        relyingParty.NoWildcardUri));
            }
            var selectedEndpoint = discoveredEndpoints[0];

            EncodableResponse message = EncodableResponse.PrepareIndirectMessage(
                selectedEndpoint.Protocol, selectedEndpoint.RelyingPartyEndpoint, null);

            CreatePositiveAssertion(message, provider, localIdentifier, claimedIdentifier);
            return(provider.Encoder.Encode(message));
        }
		public IDictionary<string, string> SendDirectMessageAndGetResponse(ServiceEndpoint providerEndpoint, IDictionary<string, string> fields) {
			OpenIdProvider provider = new OpenIdProvider(providerStore, providerEndpoint.ProviderEndpoint,
				providerEndpoint.ProviderEndpoint, fields.ToNameValueCollection());
			Debug.Assert(provider.Request.IsResponseReady, "Direct messages should always have an immediately available response.");
			Response webResponse = (Response)provider.Request.Response;
			EncodableResponse opAuthResponse = (EncodableResponse)webResponse.EncodableMessage;
			return opAuthResponse.EncodedFields;
		}
Example #7
0
		public PlainTextProviderSession(OpenIdProvider provider) : base(provider) {
			// Extra requirements for OpenId 2.0 compliance.  Although the 1.0 spec
			// doesn't require use of an encrypted session, it's stupid not to encrypt
			// the shared secret key, so we'll enforce the rule for 1.0 and 2.0 RPs.
			if (!provider.RequestUrl.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase)) {
				throw new OpenIdException(Strings.EncryptionRequired, provider.Query);
			}
		}
Example #8
0
 protected ProviderSession(OpenIdProvider provider)
 {
     if (provider == null)
     {
         throw new ArgumentNullException("provider");
     }
     Provider = provider;
 }
Example #9
0
		/// <summary>
		/// This method is used to throw a carefully crafted exception that will end up getting
		/// encoded as a response to the RP, given hints as to what 
		/// assoc_type and session_type args we support.
		/// </summary>
		/// <returns>A dictionary that should be passed to the OpenIdException
		/// via the <see cref="OpenIdException.ExtraArgsToReturn"/> property.</returns>
		internal static IDictionary<string, string> CreateAssociationTypeHints(
			OpenIdProvider provider) {
			Protocol protocol = provider.Protocol;
			return new Dictionary<string, string> {
				{ protocol.openidnp.error_code, protocol.Args.ErrorCode.UnsupportedType },
				{ protocol.openidnp.session_type, protocol.Args.SessionType.DH_SHA1 },
				{ protocol.openidnp.assoc_type, protocol.Args.SignatureAlgorithm.HMAC_SHA1 },
			};
		}
Example #10
0
 public PlainTextProviderSession(OpenIdProvider provider) : base(provider)
 {
     // Extra requirements for OpenId 2.0 compliance.  Although the 1.0 spec
     // doesn't require use of an encrypted session, it's stupid not to encrypt
     // the shared secret key, so we'll enforce the rule for 1.0 and 2.0 RPs.
     if (!provider.RequestUrl.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
     {
         throw new OpenIdException(Strings.EncryptionRequired, provider.Query);
     }
 }
Example #11
0
        /// <summary>
        /// This method is used to throw a carefully crafted exception that will end up getting
        /// encoded as a response to the RP, given hints as to what
        /// assoc_type and session_type args we support.
        /// </summary>
        /// <returns>A dictionary that should be passed to the OpenIdException
        /// via the <see cref="OpenIdException.ExtraArgsToReturn"/> property.</returns>
        internal static IDictionary <string, string> CreateAssociationTypeHints(
            OpenIdProvider provider)
        {
            Protocol protocol = provider.Protocol;

            return(new Dictionary <string, string> {
                { protocol.openidnp.error_code, protocol.Args.ErrorCode.UnsupportedType },
                { protocol.openidnp.session_type, protocol.Args.SessionType.DH_SHA1 },
                { protocol.openidnp.assoc_type, protocol.Args.SignatureAlgorithm.HMAC_SHA1 },
            });
        }
Example #12
0
		public DiffieHellmanProviderSession(OpenIdProvider provider)
			: base(provider) {
			sessionType = Util.GetRequiredArg(provider.Query, Protocol.openid.session_type);
			Debug.Assert(Array.IndexOf(Protocol.Args.SessionType.AllDiffieHellman, sessionType) >= 0, "We should not have been invoked if this wasn't a recognized DH session request.");

			byte[] dh_modulus = Util.GetOptionalBase64Arg(Provider.Query, Protocol.openid.dh_modulus) ?? DiffieHellmanUtil.DEFAULT_MOD;
			byte[] dh_gen = Util.GetOptionalBase64Arg(Provider.Query, Protocol.openid.dh_gen) ?? DiffieHellmanUtil.DEFAULT_GEN;
			dh = new DiffieHellmanManaged(dh_modulus, dh_gen, 1024);

			consumerPublicKey = Util.GetRequiredBase64Arg(Provider.Query, Protocol.openid.dh_consumer_public);
		}
Example #13
0
		public AssociateRequest(OpenIdProvider provider)
			: base(provider) {
			session = ProviderSession.CreateSession(provider);
			assoc_type = Util.GetRequiredArg(Query, Protocol.openid.assoc_type);
			if (Array.IndexOf(Protocol.Args.SignatureAlgorithm.All, assoc_type) < 0) {
				throw new OpenIdException(string.Format(CultureInfo.CurrentCulture,
					Strings.InvalidOpenIdQueryParameterValue,
					Protocol.openid.assoc_type, assoc_type), provider.Query) {
						ExtraArgsToReturn = CreateAssociationTypeHints(provider),
					};
			}
		}
Example #14
0
 protected Request(OpenIdProvider provider)
 {
     if (provider == null)
     {
         throw new ArgumentNullException("provider");
     }
     Provider           = provider;
     Query              = provider.Query;
     Protocol           = Protocol.Detect(Query);
     IncomingExtensions = ExtensionArgumentsManager.CreateIncomingExtensions(Query);
     OutgoingExtensions = ExtensionArgumentsManager.CreateOutgoingExtensions(Protocol);
 }
Example #15
0
		public CheckAuthRequest(OpenIdProvider provider)
			: base(provider) {
			AssociationHandle = Util.GetRequiredArg(Query, Protocol.openid.assoc_handle);
			signature = Util.GetRequiredArg(Query, Protocol.openid.sig);
			signedKeyOrder = Util.GetRequiredArg(Query, Protocol.openid.signed).Split(',');

			signedFields = new Dictionary<string, string>();
			Debug.Assert(!signedKeyOrder.Contains(Protocol.openidnp.mode), "openid.mode must not be included in signature because it necessarily changes in checkauth requests.");
			foreach (string key in signedKeyOrder) {
				signedFields.Add(key, Util.GetRequiredArgAllowEmptyValue(Query, Protocol.openid.Prefix + key));
			}
		}
Example #16
0
        public DiffieHellmanProviderSession(OpenIdProvider provider)
            : base(provider)
        {
            sessionType = Util.GetRequiredArg(provider.Query, Protocol.openid.session_type);
            Debug.Assert(Array.IndexOf(Protocol.Args.SessionType.AllDiffieHellman, sessionType) >= 0, "We should not have been invoked if this wasn't a recognized DH session request.");

            byte[] dh_modulus = Util.GetOptionalBase64Arg(Provider.Query, Protocol.openid.dh_modulus) ?? DiffieHellmanUtil.DEFAULT_MOD;
            byte[] dh_gen     = Util.GetOptionalBase64Arg(Provider.Query, Protocol.openid.dh_gen) ?? DiffieHellmanUtil.DEFAULT_GEN;
            dh = new DiffieHellmanManaged(dh_modulus, dh_gen, 1024);

            consumerPublicKey = Util.GetRequiredBase64Arg(Provider.Query, Protocol.openid.dh_consumer_public);
        }
Example #17
0
        internal CheckIdRequest(OpenIdProvider provider)
            : base(provider)
        {
            // handle the mandatory protocol fields
            string mode = Util.GetRequiredArg(Query, Protocol.openid.mode);
            if (Protocol.Args.Mode.checkid_immediate.Equals(mode, StringComparison.Ordinal)) {
                Immediate = true;
            } else if (Protocol.Args.Mode.checkid_setup.Equals(mode, StringComparison.Ordinal)) {
                Immediate = false; // implied
            } else {
                throw new OpenIdException(string.Format(CultureInfo.CurrentCulture,
                    Strings.InvalidOpenIdQueryParameterValue, Protocol.openid.mode, mode), Query);
            }

            // The spec says claimed_id and identity can both be either present or
            // absent.  But for now we don't have or support extensions that don't
            // use these parameters, so we require them.  In the future that may change.
            if (Protocol.Version.Major >= 2) {
                claimedIdentifier = Util.GetRequiredIdentifierArg(Query, Protocol.openid.claimed_id);
            }
            localIdentifier = Util.GetRequiredIdentifierArg(Query, Protocol.openid.identity);
            // The spec says return_to is optional, but what good is authenticating
            // a user if the user won't be sent back?
            ReturnTo = Util.GetRequiredUriArg(Query, Protocol.openid.return_to);
            Realm = Util.GetOptionalRealmArg(Query, Protocol.openid.Realm) ?? ReturnTo;
            AssociationHandle = Util.GetOptionalArg(Query, Protocol.openid.assoc_handle);

            if (!Realm.Contains(ReturnTo)) {
                throw new OpenIdException(string.Format(CultureInfo.CurrentCulture,
                    Strings.ReturnToNotUnderRealm, ReturnTo.AbsoluteUri, Realm), Query);
            }

            if (Protocol.Version.Major >= 2) {
                if (LocalIdentifier == Protocol.ClaimedIdentifierForOPIdentifier ^
                    ClaimedIdentifier == Protocol.ClaimedIdentifierForOPIdentifier) {
                    throw new OpenIdException(string.Format(CultureInfo.CurrentCulture,
                        Strings.MatchingArgumentsExpected, Protocol.openid.claimed_id,
                        Protocol.openid.identity, Protocol.ClaimedIdentifierForOPIdentifier),
                        Query);
                }
            }

            if (ClaimedIdentifier == Protocol.ClaimedIdentifierForOPIdentifier &&
                Protocol.ClaimedIdentifierForOPIdentifier != null) {
                // Force the OP to deal with identifier_select by nulling out the two identifiers.
                IsDirectedIdentity = true;
                claimedIdentifier = null;
                localIdentifier = null;
            }
        }
Example #18
0
        public CheckAuthRequest(OpenIdProvider provider)
            : base(provider)
        {
            AssociationHandle = Util.GetRequiredArg(Query, Protocol.openid.assoc_handle);
            signature         = Util.GetRequiredArg(Query, Protocol.openid.sig);
            signedKeyOrder    = Util.GetRequiredArg(Query, Protocol.openid.signed).Split(',');

            signedFields = new Dictionary <string, string>();
            Debug.Assert(!signedKeyOrder.Contains(Protocol.openidnp.mode), "openid.mode must not be included in signature because it necessarily changes in checkauth requests.");
            foreach (string key in signedKeyOrder)
            {
                signedFields.Add(key, Util.GetRequiredArgAllowEmptyValue(Query, Protocol.openid.Prefix + key));
            }
        }
Example #19
0
 public AssociateRequest(OpenIdProvider provider)
     : base(provider)
 {
     session    = ProviderSession.CreateSession(provider);
     assoc_type = Util.GetRequiredArg(Query, Protocol.openid.assoc_type);
     if (Array.IndexOf(Protocol.Args.SignatureAlgorithm.All, assoc_type) < 0)
     {
         throw new OpenIdException(string.Format(CultureInfo.CurrentCulture,
                                                 Strings.InvalidOpenIdQueryParameterValue,
                                                 Protocol.openid.assoc_type, assoc_type), provider.Query)
               {
                   ExtraArgsToReturn = CreateAssociationTypeHints(provider),
               };
     }
 }
Example #20
0
        /// <summary>
        /// Creates a message that can be sent to a user agent to redirect them to a 
        /// relying party web site complete with authentication information to 
        /// automatically log them into that web site.
        /// </summary>
        public static IResponse CreateUnsolicitedAssertion(OpenIdProvider provider,
            Realm relyingParty, Identifier claimedIdentifier, Identifier localIdentifier)
        {
            if (relyingParty == null) throw new ArgumentNullException("relyingParty");
            if (claimedIdentifier == null) throw new ArgumentNullException("claimedIdentifier");
            if (localIdentifier == null) throw new ArgumentNullException("localIdentifier");

            var discoveredEndpoints = new List<RelyingPartyReceivingEndpoint>(relyingParty.Discover(true));
            if (discoveredEndpoints.Count == 0) throw new OpenIdException(
                string.Format(CultureInfo.CurrentCulture, Strings.NoRelyingPartyEndpointDiscovered,
                relyingParty.NoWildcardUri));
            var selectedEndpoint = discoveredEndpoints[0];

            EncodableResponse message = EncodableResponse.PrepareIndirectMessage(
                selectedEndpoint.Protocol, selectedEndpoint.RelyingPartyEndpoint, null);
            CreatePositiveAssertion(message, provider, localIdentifier, claimedIdentifier);
            return provider.Encoder.Encode(message);
        }
Example #21
0
		public static ProviderSession CreateSession(OpenIdProvider provider) {
			if (provider == null) throw new ArgumentNullException("provider");
			Protocol protocol = provider.Protocol;
			string session_type = protocol.Version.Major >= 2 ?
				Util.GetRequiredArg(provider.Query, protocol.openid.session_type) :
				(Util.GetOptionalArg(provider.Query, protocol.openid.session_type) ?? "");

			if (protocol.Args.SessionType.NoEncryption.Equals(session_type, StringComparison.Ordinal)) {
				return new PlainTextProviderSession(provider);
			} else if (Array.IndexOf(protocol.Args.SessionType.AllDiffieHellman, session_type) >= 0) {
				return new DiffieHellmanProviderSession(provider);
			} else {
				throw new OpenIdException(string.Format(CultureInfo.CurrentCulture,
					Strings.InvalidOpenIdQueryParameterValue,
					protocol.openid.session_type, session_type), provider.Query) {
						ExtraArgsToReturn = AssociateRequest.CreateAssociationTypeHints(provider),
					};
			}
		}
Example #22
0
        public virtual Association CreateAssociation(AssociationRelyingPartyType associationType, OpenIdProvider provider)
        {
            if (provider == null && associationType == AssociationRelyingPartyType.Smart)
                throw new ArgumentNullException("provider", "For Smart associations, the provider must be given.");

            string assoc_type;
            Protocol associationProtocol;
            if (associationType == AssociationRelyingPartyType.Dumb) {
                // We'll just use the best association available.
                associationProtocol = Protocol.Default;
                assoc_type = associationProtocol.Args.SignatureAlgorithm.Best;
            } else {
                associationProtocol = provider.Protocol;
                assoc_type = Util.GetRequiredArg(provider.Query, provider.Protocol.openid.assoc_type);
                Debug.Assert(Array.IndexOf(provider.Protocol.Args.SignatureAlgorithm.All, assoc_type) >= 0, "This should have been checked by our caller.");
            }
            int secretLength = HmacShaAssociation.GetSecretLength(associationProtocol, assoc_type);

            RNGCryptoServiceProvider generator = new RNGCryptoServiceProvider();
            byte[] secret = new byte[secretLength];
            byte[] uniq_bytes = new byte[4];
            string uniq;
            string handle;
            HmacShaAssociation assoc;

            generator.GetBytes(secret);
            generator.GetBytes(uniq_bytes);

            uniq = Convert.ToBase64String(uniq_bytes);

            double seconds = DateTime.UtcNow.Subtract(Association.UnixEpoch).TotalSeconds;

            handle = "{{" + assoc_type + "}{" + seconds + "}{" + uniq + "}";

            TimeSpan lifeSpan = associationType == AssociationRelyingPartyType.Dumb ? dumbSecretLifetime : smartAssociationLifetime;
            assoc = HmacShaAssociation.Create(secretLength, handle, secret, lifeSpan);

            store.StoreAssociation(associationType, assoc);

            return assoc;
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        TestSupport.Scenarios scenario = (TestSupport.Scenarios)Enum.Parse(typeof(TestSupport.Scenarios), Request.QueryString["user"]);
        UriBuilder providerEndpoint = new UriBuilder(Request.Url);
        providerEndpoint.Query = "user="******"GET" ? Request.QueryString : Request.Form);
        if (provider.Request != null) {
            if (!provider.Request.IsResponseReady) {
                var idreq = provider.Request as IAuthenticationRequest;
                idreq.ClaimedIdentifier = new Uri(Request.Url, Page.ResolveUrl("~/DirectedIdentityEndpoint.aspx?user="******"&version=" + ProtocolVersion.V20));

                switch (scenario) {
                    case TestSupport.Scenarios.AutoApproval:
                        // immediately approve
                        idreq.IsAuthenticated = true;
                        break;
                    case TestSupport.Scenarios.AutoApprovalAddFragment:
                        idreq.SetClaimedIdentifierFragment("frag");
                        idreq.IsAuthenticated = true;
                        break;
                    case TestSupport.Scenarios.ApproveOnSetup:
                        idreq.IsAuthenticated = !idreq.Immediate;
                        break;
                    case TestSupport.Scenarios.AlwaysDeny:
                        idreq.IsAuthenticated = false;
                        break;
                    case TestSupport.Scenarios.ExtensionFullCooperation:
                    case TestSupport.Scenarios.ExtensionPartialCooperation:
                        throw new NotImplementedException();
                        //idreq.IsAuthenticated = true;
                        //break;
                    default:
                        throw new InvalidOperationException("Unrecognized scenario");
                }
            }
            provider.Request.Response.Send();
        }
    }
Example #24
0
        /// <summary>
        /// Creates the appropriate Request-derived type based on the request dictionary.
        /// </summary>
        /// <param name="provider">The Provider instance that called this method.</param>
        /// <returns>A Request-derived type appropriate for this stage in authentication.</returns>
        internal static Request CreateRequest(OpenIdProvider provider)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }
            Debug.Assert(provider.Protocol != null, "This should have been set already.");
            string mode = Util.GetRequiredArg(provider.Query, provider.Protocol.openid.mode);

            Request request;

            try {
                if (mode == provider.Protocol.Args.Mode.checkid_setup ||
                    mode == provider.Protocol.Args.Mode.checkid_immediate)
                {
                    request = new CheckIdRequest(provider);
                }
                else if (mode == provider.Protocol.Args.Mode.check_authentication)
                {
                    request = new CheckAuthRequest(provider);
                }
                else if (mode == provider.Protocol.Args.Mode.associate)
                {
                    request = new AssociateRequest(provider);
                }
                else
                {
                    throw new OpenIdException(string.Format(CultureInfo.CurrentCulture,
                                                            Strings.InvalidOpenIdQueryParameterValue, provider.Protocol.openid.mode,
                                                            mode), provider.Query);
                }
            } catch (OpenIdException ex) {
                request = new FaultyRequest(provider, ex);
            }
            return(request);
        }
Example #25
0
 internal static OpenIdProvider CreateProvider(NameValueCollection fields, bool useSsl)
 {
     Protocol protocol = fields != null ? Protocol.Detect(fields.ToDictionary()) : Protocol.v20;
     Uri opEndpoint = GetFullUrl(ProviderPage, null, useSsl);
     var provider = new OpenIdProvider(ProviderStore, opEndpoint, opEndpoint, fields ?? new NameValueCollection());
     return provider;
 }
 protected AssociatedRequest(OpenIdProvider provider) : base(provider)
 {
 }
Example #27
0
 internal FaultyRequest(OpenIdProvider provider, IEncodable response)
     : base(provider)
 {
     Response = response;
 }
Example #28
0
 public void CtorNullRequestUrl()
 {
     OpenIdProvider op = new OpenIdProvider(new ProviderMemoryStore(),
         providerEndpoint, null, new NameValueCollection());
 }
Example #29
0
 public void CtorNullStore()
 {
     OpenIdProvider op = new OpenIdProvider(null, providerEndpoint,
         emptyRequestUrl, new NameValueCollection());
 }
Example #30
0
 public void CtorNonDefault()
 {
     OpenIdProvider op = new OpenIdProvider(new ProviderMemoryStore(),
         providerEndpoint, emptyRequestUrl, new NameValueCollection());
 }
Example #31
0
 public void CtorNullQuery()
 {
     OpenIdProvider op = new OpenIdProvider(new ProviderMemoryStore(),
         providerEndpoint, emptyRequestUrl, null);
 }
Example #32
0
 public void RequestNullOnEmptyRequest()
 {
     OpenIdProvider op = new OpenIdProvider(new ProviderMemoryStore(),
         providerEndpoint, emptyRequestUrl, new NameValueCollection());
     Assert.IsNull(op.Request);
 }
Example #33
0
 public void CtorDefault()
 {
     OpenIdProvider op = new OpenIdProvider();
 }
Example #34
0
 protected ProviderSession(OpenIdProvider provider)
 {
     if (provider == null) throw new ArgumentNullException("provider");
     Provider = provider;
 }
Example #35
0
 protected AssociatedRequest(OpenIdProvider provider)
     : base(provider)
 {
 }
Example #36
0
        internal CheckIdRequest(OpenIdProvider provider) : base(provider)
        {
            // handle the mandatory protocol fields
            string mode = Util.GetRequiredArg(Query, Protocol.openid.mode);

            if (Protocol.Args.Mode.checkid_immediate.Equals(mode, StringComparison.Ordinal))
            {
                Immediate = true;
            }
            else if (Protocol.Args.Mode.checkid_setup.Equals(mode, StringComparison.Ordinal))
            {
                Immediate = false;                 // implied
            }
            else
            {
                throw new OpenIdException(string.Format(CultureInfo.CurrentCulture,
                                                        Strings.InvalidOpenIdQueryParameterValue, Protocol.openid.mode, mode), Query);
            }

            // The spec says claimed_id and identity can both be either present or
            // absent.  But for now we don't have or support extensions that don't
            // use these parameters, so we require them.  In the future that may change.
            if (Protocol.Version.Major >= 2)
            {
                claimedIdentifier = Util.GetRequiredIdentifierArg(Query, Protocol.openid.claimed_id);
            }
            localIdentifier = Util.GetRequiredIdentifierArg(Query, Protocol.openid.identity);
            // The spec says return_to is optional, but what good is authenticating
            // a user if the user won't be sent back?
            ReturnTo          = Util.GetRequiredUriArg(Query, Protocol.openid.return_to);
            Realm             = Util.GetOptionalRealmArg(Query, Protocol.openid.Realm) ?? ReturnTo;
            AssociationHandle = Util.GetOptionalArg(Query, Protocol.openid.assoc_handle);

            if (!Realm.Contains(ReturnTo))
            {
                throw new OpenIdException(string.Format(CultureInfo.CurrentCulture,
                                                        Strings.ReturnToNotUnderRealm, ReturnTo.AbsoluteUri, Realm), Query);
            }

            if (Protocol.Version.Major >= 2)
            {
                if (LocalIdentifier == Protocol.ClaimedIdentifierForOPIdentifier ^
                    ClaimedIdentifier == Protocol.ClaimedIdentifierForOPIdentifier)
                {
                    throw new OpenIdException(string.Format(CultureInfo.CurrentCulture,
                                                            Strings.MatchingArgumentsExpected, Protocol.openid.claimed_id,
                                                            Protocol.openid.identity, Protocol.ClaimedIdentifierForOPIdentifier),
                                              Query);
                }
            }

            if (ClaimedIdentifier == Protocol.ClaimedIdentifierForOPIdentifier &&
                Protocol.ClaimedIdentifierForOPIdentifier != null)
            {
                // Force the OP to deal with identifier_select by nulling out the two identifiers.
                IsDirectedIdentity = true;
                claimedIdentifier  = null;
                localIdentifier    = null;
            }

            // URL delegation is only detectable from 2.0 RPs, since openid.claimed_id isn't included from 1.0 RPs.
            // If the openid.claimed_id is present, and if it's different than the openid.identity argument, then
            // the RP has discovered a claimed identifier that has delegated authentication to this Provider.
            IsDelegatedIdentifier = ClaimedIdentifier != null && ClaimedIdentifier != LocalIdentifier;
        }
Example #37
0
        /// <summary>
        /// Checks for incoming OpenID requests, responds to ones it can
        /// respond to without policy checks, and fires events for custom
        /// handling of the ones it cannot decide on automatically.
        /// </summary>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (Enabled) {
                // Use the explicitly given state store on this control if there is one.
                // Then try the configuration file specified one.  Finally, use the default
                // in-memory one that's built into OpenIdProvider.
                OpenIdProvider provider = new OpenIdProvider(
                    CustomApplicationStore ?? OpenIdProvider.Configuration.Store.CreateInstanceOfStore(OpenIdProvider.HttpApplicationStore),
                    OpenIdProvider.DefaultProviderEndpoint,
                    OpenIdProvider.DefaultRequestUrl,
                    OpenIdProvider.DefaultQuery);

                // determine what incoming message was received
                if (provider.Request != null) {
                    // process the incoming message appropriately and send the response
                    if (!provider.Request.IsResponseReady) {
                        var idrequest = (CheckIdRequest)provider.Request;
                        PendingAuthenticationRequest = idrequest;
                        OnAuthenticationChallenge(idrequest);
                    } else {
                        PendingAuthenticationRequest = null;
                    }
                    if (provider.Request.IsResponseReady) {
                        provider.Request.Response.Send();
                        Page.Response.End();
                        PendingAuthenticationRequest = null;
                    }
                }
            }
        }
Example #38
0
 internal static OpenIdProvider CreateProviderForRequest(DotNetOpenId.RelyingParty.IAuthenticationRequest request)
 {
     IResponse relyingPartyAuthenticationRequest = request.RedirectingResponse;
     var rpWebMessageToOP = (Response)relyingPartyAuthenticationRequest;
     var rpMessageToOP = (IndirectMessageRequest)rpWebMessageToOP.EncodableMessage;
     var opEndpoint = (ServiceEndpoint)request.Provider;
     var provider = new OpenIdProvider(ProviderStore, opEndpoint.ProviderEndpoint,
         opEndpoint.ProviderEndpoint, rpMessageToOP.EncodedFields.ToNameValueCollection());
     return provider;
 }
Example #39
0
        public virtual Association CreateAssociation(AssociationRelyingPartyType associationType, OpenIdProvider provider)
        {
            if (provider == null && associationType == AssociationRelyingPartyType.Smart)
            {
                throw new ArgumentNullException("provider", "For Smart associations, the provider must be given.");
            }

            string   assoc_type;
            Protocol associationProtocol;

            if (associationType == AssociationRelyingPartyType.Dumb)
            {
                // We'll just use the best association available.
                associationProtocol = Protocol.Default;
                assoc_type          = associationProtocol.Args.SignatureAlgorithm.Best;
            }
            else
            {
                associationProtocol = provider.Protocol;
                assoc_type          = Util.GetRequiredArg(provider.Query, provider.Protocol.openid.assoc_type);
                Debug.Assert(Array.IndexOf(provider.Protocol.Args.SignatureAlgorithm.All, assoc_type) >= 0, "This should have been checked by our caller.");
            }
            int secretLength = HmacShaAssociation.GetSecretLength(associationProtocol, assoc_type);

            RNGCryptoServiceProvider generator = new RNGCryptoServiceProvider();

            byte[]             secret     = new byte[secretLength];
            byte[]             uniq_bytes = new byte[4];
            string             uniq;
            string             handle;
            HmacShaAssociation assoc;

            generator.GetBytes(secret);
            generator.GetBytes(uniq_bytes);

            uniq = Convert.ToBase64String(uniq_bytes);

            double seconds = DateTime.UtcNow.Subtract(Association.UnixEpoch).TotalSeconds;

            handle = "{{" + assoc_type + "}{" + seconds + "}{" + uniq + "}";

            TimeSpan lifeSpan = associationType == AssociationRelyingPartyType.Dumb ? dumbSecretLifetime : smartAssociationLifetime;

            assoc = HmacShaAssociation.Create(secretLength, handle, secret, lifeSpan);

            store.StoreAssociation(associationType, assoc);

            return(assoc);
        }
Example #40
-1
 internal FaultyRequest(OpenIdProvider provider, IEncodable response)
     : base(provider)
 {
     Response = response;
 }