summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/.gitignore3
-rw-r--r--src/DotNetOpenAuth.BuildTasks/ChangeProjectReferenceToAssemblyReference.cs13
-rw-r--r--src/DotNetOpenAuth.BuildTasks/DotNetOpenAuth.BuildTasks.csproj1
-rw-r--r--src/DotNetOpenAuth.BuildTasks/DotNetOpenAuth.BuildTasks.sln12
-rw-r--r--src/DotNetOpenAuth.BuildTasks/DowngradeProjects.cs2
-rw-r--r--src/DotNetOpenAuth.BuildTasks/GetBuildVersion.cs15
-rw-r--r--src/DotNetOpenAuth.BuildTasks/NuGetPack.cs39
-rw-r--r--src/DotNetOpenAuth.BuildTasks/PathSegment.cs5
-rw-r--r--src/DotNetOpenAuth.BuildTasks/RegexFileReplace.cs55
-rw-r--r--src/DotNetOpenAuth.Core.UI/ComponentModel/ClaimTypeSuggestions.cs (renamed from src/DotNetOpenAuth/ComponentModel/ClaimTypeSuggestions.cs)0
-rw-r--r--src/DotNetOpenAuth.Core.UI/ComponentModel/ConverterBase.cs (renamed from src/DotNetOpenAuth/ComponentModel/ConverterBase.cs)2
-rw-r--r--src/DotNetOpenAuth.Core.UI/ComponentModel/SuggestedStringsConverter.cs (renamed from src/DotNetOpenAuth/ComponentModel/SuggestedStringsConverter.cs)4
-rw-r--r--src/DotNetOpenAuth.Core.UI/ComponentModel/SuggestedStringsConverterContract.cs (renamed from src/DotNetOpenAuth/ComponentModel/SuggestedStringsConverterContract.cs)0
-rw-r--r--src/DotNetOpenAuth.Core.UI/DotNetOpenAuth.Core.UI.csproj38
-rw-r--r--src/DotNetOpenAuth.Core.UI/Properties/AssemblyInfo.cs74
-rw-r--r--src/DotNetOpenAuth.Core/Assumes.cs97
-rw-r--r--src/DotNetOpenAuth.Core/CodeAnalysisDictionary.xml71
-rw-r--r--src/DotNetOpenAuth.Core/Configuration/DotNetOpenAuth.xsd (renamed from src/DotNetOpenAuth/Configuration/DotNetOpenAuth.xsd)69
-rw-r--r--src/DotNetOpenAuth.Core/Configuration/DotNetOpenAuthSection.cs70
-rw-r--r--src/DotNetOpenAuth.Core/Configuration/HostNameElement.cs (renamed from src/DotNetOpenAuth/Configuration/HostNameElement.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Configuration/HostNameOrRegexCollection.cs (renamed from src/DotNetOpenAuth/Configuration/HostNameOrRegexCollection.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Configuration/MessagingElement.cs (renamed from src/DotNetOpenAuth/Configuration/MessagingElement.cs)65
-rw-r--r--src/DotNetOpenAuth.Core/Configuration/ReportingElement.cs (renamed from src/DotNetOpenAuth/Configuration/ReportingElement.cs)18
-rw-r--r--src/DotNetOpenAuth.Core/Configuration/TrustedProviderConfigurationCollection.cs (renamed from src/DotNetOpenAuth/Configuration/TrustedProviderConfigurationCollection.cs)2
-rw-r--r--src/DotNetOpenAuth.Core/Configuration/TrustedProviderEndpointConfigurationElement.cs (renamed from src/DotNetOpenAuth/Configuration/TrustedProviderEndpointConfigurationElement.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Configuration/TypeConfigurationCollection.cs (renamed from src/DotNetOpenAuth/Configuration/TypeConfigurationCollection.cs)4
-rw-r--r--src/DotNetOpenAuth.Core/Configuration/TypeConfigurationElement.cs (renamed from src/DotNetOpenAuth/Configuration/TypeConfigurationElement.cs)8
-rw-r--r--src/DotNetOpenAuth.Core/Configuration/UntrustedWebRequestElement.cs (renamed from src/DotNetOpenAuth/Configuration/UntrustedWebRequestElement.cs)1
-rw-r--r--src/DotNetOpenAuth.Core/DotNetOpenAuth.Core.csproj168
-rw-r--r--src/DotNetOpenAuth.Core/DotNetOpenAuth.ico (renamed from src/DotNetOpenAuth/DotNetOpenAuth.ico)bin1150 -> 1150 bytes
-rw-r--r--src/DotNetOpenAuth.Core/GlobalSuppressions.cs (renamed from src/DotNetOpenAuth/GlobalSuppressions.cs)1
-rw-r--r--src/DotNetOpenAuth.Core/IEmbeddedResourceRetrieval.cs (renamed from src/DotNetOpenAuth/IEmbeddedResourceRetrieval.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Logger.cs (renamed from src/DotNetOpenAuth/Logger.cs)6
-rw-r--r--src/DotNetOpenAuth.Core/Loggers/ILog.cs (renamed from src/DotNetOpenAuth/Loggers/ILog.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Loggers/Log4NetLogger.cs (renamed from src/DotNetOpenAuth/Loggers/Log4NetLogger.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Loggers/NoOpLogger.cs (renamed from src/DotNetOpenAuth/Loggers/NoOpLogger.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Loggers/TraceLogger.cs (renamed from src/DotNetOpenAuth/Loggers/TraceLogger.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/BinaryDataBagFormatter.cs80
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Bindings/AsymmetricCryptoKeyStoreWrapper.cs163
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Bindings/Bindings.cd (renamed from src/DotNetOpenAuth/Messaging/Bindings/Bindings.cd)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Bindings/CryptoKey.cs93
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Bindings/CryptoKeyCollisionException.cs68
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Bindings/ExpiredMessageException.cs (renamed from src/DotNetOpenAuth/Messaging/Bindings/ExpiredMessageException.cs)3
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Bindings/ICryptoKeyStore.cs118
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Bindings/IExpiringProtocolMessage.cs (renamed from src/DotNetOpenAuth/Messaging/Bindings/IExpiringProtocolMessage.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Bindings/INonceStore.cs (renamed from src/DotNetOpenAuth/Messaging/Bindings/INonceStore.cs)2
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Bindings/IReplayProtectedProtocolMessage.cs (renamed from src/DotNetOpenAuth/Messaging/Bindings/IReplayProtectedProtocolMessage.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Bindings/InvalidSignatureException.cs (renamed from src/DotNetOpenAuth/Messaging/Bindings/InvalidSignatureException.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Bindings/MemoryCryptoKeyStore.cs156
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Bindings/NonceMemoryStore.cs (renamed from src/DotNetOpenAuth/Messaging/Bindings/NonceMemoryStore.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Bindings/ReplayedMessageException.cs (renamed from src/DotNetOpenAuth/Messaging/Bindings/ReplayedMessageException.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Bindings/StandardExpirationBindingElement.cs (renamed from src/DotNetOpenAuth/Messaging/Bindings/StandardExpirationBindingElement.cs)4
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Bindings/StandardReplayProtectionBindingElement.cs (renamed from src/DotNetOpenAuth/Messaging/Bindings/StandardReplayProtectionBindingElement.cs)2
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/CachedDirectWebResponse.cs (renamed from src/DotNetOpenAuth/Messaging/CachedDirectWebResponse.cs)10
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Channel.cs (renamed from src/DotNetOpenAuth/Messaging/Channel.cs)243
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/ChannelContract.cs (renamed from src/DotNetOpenAuth/Messaging/ChannelContract.cs)4
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/ChannelEventArgs.cs (renamed from src/DotNetOpenAuth/Messaging/ChannelEventArgs.cs)2
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/DataBag.cs147
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/DataBagFormatterBase.cs354
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/DirectWebRequestOptions.cs (renamed from src/DotNetOpenAuth/Messaging/DirectWebRequestOptions.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/EmptyDictionary.cs (renamed from src/DotNetOpenAuth/Messaging/EmptyDictionary.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/EmptyEnumerator.cs (renamed from src/DotNetOpenAuth/Messaging/EmptyEnumerator.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/EmptyList.cs (renamed from src/DotNetOpenAuth/Messaging/EmptyList.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/EnumerableCache.cs (renamed from src/DotNetOpenAuth/Messaging/EnumerableCache.cs)8
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/ErrorUtilities.cs (renamed from src/DotNetOpenAuth/Messaging/ErrorUtilities.cs)68
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Exceptions.cd (renamed from src/DotNetOpenAuth/Messaging/Exceptions.cd)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/HostErrorException.cs (renamed from src/DotNetOpenAuth/Messaging/HostErrorException.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/HttpDeliveryMethods.cs (renamed from src/DotNetOpenAuth/Messaging/HttpDeliveryMethods.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/HttpRequestInfo.cs (renamed from src/DotNetOpenAuth/Messaging/HttpRequestInfo.cs)28
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/IChannelBindingElement.cs (renamed from src/DotNetOpenAuth/Messaging/IChannelBindingElement.cs)8
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/IDataBagFormatter.cs75
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/IDirectResponseProtocolMessage.cs (renamed from src/DotNetOpenAuth/Messaging/IDirectResponseProtocolMessage.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/IDirectWebRequestHandler.cs223
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/IDirectWebRequestHandler.cs.orig (renamed from src/DotNetOpenAuth/Messaging/IDirectWebRequestHandler.cs)7
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/IDirectedProtocolMessage.cs (renamed from src/DotNetOpenAuth/Messaging/IDirectedProtocolMessage.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/IExtensionMessage.cs (renamed from src/DotNetOpenAuth/Messaging/IExtensionMessage.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/IHttpDirectResponse.cs (renamed from src/DotNetOpenAuth/Messaging/IHttpDirectResponse.cs)10
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/IHttpDirectResponseContract.cs43
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/IHttpIndirectResponse.cs22
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/IMessage.cs (renamed from src/DotNetOpenAuth/Messaging/IMessage.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/IMessageFactory.cs (renamed from src/DotNetOpenAuth/Messaging/IMessageFactory.cs)8
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/IMessageOriginalPayload.cs (renamed from src/DotNetOpenAuth/Messaging/IMessageOriginalPayload.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/IMessageWithBinaryData.cs (renamed from src/DotNetOpenAuth/Messaging/IMessageWithBinaryData.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/IMessageWithEvents.cs (renamed from src/DotNetOpenAuth/Messaging/IMessageWithEvents.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/IProtocolMessage.cs (renamed from src/DotNetOpenAuth/Messaging/IProtocolMessage.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/IProtocolMessageWithExtensions.cs (renamed from src/DotNetOpenAuth/Messaging/IProtocolMessageWithExtensions.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/IStreamSerializingDataBag.cs55
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/ITamperResistantProtocolMessage.cs (renamed from src/DotNetOpenAuth/Messaging/ITamperResistantProtocolMessage.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/IncomingWebResponse.cs (renamed from src/DotNetOpenAuth/Messaging/IncomingWebResponse.cs)6
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/IncomingWebResponseContract.cs (renamed from src/DotNetOpenAuth/Messaging/IncomingWebResponseContract.cs)4
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/InternalErrorException.cs (renamed from src/DotNetOpenAuth/Messaging/InternalErrorException.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/KeyedCollectionDelegate.cs (renamed from src/DotNetOpenAuth/Messaging/KeyedCollectionDelegate.cs)2
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/MessagePartAttribute.cs (renamed from src/DotNetOpenAuth/Messaging/MessagePartAttribute.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/MessageProtections.cs (renamed from src/DotNetOpenAuth/Messaging/MessageProtections.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/MessageReceivingEndpoint.cs (renamed from src/DotNetOpenAuth/Messaging/MessageReceivingEndpoint.cs)12
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/MessageSerializer.cs (renamed from src/DotNetOpenAuth/Messaging/MessageSerializer.cs)124
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/MessageTransport.cs (renamed from src/DotNetOpenAuth/Messaging/MessageTransport.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Messaging.cd (renamed from src/DotNetOpenAuth/Messaging/Messaging.cd)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/MessagingStrings.Designer.cs (renamed from src/DotNetOpenAuth/Messaging/MessagingStrings.Designer.cs)47
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/MessagingStrings.resx (renamed from src/DotNetOpenAuth/Messaging/MessagingStrings.resx)17
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/MessagingStrings.sr.resx (renamed from src/DotNetOpenAuth/Messaging/MessagingStrings.sr.resx)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/MessagingUtilities.cs (renamed from src/DotNetOpenAuth/Messaging/MessagingUtilities.cs)770
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/MultipartPostPart.cs (renamed from src/DotNetOpenAuth/Messaging/MultipartPostPart.cs)20
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/NetworkDirectWebResponse.cs (renamed from src/DotNetOpenAuth/Messaging/NetworkDirectWebResponse.cs)4
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponse.cs (renamed from src/DotNetOpenAuth/Messaging/OutgoingWebResponse.cs)152
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponseActionResult.cs (renamed from src/DotNetOpenAuth/Messaging/OutgoingWebResponseActionResult.cs)4
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/ProtocolException.cs (renamed from src/DotNetOpenAuth/Messaging/ProtocolException.cs)2
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Reflection/IMessagePartEncoder.cs (renamed from src/DotNetOpenAuth/Messaging/Reflection/IMessagePartEncoder.cs)4
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Reflection/IMessagePartNullEncoder.cs (renamed from src/DotNetOpenAuth/Messaging/Reflection/IMessagePartNullEncoder.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Reflection/IMessagePartOriginalEncoder.cs (renamed from src/DotNetOpenAuth/Messaging/Reflection/IMessagePartOriginalEncoder.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDescription.cs284
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDescriptionCollection.cs (renamed from src/DotNetOpenAuth/Messaging/Reflection/MessageDescriptionCollection.cs)47
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDictionary.cs (renamed from src/DotNetOpenAuth/Messaging/Reflection/MessageDictionary.cs)6
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Reflection/MessagePart.cs (renamed from src/DotNetOpenAuth/Messaging/Reflection/MessagePart.cs)145
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Reflection/ValueMapping.cs (renamed from src/DotNetOpenAuth/Messaging/Reflection/ValueMapping.cs)6
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/StandardMessageFactory.cs298
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/StandardMessageFactoryChannel.cs111
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/StandardWebRequestHandler.cs (renamed from src/DotNetOpenAuth/Messaging/StandardWebRequestHandler.cs)11
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/TimespanSecondsEncoder.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/TimespanSecondsEncoder.cs)9
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/TimestampEncoder.cs61
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/UnprotectedMessageException.cs (renamed from src/DotNetOpenAuth/Messaging/UnprotectedMessageException.cs)0
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/UntrustedWebRequestHandler.cs (renamed from src/DotNetOpenAuth/Messaging/UntrustedWebRequestHandler.cs)20
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/UriStyleMessageFormatter.cs77
-rw-r--r--src/DotNetOpenAuth.Core/Migrated rules for DotNetOpenAuth.ruleset (renamed from src/DotNetOpenAuth/Migrated rules for DotNetOpenAuth.ruleset)0
-rw-r--r--src/DotNetOpenAuth.Core/Properties/AssemblyInfo.cs88
-rw-r--r--src/DotNetOpenAuth.Core/Reporting.cs (renamed from src/DotNetOpenAuth/Reporting.cs)89
-rw-r--r--src/DotNetOpenAuth.Core/Requires.cs250
-rw-r--r--src/DotNetOpenAuth.Core/Settings.StyleCop (renamed from src/DotNetOpenAuth/Settings.StyleCop)0
-rw-r--r--src/DotNetOpenAuth.Core/Strings.Designer.cs (renamed from src/DotNetOpenAuth/Strings.Designer.cs)20
-rw-r--r--src/DotNetOpenAuth.Core/Strings.resx (renamed from src/DotNetOpenAuth/Strings.resx)6
-rw-r--r--src/DotNetOpenAuth.Core/Strings.sr.resx (renamed from src/DotNetOpenAuth/Strings.sr.resx)0
-rw-r--r--src/DotNetOpenAuth.Core/UriUtil.cs (renamed from src/DotNetOpenAuth/UriUtil.cs)6
-rw-r--r--src/DotNetOpenAuth.Core/Util.cs (renamed from src/DotNetOpenAuth/Util.cs)4
-rw-r--r--src/DotNetOpenAuth.InfoCard.UI/ComponentModel/IssuersSuggestions.cs (renamed from src/DotNetOpenAuth/ComponentModel/IssuersSuggestions.cs)0
-rw-r--r--src/DotNetOpenAuth.InfoCard.UI/ComponentModel/UriConverter.cs (renamed from src/DotNetOpenAuth/ComponentModel/UriConverter.cs)2
-rw-r--r--src/DotNetOpenAuth.InfoCard.UI/DotNetOpenAuth.InfoCard.UI.csproj68
-rw-r--r--src/DotNetOpenAuth.InfoCard.UI/InfoCard/ClaimType.cs (renamed from src/DotNetOpenAuth/InfoCard/ClaimType.cs)0
-rw-r--r--src/DotNetOpenAuth.InfoCard.UI/InfoCard/InfoCardImage.cs (renamed from src/DotNetOpenAuth/InfoCard/InfoCardImage.cs)0
-rw-r--r--src/DotNetOpenAuth.InfoCard.UI/InfoCard/InfoCardSelector.cs (renamed from src/DotNetOpenAuth/InfoCard/InfoCardSelector.cs)14
-rw-r--r--src/DotNetOpenAuth.InfoCard.UI/InfoCard/ReceivedTokenEventArgs.cs (renamed from src/DotNetOpenAuth/InfoCard/ReceivedTokenEventArgs.cs)0
-rw-r--r--src/DotNetOpenAuth.InfoCard.UI/InfoCard/ReceivingTokenEventArgs.cs (renamed from src/DotNetOpenAuth/InfoCard/ReceivingTokenEventArgs.cs)8
-rw-r--r--src/DotNetOpenAuth.InfoCard.UI/InfoCard/SupportingScript.js (renamed from src/DotNetOpenAuth/InfoCard/SupportingScript.js)0
-rw-r--r--src/DotNetOpenAuth.InfoCard.UI/InfoCard/TokenProcessingErrorEventArgs.cs (renamed from src/DotNetOpenAuth/InfoCard/TokenProcessingErrorEventArgs.cs)4
-rw-r--r--src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_114x80.png (renamed from src/DotNetOpenAuth/InfoCard/infocard_114x80.png)bin3821 -> 3821 bytes
-rw-r--r--src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_14x10.png (renamed from src/DotNetOpenAuth/InfoCard/infocard_14x10.png)bin478 -> 478 bytes
-rw-r--r--src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_214x150.png (renamed from src/DotNetOpenAuth/InfoCard/infocard_214x150.png)bin8346 -> 8346 bytes
-rw-r--r--src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_23x16.png (renamed from src/DotNetOpenAuth/InfoCard/infocard_23x16.png)bin810 -> 810 bytes
-rw-r--r--src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_300x210.png (renamed from src/DotNetOpenAuth/InfoCard/infocard_300x210.png)bin13184 -> 13184 bytes
-rw-r--r--src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_34x24.png (renamed from src/DotNetOpenAuth/InfoCard/infocard_34x24.png)bin1129 -> 1129 bytes
-rw-r--r--src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_365x256.png (renamed from src/DotNetOpenAuth/InfoCard/infocard_365x256.png)bin17191 -> 17191 bytes
-rw-r--r--src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_41x29.png (renamed from src/DotNetOpenAuth/InfoCard/infocard_41x29.png)bin1297 -> 1297 bytes
-rw-r--r--src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_50x35.png (renamed from src/DotNetOpenAuth/InfoCard/infocard_50x35.png)bin1644 -> 1644 bytes
-rw-r--r--src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_60x42.png (renamed from src/DotNetOpenAuth/InfoCard/infocard_60x42.png)bin2071 -> 2071 bytes
-rw-r--r--src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_71x50.png (renamed from src/DotNetOpenAuth/InfoCard/infocard_71x50.png)bin2394 -> 2394 bytes
-rw-r--r--src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_81x57.png (renamed from src/DotNetOpenAuth/InfoCard/infocard_81x57.png)bin2850 -> 2850 bytes
-rw-r--r--src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_92x64.png (renamed from src/DotNetOpenAuth/InfoCard/infocard_92x64.png)bin3174 -> 3174 bytes
-rw-r--r--src/DotNetOpenAuth.InfoCard.UI/Properties/AssemblyInfo.cs56
-rw-r--r--src/DotNetOpenAuth.InfoCard/DotNetOpenAuth.InfoCard.csproj52
-rw-r--r--src/DotNetOpenAuth.InfoCard/InfoCard/InfoCardStrings.Designer.cs (renamed from src/DotNetOpenAuth/InfoCard/InfoCardStrings.Designer.cs)0
-rw-r--r--src/DotNetOpenAuth.InfoCard/InfoCard/InfoCardStrings.resx (renamed from src/DotNetOpenAuth/InfoCard/InfoCardStrings.resx)0
-rw-r--r--src/DotNetOpenAuth.InfoCard/InfoCard/InfoCardStrings.sr.resx (renamed from src/DotNetOpenAuth/InfoCard/InfoCardStrings.sr.resx)0
-rw-r--r--src/DotNetOpenAuth.InfoCard/InfoCard/Token/InformationCardException.cs (renamed from src/DotNetOpenAuth/InfoCard/Token/InformationCardException.cs)0
-rw-r--r--src/DotNetOpenAuth.InfoCard/InfoCard/Token/Token.cs (renamed from src/DotNetOpenAuth/InfoCard/Token/Token.cs)22
-rw-r--r--src/DotNetOpenAuth.InfoCard/InfoCard/Token/TokenDecryptor.cs (renamed from src/DotNetOpenAuth/InfoCard/Token/TokenDecryptor.cs)4
-rw-r--r--src/DotNetOpenAuth.InfoCard/InfoCard/Token/TokenUtility.cs (renamed from src/DotNetOpenAuth/InfoCard/Token/TokenUtility.cs)21
-rw-r--r--src/DotNetOpenAuth.InfoCard/InfoCard/WellKnownClaimTypes.cs (renamed from src/DotNetOpenAuth/InfoCard/WellKnownClaimTypes.cs)0
-rw-r--r--src/DotNetOpenAuth.InfoCard/InfoCard/WellKnownIssuers.cs (renamed from src/DotNetOpenAuth/InfoCard/WellKnownIssuers.cs)0
-rw-r--r--src/DotNetOpenAuth.InfoCard/InfoCardErrorUtilities.cs39
-rw-r--r--src/DotNetOpenAuth.InfoCard/Properties/AssemblyInfo.cs56
-rw-r--r--src/DotNetOpenAuth.OAuth.Consumer/DotNetOpenAuth.OAuth.Consumer.csproj50
-rw-r--r--src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/IConsumerTokenManager.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/IConsumerTokenManager.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/OAuthConsumerChannel.cs70
-rw-r--r--src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/OAuthConsumerMessageFactory.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/OAuthConsumerMessageFactory.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/RsaSha1ConsumerSigningBindingElement.cs74
-rw-r--r--src/DotNetOpenAuth.OAuth.Consumer/OAuth/ConsumerBase.cs (renamed from src/DotNetOpenAuth/OAuth/ConsumerBase.cs)34
-rw-r--r--src/DotNetOpenAuth.OAuth.Consumer/OAuth/DesktopConsumer.cs (renamed from src/DotNetOpenAuth/OAuth/DesktopConsumer.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth.Consumer/OAuth/WebConsumer.cs (renamed from src/DotNetOpenAuth/OAuth/WebConsumer.cs)8
-rw-r--r--src/DotNetOpenAuth.OAuth.Consumer/Properties/AssemblyInfo.cs58
-rw-r--r--src/DotNetOpenAuth.OAuth.Consumer/Properties/Properties/AssemblyInfo.cs58
-rw-r--r--src/DotNetOpenAuth.OAuth.ServiceProvider/DotNetOpenAuth.OAuth.ServiceProvider.csproj57
-rw-r--r--src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/IConsumerDescription.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/IConsumerDescription.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/IServiceProviderAccessToken.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/IServiceProviderAccessToken.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/IServiceProviderRequestToken.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/IServiceProviderRequestToken.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/IServiceProviderTokenManager.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/IServiceProviderTokenManager.cs)14
-rw-r--r--src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/ITokenGenerator.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/ITokenGenerator.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthIdentity.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/OAuthIdentity.cs)2
-rw-r--r--src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthPrincipal.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/OAuthPrincipal.cs)38
-rw-r--r--src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthServiceProviderChannel.cs74
-rw-r--r--src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthServiceProviderMessageFactory.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/OAuthServiceProviderMessageFactory.cs)2
-rw-r--r--src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/RsaSha1ServiceProviderSigningBindingElement.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/RsaSha1SigningBindingElement.cs)74
-rw-r--r--src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/StandardTokenGenerator.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/StandardTokenGenerator.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/TokenHandlingBindingElement.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/TokenHandlingBindingElement.cs)6
-rw-r--r--src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ServiceProvider.cs (renamed from src/DotNetOpenAuth/OAuth/ServiceProvider.cs)56
-rw-r--r--src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/VerificationCodeFormat.cs (renamed from src/DotNetOpenAuth/OAuth/VerificationCodeFormat.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth.ServiceProvider/Properties/AssemblyInfo.cs56
-rw-r--r--src/DotNetOpenAuth.OAuth/Configuration/OAuthConsumerElement.cs (renamed from src/DotNetOpenAuth/Configuration/OAuthConsumerElement.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/Configuration/OAuthConsumerSecuritySettingsElement.cs (renamed from src/DotNetOpenAuth/Configuration/OAuthConsumerSecuritySettingsElement.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/Configuration/OAuthElement.cs (renamed from src/DotNetOpenAuth/Configuration/OAuthElement.cs)18
-rw-r--r--src/DotNetOpenAuth.OAuth/Configuration/OAuthServiceProviderElement.cs (renamed from src/DotNetOpenAuth/Configuration/OAuthServiceProviderElement.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/Configuration/OAuthServiceProviderSecuritySettingsElement.cs (renamed from src/DotNetOpenAuth/Configuration/OAuthServiceProviderSecuritySettingsElement.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/DotNetOpenAuth.OAuth.csproj94
-rw-r--r--src/DotNetOpenAuth.OAuth/Messaging/ITamperProtectionChannelBindingElement.cs (renamed from src/DotNetOpenAuth/Messaging/ITamperProtectionChannelBindingElement.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/HmacSha1SigningBindingElement.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/HmacSha1SigningBindingElement.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/ICombinedOpenIdProviderTokenManager.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/ICombinedOpenIdProviderTokenManager.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/IOpenIdOAuthTokenManager.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/IOpenIdOAuthTokenManager.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/ITamperResistantOAuthMessage.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/ITamperResistantOAuthMessage.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/ITokenManager.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/ITokenManager.cs)24
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/OAuthChannel.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/OAuthChannel.cs)179
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/OAuthHttpMethodBindingElement.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/OAuthHttpMethodBindingElement.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/PlaintextSigningBindingElement.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/PlaintextSigningBindingElement.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/RsaSha1SigningBindingElement.cs31
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementBase.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/SigningBindingElementBase.cs)10
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementBaseContract.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/SigningBindingElementBaseContract.cs)4
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementChain.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/SigningBindingElementChain.cs)7
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/TokenType.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/TokenType.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/UriOrOobEncoding.cs (renamed from src/DotNetOpenAuth/OAuth/ChannelElements/UriOrOobEncoding.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/ClassDiagram.cd (renamed from src/DotNetOpenAuth/OAuth/ClassDiagram.cd)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/ConsumerSecuritySettings.cs (renamed from src/DotNetOpenAuth/OAuth/ConsumerSecuritySettings.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/Messages/AccessProtectedResourceRequest.cs (renamed from src/DotNetOpenAuth/OAuth/Messages/AccessProtectedResourceRequest.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/Messages/AuthorizedTokenRequest.cs (renamed from src/DotNetOpenAuth/OAuth/Messages/AuthorizedTokenRequest.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/Messages/AuthorizedTokenResponse.cs (renamed from src/DotNetOpenAuth/OAuth/Messages/AuthorizedTokenResponse.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/Messages/ITokenContainingMessage.cs (renamed from src/DotNetOpenAuth/OAuth/Messages/ITokenContainingMessage.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/Messages/ITokenSecretContainingMessage.cs (renamed from src/DotNetOpenAuth/OAuth/Messages/ITokenSecretContainingMessage.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/Messages/MessageBase.cs (renamed from src/DotNetOpenAuth/OAuth/Messages/MessageBase.cs)10
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/Messages/OAuth Messages.cd (renamed from src/DotNetOpenAuth/OAuth/Messages/OAuth Messages.cd)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/Messages/SignedMessageBase.cs (renamed from src/DotNetOpenAuth/OAuth/Messages/SignedMessageBase.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/Messages/UnauthorizedTokenRequest.cs (renamed from src/DotNetOpenAuth/OAuth/Messages/UnauthorizedTokenRequest.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/Messages/UnauthorizedTokenResponse.cs (renamed from src/DotNetOpenAuth/OAuth/Messages/UnauthorizedTokenResponse.cs)4
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/Messages/UserAuthorizationRequest.cs (renamed from src/DotNetOpenAuth/OAuth/Messages/UserAuthorizationRequest.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/Messages/UserAuthorizationResponse.cs (renamed from src/DotNetOpenAuth/OAuth/Messages/UserAuthorizationResponse.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/OAuthStrings.Designer.cs (renamed from src/DotNetOpenAuth/OAuth/OAuthStrings.Designer.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/OAuthStrings.resx (renamed from src/DotNetOpenAuth/OAuth/OAuthStrings.resx)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/OAuthStrings.sr.resx (renamed from src/DotNetOpenAuth/OAuth/OAuthStrings.sr.resx)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/Protocol.cs (renamed from src/DotNetOpenAuth/OAuth/Protocol.cs)6
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/SecuritySettings.cs (renamed from src/DotNetOpenAuth/OAuth/SecuritySettings.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/ServiceProviderDescription.cs (renamed from src/DotNetOpenAuth/OAuth/ServiceProviderDescription.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuth/ServiceProviderSecuritySettings.cs (renamed from src/DotNetOpenAuth/OAuth/ServiceProviderSecuritySettings.cs)0
-rw-r--r--src/DotNetOpenAuth.OAuth/OAuthReporting.cs56
-rw-r--r--src/DotNetOpenAuth.OAuth/Properties/AssemblyInfo.cs62
-rw-r--r--src/DotNetOpenAuth.OAuth2.AuthorizationServer/DotNetOpenAuth.OAuth2.AuthorizationServer.csproj41
-rw-r--r--src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/AuthorizationServer.cs258
-rw-r--r--src/DotNetOpenAuth.OAuth2.AuthorizationServer/Properties/AssemblyInfo.cs54
-rw-r--r--src/DotNetOpenAuth.OAuth2.Client.UI/DotNetOpenAuth.OAuth2.Client.UI.csproj55
-rw-r--r--src/DotNetOpenAuth.OAuth2.Client.UI/OAuth2/ClientAuthorizationView.Designer.cs56
-rw-r--r--src/DotNetOpenAuth.OAuth2.Client.UI/OAuth2/ClientAuthorizationView.cs192
-rw-r--r--src/DotNetOpenAuth.OAuth2.Client.UI/OAuth2/ClientAuthorizationView.resx120
-rw-r--r--src/DotNetOpenAuth.OAuth2.Client.UI/Properties/AssemblyInfo.cs54
-rw-r--r--src/DotNetOpenAuth.OAuth2.Client/DotNetOpenAuth.OAuth2.Client.csproj43
-rw-r--r--src/DotNetOpenAuth.OAuth2.Client/OAuth2/ClientBase.cs256
-rw-r--r--src/DotNetOpenAuth.OAuth2.Client/OAuth2/UserAgentClient.cs123
-rw-r--r--src/DotNetOpenAuth.OAuth2.Client/OAuth2/WebServerClient.cs130
-rw-r--r--src/DotNetOpenAuth.OAuth2.Client/Properties/AssemblyInfo.cs54
-rw-r--r--src/DotNetOpenAuth.OAuth2.ResourceServer/DotNetOpenAuth.OAuth2.ResourceServer.csproj41
-rw-r--r--src/DotNetOpenAuth.OAuth2.ResourceServer/OAuth2/ResourceServer.cs136
-rw-r--r--src/DotNetOpenAuth.OAuth2.ResourceServer/Properties/AssemblyInfo.cs54
-rw-r--r--src/DotNetOpenAuth.OAuth2/DotNetOpenAuth.OAuth2.csproj100
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/AuthorizationServerDescription.cs62
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/AuthorizationState.cs93
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AccessRequestBindingElement.cs158
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AccessToken.cs102
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AccessTokenBindingElement.cs93
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthServerAllFlowsBindingElement.cs83
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthServerBindingElementBase.cs92
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthorizationCode.cs100
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthorizationCodeBindingElement.cs101
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthorizationDataBag.cs51
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/EndUserAuthorizationResponseTypeEncoder.cs66
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/GrantTypeEncoder.cs78
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/IAuthorizationCarryingRequest.cs54
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/IAuthorizationDescription.cs90
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2AuthorizationServerChannel.cs108
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2ChannelBase.cs69
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2ClientChannel.cs122
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2ResourceServerChannel.cs153
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/RefreshToken.cs56
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/ScopeEncoder.cs51
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/IAccessTokenAnalyzer.cs64
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/IAuthorizationServer.cs238
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/IAuthorizationState.cs67
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/IClientAuthorizationTracker.cs53
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/IConsumerDescription.cs101
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessProtectedResourceRequest.cs73
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenAuthorizationCodeRequest.cs94
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenClientCredentialsRequest.cs41
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenFailedResponse.cs86
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenRefreshRequest.cs75
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenRequestBase.cs78
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenResourceOwnerPasswordCredentialsRequest.cs50
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenSuccessResponse.cs99
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AuthenticatedClientRequestBase.cs42
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationFailedResponse.cs81
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationRequest.cs118
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationResponseType.cs25
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessAccessTokenResponse.cs121
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessAuthCodeResponse.cs76
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessResponseBase.cs69
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/Messages/GrantType.cs42
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/Messages/IAccessTokenRequest.cs37
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/Messages/IMessageWithClientState.cs21
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/Messages/MessageBase.cs239
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/Messages/OAuth 2 Messages.cd164
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/Messages/ScopedAccessTokenRequest.cs41
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/Messages/UnauthorizedResponse.cs115
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/OAuth 2 client facades.cd31
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/OAuthStrings.Designer.cs144
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/OAuthStrings.resx147
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/OAuthUtilities.cs123
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/Protocol.cs355
-rw-r--r--src/DotNetOpenAuth.OAuth2/OAuth2/StandardAccessTokenAnalyzer.cs66
-rw-r--r--src/DotNetOpenAuth.OAuth2/Properties/AssemblyInfo.cs60
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider.UI/DotNetOpenAuth.OpenId.Provider.UI.csproj59
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/AnonymousRequestEventArgs.cs (renamed from src/DotNetOpenAuth/OpenId/Provider/AnonymousRequestEventArgs.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/AuthenticationChallengeEventArgs.cs (renamed from src/DotNetOpenAuth/OpenId/Provider/AuthenticationChallengeEventArgs.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/IdentityEndpoint.cs (renamed from src/DotNetOpenAuth/OpenId/Provider/IdentityEndpoint.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/IdentityEndpointNormalizationEventArgs.cs (renamed from src/DotNetOpenAuth/OpenId/Provider/IdentityEndpointNormalizationEventArgs.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/ProviderEndpoint.cs (renamed from src/DotNetOpenAuth/OpenId/Provider/ProviderEndpoint.cs)31
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider.UI/Properties/AssemblyInfo.cs (renamed from src/DotNetOpenAuth/Properties/AssemblyInfo.cs)9
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/DotNetOpenAuth.OpenId.Provider.csproj88
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/AssociateUnencryptedProviderRequest.cs41
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/OpenIdProviderChannel.cs76
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/OpenIdProviderMessageFactory.cs86
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/ProviderSigningBindingElement.cs251
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateDiffieHellmanProviderRequest.cs43
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateDiffieHellmanProviderResponse.cs (renamed from src/DotNetOpenAuth/OpenId/Messages/AssociateDiffieHellmanResponse.cs)58
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateRequestProviderTools.cs100
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateSuccessfulResponseProvider.cs55
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateSuccessfulResponseProviderContract.cs96
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateUnencryptedResponseProvider.cs73
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/CheckAuthenticationResponseProvider.cs42
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/IAssociateRequestProvider.cs29
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AnonymousRequest.cs (renamed from src/DotNetOpenAuth/OpenId/Provider/AnonymousRequest.cs)4
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AssociationDataBag.cs95
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AssociationRelyingPartyType.cs26
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AuthenticationRequest.cs (renamed from src/DotNetOpenAuth/OpenId/Provider/AuthenticationRequest.cs)4
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AutoResponsiveRequest.cs (renamed from src/DotNetOpenAuth/OpenId/Provider/AutoResponsiveRequest.cs)4
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Behaviors/AXFetchAsSregTransform.cs (renamed from src/DotNetOpenAuth/OpenId/Behaviors/AXFetchAsSregTransform.cs)60
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Behaviors/GsaIcamProfile.cs (renamed from src/DotNetOpenAuth/OpenId/Behaviors/GsaIcamProfile.cs)100
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Behaviors/PpidGeneration.cs (renamed from src/DotNetOpenAuth/OpenId/Behaviors/PpidGeneration.cs)3
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Extensions/ExtensionsInteropHelper.cs162
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Extensions/UI/UIRequestTools.cs68
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/HmacShaAssociationProvider.cs71
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/HostProcessedRequest.cs (renamed from src/DotNetOpenAuth/OpenId/Provider/HostProcessedRequest.cs)24
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/IAnonymousRequest.cs (renamed from src/DotNetOpenAuth/OpenId/Provider/IAnonymousRequest.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/IDirectedIdentityIdentifierProvider.cs (renamed from src/DotNetOpenAuth/OpenId/Provider/IDirectedIdentityIdentifierProvider.cs)8
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/IErrorReporting.cs (renamed from src/DotNetOpenAuth/OpenId/Provider/IErrorReporting.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/IProviderAssociationStore.cs90
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/OpenIdProvider.cs (renamed from src/DotNetOpenAuth/OpenId/Provider/OpenIdProvider.cs)213
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/OpenIdProviderUtilities.cs70
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/PrivatePersonalIdentifierProviderBase.cs (renamed from src/DotNetOpenAuth/OpenId/Provider/PrivatePersonalIdentifierProviderBase.cs)9
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/ProviderAssociationHandleEncoder.cs84
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/ProviderAssociationKeyStorage.cs79
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Request.cs (renamed from src/DotNetOpenAuth/OpenId/Provider/Request.cs)10
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/RequestContract.cs (renamed from src/DotNetOpenAuth/OpenId/Provider/RequestContract.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/StandardProviderApplicationStore.cs117
-rw-r--r--src/DotNetOpenAuth.OpenId.Provider/Properties/AssemblyInfo.cs54
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/ComponentModel/IdentifierConverter.cs (renamed from src/DotNetOpenAuth/ComponentModel/IdentifierConverter.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/DotNetOpenAuth.OpenId.RelyingParty.UI.csproj87
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/Mvc/OpenIdAjaxOptions.cs (renamed from src/DotNetOpenAuth/Mvc/OpenIdAjaxOptions.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/Mvc/OpenIdHelper.cs (renamed from src/DotNetOpenAuth/Mvc/OpenIdHelper.cs)50
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/Controls.cd (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/Controls.cd)0
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxRelyingParty.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdAjaxRelyingParty.cs)14
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxTextBox.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdAjaxTextBox.cs)12
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxTextBox.css (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdAjaxTextBox.css)0
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxTextBox.js (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdAjaxTextBox.js)0
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdButton.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdButton.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdEventArgs.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdEventArgs.cs)4
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdLogin.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdLogin.cs)6
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdMobileTextBox.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdMobileTextBox.cs)20
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyAjaxControlBase.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingPartyAjaxControlBase.cs)10
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyAjaxControlBase.js (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingPartyAjaxControlBase.js)0
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyControlBase.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingPartyControlBase.cs)44
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyControlBase.js (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingPartyControlBase.js)0
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdSelector.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdSelector.cs)70
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdSelector.css (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdSelector.css)0
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdSelector.js (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdSelector.js)0
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdTextBox.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdTextBox.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/PopupBehavior.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/PopupBehavior.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/SelectorButton.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/SelectorButton.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/SelectorButtonContract.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/SelectorButtonContract.cs)6
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/SelectorOpenIdButton.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/SelectorOpenIdButton.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/SelectorProviderButton.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/SelectorProviderButton.cs)4
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/login_failure.png (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/login_failure.png)bin714 -> 714 bytes
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/login_success (lock).png (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/login_success (lock).png)bin571 -> 571 bytes
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/login_success.png (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/login_success.png)bin464 -> 464 bytes
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/openid_login.png (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/openid_login.png)bin457 -> 457 bytes
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/spinner.gif (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/spinner.gif)bin725 -> 725 bytes
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/Properties/AssemblyInfo.cs60
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/DotNetOpenAuth.OpenId.RelyingParty.csproj88
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/ExtensionsBindingElementRelyingParty.cs38
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/OpenIdRelyingPartyChannel.cs120
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/OpenIdRelyingPartyMessageFactory.cs (renamed from src/DotNetOpenAuth/OpenId/ChannelElements/OpenIdMessageFactory.cs)40
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/RelyingPartySecurityOptions.cs (renamed from src/DotNetOpenAuth/OpenId/ChannelElements/RelyingPartySecurityOptions.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/RelyingPartySigningBindingElement.cs110
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/ReturnToNonceBindingElement.cs (renamed from src/DotNetOpenAuth/OpenId/ChannelElements/ReturnToNonceBindingElement.cs)17
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/HostMetaDiscoveryService.cs (renamed from src/DotNetOpenAuth/OpenId/HostMetaDiscoveryService.cs)42
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Interop/AuthenticationResponseShim.cs (renamed from src/DotNetOpenAuth/OpenId/Interop/AuthenticationResponseShim.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Interop/ClaimsResponseShim.cs (renamed from src/DotNetOpenAuth/OpenId/Interop/ClaimsResponseShim.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Interop/OpenIdRelyingPartyShim.cs (renamed from src/DotNetOpenAuth/OpenId/Interop/OpenIdRelyingPartyShim.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/AssociateDiffieHellmanRelyingPartyResponse.cs50
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/AssociateRequestRelyingParty.cs83
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/AssociateSuccessfulResponseRelyingPartyContract.cs79
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/AssociateUnencryptedResponseRelyingParty.cs36
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/IAssociateSuccessfulResponseRelyingParty.cs27
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/AssociationManager.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/AssociationManager.cs)28
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/AssociationPreference.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/AssociationPreference.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Associations.cs (renamed from src/DotNetOpenAuth/OpenId/Associations.cs)8
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/AuthenticationRequest.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/AuthenticationRequest.cs)28
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Behaviors/AXFetchAsSregTransform.cs76
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Behaviors/GsaIcamProfile.cs124
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/CryptoKeyStoreAsRelyingPartyAssociationStore.cs87
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/DuplicateRequestedHostsComparer.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/DuplicateRequestedHostsComparer.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Extensions/ExtensionsInteropHelper.cs152
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Extensions/UIUtilities.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/UI/UIUtilities.cs)24
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/FailedAuthenticationResponse.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/FailedAuthenticationResponse.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/IRelyingPartyAssociationStore.cs153
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/ISetupRequiredAuthenticationResponse.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/ISetupRequiredAuthenticationResponse.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/NegativeAuthenticationResponse.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/NegativeAuthenticationResponse.cs)3
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/OpenIdRelyingParty.cd (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingParty.cd)0
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/OpenIdRelyingParty.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingParty.cs)100
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/PositiveAnonymousResponse.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/PositiveAnonymousResponse.cs)6
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/PositiveAuthenticationResponse.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/PositiveAuthenticationResponse.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/PositiveAuthenticationResponseSnapshot.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/PositiveAuthenticationResponseSnapshot.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/SimpleXrdsProviderEndpoint.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/SimpleXrdsProviderEndpoint.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/StandardRelyingPartyApplicationStore.cs110
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/WellKnownProviders.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/WellKnownProviders.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty/Properties/AssemblyInfo.cs58
-rw-r--r--src/DotNetOpenAuth.OpenId.UI/DotNetOpenAuth.OpenId.UI.csproj43
-rw-r--r--src/DotNetOpenAuth.OpenId.UI/Properties/AssemblyInfo.cs66
-rw-r--r--src/DotNetOpenAuth.OpenId.UI/XrdsPublisher.cs (renamed from src/DotNetOpenAuth/XrdsPublisher.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/Configuration/AssociationTypeCollection.cs (renamed from src/DotNetOpenAuth/Configuration/AssociationTypeCollection.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/Configuration/AssociationTypeElement.cs (renamed from src/DotNetOpenAuth/Configuration/AssociationTypeElement.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/Configuration/OpenIdElement.cs (renamed from src/DotNetOpenAuth/Configuration/OpenIdElement.cs)20
-rw-r--r--src/DotNetOpenAuth.OpenId/Configuration/OpenIdProviderElement.cs (renamed from src/DotNetOpenAuth/Configuration/OpenIdProviderElement.cs)10
-rw-r--r--src/DotNetOpenAuth.OpenId/Configuration/OpenIdProviderSecuritySettingsElement.cs (renamed from src/DotNetOpenAuth/Configuration/OpenIdProviderSecuritySettingsElement.cs)17
-rw-r--r--src/DotNetOpenAuth.OpenId/Configuration/OpenIdRelyingPartyElement.cs (renamed from src/DotNetOpenAuth/Configuration/OpenIdRelyingPartyElement.cs)9
-rw-r--r--src/DotNetOpenAuth.OpenId/Configuration/OpenIdRelyingPartySecuritySettingsElement.cs (renamed from src/DotNetOpenAuth/Configuration/OpenIdRelyingPartySecuritySettingsElement.cs)18
-rw-r--r--src/DotNetOpenAuth.OpenId/Configuration/XriResolverElement.cs (renamed from src/DotNetOpenAuth/Configuration/XriResolverElement.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/DotNetOpenAuth.OpenId.csproj188
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Association.cs (renamed from src/DotNetOpenAuth/OpenId/Association.cs)47
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/AssociationContract.cs (renamed from src/DotNetOpenAuth/OpenId/AssociationContract.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/AuthenticationRequestMode.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/AuthenticationRequestMode.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Behaviors/AXFetchAsSregTransformBase.cs37
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Behaviors/BehaviorStrings.Designer.cs (renamed from src/DotNetOpenAuth/OpenId/Behaviors/BehaviorStrings.Designer.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Behaviors/BehaviorStrings.resx (renamed from src/DotNetOpenAuth/OpenId/Behaviors/BehaviorStrings.resx)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Behaviors/BehaviorStrings.sr.resx (renamed from src/DotNetOpenAuth/OpenId/Behaviors/BehaviorStrings.sr.resx)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Behaviors/GsaIcamProfileBase.cs58
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/BackwardCompatibilityBindingElement.cs (renamed from src/DotNetOpenAuth/OpenId/ChannelElements/BackwardCompatibilityBindingElement.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/ExtensionsBindingElement.cs (renamed from src/DotNetOpenAuth/OpenId/ChannelElements/ExtensionsBindingElement.cs)19
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/IOpenIdExtensionFactory.cs (renamed from src/DotNetOpenAuth/OpenId/ChannelElements/IOpenIdExtensionFactory.cs)6
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/ITamperResistantOpenIdMessage.cs (renamed from src/DotNetOpenAuth/OpenId/ChannelElements/ITamperResistantOpenIdMessage.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/KeyValueFormEncoding.cs (renamed from src/DotNetOpenAuth/OpenId/ChannelElements/KeyValueFormEncoding.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/OpenIdChannel.cs (renamed from src/DotNetOpenAuth/OpenId/ChannelElements/OpenIdChannel.cs)154
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/OriginalStringUriEncoder.cs (renamed from src/DotNetOpenAuth/OpenId/ChannelElements/OriginalStringUriEncoder.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/ReturnToSignatureBindingElement.cs (renamed from src/DotNetOpenAuth/OpenId/ChannelElements/ReturnToSignatureBindingElement.cs)53
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SigningBindingElement.cs199
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SigningBindingElementContract.cs64
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SkipSecurityBindingElement.cs (renamed from src/DotNetOpenAuth/OpenId/ChannelElements/SkipSecurityBindingElement.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/DiffieHellmanUtilities.cs (renamed from src/DotNetOpenAuth/OpenId/DiffieHellmanUtilities.cs)20
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/AliasManager.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/AliasManager.cs)20
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/AXAttributeFormats.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/AXAttributeFormats.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/AXUtilities.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/AXUtilities.cs)12
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/AttributeRequest.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/AttributeRequest.cs)8
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/AttributeValues.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/AttributeValues.cs)4
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/Constants.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/Constants.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/FetchRequest.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/FetchRequest.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/FetchResponse.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/FetchResponse.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/StoreRequest.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/StoreRequest.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/StoreResponse.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/StoreResponse.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/WellKnownAttributes.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/WellKnownAttributes.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/ExtensionArgumentsManager.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/ExtensionArgumentsManager.cs)14
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/ExtensionBase.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/ExtensionBase.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/IClientScriptExtensionResponse.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/IClientScriptExtensionResponse.cs)1
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/OAuth/AuthorizationApprovedResponse.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/OAuth/AuthorizationApprovedResponse.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/OAuth/AuthorizationDeclinedResponse.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/OAuth/AuthorizationDeclinedResponse.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/OAuth/AuthorizationRequest.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/OAuth/AuthorizationRequest.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/OAuth/Constants.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/OAuth/Constants.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/OpenIdExtensionFactoryAggregator.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/OpenIdExtensionFactoryAggregator.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/OpenIdExtensionsInteropHelper.cs124
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/AuthenticationPolicies.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/AuthenticationPolicies.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/Constants.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/Constants.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/DateTimeEncoder.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/DateTimeEncoder.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/NistAssuranceLevel.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/NistAssuranceLevel.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/PapeUtilities.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/PapeUtilities.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyRequest.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyRequest.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyResponse.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyResponse.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/SimpleRegistration/ClaimsRequest.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/SimpleRegistration/ClaimsRequest.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/SimpleRegistration/ClaimsResponse.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/SimpleRegistration/ClaimsResponse.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/SimpleRegistration/Constants.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/SimpleRegistration/Constants.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/SimpleRegistration/DemandLevel.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/SimpleRegistration/DemandLevel.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/SimpleRegistration/Gender.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/SimpleRegistration/Gender.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/StandardOpenIdExtensionFactory.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/StandardOpenIdExtensionFactory.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/UI/UIConstants.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/UI/UIConstants.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/UI/UIModes.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/UI/UIModes.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/UI/UIRequest.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/UI/UIRequest.cs)64
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Extensions/UI/UIUtilities.cs28
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/HmacShaAssociation.cs (renamed from src/DotNetOpenAuth/OpenId/HmacShaAssociation.cs)92
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/IIdentifierDiscoveryService.cs (renamed from src/DotNetOpenAuth/OpenId/IIdentifierDiscoveryService.cs)4
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/IOpenIdApplicationStore.cs16
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/IProviderEndpoint.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/IProviderEndpoint.cs)3
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Identifier.cs (renamed from src/DotNetOpenAuth/OpenId/Identifier.cs)24
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/IdentifierContract.cs (renamed from src/DotNetOpenAuth/OpenId/IdentifierContract.cs)1
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/IdentifierDiscoveryResult.cs (renamed from src/DotNetOpenAuth/OpenId/IdentifierDiscoveryResult.cs)10
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateDiffieHellmanRequest.cs (renamed from src/DotNetOpenAuth/OpenId/Messages/AssociateDiffieHellmanRequest.cs)27
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateDiffieHellmanResponse.cs45
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateRequest.cs67
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateSuccessfulResponse.cs (renamed from src/DotNetOpenAuth/OpenId/Messages/AssociateSuccessfulResponse.cs)62
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateSuccessfulResponseContract.cs17
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateUnencryptedRequest.cs (renamed from src/DotNetOpenAuth/OpenId/Messages/AssociateUnencryptedRequest.cs)19
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateUnencryptedResponse.cs35
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateUnsuccessfulResponse.cs (renamed from src/DotNetOpenAuth/OpenId/Messages/AssociateUnsuccessfulResponse.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Messages/CheckAuthenticationRequest.cs (renamed from src/DotNetOpenAuth/OpenId/Messages/CheckAuthenticationRequest.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Messages/CheckAuthenticationResponse.cs (renamed from src/DotNetOpenAuth/OpenId/Messages/CheckAuthenticationResponse.cs)24
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Messages/CheckIdRequest.cs (renamed from src/DotNetOpenAuth/OpenId/Messages/CheckIdRequest.cs)1
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Messages/DirectErrorResponse.cs (renamed from src/DotNetOpenAuth/OpenId/Messages/DirectErrorResponse.cs)8
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Messages/DirectResponseBase.cs (renamed from src/DotNetOpenAuth/OpenId/Messages/DirectResponseBase.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Messages/IErrorMessage.cs (renamed from src/DotNetOpenAuth/OpenId/Messages/IErrorMessage.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Messages/IOpenIdMessageExtension.cs (renamed from src/DotNetOpenAuth/OpenId/Messages/IOpenIdMessageExtension.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Messages/IndirectErrorResponse.cs (renamed from src/DotNetOpenAuth/OpenId/Messages/IndirectErrorResponse.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Messages/IndirectResponseBase.cs (renamed from src/DotNetOpenAuth/OpenId/Messages/IndirectResponseBase.cs)6
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Messages/IndirectSignedResponse.cs (renamed from src/DotNetOpenAuth/OpenId/Messages/IndirectSignedResponse.cs)8
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Messages/NegativeAssertionResponse.cs (renamed from src/DotNetOpenAuth/OpenId/Messages/NegativeAssertionResponse.cs)7
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Messages/PositiveAssertionResponse.cs (renamed from src/DotNetOpenAuth/OpenId/Messages/PositiveAssertionResponse.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Messages/RequestBase.cs (renamed from src/DotNetOpenAuth/OpenId/Messages/RequestBase.cs)6
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Messages/SignedResponseRequest.cs (renamed from src/DotNetOpenAuth/OpenId/Messages/SignedResponseRequest.cs)5
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/NoDiscoveryIdentifier.cs (renamed from src/DotNetOpenAuth/OpenId/NoDiscoveryIdentifier.cs)3
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/OpenIdStrings.Designer.cs (renamed from src/DotNetOpenAuth/OpenId/OpenIdStrings.Designer.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/OpenIdStrings.resx (renamed from src/DotNetOpenAuth/OpenId/OpenIdStrings.resx)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/OpenIdStrings.sr.resx (renamed from src/DotNetOpenAuth/OpenId/OpenIdStrings.sr.resx)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/OpenIdUtilities.cs (renamed from src/DotNetOpenAuth/OpenId/OpenIdUtilities.cs)28
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/OpenIdXrdsHelper.cs68
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Protocol.cs (renamed from src/DotNetOpenAuth/OpenId/Protocol.cs)6
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Provider/IAuthenticationRequest.cs (renamed from src/DotNetOpenAuth/OpenId/Provider/IAuthenticationRequest.cs)14
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Provider/IHostProcessedRequest.cs (renamed from src/DotNetOpenAuth/OpenId/Provider/IHostProcessedRequest.cs)22
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Provider/IProviderBehavior.cs (renamed from src/DotNetOpenAuth/OpenId/Provider/IProviderBehavior.cs)6
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Provider/IRequest.cs (renamed from src/DotNetOpenAuth/OpenId/Provider/IRequest.cs)10
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Provider/ProviderSecuritySettings.cs (renamed from src/DotNetOpenAuth/OpenId/Provider/ProviderSecuritySettings.cs)13
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Provider/RelyingPartyDiscoveryResult.cs (renamed from src/DotNetOpenAuth/OpenId/Provider/RelyingPartyDiscoveryResult.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/ProviderEndpointDescription.cs (renamed from src/DotNetOpenAuth/OpenId/ProviderEndpointDescription.cs)8
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Realm.cs (renamed from src/DotNetOpenAuth/OpenId/Realm.cs)20
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/AuthenticationStatus.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/AuthenticationStatus.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationRequest.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/IAuthenticationRequest.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationRequestContract.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/IAuthenticationRequestContract.cs)20
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationResponse.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/IAuthenticationResponse.cs)10
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IRelyingPartyBehavior.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/IRelyingPartyBehavior.cs)6
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/RelyingPartySecuritySettings.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/RelyingPartySecuritySettings.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/RelyingPartyDescription.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingPartyDescription.cs)4
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/SecuritySettings.cs (renamed from src/DotNetOpenAuth/OpenId/SecuritySettings.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/UriDiscoveryService.cs (renamed from src/DotNetOpenAuth/OpenId/UriDiscoveryService.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/UriIdentifier.cs (renamed from src/DotNetOpenAuth/OpenId/UriIdentifier.cs)23
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/XriDiscoveryProxyService.cs (renamed from src/DotNetOpenAuth/OpenId/XriDiscoveryProxyService.cs)8
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/XriIdentifier.cs (renamed from src/DotNetOpenAuth/OpenId/XriIdentifier.cs)13
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenIdXrdsHelper.cs (renamed from src/DotNetOpenAuth/OpenId/OpenIdXrdsHelper.cs)75
-rw-r--r--src/DotNetOpenAuth.OpenId/Properties/AssemblyInfo.cs66
-rw-r--r--src/DotNetOpenAuth.OpenId/Xrds/ServiceElement.cs (renamed from src/DotNetOpenAuth/Xrds/ServiceElement.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/Xrds/TypeElement.cs (renamed from src/DotNetOpenAuth/Xrds/TypeElement.cs)4
-rw-r--r--src/DotNetOpenAuth.OpenId/Xrds/UriElement.cs (renamed from src/DotNetOpenAuth/Xrds/UriElement.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/Xrds/XrdElement.cs (renamed from src/DotNetOpenAuth/Xrds/XrdElement.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/Xrds/XrdsDocument.cs (renamed from src/DotNetOpenAuth/Xrds/XrdsDocument.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/Xrds/XrdsNode.cs (renamed from src/DotNetOpenAuth/Xrds/XrdsNode.cs)8
-rw-r--r--src/DotNetOpenAuth.OpenId/Xrds/XrdsStrings.Designer.cs (renamed from src/DotNetOpenAuth/Xrds/XrdsStrings.Designer.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/Xrds/XrdsStrings.resx (renamed from src/DotNetOpenAuth/Xrds/XrdsStrings.resx)0
-rw-r--r--src/DotNetOpenAuth.OpenId/Xrds/XrdsStrings.sr.resx (renamed from src/DotNetOpenAuth/Xrds/XrdsStrings.sr.resx)0
-rw-r--r--src/DotNetOpenAuth.OpenId/Yadis/ContentTypes.cs (renamed from src/DotNetOpenAuth/Yadis/ContentTypes.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/Yadis/DiscoveryResult.cs (renamed from src/DotNetOpenAuth/Yadis/DiscoveryResult.cs)0
-rw-r--r--src/DotNetOpenAuth.OpenId/Yadis/HtmlParser.cs (renamed from src/DotNetOpenAuth/Yadis/HtmlParser.cs)4
-rw-r--r--src/DotNetOpenAuth.OpenId/Yadis/Yadis.cs (renamed from src/DotNetOpenAuth/Yadis/Yadis.cs)6
-rw-r--r--src/DotNetOpenAuth.OpenIdInfoCard.UI/DotNetOpenAuth.OpenIdInfoCard.UI.csproj68
-rw-r--r--src/DotNetOpenAuth.OpenIdInfoCard.UI/OpenId/RelyingParty/OpenIdInfoCardSelector.cs125
-rw-r--r--src/DotNetOpenAuth.OpenIdInfoCard.UI/OpenId/RelyingParty/SelectorInfoCardButton.cs (renamed from src/DotNetOpenAuth/OpenId/RelyingParty/SelectorInfoCardButton.cs)2
-rw-r--r--src/DotNetOpenAuth.OpenIdInfoCard.UI/Properties/AssemblyInfo.cs84
-rw-r--r--src/DotNetOpenAuth.Test/App.config7
-rw-r--r--src/DotNetOpenAuth.Test/Configuration/SectionTests.cs8
-rw-r--r--src/DotNetOpenAuth.Test/CoordinatorBase.cs4
-rw-r--r--src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj118
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs4
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/CollectionAssert.cs10
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/MessageSerializerTests.cs33
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs18
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/Reflection/MessageDescriptionTests.cs10
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/ResponseTests.cs8
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/StandardMessageFactoryTests.cs178
-rw-r--r--src/DotNetOpenAuth.Test/Mocks/CoordinatingChannel.cs6
-rw-r--r--src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthConsumerChannel.cs (renamed from src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthChannel.cs)61
-rw-r--r--src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthServiceProviderChannel.cs163
-rw-r--r--src/DotNetOpenAuth.Test/Mocks/CoordinatingOutgoingWebResponse.cs10
-rw-r--r--src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs14
-rw-r--r--src/DotNetOpenAuth.Test/Mocks/MockIdentifier.cs6
-rw-r--r--src/DotNetOpenAuth.Test/Mocks/MockRealm.cs2
-rw-r--r--src/DotNetOpenAuth.Test/Mocks/TestBadChannel.cs4
-rw-r--r--src/DotNetOpenAuth.Test/Mocks/TestChannel.cs15
-rw-r--r--src/DotNetOpenAuth.Test/Mocks/TestDirectResponseMessageWithHttpStatus.cs12
-rw-r--r--src/DotNetOpenAuth.Test/OAuth/AppendixScenarios.cs4
-rw-r--r--src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs22
-rw-r--r--src/DotNetOpenAuth.Test/OAuth/OAuthCoordinator.cs12
-rw-r--r--src/DotNetOpenAuth.Test/OAuth2/MessageFactoryTests.cs127
-rw-r--r--src/DotNetOpenAuth.Test/OAuth2/OAuth2ChannelTests.cs21
-rw-r--r--src/DotNetOpenAuth.Test/OAuth2/OAuth2TestBase.cs15
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs24
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs21
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs18
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs2
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs50
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeRequestTests.cs2
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs16
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs3
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs14
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPResponseTests.cs4
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/IdentifierTests.cs2
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/Messages/AssociateRequestTests.cs4
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/Messages/IndirectSignedResponseTests.cs2
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/NonIdentityTests.cs8
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/OpenIdCoordinator.cs4
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs6
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs2
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/Provider/HostProcessedRequestTests.cs14
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs4
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/Provider/PerformanceTests.cs8
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/RelyingParty/AssociationsTests.cs (renamed from src/DotNetOpenAuth.Test/OpenId/AssociationsTests.cs)3
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/RelyingParty/IdentifierDiscoveryResultTests.cs4
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs2
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/XriIdentifierTests.cs2
-rw-r--r--src/DotNetOpenAuth.TestWeb/OpenIdProviderEndpoint.ashx2
-rw-r--r--src/DotNetOpenAuth.sln282
-rw-r--r--src/DotNetOpenAuth/Configuration/DotNetOpenAuthSection.cs134
-rw-r--r--src/DotNetOpenAuth/DotNetOpenAuth.csproj805
-rw-r--r--src/DotNetOpenAuth/DotNetOpenAuth.proj78
-rw-r--r--src/DotNetOpenAuth/Messaging/Reflection/MessageDescription.cs177
-rw-r--r--src/DotNetOpenAuth/OpenId/AssociationMemoryStore.cs133
-rw-r--r--src/DotNetOpenAuth/OpenId/ChannelElements/SigningBindingElement.cs415
-rw-r--r--src/DotNetOpenAuth/OpenId/DiffieHellman/DHParameters.cs31
-rw-r--r--src/DotNetOpenAuth/OpenId/Extensions/ExtensionsInteropHelper.cs383
-rw-r--r--src/DotNetOpenAuth/OpenId/IAssociationStore.cs189
-rw-r--r--src/DotNetOpenAuth/OpenId/Messages/AssociateRequest.cs215
-rw-r--r--src/DotNetOpenAuth/OpenId/Messages/AssociateSuccessfulResponseContract.cs29
-rw-r--r--src/DotNetOpenAuth/OpenId/Messages/AssociateUnencryptedResponse.cs67
-rw-r--r--src/DotNetOpenAuth/OpenId/Provider/IProviderApplicationStore.cs20
-rw-r--r--src/DotNetOpenAuth/OpenId/Provider/StandardProviderApplicationStore.cs131
-rw-r--r--src/DotNetOpenAuth/OpenId/RelyingParty/IRelyingPartyApplicationStore.cs21
-rw-r--r--src/DotNetOpenAuth/OpenId/RelyingParty/PrivateSecretManager.cs122
-rw-r--r--src/DotNetOpenAuth/OpenId/RelyingParty/StandardRelyingPartyApplicationStore.cs115
-rw-r--r--src/Mono.Math/BigInteger.cs (renamed from src/DotNetOpenAuth/OpenId/DiffieHellman/mono/BigInteger.cs)0
-rw-r--r--src/Mono.Math/ConfidenceFactor.cs (renamed from src/DotNetOpenAuth/OpenId/DiffieHellman/mono/ConfidenceFactor.cs)0
-rw-r--r--src/Mono.Math/Mono.Math.csproj46
-rw-r--r--src/Mono.Math/NextPrimeFinder.cs (renamed from src/DotNetOpenAuth/OpenId/DiffieHellman/mono/NextPrimeFinder.cs)0
-rw-r--r--src/Mono.Math/PrimalityTests.cs (renamed from src/DotNetOpenAuth/OpenId/DiffieHellman/mono/PrimalityTests.cs)0
-rw-r--r--src/Mono.Math/PrimeGeneratorBase.cs (renamed from src/DotNetOpenAuth/OpenId/DiffieHellman/mono/PrimeGeneratorBase.cs)0
-rw-r--r--src/Mono.Math/Properties/AssemblyInfo.cs52
-rw-r--r--src/Mono.Math/SequentialSearchPrimeGeneratorBase.cs (renamed from src/DotNetOpenAuth/OpenId/DiffieHellman/mono/SequentialSearchPrimeGeneratorBase.cs)0
-rw-r--r--src/Org.Mentalis.Security.Cryptography/DHKeyGeneration.cs (renamed from src/DotNetOpenAuth/OpenId/DiffieHellman/DHKeyGeneration.cs)8
-rw-r--r--src/Org.Mentalis.Security.Cryptography/DHParameters.cs38
-rw-r--r--src/Org.Mentalis.Security.Cryptography/DiffieHellman.cs (renamed from src/DotNetOpenAuth/OpenId/DiffieHellman/DiffieHellman.cs)9
-rw-r--r--src/Org.Mentalis.Security.Cryptography/DiffieHellmanManaged.cs (renamed from src/DotNetOpenAuth/OpenId/DiffieHellman/DiffieHellmanManaged.cs)9
-rw-r--r--src/Org.Mentalis.Security.Cryptography/Org.Mentalis.Security.Cryptography.csproj38
-rw-r--r--src/Org.Mentalis.Security.Cryptography/Properties/AssemblyInfo.cs60
-rw-r--r--src/version.txt2
655 files changed, 20430 insertions, 5342 deletions
diff --git a/src/.gitignore b/src/.gitignore
index 22d54e5..ad0e465 100644
--- a/src/.gitignore
+++ b/src/.gitignore
@@ -1,3 +1,6 @@
+Backup*
+_UpgradeReport_Files
+UpgradeLog.XML
PrecompiledWeb
_ReSharper.*
*.suo
diff --git a/src/DotNetOpenAuth.BuildTasks/ChangeProjectReferenceToAssemblyReference.cs b/src/DotNetOpenAuth.BuildTasks/ChangeProjectReferenceToAssemblyReference.cs
index fb42ade..a25701d 100644
--- a/src/DotNetOpenAuth.BuildTasks/ChangeProjectReferenceToAssemblyReference.cs
+++ b/src/DotNetOpenAuth.BuildTasks/ChangeProjectReferenceToAssemblyReference.cs
@@ -26,7 +26,7 @@
public ITaskItem[] ProjectReferences { get; set; }
/// <summary>
- /// The assembly references to add.
+ /// The assembly references to replace removed project references with.
/// </summary>
[Required]
public ITaskItem[] References { get; set; }
@@ -34,6 +34,9 @@
public override bool Execute() {
if (this.ProjectReferences.Length != this.References.Length) {
this.Log.LogError("ProjectReferences and References arrays do not have matching lengths.");
+ this.Log.LogError("ProjectReferences contents ({0} elements): {1}", this.ProjectReferences.Length, String.Join<ITaskItem>(";", this.ProjectReferences));
+ this.Log.LogError("References contents ({0} elements): {1}", this.References.Length, String.Join<ITaskItem>(";", this.References));
+ return false;
}
foreach (var project in Projects) {
@@ -50,8 +53,12 @@
doc.RemoveItem(matchingReference.Remove);
if (matchingReference.Add.ItemSpec != "REMOVE") {
this.Log.LogMessage("Adding assembly reference to \"{0}\" to \"{1}\".", matchingReference.Add.ItemSpec, project.ItemSpec);
- var newReference = doc.AddNewItem("Reference", Path.GetFileNameWithoutExtension(matchingReference.Add.ItemSpec), true);
- newReference.SetMetadata("HintPath", matchingReference.Add.ItemSpec);
+
+ string newItemSpec = Path.GetFileNameWithoutExtension(matchingReference.Add.ItemSpec);
+ if (!doc.GetEvaluatedItemsByName("Reference").OfType<BuildItem>().Any(bi => String.Equals(bi.Include, newItemSpec, StringComparison.OrdinalIgnoreCase))) {
+ var newReference = doc.AddNewItem("Reference", newItemSpec, true);
+ newReference.SetMetadata("HintPath", matchingReference.Add.ItemSpec);
+ }
}
}
diff --git a/src/DotNetOpenAuth.BuildTasks/DotNetOpenAuth.BuildTasks.csproj b/src/DotNetOpenAuth.BuildTasks/DotNetOpenAuth.BuildTasks.csproj
index 310ee9d..f7d7256 100644
--- a/src/DotNetOpenAuth.BuildTasks/DotNetOpenAuth.BuildTasks.csproj
+++ b/src/DotNetOpenAuth.BuildTasks/DotNetOpenAuth.BuildTasks.csproj
@@ -103,6 +103,7 @@
<Compile Include="ChangeProjectReferenceToAssemblyReference.cs" />
<Compile Include="CompareFiles.cs" />
<Compile Include="ChangeAssemblyReference.cs" />
+ <Compile Include="RegexFileReplace.cs" />
<Compile Include="CopyWithTokenSubstitution.cs" />
<Compile Include="CreateWebApplication.cs" />
<Compile Include="DeleteWebApplication.cs" />
diff --git a/src/DotNetOpenAuth.BuildTasks/DotNetOpenAuth.BuildTasks.sln b/src/DotNetOpenAuth.BuildTasks/DotNetOpenAuth.BuildTasks.sln
index 5c2ffbb..ddf80bd 100644
--- a/src/DotNetOpenAuth.BuildTasks/DotNetOpenAuth.BuildTasks.sln
+++ b/src/DotNetOpenAuth.BuildTasks/DotNetOpenAuth.BuildTasks.sln
@@ -10,13 +10,13 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
..\..\lib\DotNetOpenAuth.BuildTasks.targets = ..\..\lib\DotNetOpenAuth.BuildTasks.targets
..\..\tools\DotNetOpenAuth.Common.Settings.targets = ..\..\tools\DotNetOpenAuth.Common.Settings.targets
..\..\nuget\DotNetOpenAuth.nuspec = ..\..\nuget\DotNetOpenAuth.nuspec
+ ..\DotNetOpenAuth\DotNetOpenAuth.proj = ..\DotNetOpenAuth\DotNetOpenAuth.proj
..\..\tools\DotNetOpenAuth.props = ..\..\tools\DotNetOpenAuth.props
..\..\tools\DotNetOpenAuth.targets = ..\..\tools\DotNetOpenAuth.targets
..\..\tools\DotNetOpenAuth.Versioning.targets = ..\..\tools\DotNetOpenAuth.Versioning.targets
..\..\tools\drop.proj = ..\..\tools\drop.proj
..\..\EnlistmentInfo.props = ..\..\EnlistmentInfo.props
..\..\EnlistmentInfo.targets = ..\..\EnlistmentInfo.targets
- ..\..\nuget\nuget.proj = ..\..\nuget\nuget.proj
..\..\tools\ohloh.proj = ..\..\tools\ohloh.proj
..\..\projecttemplates\projecttemplates.proj = ..\..\projecttemplates\projecttemplates.proj
..\..\samples\Samples.proj = ..\..\samples\Samples.proj
@@ -29,14 +29,16 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.BuildTasks",
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NuGet", "NuGet", "{D49E2011-0E1C-4AB5-9887-BD1D42266503}"
ProjectSection(SolutionItems) = preProject
- ..\..\nuget\DotNetOpenAuth.nuspec = ..\..\nuget\DotNetOpenAuth.nuspec
+ ..\..\nuget\DotNetOpenAuth.Core.nuspec = ..\..\nuget\DotNetOpenAuth.Core.nuspec
+ ..\..\nuget\DotNetOpenAuth.OAuth.Consumer.nuspec = ..\..\nuget\DotNetOpenAuth.OAuth.Consumer.nuspec
+ ..\..\nuget\DotNetOpenAuth.OAuth.Core.nuspec = ..\..\nuget\DotNetOpenAuth.OAuth.Core.nuspec
+ ..\..\nuget\DotNetOpenAuth.OpenId.Core.nuspec = ..\..\nuget\DotNetOpenAuth.OpenId.Core.nuspec
+ ..\..\nuget\DotNetOpenAuth.OpenId.RelyingParty.nuspec = ..\..\nuget\DotNetOpenAuth.OpenId.RelyingParty.nuspec
+ ..\..\nuget\DotNetOpenAuth.Ultimate.nuspec = ..\..\nuget\DotNetOpenAuth.Ultimate.nuspec
..\..\nuget\nuget.proj = ..\..\nuget\nuget.proj
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "content", "content", "{BF3868D6-3BBA-4E40-B180-213370C15494}"
- ProjectSection(SolutionItems) = preProject
- ..\..\nuget\content\web.config.transform = ..\..\nuget\content\web.config.transform
- EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
diff --git a/src/DotNetOpenAuth.BuildTasks/DowngradeProjects.cs b/src/DotNetOpenAuth.BuildTasks/DowngradeProjects.cs
index 2f09583..380bd17 100644
--- a/src/DotNetOpenAuth.BuildTasks/DowngradeProjects.cs
+++ b/src/DotNetOpenAuth.BuildTasks/DowngradeProjects.cs
@@ -68,7 +68,7 @@ namespace DotNetOpenAuth.BuildTasks {
case ProjectClassification.VS2010Project:
this.Log.LogMessage(MessageImportance.Low, "Downgrading project \"{0}\".", taskItem.ItemSpec);
var project = new Project();
- project.Load(taskItem.ItemSpec);
+ project.Load(taskItem.ItemSpec, ProjectLoadSettings.IgnoreMissingImports);
project.DefaultToolsVersion = "3.5";
if (this.DowngradeMvc2ToMvc1) {
diff --git a/src/DotNetOpenAuth.BuildTasks/GetBuildVersion.cs b/src/DotNetOpenAuth.BuildTasks/GetBuildVersion.cs
index 9818885..50bc89f 100644
--- a/src/DotNetOpenAuth.BuildTasks/GetBuildVersion.cs
+++ b/src/DotNetOpenAuth.BuildTasks/GetBuildVersion.cs
@@ -35,6 +35,12 @@ namespace DotNetOpenAuth.BuildTasks {
public string GitCommitId { get; private set; }
/// <summary>
+ /// Gets the build number (JDate) for this version.
+ /// </summary>
+ [Output]
+ public int BuildNumber { get; private set; }
+
+ /// <summary>
/// The file that contains the version base (Major.Minor.Build) to use.
/// </summary>
[Required]
@@ -48,11 +54,12 @@ namespace DotNetOpenAuth.BuildTasks {
public override bool Execute() {
try {
Version typedVersion = ReadVersionFromFile();
- SimpleVersion = typedVersion.ToString();
+ this.SimpleVersion = typedVersion.ToString();
+ this.BuildNumber = this.CalculateJDate(DateTime.Now);
+
+ var fullVersion = new Version(typedVersion.Major, typedVersion.Minor, typedVersion.Build, this.BuildNumber);
+ this.Version = fullVersion.ToString();
- var fullVersion = new Version(typedVersion.Major, typedVersion.Minor, typedVersion.Build, CalculateJDate(DateTime.Now));
- Version = fullVersion.ToString();
-
this.GitCommitId = GetGitHeadCommitId();
} catch (ArgumentOutOfRangeException ex) {
Log.LogErrorFromException(ex);
diff --git a/src/DotNetOpenAuth.BuildTasks/NuGetPack.cs b/src/DotNetOpenAuth.BuildTasks/NuGetPack.cs
index 356c51f..91365e5 100644
--- a/src/DotNetOpenAuth.BuildTasks/NuGetPack.cs
+++ b/src/DotNetOpenAuth.BuildTasks/NuGetPack.cs
@@ -35,6 +35,16 @@ namespace DotNetOpenAuth.BuildTasks {
public ITaskItem OutputPackageDirectory { get; set; }
/// <summary>
+ /// Gets or sets the semicolon delimited list of properties to supply to the NuGet Pack command to perform token substitution.
+ /// </summary>
+ public string Properties { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to generate a symbols nuget package.
+ /// </summary>
+ public bool Symbols { get; set; }
+
+ /// <summary>
/// Returns the fully qualified path to the executable file.
/// </summary>
/// <returns>
@@ -63,15 +73,7 @@ namespace DotNetOpenAuth.BuildTasks {
Directory.CreateDirectory(Path.GetDirectoryName(this.OutputPackageDirectory.ItemSpec));
}
- string fullPackagePath = this.DeriveFullPackagePath();
- this.Log.LogMessage("Creating NuGet package '{0}'.", fullPackagePath);
-
bool result = base.Execute();
-
- if (result) {
- this.Log.LogMessage(MessageImportance.High, "Successfully created package '{0}'.", fullPackagePath);
- }
-
return result;
}
@@ -86,23 +88,14 @@ namespace DotNetOpenAuth.BuildTasks {
args.AppendSwitch("pack");
args.AppendFileNameIfNotNull(this.NuSpec);
- args.AppendSwitchIfNotNull("-b ", this.BaseDirectory);
- args.AppendSwitchIfNotNull("-o ", this.OutputPackageDirectory);
+ args.AppendSwitchIfNotNull("-BasePath ", this.BaseDirectory);
+ args.AppendSwitchIfNotNull("-OutputDirectory ", this.OutputPackageDirectory);
+ args.AppendSwitchIfNotNull("-Properties ", this.Properties);
+ if (this.Symbols) {
+ args.AppendSwitch("-Symbols");
+ }
return args.ToString();
}
-
- /// <summary>
- /// Derives the path to the generated .nupkg file.
- /// </summary>
- /// <returns>A relative path.</returns>
- private string DeriveFullPackagePath() {
- var spec = XDocument.Load(this.NuSpec.ItemSpec);
- var metadata = spec.Element("package").Element("metadata");
- string id = metadata.Element("id").Value;
- string version = metadata.Element("version").Value;
- string baseDirectory = this.OutputPackageDirectory != null ? this.OutputPackageDirectory.ItemSpec : String.Empty;
- return Path.Combine(baseDirectory, String.Format("{0}.{1}.nupkg", id, version));
- }
}
}
diff --git a/src/DotNetOpenAuth.BuildTasks/PathSegment.cs b/src/DotNetOpenAuth.BuildTasks/PathSegment.cs
index 1f17b5e..9179c82 100644
--- a/src/DotNetOpenAuth.BuildTasks/PathSegment.cs
+++ b/src/DotNetOpenAuth.BuildTasks/PathSegment.cs
@@ -292,12 +292,9 @@ namespace DotNetOpenAuth.BuildTasks {
if (match == null) {
match = new PathSegment(segments[segmentIndex], this);
this.Children.Add(match);
- if (segments.Length == segmentIndex + 1) {
- return match;
- }
}
- return match.Add(segments, segmentIndex + 1);
+ return segments.Length == segmentIndex + 1 ? match : match.Add(segments, segmentIndex + 1);
}
private PathSegment FindByOriginalPath(string[] segments, int segmentIndex) {
diff --git a/src/DotNetOpenAuth.BuildTasks/RegexFileReplace.cs b/src/DotNetOpenAuth.BuildTasks/RegexFileReplace.cs
new file mode 100644
index 0000000..294a859
--- /dev/null
+++ b/src/DotNetOpenAuth.BuildTasks/RegexFileReplace.cs
@@ -0,0 +1,55 @@
+//-----------------------------------------------------------------------
+// <copyright file="RegexFileReplace.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.BuildTasks {
+ using System;
+ using System.Collections.Generic;
+ using System.IO;
+ using System.Linq;
+ using System.Reflection;
+ using System.Text;
+ using Microsoft.Build.BuildEngine;
+ using Microsoft.Build.Framework;
+ using Microsoft.Build.Utilities;
+ using System.Text.RegularExpressions;
+
+ public class RegexFileReplace : Task {
+ /// <summary>
+ /// Gets or sets the set of files to search.
+ /// </summary>
+ [Required]
+ public ITaskItem[] Files { get; set; }
+
+ /// <summary>
+ /// Gets or sets the files to save the changed files to. This may be the same as the input files to make the change in place.
+ /// </summary>
+ public ITaskItem[] OutputFiles { get; set; }
+
+ public string Pattern { get; set; }
+
+ public string Replacement { get; set; }
+
+ /// <summary>
+ /// Executes this instance.
+ /// </summary>
+ public override bool Execute() {
+ if (this.OutputFiles == null || this.OutputFiles.Length == 0) {
+ this.OutputFiles = this.Files;
+ }
+
+ foreach (var file in this.Files) {
+ string[] lines = File.ReadAllLines(file.ItemSpec);
+ for (int i = 0; i < lines.Length; i++) {
+ lines[i] = Regex.Replace(lines[i], this.Pattern, this.Replacement);
+ }
+
+ File.WriteAllLines(file.ItemSpec, lines);
+ }
+
+ return !this.Log.HasLoggedErrors;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/ComponentModel/ClaimTypeSuggestions.cs b/src/DotNetOpenAuth.Core.UI/ComponentModel/ClaimTypeSuggestions.cs
index c9f4d96..c9f4d96 100644
--- a/src/DotNetOpenAuth/ComponentModel/ClaimTypeSuggestions.cs
+++ b/src/DotNetOpenAuth.Core.UI/ComponentModel/ClaimTypeSuggestions.cs
diff --git a/src/DotNetOpenAuth/ComponentModel/ConverterBase.cs b/src/DotNetOpenAuth.Core.UI/ComponentModel/ConverterBase.cs
index c41ac47..404d375 100644
--- a/src/DotNetOpenAuth/ComponentModel/ConverterBase.cs
+++ b/src/DotNetOpenAuth.Core.UI/ComponentModel/ConverterBase.cs
@@ -12,7 +12,7 @@ namespace DotNetOpenAuth.ComponentModel {
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Globalization;
-using System.Reflection;
+ using System.Reflection;
using System.Security;
using System.Security.Permissions;
diff --git a/src/DotNetOpenAuth/ComponentModel/SuggestedStringsConverter.cs b/src/DotNetOpenAuth.Core.UI/ComponentModel/SuggestedStringsConverter.cs
index 864d001..62a4b13 100644
--- a/src/DotNetOpenAuth/ComponentModel/SuggestedStringsConverter.cs
+++ b/src/DotNetOpenAuth.Core.UI/ComponentModel/SuggestedStringsConverter.cs
@@ -36,14 +36,14 @@ namespace DotNetOpenAuth.ComponentModel {
/// <param name="type">The type to reflect over.</param>
/// <returns>A collection of values.</returns>
internal static ICollection GetStandardValuesForCacheShared(Type type) {
- Contract.Requires<ArgumentNullException>(type != null);
+ Requires.NotNull(type, "type");
Contract.Ensures(Contract.Result<ICollection>() != null);
var fields = from field in type.GetFields(BindingFlags.Static | BindingFlags.Public)
select field.GetValue(null);
var properties = from prop in type.GetProperties(BindingFlags.Static | BindingFlags.Public)
select prop.GetValue(null, null);
- return (fields.Concat(properties)).ToArray();
+ return fields.Concat(properties).ToArray();
}
/// <summary>
diff --git a/src/DotNetOpenAuth/ComponentModel/SuggestedStringsConverterContract.cs b/src/DotNetOpenAuth.Core.UI/ComponentModel/SuggestedStringsConverterContract.cs
index 1573208..1573208 100644
--- a/src/DotNetOpenAuth/ComponentModel/SuggestedStringsConverterContract.cs
+++ b/src/DotNetOpenAuth.Core.UI/ComponentModel/SuggestedStringsConverterContract.cs
diff --git a/src/DotNetOpenAuth.Core.UI/DotNetOpenAuth.Core.UI.csproj b/src/DotNetOpenAuth.Core.UI/DotNetOpenAuth.Core.UI.csproj
new file mode 100644
index 0000000..eba7fbe
--- /dev/null
+++ b/src/DotNetOpenAuth.Core.UI/DotNetOpenAuth.Core.UI.csproj
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))\EnlistmentInfo.props" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))' != '' " />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" />
+ <PropertyGroup>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{173E7B8D-E751-46E2-A133-F72297C0D2F4}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>DotNetOpenAuth</RootNamespace>
+ <AssemblyName>DotNetOpenAuth.Core.UI</AssemblyName>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" />
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="ComponentModel\ClaimTypeSuggestions.cs" />
+ <Compile Include="ComponentModel\ConverterBase.cs" />
+ <Compile Include="ComponentModel\SuggestedStringsConverter.cs" />
+ <Compile Include="ComponentModel\SuggestedStringsConverterContract.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\DotNetOpenAuth.Core\DotNetOpenAuth.Core.csproj">
+ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project>
+ <Name>DotNetOpenAuth.Core</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
+</Project> \ No newline at end of file
diff --git a/src/DotNetOpenAuth.Core.UI/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth.Core.UI/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..3a94681
--- /dev/null
+++ b/src/DotNetOpenAuth.Core.UI/Properties/AssemblyInfo.cs
@@ -0,0 +1,74 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssemblyInfo.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+// We DON'T put an AssemblyVersionAttribute in here because it is generated in the build.
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Net;
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Security.Permissions;
+using System.Web.UI;
+
+[assembly: TagPrefix("DotNetOpenAuth", "dnoa")]
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("DotNetOpenAuth")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DotNetOpenAuth")]
+[assembly: AssemblyCopyright("Copyright © 2008")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+[assembly: NeutralResourcesLanguage("en-US")]
+[assembly: CLSCompliant(true)]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("7d73990c-47c0-4256-9f20-a893add9e289")]
+
+[assembly: ContractVerification(true)]
+
+#if StrongNameSigned
+// See comment at top of this file. We need this so that strong-naming doesn't
+// keep this assembly from being useful to shared host (medium trust) web sites.
+[assembly: AllowPartiallyTrustedCallers]
+
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.InfoCard, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.UI, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.RelyingParty, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.RelyingParty.UI, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider.UI, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
+#else
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.InfoCard")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.UI")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.RelyingParty")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.RelyingParty.UI")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider.UI")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
+#endif
diff --git a/src/DotNetOpenAuth.Core/Assumes.cs b/src/DotNetOpenAuth.Core/Assumes.cs
new file mode 100644
index 0000000..67205a2
--- /dev/null
+++ b/src/DotNetOpenAuth.Core/Assumes.cs
@@ -0,0 +1,97 @@
+//-----------------------------------------------------------------------
+// <copyright file="Assumes.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+
+ /// <summary>
+ /// Internal state consistency checks that throw an internal error exception when they fail.
+ /// </summary>
+ internal static class Assumes {
+ /// <summary>
+ /// Validates some expression describing the acceptable condition evaluates to true.
+ /// </summary>
+ /// <param name="condition">The expression that must evaluate to true to avoid an internal error exception.</param>
+ /// <param name="message">The message to include with the exception.</param>
+ [Pure, DebuggerStepThrough]
+ internal static void True(bool condition, string message = null) {
+ if (!condition) {
+ Fail(message);
+ }
+ }
+
+ /// <summary>
+ /// Validates some expression describing the acceptable condition evaluates to true.
+ /// </summary>
+ /// <param name="condition">The expression that must evaluate to true to avoid an internal error exception.</param>
+ /// <param name="unformattedMessage">The unformatted message.</param>
+ /// <param name="args">Formatting arguments.</param>
+ [Pure, DebuggerStepThrough]
+ internal static void True(bool condition, string unformattedMessage, params object[] args) {
+ if (!condition) {
+ Fail(String.Format(unformattedMessage, args));
+ }
+ }
+
+ /// <summary>
+ /// Throws an internal error exception.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ [Pure, DebuggerStepThrough]
+ internal static void Fail(string message = null) {
+ if (message != null) {
+ throw new InternalErrorException(message);
+ } else {
+ throw new InternalErrorException();
+ }
+ }
+
+ /// <summary>
+ /// An internal error exception that should never be caught.
+ /// </summary>
+ [Serializable]
+ private class InternalErrorException : Exception {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="InternalErrorException"/> class.
+ /// </summary>
+ internal InternalErrorException() {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="InternalErrorException"/> class.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ internal InternalErrorException(string message) : base(message) {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="InternalErrorException"/> class.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <param name="inner">The inner exception.</param>
+ internal InternalErrorException(string message, Exception inner) : base(message, inner) {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="InternalErrorException"/> class.
+ /// </summary>
+ /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
+ /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param>
+ /// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> parameter is null. </exception>
+ /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult"/> is zero (0). </exception>
+ protected InternalErrorException(
+ System.Runtime.Serialization.SerializationInfo info,
+ System.Runtime.Serialization.StreamingContext context)
+ : base(info, context) {
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.Core/CodeAnalysisDictionary.xml b/src/DotNetOpenAuth.Core/CodeAnalysisDictionary.xml
new file mode 100644
index 0000000..8c90df3
--- /dev/null
+++ b/src/DotNetOpenAuth.Core/CodeAnalysisDictionary.xml
@@ -0,0 +1,71 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<Dictionary>
+ <Words>
+ <!--
+ This is a list of case-insensitive words that exist in the dictionary
+ but you do not want to be recognized by IdentifiersShouldBeSpelledCorrectly.
+ Do not add deprecated terms to this list, instead add these to the
+ <Deprecated> section below.
+ -->
+ <Unrecognized>
+ <!--<Word>cb</Word>-->
+ </Unrecognized>
+ <!--
+ This is a list of case-insensitive words that do not exist in the dictionary
+ but you still want to be considered as recognized by
+ IdentifiersShouldBeSpelledCorrectly. Do not add compound words (e.g. 'FileName')
+ to this list as this will cause CompoundWordsShouldBeBeCasedCorrectly to fire on
+ usages of the compound word stating that they should be changed to their discrete equivalent
+ (for example 'FileName' -> 'Filename').
+ -->
+ <Recognized>
+ <Word>OAuth</Word>
+ <!--<Word>cryptoKeyStore</Word>
+ <Word>containingMessage</Word>
+ <Word>httpRequestInfo</Word>
+ <Word>faultedMessage</Word>
+ <Word>keyStore</Word>
+ <Word>authorizationServer</Word>
+ <Word>bytesToSign</Word>
+ <Word>clientCallback</Word>-->
+ </Recognized>
+ <Deprecated>
+ <!--
+ This is a list of deprecated terms with their preferred alternates and is
+ used by UsePreferredTerms. The deprecated terms are case-insensitive,
+ however, make sure to pascal-case the preferred alternates. If a word
+ does not have a preferred alternate, simply leave it blank.
+ -->
+ <!--<Term PreferredAlternate="EnterpriseServices">complus</Term>-->
+ </Deprecated>
+ <Compound>
+ <!--
+ This is a list of discrete terms with their compound alternates and is used by
+ CompoundWordsShouldBeCasedCorrectly. These are words that exist in the
+ dictionary as discrete terms, however, should actually be cased as compound words.
+ For example, 'Filename' exists in the dictionary and hence the spelling rules will
+ not see it as unrecognized but its actual preferred usage is 'FileName'; adding it
+ below causes CompoundWordsShouldBeCasedCorrectly to fire. The discrete terms are
+ case-insensitive, however, be sure to pascal-case the compound alternates.
+ Any discrete terms added below automatically get added to the list of discrete
+ exceptions to prevent CompoundWordsShouldBeCasedCorrectly from firing both on the
+ compound word (for example 'WhiteSpace') and its discrete alternate (for example
+ 'Whitespace').
+ -->
+ <Term CompoundAlternate="OAuth">oauth</Term>
+ <!--<Term CompoundAlternate="DataBind">databind</Term>-->
+ </Compound>
+ <DiscreteExceptions>
+ <!--
+ This is a list of case-insensitive exceptions to the CompoundWordsShouldBeCasedCorrectly
+ discrete term check. As this check works solely on the basis of whether two consecutive
+ tokens exists in the dictionary, it can have a high false positive rate. For example,
+ 'onset' exists in the dictionary but the user probably intended it to be 'OnSet'.
+ Adding this word below prevents this rule from firing telling the user to change 'OnSet'
+ to 'Onset'.
+ -->
+ <Term>oauth</Term>
+ <!--<Term>onset</Term>-->
+ </DiscreteExceptions>
+ </Words>
+</Dictionary> \ No newline at end of file
diff --git a/src/DotNetOpenAuth/Configuration/DotNetOpenAuth.xsd b/src/DotNetOpenAuth.Core/Configuration/DotNetOpenAuth.xsd
index 0b27948..d193776 100644
--- a/src/DotNetOpenAuth/Configuration/DotNetOpenAuth.xsd
+++ b/src/DotNetOpenAuth.Core/Configuration/DotNetOpenAuth.xsd
@@ -190,6 +190,25 @@
</xs:attribute>
</xs:complexType>
</xs:element>
+ <xs:element name="webResourceUrlProvider">
+ <xs:annotation>
+ <xs:documentation>
+ The type that implements the DotNetOpenAuth.IEmbeddedResourceRetrieval interface
+ to instantiate for obtaining URLs that fetch embedded resource streams.
+ Primarily useful when the System.Web.UI.Page class is not used in the ASP.NET pipeline.
+ </xs:documentation>
+ </xs:annotation>
+ <xs:complexType>
+ <xs:attribute name="type" type="xs:string" use="optional">
+ <xs:annotation>
+ <xs:documentation>
+ The fully-qualified name of the type that implements the IEmbeddedResourceRetrieval interface.
+ </xs:documentation>
+ </xs:annotation>
+ </xs:attribute>
+ <xs:attribute name="xaml" type="xs:string" use="optional" />
+ </xs:complexType>
+ </xs:element>
</xs:choice>
<xs:attribute name="lifetime" type="xs:string">
<xs:annotation>
@@ -218,6 +237,14 @@
</xs:documentation>
</xs:annotation>
</xs:attribute>
+ <xs:attribute name="relaxSslRequirements" type="xs:boolean" default="false">
+ <xs:annotation>
+ <xs:documentation>
+ Whether SSL requirements within the library are disabled/relaxed.
+ Use for TESTING ONLY.
+ </xs:documentation>
+ </xs:annotation>
+ </xs:attribute>
<xs:attribute name="maximumIndirectMessageUrlLength" type="xs:int" default="2048">
<xs:annotation>
<xs:documentation>
@@ -228,6 +255,13 @@
</xs:documentation>
</xs:annotation>
</xs:attribute>
+ <xs:attribute name="privateSecretMaximumAge" type="xs:string" default="28.00:00:00">
+ <xs:annotation>
+ <xs:documentation>
+ The maximum age of a secret used for private signing or encryption before it is renewed.
+ </xs:documentation>
+ </xs:annotation>
+ </xs:attribute>
</xs:complexType>
</xs:element>
<xs:element name="openid">
@@ -330,13 +364,6 @@
</xs:documentation>
</xs:annotation>
</xs:attribute>
- <xs:attribute name="privateSecretMaximumAge" type="xs:string">
- <xs:annotation>
- <xs:documentation>
- The maximum age of a secret used for private signing before it is renewed.
- </xs:documentation>
- </xs:annotation>
- </xs:attribute>
<xs:attribute name="requireDirectedIdentity" type="xs:boolean">
<xs:annotation>
<xs:documentation>
@@ -573,6 +600,15 @@
</xs:documentation>
</xs:annotation>
</xs:attribute>
+ <xs:attribute name="encodeAssociationSecretsInHandles" type="xs:boolean" default="true">
+ <xs:annotation>
+ <xs:documentation>
+ Whether the Provider should ease the burden of storing associations
+ by encoding their secrets (in signed, encrypted form) into the association handles themselves, storing only
+ a few rotating, private symmetric keys in the Provider's store instead.
+ </xs:documentation>
+ </xs:annotation>
+ </xs:attribute>
<xs:attribute name="unsolicitedAssertionVerification">
<xs:annotation>
<xs:documentation>
@@ -926,25 +962,6 @@
</xs:attribute>
</xs:complexType>
</xs:element>
- <xs:element name="webResourceUrlProvider">
- <xs:annotation>
- <xs:documentation>
- The type that implements the DotNetOpenAuth.IEmbeddedResourceRetrieval interface
- to instantiate for obtaining URLs that fetch embedded resource streams.
- Primarily useful when the System.Web.UI.Page class is not used in the ASP.NET pipeline.
- </xs:documentation>
- </xs:annotation>
- <xs:complexType>
- <xs:attribute name="type" type="xs:string" use="optional">
- <xs:annotation>
- <xs:documentation>
- The fully-qualified name of the type that implements the IEmbeddedResourceRetrieval interface.
- </xs:documentation>
- </xs:annotation>
- </xs:attribute>
- <xs:attribute name="xaml" type="xs:string" use="optional" />
- </xs:complexType>
- </xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
diff --git a/src/DotNetOpenAuth.Core/Configuration/DotNetOpenAuthSection.cs b/src/DotNetOpenAuth.Core/Configuration/DotNetOpenAuthSection.cs
new file mode 100644
index 0000000..e0c7fc4
--- /dev/null
+++ b/src/DotNetOpenAuth.Core/Configuration/DotNetOpenAuthSection.cs
@@ -0,0 +1,70 @@
+//-----------------------------------------------------------------------
+// <copyright file="DotNetOpenAuthSection.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Configuration {
+ using System;
+ using System.Configuration;
+ using System.Diagnostics.Contracts;
+ using System.Web;
+ using System.Web.Configuration;
+
+ /// <summary>
+ /// Represents the section in the host's .config file that configures
+ /// this library's settings.
+ /// </summary>
+ [ContractVerification(true)]
+ public class DotNetOpenAuthSection : ConfigurationSectionGroup {
+ /// <summary>
+ /// The name of the section under which this library's settings must be found.
+ /// </summary>
+ internal const string SectionName = "dotNetOpenAuth";
+
+ /// <summary>
+ /// The name of the &lt;openid&gt; sub-element.
+ /// </summary>
+ private const string OpenIdElementName = "openid";
+
+ /// <summary>
+ /// The name of the &lt;oauth&gt; sub-element.
+ /// </summary>
+ private const string OAuthElementName = "oauth";
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DotNetOpenAuthSection"/> class.
+ /// </summary>
+ internal DotNetOpenAuthSection() {
+ }
+
+ /// <summary>
+ /// Gets the messaging configuration element.
+ /// </summary>
+ public static MessagingElement Messaging {
+ get { return MessagingElement.Configuration; }
+ }
+
+ /// <summary>
+ /// Gets the reporting configuration element.
+ /// </summary>
+ internal static ReportingElement Reporting {
+ get { return ReportingElement.Configuration; }
+ }
+
+ /// <summary>
+ /// Gets a named section in this section group, or <c>null</c> if no such section is defined.
+ /// </summary>
+ /// <param name="name">The name of the section to obtain.</param>
+ /// <returns>The desired section, or null if it could not be obtained.</returns>
+ internal static ConfigurationSection GetNamedSection(string name) {
+ string fullyQualifiedSectionName = SectionName + "/" + name;
+ if (HttpContext.Current != null) {
+ return (ConfigurationSection)WebConfigurationManager.GetSection(fullyQualifiedSectionName);
+ } else {
+ var configuration = ConfigurationManager.OpenExeConfiguration(null);
+ return configuration != null ? configuration.GetSection(fullyQualifiedSectionName) : null;
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/Configuration/HostNameElement.cs b/src/DotNetOpenAuth.Core/Configuration/HostNameElement.cs
index 9df218e..9df218e 100644
--- a/src/DotNetOpenAuth/Configuration/HostNameElement.cs
+++ b/src/DotNetOpenAuth.Core/Configuration/HostNameElement.cs
diff --git a/src/DotNetOpenAuth/Configuration/HostNameOrRegexCollection.cs b/src/DotNetOpenAuth.Core/Configuration/HostNameOrRegexCollection.cs
index c7d963b..c7d963b 100644
--- a/src/DotNetOpenAuth/Configuration/HostNameOrRegexCollection.cs
+++ b/src/DotNetOpenAuth.Core/Configuration/HostNameOrRegexCollection.cs
diff --git a/src/DotNetOpenAuth/Configuration/MessagingElement.cs b/src/DotNetOpenAuth.Core/Configuration/MessagingElement.cs
index 28b34a3..7c3e242 100644
--- a/src/DotNetOpenAuth/Configuration/MessagingElement.cs
+++ b/src/DotNetOpenAuth.Core/Configuration/MessagingElement.cs
@@ -15,7 +15,12 @@ namespace DotNetOpenAuth.Configuration {
/// Represents the &lt;messaging&gt; element in the host's .config file.
/// </summary>
[ContractVerification(true)]
- public class MessagingElement : ConfigurationElement {
+ public class MessagingElement : ConfigurationSection {
+ /// <summary>
+ /// The name of the &lt;webResourceUrlProvider&gt; sub-element.
+ /// </summary>
+ private const string WebResourceUrlProviderName = "webResourceUrlProvider";
+
/// <summary>
/// The name of the &lt;untrustedWebRequest&gt; sub-element.
/// </summary>
@@ -32,6 +37,11 @@ namespace DotNetOpenAuth.Configuration {
private const string MaximumClockSkewConfigName = "clockSkew";
/// <summary>
+ /// The name of the attribute that indicates whether to disable SSL requirements across the library.
+ /// </summary>
+ private const string RelaxSslRequirementsConfigName = "relaxSslRequirements";
+
+ /// <summary>
/// The name of the attribute that controls whether messaging rules are strictly followed.
/// </summary>
private const string StrictConfigName = "strict";
@@ -51,6 +61,26 @@ namespace DotNetOpenAuth.Configuration {
private const string MaximumIndirectMessageUrlLengthConfigName = "maximumIndirectMessageUrlLength";
/// <summary>
+ /// Gets the name of the @privateSecretMaximumAge attribute.
+ /// </summary>
+ private const string PrivateSecretMaximumAgeConfigName = "privateSecretMaximumAge";
+
+ /// <summary>
+ /// The name of the &lt;messaging&gt; sub-element.
+ /// </summary>
+ private const string MessagingElementName = DotNetOpenAuthSection.SectionName + "/messaging";
+
+ /// <summary>
+ /// Gets the configuration section from the .config file.
+ /// </summary>
+ public static MessagingElement Configuration {
+ get {
+ Contract.Ensures(Contract.Result<MessagingElement>() != null);
+ return (MessagingElement)ConfigurationManager.GetSection(MessagingElementName) ?? new MessagingElement();
+ }
+ }
+
+ /// <summary>
/// Gets the actual maximum message lifetime that a program should allow.
/// </summary>
/// <value>The sum of the <see cref="MaximumMessageLifetime"/> and
@@ -60,6 +90,17 @@ namespace DotNetOpenAuth.Configuration {
}
/// <summary>
+ /// Gets or sets the maximum lifetime of a private symmetric secret,
+ /// that may be used for signing or encryption.
+ /// </summary>
+ /// <value>The default value is 28 days (twice the age of the longest association).</value>
+ [ConfigurationProperty(PrivateSecretMaximumAgeConfigName, DefaultValue = "28.00:00:00")]
+ public TimeSpan PrivateSecretMaximumAge {
+ get { return (TimeSpan)this[PrivateSecretMaximumAgeConfigName]; }
+ set { this[PrivateSecretMaximumAgeConfigName] = value; }
+ }
+
+ /// <summary>
/// Gets or sets the time between a message's creation and its receipt
/// before it is considered expired.
/// </summary>
@@ -102,6 +143,16 @@ namespace DotNetOpenAuth.Configuration {
}
/// <summary>
+ /// Gets or sets a value indicating whether SSL requirements within the library are disabled/relaxed.
+ /// Use for TESTING ONLY.
+ /// </summary>
+ [ConfigurationProperty(RelaxSslRequirementsConfigName, DefaultValue = false)]
+ internal bool RelaxSslRequirements {
+ get { return (bool)this[RelaxSslRequirementsConfigName]; }
+ set { this[RelaxSslRequirementsConfigName] = value; }
+ }
+
+ /// <summary>
/// Gets or sets a value indicating whether messaging rules are strictly
/// adhered to.
/// </summary>
@@ -142,5 +193,17 @@ namespace DotNetOpenAuth.Configuration {
get { return (int)this[MaximumIndirectMessageUrlLengthConfigName]; }
set { this[MaximumIndirectMessageUrlLengthConfigName] = value; }
}
+
+ /// <summary>
+ /// Gets or sets the embedded resource retrieval provider.
+ /// </summary>
+ /// <value>
+ /// The embedded resource retrieval provider.
+ /// </value>
+ [ConfigurationProperty(WebResourceUrlProviderName)]
+ internal TypeConfigurationElement<IEmbeddedResourceRetrieval> EmbeddedResourceRetrievalProvider {
+ get { return (TypeConfigurationElement<IEmbeddedResourceRetrieval>)this[WebResourceUrlProviderName] ?? new TypeConfigurationElement<IEmbeddedResourceRetrieval>(); }
+ set { this[WebResourceUrlProviderName] = value; }
+ }
}
}
diff --git a/src/DotNetOpenAuth/Configuration/ReportingElement.cs b/src/DotNetOpenAuth.Core/Configuration/ReportingElement.cs
index 2374448..a8eb7d3 100644
--- a/src/DotNetOpenAuth/Configuration/ReportingElement.cs
+++ b/src/DotNetOpenAuth.Core/Configuration/ReportingElement.cs
@@ -8,13 +8,14 @@ namespace DotNetOpenAuth.Configuration {
using System;
using System.Collections.Generic;
using System.Configuration;
+ using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
/// <summary>
/// Represents the &lt;reporting&gt; element in the host's .config file.
/// </summary>
- internal class ReportingElement : ConfigurationElement {
+ internal class ReportingElement : ConfigurationSection {
/// <summary>
/// The name of the @enabled attribute.
/// </summary>
@@ -51,6 +52,11 @@ namespace DotNetOpenAuth.Configuration {
private const string IncludeCulturesAttributeName = "includeCultures";
/// <summary>
+ /// The name of the &lt;reporting&gt; sub-element.
+ /// </summary>
+ private const string ReportingElementName = DotNetOpenAuthSection.SectionName + "/reporting";
+
+ /// <summary>
/// The default value for the @minimumFlushInterval attribute.
/// </summary>
#if DEBUG
@@ -66,6 +72,16 @@ namespace DotNetOpenAuth.Configuration {
}
/// <summary>
+ /// Gets the configuration section from the .config file.
+ /// </summary>
+ public static ReportingElement Configuration {
+ get {
+ Contract.Ensures(Contract.Result<ReportingElement>() != null);
+ return (ReportingElement)ConfigurationManager.GetSection(ReportingElementName) ?? new ReportingElement();
+ }
+ }
+
+ /// <summary>
/// Gets or sets a value indicating whether this reporting is enabled.
/// </summary>
/// <value><c>true</c> if enabled; otherwise, <c>false</c>.</value>
diff --git a/src/DotNetOpenAuth/Configuration/TrustedProviderConfigurationCollection.cs b/src/DotNetOpenAuth.Core/Configuration/TrustedProviderConfigurationCollection.cs
index f5e62f4..1a287fd 100644
--- a/src/DotNetOpenAuth/Configuration/TrustedProviderConfigurationCollection.cs
+++ b/src/DotNetOpenAuth.Core/Configuration/TrustedProviderConfigurationCollection.cs
@@ -32,7 +32,7 @@ namespace DotNetOpenAuth.Configuration {
/// <param name="elements">The elements to initialize the collection with.</param>
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "Seems unavoidable")]
internal TrustedProviderConfigurationCollection(IEnumerable<TrustedProviderEndpointConfigurationElement> elements) {
- Contract.Requires<ArgumentNullException>(elements != null);
+ Requires.NotNull(elements, "elements");
foreach (TrustedProviderEndpointConfigurationElement element in elements) {
this.BaseAdd(element);
diff --git a/src/DotNetOpenAuth/Configuration/TrustedProviderEndpointConfigurationElement.cs b/src/DotNetOpenAuth.Core/Configuration/TrustedProviderEndpointConfigurationElement.cs
index 2576eb0..2576eb0 100644
--- a/src/DotNetOpenAuth/Configuration/TrustedProviderEndpointConfigurationElement.cs
+++ b/src/DotNetOpenAuth.Core/Configuration/TrustedProviderEndpointConfigurationElement.cs
diff --git a/src/DotNetOpenAuth/Configuration/TypeConfigurationCollection.cs b/src/DotNetOpenAuth.Core/Configuration/TypeConfigurationCollection.cs
index 000cb6a..95b9c50 100644
--- a/src/DotNetOpenAuth/Configuration/TypeConfigurationCollection.cs
+++ b/src/DotNetOpenAuth.Core/Configuration/TypeConfigurationCollection.cs
@@ -31,10 +31,10 @@ namespace DotNetOpenAuth.Configuration {
/// </summary>
/// <param name="elements">The elements that should be added to the collection initially.</param>
internal TypeConfigurationCollection(IEnumerable<Type> elements) {
- Contract.Requires<ArgumentNullException>(elements != null);
+ Requires.NotNull(elements, "elements");
foreach (Type element in elements) {
- this.BaseAdd(new TypeConfigurationElement<T> { TypeName = element.FullName });
+ this.BaseAdd(new TypeConfigurationElement<T> { TypeName = element.AssemblyQualifiedName });
}
}
diff --git a/src/DotNetOpenAuth/Configuration/TypeConfigurationElement.cs b/src/DotNetOpenAuth.Core/Configuration/TypeConfigurationElement.cs
index 0335af5..fb1dee0 100644
--- a/src/DotNetOpenAuth/Configuration/TypeConfigurationElement.cs
+++ b/src/DotNetOpenAuth.Core/Configuration/TypeConfigurationElement.cs
@@ -11,7 +11,11 @@ namespace DotNetOpenAuth.Configuration {
using System.IO;
using System.Reflection;
using System.Web;
+#if CLR4
+ using System.Xaml;
+#else
using System.Windows.Markup;
+#endif
using DotNetOpenAuth.Messaging;
/// <summary>
@@ -127,7 +131,11 @@ namespace DotNetOpenAuth.Configuration {
/// </remarks>
private static T CreateInstanceFromXaml(Stream xaml) {
Contract.Ensures(Contract.Result<T>() != null);
+#if CLR4
+ return (T)XamlServices.Load(xaml);
+#else
return (T)XamlReader.Load(xaml);
+#endif
}
}
}
diff --git a/src/DotNetOpenAuth/Configuration/UntrustedWebRequestElement.cs b/src/DotNetOpenAuth.Core/Configuration/UntrustedWebRequestElement.cs
index 89cd435..43e41d9 100644
--- a/src/DotNetOpenAuth/Configuration/UntrustedWebRequestElement.cs
+++ b/src/DotNetOpenAuth.Core/Configuration/UntrustedWebRequestElement.cs
@@ -7,6 +7,7 @@
namespace DotNetOpenAuth.Configuration {
using System;
using System.Configuration;
+ using System.Diagnostics.Contracts;
/// <summary>
/// Represents the section of a .config file where security policies regarding web requests
diff --git a/src/DotNetOpenAuth.Core/DotNetOpenAuth.Core.csproj b/src/DotNetOpenAuth.Core/DotNetOpenAuth.Core.csproj
new file mode 100644
index 0000000..3692b4e
--- /dev/null
+++ b/src/DotNetOpenAuth.Core/DotNetOpenAuth.Core.csproj
@@ -0,0 +1,168 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))\EnlistmentInfo.props" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))' != '' " />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" />
+ <PropertyGroup>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{60426312-6AE5-4835-8667-37EDEA670222}</ProjectGuid>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <AssemblyName>DotNetOpenAuth.Core</AssemblyName>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" />
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="Assumes.cs" />
+ <Compile Include="Messaging\Bindings\AsymmetricCryptoKeyStoreWrapper.cs" />
+ <Compile Include="Messaging\Bindings\CryptoKey.cs" />
+ <Compile Include="Messaging\Bindings\CryptoKeyCollisionException.cs" />
+ <Compile Include="Messaging\Bindings\ICryptoKeyStore.cs" />
+ <Compile Include="Messaging\Bindings\MemoryCryptoKeyStore.cs" />
+ <Compile Include="Messaging\BinaryDataBagFormatter.cs" />
+ <Compile Include="Messaging\CachedDirectWebResponse.cs" />
+ <Compile Include="Messaging\ChannelContract.cs" />
+ <Compile Include="Messaging\DataBagFormatterBase.cs" />
+ <Compile Include="Messaging\IHttpIndirectResponse.cs" />
+ <Compile Include="Messaging\IMessageOriginalPayload.cs" />
+ <Compile Include="Messaging\DirectWebRequestOptions.cs" />
+ <Compile Include="Messaging\EnumerableCache.cs" />
+ <Compile Include="Messaging\HostErrorException.cs" />
+ <Compile Include="Messaging\IHttpDirectResponse.cs" />
+ <Compile Include="Messaging\IExtensionMessage.cs" />
+ <Compile Include="Messaging\IHttpDirectResponseContract.cs" />
+ <Compile Include="Messaging\IMessage.cs" />
+ <Compile Include="Messaging\IncomingWebResponse.cs" />
+ <Compile Include="Messaging\IDirectResponseProtocolMessage.cs" />
+ <Compile Include="Messaging\EmptyDictionary.cs" />
+ <Compile Include="Messaging\EmptyEnumerator.cs" />
+ <Compile Include="Messaging\EmptyList.cs" />
+ <Compile Include="Messaging\ErrorUtilities.cs" />
+ <Compile Include="Messaging\IMessageWithEvents.cs" />
+ <Compile Include="Messaging\IncomingWebResponseContract.cs" />
+ <Compile Include="Messaging\IProtocolMessageWithExtensions.cs" />
+ <Compile Include="Messaging\InternalErrorException.cs" />
+ <Compile Include="Messaging\IStreamSerializingDataBag.cs" />
+ <Compile Include="Messaging\KeyedCollectionDelegate.cs" />
+ <Compile Include="Messaging\MultipartPostPart.cs" />
+ <Compile Include="Messaging\NetworkDirectWebResponse.cs" />
+ <Compile Include="Messaging\OutgoingWebResponseActionResult.cs" />
+ <Compile Include="Messaging\Reflection\IMessagePartEncoder.cs" />
+ <Compile Include="Messaging\Reflection\IMessagePartNullEncoder.cs" />
+ <Compile Include="Messaging\Reflection\IMessagePartOriginalEncoder.cs" />
+ <Compile Include="Messaging\Reflection\MessageDescriptionCollection.cs" />
+ <Compile Include="Messaging\StandardMessageFactory.cs" />
+ <Compile Include="Messaging\IDataBagFormatter.cs" />
+ <Compile Include="Messaging\UriStyleMessageFormatter.cs" />
+ <Compile Include="Messaging\StandardMessageFactoryChannel.cs" />
+ <Compile Include="Messaging\DataBag.cs" />
+ <Compile Include="Messaging\TimestampEncoder.cs" />
+ <Compile Include="Messaging\IMessageWithBinaryData.cs" />
+ <Compile Include="Messaging\ChannelEventArgs.cs" />
+ <Compile Include="Messaging\Bindings\NonceMemoryStore.cs" />
+ <Compile Include="Messaging\IDirectWebRequestHandler.cs" />
+ <Compile Include="Messaging\Bindings\INonceStore.cs" />
+ <Compile Include="Messaging\Bindings\StandardReplayProtectionBindingElement.cs" />
+ <Compile Include="Messaging\MessagePartAttribute.cs" />
+ <Compile Include="Messaging\MessageProtections.cs" />
+ <Compile Include="Messaging\IChannelBindingElement.cs" />
+ <Compile Include="Messaging\Bindings\ReplayedMessageException.cs" />
+ <Compile Include="Messaging\Bindings\ExpiredMessageException.cs" />
+ <Compile Include="Messaging\Bindings\InvalidSignatureException.cs" />
+ <Compile Include="Messaging\Bindings\IReplayProtectedProtocolMessage.cs" />
+ <Compile Include="Messaging\Bindings\IExpiringProtocolMessage.cs" />
+ <Compile Include="Messaging\Channel.cs" />
+ <Compile Include="Messaging\HttpRequestInfo.cs" />
+ <Compile Include="Messaging\IDirectedProtocolMessage.cs" />
+ <Compile Include="Messaging\IMessageFactory.cs" />
+ <Compile Include="Messaging\ITamperResistantProtocolMessage.cs" />
+ <Compile Include="Messaging\MessageSerializer.cs" />
+ <Compile Include="Messaging\MessagingStrings.Designer.cs">
+ <AutoGen>True</AutoGen>
+ <DesignTime>True</DesignTime>
+ <DependentUpon>MessagingStrings.resx</DependentUpon>
+ </Compile>
+ <Compile Include="Messaging\MessagingUtilities.cs" />
+ <Compile Include="Messaging\Bindings\StandardExpirationBindingElement.cs" />
+ <Compile Include="Messaging\Reflection\ValueMapping.cs" />
+ <Compile Include="Messaging\Reflection\MessageDescription.cs" />
+ <Compile Include="Messaging\Reflection\MessageDictionary.cs" />
+ <Compile Include="Messaging\Reflection\MessagePart.cs" />
+ <Compile Include="Messaging\UnprotectedMessageException.cs" />
+ <Compile Include="Messaging\OutgoingWebResponse.cs" />
+ <Compile Include="Messaging\IProtocolMessage.cs" />
+ <Compile Include="Messaging\HttpDeliveryMethods.cs" />
+ <Compile Include="Messaging\MessageTransport.cs" />
+ <Compile Include="Messaging\ProtocolException.cs" />
+ <Compile Include="Messaging\TimespanSecondsEncoder.cs" />
+ <Compile Include="Messaging\UntrustedWebRequestHandler.cs" />
+ <Compile Include="Messaging\StandardWebRequestHandler.cs" />
+ <Compile Include="Messaging\MessageReceivingEndpoint.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="Messaging\Bindings\Bindings.cd" />
+ <None Include="Messaging\Exceptions.cd" />
+ <None Include="Messaging\Messaging.cd" />
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="Configuration\DotNetOpenAuthSection.cs" />
+ <Compile Include="Configuration\MessagingElement.cs" />
+ <Compile Include="Configuration\ReportingElement.cs" />
+ <Compile Include="Configuration\TrustedProviderConfigurationCollection.cs" />
+ <Compile Include="Configuration\TrustedProviderEndpointConfigurationElement.cs" />
+ <Compile Include="Configuration\TypeConfigurationCollection.cs" />
+ <Compile Include="Configuration\TypeConfigurationElement.cs" />
+ <Compile Include="Configuration\UntrustedWebRequestElement.cs" />
+ <Compile Include="Configuration\HostNameOrRegexCollection.cs" />
+ <Compile Include="Configuration\HostNameElement.cs" />
+ <Compile Include="IEmbeddedResourceRetrieval.cs" />
+ <Compile Include="GlobalSuppressions.cs" />
+ <Compile Include="Logger.cs" />
+ <Compile Include="Loggers\ILog.cs" />
+ <Compile Include="Loggers\Log4NetLogger.cs" />
+ <Compile Include="Loggers\NoOpLogger.cs" />
+ <Compile Include="Loggers\TraceLogger.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ <Compile Include="Reporting.cs" />
+ <Compile Include="Requires.cs" />
+ <Compile Include="Strings.Designer.cs">
+ <AutoGen>True</AutoGen>
+ <DesignTime>True</DesignTime>
+ <DependentUpon>Strings.resx</DependentUpon>
+ </Compile>
+ <Compile Include="UriUtil.cs" />
+ <Compile Include="Util.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="Configuration\DotNetOpenAuth.xsd" />
+ <None Include="Migrated rules for DotNetOpenAuth.ruleset" />
+ </ItemGroup>
+ <ItemGroup>
+ <EmbeddedResource Include="Strings.resx">
+ <Generator>ResXFileCodeGenerator</Generator>
+ <LastGenOutput>Strings.Designer.cs</LastGenOutput>
+ <SubType>Designer</SubType>
+ </EmbeddedResource>
+ </ItemGroup>
+ <ItemGroup>
+ <EmbeddedResource Include="Strings.sr.resx" />
+ </ItemGroup>
+ <ItemGroup>
+ <EmbeddedResource Include="Messaging\MessagingStrings.resx">
+ <Generator>ResXFileCodeGenerator</Generator>
+ <LastGenOutput>MessagingStrings.Designer.cs</LastGenOutput>
+ <SubType>Designer</SubType>
+ </EmbeddedResource>
+ </ItemGroup>
+ <ItemGroup>
+ <EmbeddedResource Include="Messaging\MessagingStrings.sr.resx" />
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
+</Project> \ No newline at end of file
diff --git a/src/DotNetOpenAuth/DotNetOpenAuth.ico b/src/DotNetOpenAuth.Core/DotNetOpenAuth.ico
index e227dbe..e227dbe 100644
--- a/src/DotNetOpenAuth/DotNetOpenAuth.ico
+++ b/src/DotNetOpenAuth.Core/DotNetOpenAuth.ico
Binary files differ
diff --git a/src/DotNetOpenAuth/GlobalSuppressions.cs b/src/DotNetOpenAuth.Core/GlobalSuppressions.cs
index 8539422..2bc6c04 100644
--- a/src/DotNetOpenAuth/GlobalSuppressions.cs
+++ b/src/DotNetOpenAuth.Core/GlobalSuppressions.cs
@@ -67,3 +67,4 @@ using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", MessageId = "iframe", Scope = "resource", Target = "DotNetOpenAuth.OpenId.OpenIdStrings.resources")]
[assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", MessageId = "Sig", Scope = "resource", Target = "DotNetOpenAuth.OpenId.OpenIdStrings.resources")]
[assembly: SuppressMessage("Microsoft.Naming", "CA1701:ResourceStringCompoundWordsShouldBeCasedCorrectly", MessageId = "DSig", Scope = "resource", Target = "DotNetOpenAuth.OpenId.OpenIdStrings.resources")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "DotNetOpenAuth.OAuth2.ChannelElements")]
diff --git a/src/DotNetOpenAuth/IEmbeddedResourceRetrieval.cs b/src/DotNetOpenAuth.Core/IEmbeddedResourceRetrieval.cs
index b9a6fd0..b9a6fd0 100644
--- a/src/DotNetOpenAuth/IEmbeddedResourceRetrieval.cs
+++ b/src/DotNetOpenAuth.Core/IEmbeddedResourceRetrieval.cs
diff --git a/src/DotNetOpenAuth/Logger.cs b/src/DotNetOpenAuth.Core/Logger.cs
index 48007ed..c9283cd 100644
--- a/src/DotNetOpenAuth/Logger.cs
+++ b/src/DotNetOpenAuth.Core/Logger.cs
@@ -142,7 +142,7 @@ namespace DotNetOpenAuth {
/// <param name="name">A name that will be included in the log file.</param>
/// <returns>The <see cref="ILog"/> instance created with the given name.</returns>
internal static ILog Create(string name) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(name));
+ Requires.NotNullOrEmpty(name, "name");
return InitializeFacade(name);
}
@@ -153,7 +153,7 @@ namespace DotNetOpenAuth {
/// <param name="name">A name that will be included in the log file.</param>
/// <returns>The <see cref="ILog"/> instance created with the given name.</returns>
internal static ILog CreateWithBanner(string name) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(name));
+ Requires.NotNullOrEmpty(name, "name");
ILog log = Create(name);
log.Info(Util.LibraryVersion);
return log;
@@ -165,7 +165,7 @@ namespace DotNetOpenAuth {
/// <param name="type">A type whose full name that will be included in the log file.</param>
/// <returns>The <see cref="ILog"/> instance created with the given type name.</returns>
internal static ILog Create(Type type) {
- Contract.Requires<ArgumentNullException>(type != null);
+ Requires.NotNull(type, "type");
return Create(type.FullName);
}
diff --git a/src/DotNetOpenAuth/Loggers/ILog.cs b/src/DotNetOpenAuth.Core/Loggers/ILog.cs
index 8094296..8094296 100644
--- a/src/DotNetOpenAuth/Loggers/ILog.cs
+++ b/src/DotNetOpenAuth.Core/Loggers/ILog.cs
diff --git a/src/DotNetOpenAuth/Loggers/Log4NetLogger.cs b/src/DotNetOpenAuth.Core/Loggers/Log4NetLogger.cs
index dd71a05..dd71a05 100644
--- a/src/DotNetOpenAuth/Loggers/Log4NetLogger.cs
+++ b/src/DotNetOpenAuth.Core/Loggers/Log4NetLogger.cs
diff --git a/src/DotNetOpenAuth/Loggers/NoOpLogger.cs b/src/DotNetOpenAuth.Core/Loggers/NoOpLogger.cs
index 7d1b37f..7d1b37f 100644
--- a/src/DotNetOpenAuth/Loggers/NoOpLogger.cs
+++ b/src/DotNetOpenAuth.Core/Loggers/NoOpLogger.cs
diff --git a/src/DotNetOpenAuth/Loggers/TraceLogger.cs b/src/DotNetOpenAuth.Core/Loggers/TraceLogger.cs
index 9b0bb0f..9b0bb0f 100644
--- a/src/DotNetOpenAuth/Loggers/TraceLogger.cs
+++ b/src/DotNetOpenAuth.Core/Loggers/TraceLogger.cs
diff --git a/src/DotNetOpenAuth.Core/Messaging/BinaryDataBagFormatter.cs b/src/DotNetOpenAuth.Core/Messaging/BinaryDataBagFormatter.cs
new file mode 100644
index 0000000..0c20955
--- /dev/null
+++ b/src/DotNetOpenAuth.Core/Messaging/BinaryDataBagFormatter.cs
@@ -0,0 +1,80 @@
+//-----------------------------------------------------------------------
+// <copyright file="BinaryDataBagFormatter.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.IO;
+ using System.Linq;
+ using System.Security.Cryptography;
+ using System.Text;
+ using DotNetOpenAuth.Messaging.Bindings;
+
+ /// <summary>
+ /// A compact binary <see cref="DataBag"/> serialization class.
+ /// </summary>
+ /// <typeparam name="T">The <see cref="DataBag"/>-derived type to serialize/deserialize.</typeparam>
+ internal class BinaryDataBagFormatter<T> : DataBagFormatterBase<T> where T : DataBag, IStreamSerializingDataBag, new() {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BinaryDataBagFormatter&lt;T&gt;"/> class.
+ /// </summary>
+ /// <param name="signingKey">The crypto service provider with the asymmetric key to use for signing or verifying the token.</param>
+ /// <param name="encryptingKey">The crypto service provider with the asymmetric key to use for encrypting or decrypting the token.</param>
+ /// <param name="compressed">A value indicating whether the data in this instance will be GZip'd.</param>
+ /// <param name="maximumAge">The maximum age of a token that can be decoded; useful only when <paramref name="decodeOnceOnly"/> is <c>true</c>.</param>
+ /// <param name="decodeOnceOnly">The nonce store to use to ensure that this instance is only decoded once.</param>
+ protected internal BinaryDataBagFormatter(RSACryptoServiceProvider signingKey = null, RSACryptoServiceProvider encryptingKey = null, bool compressed = false, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null)
+ : base(signingKey, encryptingKey, compressed, maximumAge, decodeOnceOnly) {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BinaryDataBagFormatter&lt;T&gt;"/> class.
+ /// </summary>
+ /// <param name="cryptoKeyStore">The crypto key store used when signing or encrypting.</param>
+ /// <param name="bucket">The bucket in which symmetric keys are stored for signing/encrypting data.</param>
+ /// <param name="signed">A value indicating whether the data in this instance will be protected against tampering.</param>
+ /// <param name="encrypted">A value indicating whether the data in this instance will be protected against eavesdropping.</param>
+ /// <param name="compressed">A value indicating whether the data in this instance will be GZip'd.</param>
+ /// <param name="minimumAge">The minimum age.</param>
+ /// <param name="maximumAge">The maximum age of a token that can be decoded; useful only when <paramref name="decodeOnceOnly"/> is <c>true</c>.</param>
+ /// <param name="decodeOnceOnly">The nonce store to use to ensure that this instance is only decoded once.</param>
+ protected internal BinaryDataBagFormatter(ICryptoKeyStore cryptoKeyStore = null, string bucket = null, bool signed = false, bool encrypted = false, bool compressed = false, TimeSpan? minimumAge = null, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null)
+ : base(cryptoKeyStore, bucket, signed, encrypted, compressed, minimumAge, maximumAge, decodeOnceOnly) {
+ Requires.True((cryptoKeyStore != null && bucket != null) || (!signed && !encrypted), null);
+ }
+
+ /// <summary>
+ /// Serializes the <see cref="DataBag"/> instance to a buffer.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <returns>The buffer containing the serialized data.</returns>
+ protected override byte[] SerializeCore(T message) {
+ using (var stream = new MemoryStream()) {
+ message.Serialize(stream);
+ return stream.ToArray();
+ }
+ }
+
+ /// <summary>
+ /// Deserializes the <see cref="DataBag"/> instance from a buffer.
+ /// </summary>
+ /// <param name="message">The message instance to initialize with data from the buffer.</param>
+ /// <param name="data">The data buffer.</param>
+ protected override void DeserializeCore(T message, byte[] data) {
+ using (var stream = new MemoryStream(data)) {
+ message.Deserialize(stream);
+ }
+
+ // Perform basic validation on message that the MessageSerializer would have normally performed.
+ var messageDescription = MessageDescriptions.Get(message);
+ var dictionary = messageDescription.GetDictionary(message);
+ messageDescription.EnsureMessagePartsPassBasicValidation(dictionary);
+ IMessage m = message;
+ m.EnsureValidMessage();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.Core/Messaging/Bindings/AsymmetricCryptoKeyStoreWrapper.cs b/src/DotNetOpenAuth.Core/Messaging/Bindings/AsymmetricCryptoKeyStoreWrapper.cs
new file mode 100644
index 0000000..2691202
--- /dev/null
+++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/AsymmetricCryptoKeyStoreWrapper.cs
@@ -0,0 +1,163 @@
+//-----------------------------------------------------------------------
+// <copyright file="AsymmetricCryptoKeyStoreWrapper.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging.Bindings {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Security.Cryptography;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// Provides RSA encryption of symmetric keys to protect them from a theft of
+ /// the persistent store.
+ /// </summary>
+ public class AsymmetricCryptoKeyStoreWrapper : ICryptoKeyStore {
+ /// <summary>
+ /// The persistent store for asymmetrically encrypted symmetric keys.
+ /// </summary>
+ private readonly ICryptoKeyStore dataStore;
+
+ /// <summary>
+ /// The memory cache of decrypted keys.
+ /// </summary>
+ private readonly MemoryCryptoKeyStore cache = new MemoryCryptoKeyStore();
+
+ /// <summary>
+ /// The asymmetric algorithm to use encrypting/decrypting the symmetric keys.
+ /// </summary>
+ private readonly RSACryptoServiceProvider asymmetricCrypto;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AsymmetricCryptoKeyStoreWrapper"/> class.
+ /// </summary>
+ /// <param name="dataStore">The data store.</param>
+ /// <param name="asymmetricCrypto">The asymmetric protection to apply to symmetric keys. Must include the private key.</param>
+ public AsymmetricCryptoKeyStoreWrapper(ICryptoKeyStore dataStore, RSACryptoServiceProvider asymmetricCrypto) {
+ Requires.NotNull(dataStore, "dataStore");
+ Requires.NotNull(asymmetricCrypto, "asymmetricCrypto");
+ Requires.True(!asymmetricCrypto.PublicOnly, "asymmetricCrypto");
+ this.dataStore = dataStore;
+ this.asymmetricCrypto = asymmetricCrypto;
+ }
+
+ /// <summary>
+ /// Gets the key in a given bucket and handle.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <param name="handle">The key handle. Case sensitive.</param>
+ /// <returns>
+ /// The cryptographic key, or <c>null</c> if no matching key was found.
+ /// </returns>
+ public CryptoKey GetKey(string bucket, string handle) {
+ var key = this.dataStore.GetKey(bucket, handle);
+ return this.Decrypt(bucket, handle, key);
+ }
+
+ /// <summary>
+ /// Gets a sequence of existing keys within a given bucket.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <returns>
+ /// A sequence of handles and keys, ordered by descending <see cref="CryptoKey.ExpiresUtc"/>.
+ /// </returns>
+ public IEnumerable<KeyValuePair<string, CryptoKey>> GetKeys(string bucket) {
+ return this.dataStore.GetKeys(bucket)
+ .Select(pair => new KeyValuePair<string, CryptoKey>(pair.Key, this.Decrypt(bucket, pair.Key, pair.Value)));
+ }
+
+ /// <summary>
+ /// Stores a cryptographic key.
+ /// </summary>
+ /// <param name="bucket">The name of the bucket to store the key in. Case sensitive.</param>
+ /// <param name="handle">The handle to the key, unique within the bucket. Case sensitive.</param>
+ /// <param name="decryptedCryptoKey">The key to store.</param>
+ [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", MessageId = "2#", Justification = "Helps readability because multiple keys are involved.")]
+ public void StoreKey(string bucket, string handle, CryptoKey decryptedCryptoKey) {
+ byte[] encryptedKey = this.asymmetricCrypto.Encrypt(decryptedCryptoKey.Key, true);
+ var encryptedCryptoKey = new CryptoKey(encryptedKey, decryptedCryptoKey.ExpiresUtc);
+ this.dataStore.StoreKey(bucket, handle, encryptedCryptoKey);
+
+ this.cache.StoreKey(bucket, handle, new CachedCryptoKey(encryptedCryptoKey, decryptedCryptoKey));
+ }
+
+ /// <summary>
+ /// Removes the key.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <param name="handle">The key handle. Case sensitive.</param>
+ public void RemoveKey(string bucket, string handle) {
+ this.dataStore.RemoveKey(bucket, handle);
+ this.cache.RemoveKey(bucket, handle);
+ }
+
+ /// <summary>
+ /// Decrypts the specified key.
+ /// </summary>
+ /// <param name="bucket">The bucket.</param>
+ /// <param name="handle">The handle.</param>
+ /// <param name="encryptedCryptoKey">The encrypted key.</param>
+ /// <returns>
+ /// The decrypted key.
+ /// </returns>
+ [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", MessageId = "2#", Justification = "Helps readability because multiple keys are involved.")]
+ private CryptoKey Decrypt(string bucket, string handle, CryptoKey encryptedCryptoKey) {
+ if (encryptedCryptoKey == null) {
+ return null;
+ }
+
+ // Avoid the asymmetric decryption if possible by looking up whether we have that in our cache.
+ CachedCryptoKey cached = (CachedCryptoKey)this.cache.GetKey(bucket, handle);
+ if (cached != null && MessagingUtilities.AreEquivalent(cached.EncryptedKey, encryptedCryptoKey.Key)) {
+ return cached;
+ }
+
+ byte[] decryptedKey = this.asymmetricCrypto.Decrypt(encryptedCryptoKey.Key, true);
+ var decryptedCryptoKey = new CryptoKey(decryptedKey, encryptedCryptoKey.ExpiresUtc);
+
+ // Store the decrypted version in the cache to save time next time.
+ this.cache.StoreKey(bucket, handle, new CachedCryptoKey(encryptedCryptoKey, decryptedCryptoKey));
+
+ return decryptedCryptoKey;
+ }
+
+ /// <summary>
+ /// An encrypted key and its decrypted equivalent.
+ /// </summary>
+ private class CachedCryptoKey : CryptoKey {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CachedCryptoKey"/> class.
+ /// </summary>
+ /// <param name="encrypted">The encrypted key.</param>
+ /// <param name="decrypted">The decrypted key.</param>
+ internal CachedCryptoKey(CryptoKey encrypted, CryptoKey decrypted)
+ : base(decrypted.Key, decrypted.ExpiresUtc) {
+ Contract.Requires(encrypted != null);
+ Contract.Requires(decrypted != null);
+ Contract.Requires(encrypted.ExpiresUtc == decrypted.ExpiresUtc);
+
+ this.EncryptedKey = encrypted.Key;
+ }
+
+ /// <summary>
+ /// Gets the encrypted key.
+ /// </summary>
+ internal byte[] EncryptedKey { get; private set; }
+
+ /// <summary>
+ /// Invariant conditions.
+ /// </summary>
+ [ContractInvariantMethod]
+ [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Required for code contracts.")]
+ private void ObjectInvariant() {
+ Contract.Invariant(this.EncryptedKey != null);
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/Bindings/Bindings.cd b/src/DotNetOpenAuth.Core/Messaging/Bindings/Bindings.cd
index e52e81e..e52e81e 100644
--- a/src/DotNetOpenAuth/Messaging/Bindings/Bindings.cd
+++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/Bindings.cd
diff --git a/src/DotNetOpenAuth.Core/Messaging/Bindings/CryptoKey.cs b/src/DotNetOpenAuth.Core/Messaging/Bindings/CryptoKey.cs
new file mode 100644
index 0000000..7160014
--- /dev/null
+++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/CryptoKey.cs
@@ -0,0 +1,93 @@
+//-----------------------------------------------------------------------
+// <copyright file="CryptoKey.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging.Bindings {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A cryptographic key and metadata concerning it.
+ /// </summary>
+ public class CryptoKey {
+ /// <summary>
+ /// Backing field for the <see cref="Key"/> property.
+ /// </summary>
+ private readonly byte[] key;
+
+ /// <summary>
+ /// Backing field for the <see cref="ExpiresUtc"/> property.
+ /// </summary>
+ private readonly DateTime expiresUtc;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CryptoKey"/> class.
+ /// </summary>
+ /// <param name="key">The cryptographic key.</param>
+ /// <param name="expiresUtc">The expires UTC.</param>
+ public CryptoKey(byte[] key, DateTime expiresUtc) {
+ Requires.NotNull(key, "key");
+ Requires.True(expiresUtc.Kind == DateTimeKind.Utc, "expiresUtc");
+ this.key = key;
+ this.expiresUtc = expiresUtc;
+ }
+
+ /// <summary>
+ /// Gets the key.
+ /// </summary>
+ [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "It's a buffer")]
+ public byte[] Key {
+ get {
+ Contract.Ensures(Contract.Result<byte[]>() != null);
+ return this.key;
+ }
+ }
+
+ /// <summary>
+ /// Gets the expiration date of this key (UTC time).
+ /// </summary>
+ public DateTime ExpiresUtc {
+ get {
+ Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Utc);
+ return this.expiresUtc;
+ }
+ }
+
+ /// <summary>
+ /// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
+ /// </summary>
+ /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
+ /// <returns>
+ /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
+ /// </returns>
+ /// <exception cref="T:System.NullReferenceException">
+ /// The <paramref name="obj"/> parameter is null.
+ /// </exception>
+ public override bool Equals(object obj) {
+ var other = obj as CryptoKey;
+ if (other == null) {
+ return false;
+ }
+
+ return this.ExpiresUtc == other.ExpiresUtc
+ && MessagingUtilities.AreEquivalent(this.Key, other.Key);
+ }
+
+ /// <summary>
+ /// Returns a hash code for this instance.
+ /// </summary>
+ /// <returns>
+ /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
+ /// </returns>
+ public override int GetHashCode() {
+ return this.ExpiresUtc.GetHashCode();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.Core/Messaging/Bindings/CryptoKeyCollisionException.cs b/src/DotNetOpenAuth.Core/Messaging/Bindings/CryptoKeyCollisionException.cs
new file mode 100644
index 0000000..ebd29de
--- /dev/null
+++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/CryptoKeyCollisionException.cs
@@ -0,0 +1,68 @@
+//-----------------------------------------------------------------------
+// <copyright file="CryptoKeyCollisionException.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging.Bindings {
+ using System;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Security.Permissions;
+
+ /// <summary>
+ /// Thrown by a hosting application or web site when a cryptographic key is created with a
+ /// bucket and handle that conflicts with a previously stored and unexpired key.
+ /// </summary>
+ [SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors", Justification = "Specialized exception has no need of a message parameter.")]
+ [Serializable]
+ public class CryptoKeyCollisionException : ArgumentException {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CryptoKeyCollisionException"/> class.
+ /// </summary>
+ public CryptoKeyCollisionException() {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CryptoKeyCollisionException"/> class.
+ /// </summary>
+ /// <param name="inner">The inner exception to include.</param>
+ public CryptoKeyCollisionException(Exception inner) : base(null, inner) {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CryptoKeyCollisionException"/> class.
+ /// </summary>
+ /// <param name="info">The <see cref="System.Runtime.Serialization.SerializationInfo"/>
+ /// that holds the serialized object data about the exception being thrown.</param>
+ /// <param name="context">The System.Runtime.Serialization.StreamingContext
+ /// that contains contextual information about the source or destination.</param>
+ protected CryptoKeyCollisionException(
+ System.Runtime.Serialization.SerializationInfo info,
+ System.Runtime.Serialization.StreamingContext context)
+ : base(info, context) {
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// When overridden in a derived class, sets the <see cref="T:System.Runtime.Serialization.SerializationInfo"/> with information about the exception.
+ /// </summary>
+ /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
+ /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param>
+ /// <exception cref="T:System.ArgumentNullException">
+ /// The <paramref name="info"/> parameter is a null reference (Nothing in Visual Basic).
+ /// </exception>
+ /// <PermissionSet>
+ /// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Read="*AllFiles*" PathDiscovery="*AllFiles*"/>
+ /// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="SerializationFormatter"/>
+ /// </PermissionSet>
+#if CLR4
+ [System.Security.SecurityCritical]
+#else
+ [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
+#endif
+ public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) {
+ base.GetObjectData(info, context);
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/Bindings/ExpiredMessageException.cs b/src/DotNetOpenAuth.Core/Messaging/Bindings/ExpiredMessageException.cs
index 73ce289..196946d 100644
--- a/src/DotNetOpenAuth/Messaging/Bindings/ExpiredMessageException.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/ExpiredMessageException.cs
@@ -21,7 +21,8 @@ namespace DotNetOpenAuth.Messaging.Bindings {
/// <param name="faultedMessage">The expired message.</param>
public ExpiredMessageException(DateTime utcExpirationDate, IProtocolMessage faultedMessage)
: base(string.Format(CultureInfo.CurrentCulture, MessagingStrings.ExpiredMessage, utcExpirationDate.ToLocalTime(), DateTime.Now), faultedMessage) {
- Contract.Requires<ArgumentException>(utcExpirationDate.Kind == DateTimeKind.Utc);
+ Requires.True(utcExpirationDate.Kind == DateTimeKind.Utc, "utcExpirationDate");
+ Requires.NotNull(faultedMessage, "faultedMessage");
}
/// <summary>
diff --git a/src/DotNetOpenAuth.Core/Messaging/Bindings/ICryptoKeyStore.cs b/src/DotNetOpenAuth.Core/Messaging/Bindings/ICryptoKeyStore.cs
new file mode 100644
index 0000000..861ba89
--- /dev/null
+++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/ICryptoKeyStore.cs
@@ -0,0 +1,118 @@
+//-----------------------------------------------------------------------
+// <copyright file="ICryptoKeyStore.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging.Bindings {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A persistent store for rotating symmetric cryptographic keys.
+ /// </summary>
+ /// <remarks>
+ /// Implementations should persist it in such a way that the keys are shared across all servers
+ /// on a web farm, where applicable.
+ /// The store should consider protecting the persistent store against theft resulting in the loss
+ /// of the confidentiality of the keys. One possible mitigation is to asymmetrically encrypt
+ /// each key using a certificate installed in the server's certificate store.
+ /// </remarks>
+ [ContractClass(typeof(ICryptoKeyStoreContract))]
+ public interface ICryptoKeyStore {
+ /// <summary>
+ /// Gets the key in a given bucket and handle.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <param name="handle">The key handle. Case sensitive.</param>
+ /// <returns>The cryptographic key, or <c>null</c> if no matching key was found.</returns>
+ CryptoKey GetKey(string bucket, string handle);
+
+ /// <summary>
+ /// Gets a sequence of existing keys within a given bucket.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <returns>A sequence of handles and keys, ordered by descending <see cref="CryptoKey.ExpiresUtc"/>.</returns>
+ [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Important for scalability")]
+ IEnumerable<KeyValuePair<string, CryptoKey>> GetKeys(string bucket);
+
+ /// <summary>
+ /// Stores a cryptographic key.
+ /// </summary>
+ /// <param name="bucket">The name of the bucket to store the key in. Case sensitive.</param>
+ /// <param name="handle">The handle to the key, unique within the bucket. Case sensitive.</param>
+ /// <param name="key">The key to store.</param>
+ /// <exception cref="CryptoKeyCollisionException">Thrown in the event of a conflict with an existing key in the same bucket and with the same handle.</exception>
+ void StoreKey(string bucket, string handle, CryptoKey key);
+
+ /// <summary>
+ /// Removes the key.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <param name="handle">The key handle. Case sensitive.</param>
+ void RemoveKey(string bucket, string handle);
+ }
+
+ /// <summary>
+ /// Code contract for the <see cref="ICryptoKeyStore"/> interface.
+ /// </summary>
+ [ContractClassFor(typeof(ICryptoKeyStore))]
+ internal abstract class ICryptoKeyStoreContract : ICryptoKeyStore {
+ /// <summary>
+ /// Gets the key in a given bucket and handle.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <param name="handle">The key handle. Case sensitive.</param>
+ /// <returns>
+ /// The cryptographic key, or <c>null</c> if no matching key was found.
+ /// </returns>
+ CryptoKey ICryptoKeyStore.GetKey(string bucket, string handle) {
+ Requires.NotNullOrEmpty(bucket, "bucket");
+ Requires.NotNullOrEmpty(handle, "handle");
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Gets a sequence of existing keys within a given bucket.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <returns>
+ /// A sequence of handles and keys, ordered by descending <see cref="CryptoKey.ExpiresUtc"/>.
+ /// </returns>
+ IEnumerable<KeyValuePair<string, CryptoKey>> ICryptoKeyStore.GetKeys(string bucket) {
+ Requires.NotNullOrEmpty(bucket, "bucket");
+ Contract.Ensures(Contract.Result<IEnumerable<KeyValuePair<string, CryptoKey>>>() != null);
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Stores a cryptographic key.
+ /// </summary>
+ /// <param name="bucket">The name of the bucket to store the key in. Case sensitive.</param>
+ /// <param name="handle">The handle to the key, unique within the bucket. Case sensitive.</param>
+ /// <param name="key">The key to store.</param>
+ /// <exception cref="CryptoKeyCollisionException">Thrown in the event of a conflict with an existing key in the same bucket and with the same handle.</exception>
+ void ICryptoKeyStore.StoreKey(string bucket, string handle, CryptoKey key) {
+ Requires.NotNullOrEmpty(bucket, "bucket");
+ Requires.NotNullOrEmpty(handle, "handle");
+ Requires.NotNull(key, "key");
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Removes the key.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <param name="handle">The key handle. Case sensitive.</param>
+ void ICryptoKeyStore.RemoveKey(string bucket, string handle) {
+ Requires.NotNullOrEmpty(bucket, "bucket");
+ Requires.NotNullOrEmpty(handle, "handle");
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/Bindings/IExpiringProtocolMessage.cs b/src/DotNetOpenAuth.Core/Messaging/Bindings/IExpiringProtocolMessage.cs
index fc43ae6..fc43ae6 100644
--- a/src/DotNetOpenAuth/Messaging/Bindings/IExpiringProtocolMessage.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/IExpiringProtocolMessage.cs
diff --git a/src/DotNetOpenAuth/Messaging/Bindings/INonceStore.cs b/src/DotNetOpenAuth.Core/Messaging/Bindings/INonceStore.cs
index 6b6e2e1..7a3e8bb 100644
--- a/src/DotNetOpenAuth/Messaging/Bindings/INonceStore.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/INonceStore.cs
@@ -31,7 +31,7 @@ namespace DotNetOpenAuth.Messaging.Bindings {
/// be processed within before being discarded as an expired message.
/// This maximum message age can be looked up via the
/// <see cref="DotNetOpenAuth.Configuration.MessagingElement.MaximumMessageLifetime"/>
- /// property, accessible via the <see cref="DotNetOpenAuth.Configuration.DotNetOpenAuthSection.Configuration"/>
+ /// property, accessible via the <see cref="DotNetOpenAuth.Configuration.MessagingElement.Configuration"/>
/// property.
/// </remarks>
bool StoreNonce(string context, string nonce, DateTime timestampUtc);
diff --git a/src/DotNetOpenAuth/Messaging/Bindings/IReplayProtectedProtocolMessage.cs b/src/DotNetOpenAuth.Core/Messaging/Bindings/IReplayProtectedProtocolMessage.cs
index 1edf934..1edf934 100644
--- a/src/DotNetOpenAuth/Messaging/Bindings/IReplayProtectedProtocolMessage.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/IReplayProtectedProtocolMessage.cs
diff --git a/src/DotNetOpenAuth/Messaging/Bindings/InvalidSignatureException.cs b/src/DotNetOpenAuth.Core/Messaging/Bindings/InvalidSignatureException.cs
index 28b7e96..28b7e96 100644
--- a/src/DotNetOpenAuth/Messaging/Bindings/InvalidSignatureException.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/InvalidSignatureException.cs
diff --git a/src/DotNetOpenAuth.Core/Messaging/Bindings/MemoryCryptoKeyStore.cs b/src/DotNetOpenAuth.Core/Messaging/Bindings/MemoryCryptoKeyStore.cs
new file mode 100644
index 0000000..63d1953
--- /dev/null
+++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/MemoryCryptoKeyStore.cs
@@ -0,0 +1,156 @@
+//-----------------------------------------------------------------------
+// <copyright file="MemoryCryptoKeyStore.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging.Bindings {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+
+ /// <summary>
+ /// A in-memory store of crypto keys.
+ /// </summary>
+ internal class MemoryCryptoKeyStore : ICryptoKeyStore {
+ /// <summary>
+ /// How frequently to check for and remove expired secrets.
+ /// </summary>
+ private static readonly TimeSpan cleaningInterval = TimeSpan.FromMinutes(30);
+
+ /// <summary>
+ /// An in-memory cache of decrypted symmetric keys.
+ /// </summary>
+ /// <remarks>
+ /// The key is the bucket name. The value is a dictionary whose key is the handle and whose value is the cached key.
+ /// </remarks>
+ private readonly Dictionary<string, Dictionary<string, CryptoKey>> store = new Dictionary<string, Dictionary<string, CryptoKey>>(StringComparer.Ordinal);
+
+ /// <summary>
+ /// The last time the cache had expired keys removed from it.
+ /// </summary>
+ private DateTime lastCleaning = DateTime.UtcNow;
+
+ /// <summary>
+ /// Gets the key in a given bucket and handle.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <param name="handle">The key handle. Case sensitive.</param>
+ /// <returns>
+ /// The cryptographic key, or <c>null</c> if no matching key was found.
+ /// </returns>
+ public CryptoKey GetKey(string bucket, string handle) {
+ lock (this.store) {
+ Dictionary<string, CryptoKey> cacheBucket;
+ if (this.store.TryGetValue(bucket, out cacheBucket)) {
+ CryptoKey key;
+ if (cacheBucket.TryGetValue(handle, out key)) {
+ return key;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ /// <summary>
+ /// Gets a sequence of existing keys within a given bucket.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <returns>
+ /// A sequence of handles and keys, ordered by descending <see cref="CryptoKey.ExpiresUtc"/>.
+ /// </returns>
+ public IEnumerable<KeyValuePair<string, CryptoKey>> GetKeys(string bucket) {
+ lock (this.store) {
+ Dictionary<string, CryptoKey> cacheBucket;
+ if (this.store.TryGetValue(bucket, out cacheBucket)) {
+ return cacheBucket.ToList();
+ } else {
+ return Enumerable.Empty<KeyValuePair<string, CryptoKey>>();
+ }
+ }
+ }
+
+ /// <summary>
+ /// Stores a cryptographic key.
+ /// </summary>
+ /// <param name="bucket">The name of the bucket to store the key in. Case sensitive.</param>
+ /// <param name="handle">The handle to the key, unique within the bucket. Case sensitive.</param>
+ /// <param name="key">The key to store.</param>
+ /// <exception cref="CryptoKeyCollisionException">Thrown in the event of a conflict with an existing key in the same bucket and with the same handle.</exception>
+ public void StoreKey(string bucket, string handle, CryptoKey key) {
+ lock (this.store) {
+ Dictionary<string, CryptoKey> cacheBucket;
+ if (!this.store.TryGetValue(bucket, out cacheBucket)) {
+ this.store[bucket] = cacheBucket = new Dictionary<string, CryptoKey>(StringComparer.Ordinal);
+ }
+
+ if (cacheBucket.ContainsKey(handle)) {
+ throw new CryptoKeyCollisionException();
+ }
+
+ cacheBucket[handle] = key;
+
+ this.CleanExpiredKeysFromMemoryCacheIfAppropriate();
+ }
+ }
+
+ /// <summary>
+ /// Removes the key.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <param name="handle">The key handle. Case sensitive.</param>
+ public void RemoveKey(string bucket, string handle) {
+ lock (this.store) {
+ Dictionary<string, CryptoKey> cacheBucket;
+ if (this.store.TryGetValue(bucket, out cacheBucket)) {
+ cacheBucket.Remove(handle);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Cleans the expired keys from memory cache if the cleaning interval has passed.
+ /// </summary>
+ private void CleanExpiredKeysFromMemoryCacheIfAppropriate() {
+ if (DateTime.UtcNow > this.lastCleaning + cleaningInterval) {
+ lock (this.store) {
+ if (DateTime.UtcNow > this.lastCleaning + cleaningInterval) {
+ this.ClearExpiredKeysFromMemoryCache();
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// Weeds out expired keys from the in-memory cache.
+ /// </summary>
+ private void ClearExpiredKeysFromMemoryCache() {
+ lock (this.store) {
+ var emptyBuckets = new List<string>();
+ foreach (var bucketPair in this.store) {
+ var expiredKeys = new List<string>();
+ foreach (var handlePair in bucketPair.Value) {
+ if (handlePair.Value.ExpiresUtc < DateTime.UtcNow) {
+ expiredKeys.Add(handlePair.Key);
+ }
+ }
+
+ foreach (var expiredKey in expiredKeys) {
+ bucketPair.Value.Remove(expiredKey);
+ }
+
+ if (bucketPair.Value.Count == 0) {
+ emptyBuckets.Add(bucketPair.Key);
+ }
+ }
+
+ foreach (string emptyBucket in emptyBuckets) {
+ this.store.Remove(emptyBucket);
+ }
+
+ this.lastCleaning = DateTime.UtcNow;
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/Bindings/NonceMemoryStore.cs b/src/DotNetOpenAuth.Core/Messaging/Bindings/NonceMemoryStore.cs
index 6e64acc..6e64acc 100644
--- a/src/DotNetOpenAuth/Messaging/Bindings/NonceMemoryStore.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/NonceMemoryStore.cs
diff --git a/src/DotNetOpenAuth/Messaging/Bindings/ReplayedMessageException.cs b/src/DotNetOpenAuth.Core/Messaging/Bindings/ReplayedMessageException.cs
index 2b8df9d..2b8df9d 100644
--- a/src/DotNetOpenAuth/Messaging/Bindings/ReplayedMessageException.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/ReplayedMessageException.cs
diff --git a/src/DotNetOpenAuth/Messaging/Bindings/StandardExpirationBindingElement.cs b/src/DotNetOpenAuth.Core/Messaging/Bindings/StandardExpirationBindingElement.cs
index 4396c16..f8c8c6a 100644
--- a/src/DotNetOpenAuth/Messaging/Bindings/StandardExpirationBindingElement.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/StandardExpirationBindingElement.cs
@@ -42,7 +42,7 @@ namespace DotNetOpenAuth.Messaging.Bindings {
/// being discarded as too old.
/// </summary>
protected internal static TimeSpan MaximumMessageAge {
- get { return Configuration.DotNetOpenAuthSection.Configuration.Messaging.MaximumMessageLifetime; }
+ get { return Configuration.DotNetOpenAuthSection.Messaging.MaximumMessageLifetime; }
}
#region IChannelBindingElement Methods
@@ -92,7 +92,7 @@ namespace DotNetOpenAuth.Messaging.Bindings {
// Mitigate HMAC attacks (just guessing the signature until they get it) by
// disallowing post-dated messages.
ErrorUtilities.VerifyProtocol(
- creationDate <= DateTime.UtcNow + DotNetOpenAuthSection.Configuration.Messaging.MaximumClockSkew,
+ creationDate <= DateTime.UtcNow + DotNetOpenAuthSection.Messaging.MaximumClockSkew,
MessagingStrings.MessageTimestampInFuture,
creationDate);
diff --git a/src/DotNetOpenAuth/Messaging/Bindings/StandardReplayProtectionBindingElement.cs b/src/DotNetOpenAuth.Core/Messaging/Bindings/StandardReplayProtectionBindingElement.cs
index bb56cfd..78fd1d5 100644
--- a/src/DotNetOpenAuth/Messaging/Bindings/StandardReplayProtectionBindingElement.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/StandardReplayProtectionBindingElement.cs
@@ -42,7 +42,7 @@ namespace DotNetOpenAuth.Messaging.Bindings {
/// <param name="nonceStore">The store where nonces will be persisted and checked.</param>
/// <param name="allowEmptyNonces">A value indicating whether zero-length nonces will be allowed.</param>
internal StandardReplayProtectionBindingElement(INonceStore nonceStore, bool allowEmptyNonces) {
- Contract.Requires<ArgumentNullException>(nonceStore != null);
+ Requires.NotNull(nonceStore, "nonceStore");
this.nonceStore = nonceStore;
this.AllowZeroLengthNonce = allowEmptyNonces;
diff --git a/src/DotNetOpenAuth/Messaging/CachedDirectWebResponse.cs b/src/DotNetOpenAuth.Core/Messaging/CachedDirectWebResponse.cs
index 111d636..2f3a1d9 100644
--- a/src/DotNetOpenAuth/Messaging/CachedDirectWebResponse.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/CachedDirectWebResponse.cs
@@ -38,8 +38,8 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="maximumBytesToRead">The maximum bytes to read.</param>
internal CachedDirectWebResponse(Uri requestUri, HttpWebResponse response, int maximumBytesToRead)
: base(requestUri, response) {
- Contract.Requires<ArgumentNullException>(requestUri != null);
- Contract.Requires<ArgumentNullException>(response != null);
+ Requires.NotNull(requestUri, "requestUri");
+ Requires.NotNull(response, "response");
this.responseStream = CacheNetworkStreamAndClose(response, maximumBytesToRead);
// BUGBUG: if the response was exactly maximumBytesToRead, we'll incorrectly believe it was truncated.
@@ -58,8 +58,8 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="responseStream">The response stream.</param>
internal CachedDirectWebResponse(Uri requestUri, Uri responseUri, WebHeaderCollection headers, HttpStatusCode statusCode, string contentType, string contentEncoding, MemoryStream responseStream)
: base(requestUri, responseUri, headers, statusCode, contentType, contentEncoding) {
- Contract.Requires<ArgumentNullException>(requestUri != null);
- Contract.Requires<ArgumentNullException>(responseStream != null);
+ Requires.NotNull(requestUri, "requestUri");
+ Requires.NotNull(responseStream, "responseStream");
this.responseStream = responseStream;
}
@@ -159,7 +159,7 @@ namespace DotNetOpenAuth.Messaging {
/// <returns>The seekable Stream instance that contains a copy of what was returned in the HTTP response.</returns>
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Diagnostics.Contracts.__ContractsRuntime.Assume(System.Boolean,System.String,System.String)", Justification = "No localization required.")]
private static MemoryStream CacheNetworkStreamAndClose(HttpWebResponse response, int maximumBytesToRead) {
- Contract.Requires<ArgumentNullException>(response != null);
+ Requires.NotNull(response, "response");
Contract.Ensures(Contract.Result<MemoryStream>() != null);
// Now read and cache the network stream
diff --git a/src/DotNetOpenAuth/Messaging/Channel.cs b/src/DotNetOpenAuth.Core/Messaging/Channel.cs
index 0abdcfa..f017214 100644
--- a/src/DotNetOpenAuth/Messaging/Channel.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/Channel.cs
@@ -8,6 +8,7 @@ namespace DotNetOpenAuth.Messaging {
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
+ using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
@@ -17,9 +18,11 @@ namespace DotNetOpenAuth.Messaging {
using System.Net;
using System.Net.Cache;
using System.Net.Mime;
+ using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading;
using System.Web;
+ using System.Xml;
using DotNetOpenAuth.Messaging.Reflection;
/// <summary>
@@ -41,6 +44,22 @@ namespace DotNetOpenAuth.Messaging {
protected internal const string HttpFormUrlEncoded = "application/x-www-form-urlencoded";
/// <summary>
+ /// The content-type used for JSON serialized objects.
+ /// </summary>
+ protected internal const string JsonEncoded = "application/json";
+
+ /// <summary>
+ /// The "text/javascript" content-type that some servers return instead of the standard <see cref="JsonEncoded"/> one.
+ /// </summary>
+ protected internal const string JsonTextEncoded = "text/javascript";
+
+ /// <summary>
+ /// The content-type for plain text.
+ /// </summary>
+ [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "PlainText", Justification = "Not 'Plaintext' in the crypographic sense.")]
+ protected internal const string PlainTextEncoded = "text/plain";
+
+ /// <summary>
/// The content-type used on HTTP POST requests where the POST entity is a
/// URL-encoded series of key=value pairs.
/// This includes the <see cref="PostEntityEncoding"/> character encoding.
@@ -115,7 +134,7 @@ namespace DotNetOpenAuth.Messaging {
/// <summary>
/// Backing field for the <see cref="MaximumIndirectMessageUrlLength"/> property.
/// </summary>
- private int maximumIndirectMessageUrlLength = Configuration.DotNetOpenAuthSection.Configuration.Messaging.MaximumIndirectMessageUrlLength;
+ private int maximumIndirectMessageUrlLength = Configuration.DotNetOpenAuthSection.Messaging.MaximumIndirectMessageUrlLength;
/// <summary>
/// Initializes a new instance of the <see cref="Channel"/> class.
@@ -126,10 +145,17 @@ namespace DotNetOpenAuth.Messaging {
/// </param>
/// <param name="bindingElements">The binding elements to use in sending and receiving messages.</param>
protected Channel(IMessageFactory messageTypeProvider, params IChannelBindingElement[] bindingElements) {
- Contract.Requires<ArgumentNullException>(messageTypeProvider != null);
+ Requires.NotNull(messageTypeProvider, "messageTypeProvider");
this.messageTypeProvider = messageTypeProvider;
this.WebRequestHandler = new StandardWebRequestHandler();
+ this.XmlDictionaryReaderQuotas = new XmlDictionaryReaderQuotas {
+ MaxArrayLength = 1,
+ MaxDepth = 2,
+ MaxBytesPerRead = 8 * 1024,
+ MaxStringContentLength = 16 * 1024,
+ };
+
this.outgoingBindingElements = new List<IChannelBindingElement>(ValidateAndPrepareBindingElements(bindingElements));
this.incomingBindingElements = new List<IChannelBindingElement>(this.outgoingBindingElements);
this.incomingBindingElements.Reverse();
@@ -167,7 +193,7 @@ namespace DotNetOpenAuth.Messaging {
}
set {
- Contract.Requires<ArgumentOutOfRangeException>(value >= 500 && value <= 4096);
+ Requires.InRange(value >= 500 && value <= 4096, "value");
this.maximumIndirectMessageUrlLength = value;
}
}
@@ -175,13 +201,13 @@ namespace DotNetOpenAuth.Messaging {
/// <summary>
/// Gets or sets the message descriptions.
/// </summary>
- internal MessageDescriptionCollection MessageDescriptions {
+ internal virtual MessageDescriptionCollection MessageDescriptions {
get {
return this.messageDescriptions;
}
set {
- Contract.Requires<ArgumentNullException>(value != null);
+ Requires.NotNull(value, "value");
this.messageDescriptions = value;
}
}
@@ -233,11 +259,12 @@ namespace DotNetOpenAuth.Messaging {
protected internal bool IsDisposed { get; set; }
/// <summary>
- /// Gets a tool that can figure out what kind of message is being received
+ /// Gets or sets a tool that can figure out what kind of message is being received
/// so it can be deserialized.
/// </summary>
- protected IMessageFactory MessageFactory {
+ protected virtual IMessageFactory MessageFactory {
get { return this.messageTypeProvider; }
+ set { this.messageTypeProvider = value; }
}
/// <summary>
@@ -250,12 +277,18 @@ namespace DotNetOpenAuth.Messaging {
}
set {
- Contract.Requires<ArgumentNullException>(value != null);
+ Requires.NotNull(value, "value");
this.cachePolicy = value;
}
}
/// <summary>
+ /// Gets or sets the XML dictionary reader quotas.
+ /// </summary>
+ /// <value>The XML dictionary reader quotas.</value>
+ protected virtual XmlDictionaryReaderQuotas XmlDictionaryReaderQuotas { get; set; }
+
+ /// <summary>
/// Sends an indirect message (either a request or response)
/// or direct message response for transmission to a remote party
/// and ends execution on the current page or handler.
@@ -265,10 +298,30 @@ namespace DotNetOpenAuth.Messaging {
/// <remarks>
/// Requires an HttpContext.Current context.
/// </remarks>
+ [EditorBrowsable(EditorBrowsableState.Never)]
public void Send(IProtocolMessage message) {
- Contract.Requires<InvalidOperationException>(HttpContext.Current != null, MessagingStrings.CurrentHttpContextRequired);
- Contract.Requires<ArgumentNullException>(message != null);
- this.PrepareResponse(message).Send();
+ Requires.ValidState(HttpContext.Current != null, MessagingStrings.CurrentHttpContextRequired);
+ Requires.NotNull(message, "message");
+ this.PrepareResponse(message).Respond(HttpContext.Current, true);
+ }
+
+ /// <summary>
+ /// Sends an indirect message (either a request or response)
+ /// or direct message response for transmission to a remote party
+ /// and skips most of the remaining ASP.NET request handling pipeline.
+ /// Not safe to call from ASP.NET web forms.
+ /// </summary>
+ /// <param name="message">The one-way message to send</param>
+ /// <remarks>
+ /// Requires an HttpContext.Current context.
+ /// This call is not safe to make from an ASP.NET web form (.aspx file or code-behind) because
+ /// ASP.NET will render HTML after the protocol message has been sent, which will corrupt the response.
+ /// Use the <see cref="Send"/> method instead for web forms.
+ /// </remarks>
+ public void Respond(IProtocolMessage message) {
+ Requires.ValidState(HttpContext.Current != null, MessagingStrings.CurrentHttpContextRequired);
+ Requires.NotNull(message, "message");
+ this.PrepareResponse(message).Respond();
}
/// <summary>
@@ -278,7 +331,7 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="message">The one-way message to send</param>
/// <returns>The pending user agent redirect based message to be sent as an HttpResponse.</returns>
public OutgoingWebResponse PrepareResponse(IProtocolMessage message) {
- Contract.Requires<ArgumentNullException>(message != null);
+ Requires.NotNull(message, "message");
Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null);
this.ProcessOutgoingMessage(message);
@@ -358,7 +411,7 @@ namespace DotNetOpenAuth.Messaging {
/// <exception cref="ProtocolException">Thrown when a request message of an unexpected type is received.</exception>
public bool TryReadFromRequest<TRequest>(HttpRequestInfo httpRequest, out TRequest request)
where TRequest : class, IProtocolMessage {
- Contract.Requires<ArgumentNullException>(httpRequest != null);
+ Requires.NotNull(httpRequest, "httpRequest");
Contract.Ensures(Contract.Result<bool>() == (Contract.ValueAtReturn<TRequest>(out request) != null));
IProtocolMessage untypedRequest = this.ReadFromRequest(httpRequest);
@@ -399,7 +452,7 @@ namespace DotNetOpenAuth.Messaging {
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "This returns and verifies the appropriate message type.")]
public TRequest ReadFromRequest<TRequest>(HttpRequestInfo httpRequest)
where TRequest : class, IProtocolMessage {
- Contract.Requires<ArgumentNullException>(httpRequest != null);
+ Requires.NotNull(httpRequest, "httpRequest");
TRequest request;
if (this.TryReadFromRequest<TRequest>(httpRequest, out request)) {
return request;
@@ -414,7 +467,7 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="httpRequest">The request to search for an embedded message.</param>
/// <returns>The deserialized message, if one is found. Null otherwise.</returns>
public IDirectedProtocolMessage ReadFromRequest(HttpRequestInfo httpRequest) {
- Contract.Requires<ArgumentNullException>(httpRequest != null);
+ Requires.NotNull(httpRequest, "httpRequest");
if (Logger.Channel.IsInfoEnabled && httpRequest.UrlBeforeRewriting != null) {
Logger.Channel.InfoFormat("Scanning incoming request for messages: {0}", httpRequest.UrlBeforeRewriting.AbsoluteUri);
@@ -441,7 +494,7 @@ namespace DotNetOpenAuth.Messaging {
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "This returns and verifies the appropriate message type.")]
public TResponse Request<TResponse>(IDirectedProtocolMessage requestMessage)
where TResponse : class, IProtocolMessage {
- Contract.Requires<ArgumentNullException>(requestMessage != null);
+ Requires.NotNull(requestMessage, "requestMessage");
Contract.Ensures(Contract.Result<TResponse>() != null);
IProtocolMessage response = this.Request(requestMessage);
@@ -460,7 +513,7 @@ namespace DotNetOpenAuth.Messaging {
/// <returns>The remote party's response. Guaranteed to never be null.</returns>
/// <exception cref="ProtocolException">Thrown if the response does not include a protocol message.</exception>
public IProtocolMessage Request(IDirectedProtocolMessage requestMessage) {
- Contract.Requires<ArgumentNullException>(requestMessage != null);
+ Requires.NotNull(requestMessage, "requestMessage");
this.ProcessOutgoingMessage(requestMessage);
Logger.Channel.DebugFormat("Sending {0} request.", requestMessage.GetType().Name);
@@ -555,7 +608,7 @@ namespace DotNetOpenAuth.Messaging {
/// <exception cref="InvalidOperationException">Thrown if <see cref="HttpContext.Current">HttpContext.Current</see> == <c>null</c>.</exception>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Costly call should not be a property.")]
protected internal virtual HttpRequestInfo GetRequestFromContext() {
- Contract.Requires<InvalidOperationException>(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
+ Requires.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
Contract.Ensures(Contract.Result<HttpRequestInfo>() != null);
Contract.Ensures(Contract.Result<HttpRequestInfo>().Url != null);
Contract.Ensures(Contract.Result<HttpRequestInfo>().RawUrl != null);
@@ -604,7 +657,7 @@ namespace DotNetOpenAuth.Messaging {
/// </summary>
/// <param name="message">The message about to be encoded and sent.</param>
protected virtual void OnSending(IProtocolMessage message) {
- Contract.Requires<ArgumentNullException>(message != null);
+ Requires.NotNull(message, "message");
var sending = this.Sending;
if (sending != null) {
@@ -619,7 +672,7 @@ namespace DotNetOpenAuth.Messaging {
/// <returns>The response to the web request.</returns>
/// <exception cref="ProtocolException">Thrown on network or protocol errors.</exception>
protected virtual IncomingWebResponse GetDirectResponse(HttpWebRequest webRequest) {
- Contract.Requires<ArgumentNullException>(webRequest != null);
+ Requires.NotNull(webRequest, "webRequest");
return this.WebRequestHandler.GetResponse(webRequest);
}
@@ -634,8 +687,8 @@ namespace DotNetOpenAuth.Messaging {
/// this method to eliminate all use of an HTTP transport.
/// </remarks>
protected virtual IProtocolMessage RequestCore(IDirectedProtocolMessage request) {
- Contract.Requires<ArgumentNullException>(request != null);
- Contract.Requires<ArgumentException>(request.Recipient != null, MessagingStrings.DirectedMessageMissingRecipient);
+ Requires.NotNull(request, "request");
+ Requires.True(request.Recipient != null, "request", MessagingStrings.DirectedMessageMissingRecipient);
HttpWebRequest webRequest = this.CreateHttpRequest(request);
IDictionary<string, string> responseFields;
@@ -679,7 +732,7 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="request">The request to search for an embedded message.</param>
/// <returns>The deserialized message, if one is found. Null otherwise.</returns>
protected virtual IDirectedProtocolMessage ReadFromRequestCore(HttpRequestInfo request) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
Logger.Channel.DebugFormat("Incoming HTTP request: {0} {1}", request.HttpMethod, request.UrlBeforeRewriting.AbsoluteUri);
@@ -694,7 +747,7 @@ namespace DotNetOpenAuth.Messaging {
try {
recipient = request.GetRecipient();
} catch (ArgumentException ex) {
- Logger.Messaging.WarnFormat("Unrecognized HTTP request: " + ex.ToString());
+ Logger.Messaging.WarnFormat("Unrecognized HTTP request: {0}", ex);
return null;
}
@@ -708,8 +761,9 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="recipient">Information about where the message was directed. Null for direct response messages.</param>
/// <returns>The deserialized message, or null if no message could be recognized in the provided data.</returns>
protected virtual IProtocolMessage Receive(Dictionary<string, string> fields, MessageReceivingEndpoint recipient) {
- Contract.Requires<ArgumentNullException>(fields != null);
+ Requires.NotNull(fields, "fields");
+ this.FilterReceivedFields(fields);
IProtocolMessage message = this.MessageFactory.GetNewRequestMessage(recipient, fields);
// If there was no data, or we couldn't recognize it as a message, abort.
@@ -734,8 +788,9 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="message">The message to send.</param>
/// <returns>The pending user agent redirect based message to be sent as an HttpResponse.</returns>
protected virtual OutgoingWebResponse PrepareIndirectResponse(IDirectedProtocolMessage message) {
- Contract.Requires<ArgumentNullException>(message != null);
- Contract.Requires<ArgumentException>(message.Recipient != null, MessagingStrings.DirectedMessageMissingRecipient);
+ Requires.NotNull(message, "message");
+ Requires.True(message.Recipient != null, "message", MessagingStrings.DirectedMessageMissingRecipient);
+ Requires.True((message.HttpMethods & (HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.PostRequest)) != 0, "message");
Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null);
Contract.Assert(message != null && message.Recipient != null);
@@ -743,10 +798,30 @@ namespace DotNetOpenAuth.Messaging {
Contract.Assert(message != null && message.Recipient != null);
var fields = messageAccessor.Serialize();
- // First try creating a 301 redirect, and fallback to a form POST
- // if the message is too big.
- OutgoingWebResponse response = this.Create301RedirectResponse(message, fields);
- if (response.Headers[HttpResponseHeader.Location].Length > this.MaximumIndirectMessageUrlLength) {
+ OutgoingWebResponse response = null;
+ bool tooLargeForGet = false;
+ if ((message.HttpMethods & HttpDeliveryMethods.GetRequest) == HttpDeliveryMethods.GetRequest) {
+ bool payloadInFragment = false;
+ var httpIndirect = message as IHttpIndirectResponse;
+ if (httpIndirect != null) {
+ payloadInFragment = httpIndirect.Include301RedirectPayloadInFragment;
+ }
+
+ // First try creating a 301 redirect, and fallback to a form POST
+ // if the message is too big.
+ response = this.Create301RedirectResponse(message, fields, payloadInFragment);
+ tooLargeForGet = response.Headers[HttpResponseHeader.Location].Length > this.MaximumIndirectMessageUrlLength;
+ }
+
+ // Make sure that if the message is too large for GET that POST is allowed.
+ if (tooLargeForGet) {
+ ErrorUtilities.VerifyProtocol(
+ (message.HttpMethods & HttpDeliveryMethods.PostRequest) == HttpDeliveryMethods.PostRequest,
+ "Message too large for a HTTP GET, and HTTP POST is not allowed for this message type.");
+ }
+
+ // If GET didn't work out, for whatever reason...
+ if (response == null || tooLargeForGet) {
response = this.CreateFormPostResponse(message, fields);
}
@@ -759,19 +834,25 @@ namespace DotNetOpenAuth.Messaging {
/// </summary>
/// <param name="message">The message to forward.</param>
/// <param name="fields">The pre-serialized fields from the message.</param>
+ /// <param name="payloadInFragment">if set to <c>true</c> the redirect will contain the message payload in the #fragment portion of the URL rather than the ?querystring.</param>
/// <returns>The encoded HTTP response.</returns>
[Pure]
- protected virtual OutgoingWebResponse Create301RedirectResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields) {
- Contract.Requires<ArgumentNullException>(message != null);
- Contract.Requires<ArgumentException>(message.Recipient != null, MessagingStrings.DirectedMessageMissingRecipient);
- Contract.Requires<ArgumentNullException>(fields != null);
+ protected virtual OutgoingWebResponse Create301RedirectResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields, bool payloadInFragment = false) {
+ Requires.NotNull(message, "message");
+ Requires.True(message.Recipient != null, "message", MessagingStrings.DirectedMessageMissingRecipient);
+ Requires.NotNull(fields, "fields");
Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null);
// As part of this redirect, we include an HTML body in order to get passed some proxy filters
// such as WebSense.
WebHeaderCollection headers = new WebHeaderCollection();
UriBuilder builder = new UriBuilder(message.Recipient);
- MessagingUtilities.AppendQueryArgs(builder, fields);
+ if (payloadInFragment) {
+ builder.AppendFragmentArgs(fields);
+ } else {
+ builder.AppendQueryArgs(fields);
+ }
+
headers.Add(HttpResponseHeader.Location, builder.Uri.AbsoluteUri);
headers.Add(HttpResponseHeader.ContentType, "text/html; charset=utf-8");
Logger.Http.DebugFormat("Redirecting to {0}", builder.Uri.AbsoluteUri);
@@ -793,9 +874,9 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="fields">The pre-serialized fields from the message.</param>
/// <returns>The encoded HTTP response.</returns>
protected virtual OutgoingWebResponse CreateFormPostResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields) {
- Contract.Requires<ArgumentNullException>(message != null);
- Contract.Requires<ArgumentException>(message.Recipient != null, MessagingStrings.DirectedMessageMissingRecipient);
- Contract.Requires<ArgumentNullException>(fields != null);
+ Requires.NotNull(message, "message");
+ Requires.True(message.Recipient != null, "message", MessagingStrings.DirectedMessageMissingRecipient);
+ Requires.NotNull(fields, "fields");
Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null);
WebHeaderCollection headers = new WebHeaderCollection();
@@ -838,12 +919,12 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="request">The message to send.</param>
/// <returns>The <see cref="HttpWebRequest"/> prepared to send the request.</returns>
/// <remarks>
- /// This method must be overridden by a derived class, unless the <see cref="RequestCore"/> method
+ /// This method must be overridden by a derived class, unless the <see cref="Channel.RequestCore"/> method
/// is overridden and does not require this method.
/// </remarks>
protected virtual HttpWebRequest CreateHttpRequest(IDirectedProtocolMessage request) {
- Contract.Requires<ArgumentNullException>(request != null);
- Contract.Requires<ArgumentException>(request.Recipient != null, MessagingStrings.DirectedMessageMissingRecipient);
+ Requires.NotNull(request, "request");
+ Requires.True(request.Recipient != null, "request", MessagingStrings.DirectedMessageMissingRecipient);
Contract.Ensures(Contract.Result<HttpWebRequest>() != null);
throw new NotImplementedException();
}
@@ -860,6 +941,42 @@ namespace DotNetOpenAuth.Messaging {
protected abstract OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response);
/// <summary>
+ /// Serializes the given message as a JSON string.
+ /// </summary>
+ /// <param name="message">The message to serialize.</param>
+ /// <returns>A JSON string.</returns>
+ [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "This Dispose is safe.")]
+ protected virtual string SerializeAsJson(IMessage message) {
+ Requires.NotNull(message, "message");
+
+ MessageDictionary messageDictionary = this.MessageDescriptions.GetAccessor(message);
+ using (var memoryStream = new MemoryStream()) {
+ using (var jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(memoryStream, Encoding.UTF8)) {
+ MessageSerializer.Serialize(messageDictionary, jsonWriter);
+ jsonWriter.Flush();
+ }
+
+ string json = Encoding.UTF8.GetString(memoryStream.ToArray());
+ return json;
+ }
+ }
+
+ /// <summary>
+ /// Deserializes from flat data from a JSON object.
+ /// </summary>
+ /// <param name="json">A JSON string.</param>
+ /// <returns>The simple "key":"value" pairs from a JSON-encoded object.</returns>
+ protected virtual IDictionary<string, string> DeserializeFromJson(string json) {
+ Requires.NotNullOrEmpty(json, "json");
+
+ var dictionary = new Dictionary<string, string>();
+ using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(json), this.XmlDictionaryReaderQuotas)) {
+ MessageSerializer.DeserializeJsonAsFlatDictionary(dictionary, jsonReader);
+ }
+ return dictionary;
+ }
+
+ /// <summary>
/// Prepares a message for transmit by applying signatures, nonces, etc.
/// </summary>
/// <param name="message">The message to prepare for sending.</param>
@@ -868,7 +985,7 @@ namespace DotNetOpenAuth.Messaging {
/// except when sending ONE WAY request messages.
/// </remarks>
protected void ProcessOutgoingMessage(IProtocolMessage message) {
- Contract.Requires<ArgumentNullException>(message != null);
+ Requires.NotNull(message, "message");
Logger.Channel.DebugFormat("Preparing to send {0} ({1}) message.", message.GetType().Name, message.Version);
this.OnSending(message);
@@ -927,8 +1044,8 @@ namespace DotNetOpenAuth.Messaging {
/// This method satisfies OAuth 1.0 section 5.2, item #3.
/// </remarks>
protected virtual HttpWebRequest InitializeRequestAsGet(IDirectedProtocolMessage requestMessage) {
- Contract.Requires<ArgumentNullException>(requestMessage != null);
- Contract.Requires<ArgumentException>(requestMessage.Recipient != null, MessagingStrings.DirectedMessageMissingRecipient);
+ Requires.NotNull(requestMessage, "requestMessage");
+ Requires.True(requestMessage.Recipient != null, "requestMessage", MessagingStrings.DirectedMessageMissingRecipient);
var messageAccessor = this.MessageDescriptions.GetAccessor(requestMessage);
var fields = messageAccessor.Serialize();
@@ -950,8 +1067,8 @@ namespace DotNetOpenAuth.Messaging {
/// This method satisfies OAuth 1.0 section 5.2, item #3.
/// </remarks>
protected virtual HttpWebRequest InitializeRequestAsHead(IDirectedProtocolMessage requestMessage) {
- Contract.Requires<ArgumentNullException>(requestMessage != null);
- Contract.Requires<ArgumentException>(requestMessage.Recipient != null, MessagingStrings.DirectedMessageMissingRecipient);
+ Requires.NotNull(requestMessage, "requestMessage");
+ Requires.True(requestMessage.Recipient != null, "requestMessage", MessagingStrings.DirectedMessageMissingRecipient);
HttpWebRequest request = this.InitializeRequestAsGet(requestMessage);
request.Method = "HEAD";
@@ -969,13 +1086,13 @@ namespace DotNetOpenAuth.Messaging {
/// This method satisfies OAuth 1.0 section 5.2, item #2 and OpenID 2.0 section 4.1.2.
/// </remarks>
protected virtual HttpWebRequest InitializeRequestAsPost(IDirectedProtocolMessage requestMessage) {
- Contract.Requires<ArgumentNullException>(requestMessage != null);
+ Requires.NotNull(requestMessage, "requestMessage");
Contract.Ensures(Contract.Result<HttpWebRequest>() != null);
var messageAccessor = this.MessageDescriptions.GetAccessor(requestMessage);
var fields = messageAccessor.Serialize();
- HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(requestMessage.Recipient);
+ var httpRequest = (HttpWebRequest)WebRequest.Create(requestMessage.Recipient);
httpRequest.CachePolicy = this.CachePolicy;
httpRequest.Method = "POST";
@@ -1003,7 +1120,7 @@ namespace DotNetOpenAuth.Messaging {
/// This method is simply a standard HTTP PUT request with the message parts serialized to the query string.
/// </remarks>
protected virtual HttpWebRequest InitializeRequestAsPut(IDirectedProtocolMessage requestMessage) {
- Contract.Requires<ArgumentNullException>(requestMessage != null);
+ Requires.NotNull(requestMessage, "requestMessage");
Contract.Ensures(Contract.Result<HttpWebRequest>() != null);
HttpWebRequest request = this.InitializeRequestAsGet(requestMessage);
@@ -1020,7 +1137,7 @@ namespace DotNetOpenAuth.Messaging {
/// This method is simply a standard HTTP DELETE request with the message parts serialized to the query string.
/// </remarks>
protected virtual HttpWebRequest InitializeRequestAsDelete(IDirectedProtocolMessage requestMessage) {
- Contract.Requires<ArgumentNullException>(requestMessage != null);
+ Requires.NotNull(requestMessage, "requestMessage");
Contract.Ensures(Contract.Result<HttpWebRequest>() != null);
HttpWebRequest request = this.InitializeRequestAsGet(requestMessage);
@@ -1038,8 +1155,8 @@ namespace DotNetOpenAuth.Messaging {
/// the request stream, but does not call <see cref="HttpWebRequest.GetResponse"/>.
/// </remarks>
protected void SendParametersInEntity(HttpWebRequest httpRequest, IDictionary<string, string> fields) {
- Contract.Requires<ArgumentNullException>(httpRequest != null);
- Contract.Requires<ArgumentNullException>(fields != null);
+ Requires.NotNull(httpRequest, "httpRequest");
+ Requires.NotNull(fields, "fields");
string requestBody = MessagingUtilities.CreateQueryString(fields);
byte[] requestBytes = PostEntityEncoding.GetBytes(requestBody);
@@ -1080,7 +1197,7 @@ namespace DotNetOpenAuth.Messaging {
/// This can be due to tampering, replay attack or expiration, among other things.
/// </exception>
protected virtual void ProcessIncomingMessage(IProtocolMessage message) {
- Contract.Requires<ArgumentNullException>(message != null);
+ Requires.NotNull(message, "message");
if (Logger.Channel.IsInfoEnabled) {
var messageAccessor = this.MessageDescriptions.GetAccessor(message, true);
@@ -1145,6 +1262,14 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Allows preprocessing and validation of message data before an appropriate message type is
+ /// selected or deserialized.
+ /// </summary>
+ /// <param name="fields">The received message data.</param>
+ protected virtual void FilterReceivedFields(IDictionary<string, string> fields) {
+ }
+
+ /// <summary>
/// Customizes the binding element order for outgoing and incoming messages.
/// </summary>
/// <param name="outgoingOrder">The outgoing order.</param>
@@ -1155,8 +1280,8 @@ namespace DotNetOpenAuth.Messaging {
/// </remarks>
/// <exception cref="ArgumentException">Thrown if a binding element is new or missing in one of the ordered lists.</exception>
protected void CustomizeBindingElementOrder(IEnumerable<IChannelBindingElement> outgoingOrder, IEnumerable<IChannelBindingElement> incomingOrder) {
- Contract.Requires<ArgumentNullException>(outgoingOrder != null);
- Contract.Requires<ArgumentNullException>(incomingOrder != null);
+ Requires.NotNull(outgoingOrder, "outgoingOrder");
+ Requires.NotNull(incomingOrder, "incomingOrder");
ErrorUtilities.VerifyArgument(this.IsBindingElementOrderValid(outgoingOrder), MessagingStrings.InvalidCustomBindingElementOrder);
ErrorUtilities.VerifyArgument(this.IsBindingElementOrderValid(incomingOrder), MessagingStrings.InvalidCustomBindingElementOrder);
@@ -1174,7 +1299,7 @@ namespace DotNetOpenAuth.Messaging {
/// <returns>The properly ordered list of elements.</returns>
/// <exception cref="ProtocolException">Thrown when the binding elements are incomplete or inconsistent with each other.</exception>
private static IEnumerable<IChannelBindingElement> ValidateAndPrepareBindingElements(IEnumerable<IChannelBindingElement> elements) {
- Contract.Requires<ArgumentException>(elements == null || elements.All(e => e != null));
+ Requires.NullOrWithNoNullElements(elements, "elements");
Contract.Ensures(Contract.Result<IEnumerable<IChannelBindingElement>>() != null);
if (elements == null) {
return new IChannelBindingElement[0];
@@ -1247,7 +1372,7 @@ namespace DotNetOpenAuth.Messaging {
/// Thrown when any required message part does not have a value.
/// </exception>
private void EnsureValidMessageParts(IProtocolMessage message) {
- Contract.Requires<ArgumentNullException>(message != null);
+ Requires.NotNull(message, "message");
MessageDictionary dictionary = this.MessageDescriptions.GetAccessor(message);
MessageDescription description = this.MessageDescriptions.Get(message);
description.EnsureMessagePartsPassBasicValidation(dictionary);
@@ -1263,7 +1388,7 @@ namespace DotNetOpenAuth.Messaging {
/// </returns>
[Pure]
private bool IsBindingElementOrderValid(IEnumerable<IChannelBindingElement> order) {
- Contract.Requires<ArgumentNullException>(order != null);
+ Requires.NotNull(order, "order");
// Check that the same number of binding elements are defined.
if (order.Count() != this.OutgoingBindingElements.Count) {
diff --git a/src/DotNetOpenAuth/Messaging/ChannelContract.cs b/src/DotNetOpenAuth.Core/Messaging/ChannelContract.cs
index 9b85d28..bf313ef 100644
--- a/src/DotNetOpenAuth/Messaging/ChannelContract.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/ChannelContract.cs
@@ -30,7 +30,7 @@ namespace DotNetOpenAuth.Messaging {
/// </returns>
/// <exception cref="ProtocolException">Thrown when the response is not valid.</exception>
protected override IDictionary<string, string> ReadFromResponseCore(IncomingWebResponse response) {
- Contract.Requires<ArgumentNullException>(response != null);
+ Requires.NotNull(response, "response");
throw new NotImplementedException();
}
@@ -46,7 +46,7 @@ namespace DotNetOpenAuth.Messaging {
/// This method implements spec V1.0 section 5.3.
/// </remarks>
protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) {
- Contract.Requires<ArgumentNullException>(response != null);
+ Requires.NotNull(response, "response");
Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null);
throw new NotImplementedException();
}
diff --git a/src/DotNetOpenAuth/Messaging/ChannelEventArgs.cs b/src/DotNetOpenAuth.Core/Messaging/ChannelEventArgs.cs
index 1e71bf2..e09e655 100644
--- a/src/DotNetOpenAuth/Messaging/ChannelEventArgs.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/ChannelEventArgs.cs
@@ -17,7 +17,7 @@ namespace DotNetOpenAuth.Messaging {
/// </summary>
/// <param name="message">The message behind the fired event..</param>
internal ChannelEventArgs(IProtocolMessage message) {
- Contract.Requires<ArgumentNullException>(message != null);
+ Requires.NotNull(message, "message");
this.Message = message;
}
diff --git a/src/DotNetOpenAuth.Core/Messaging/DataBag.cs b/src/DotNetOpenAuth.Core/Messaging/DataBag.cs
new file mode 100644
index 0000000..17a7bda
--- /dev/null
+++ b/src/DotNetOpenAuth.Core/Messaging/DataBag.cs
@@ -0,0 +1,147 @@
+//-----------------------------------------------------------------------
+// <copyright file="DataBag.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Diagnostics.Contracts;
+
+ /// <summary>
+ /// A collection of message parts that will be serialized into a single string,
+ /// to be set into a larger message.
+ /// </summary>
+ internal abstract class DataBag : IMessage {
+ /// <summary>
+ /// The default version for DataBags.
+ /// </summary>
+ private static readonly Version DefaultVersion = new Version(1, 0);
+
+ /// <summary>
+ /// The backing field for the <see cref="IMessage.Version"/> property.
+ /// </summary>
+ private Version version;
+
+ /// <summary>
+ /// A dictionary to contain extra message data.
+ /// </summary>
+ private Dictionary<string, string> extraData = new Dictionary<string, string>();
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DataBag"/> class.
+ /// </summary>
+ protected DataBag()
+ : this(DefaultVersion) {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DataBag"/> class.
+ /// </summary>
+ /// <param name="version">The DataBag version.</param>
+ protected DataBag(Version version) {
+ Contract.Requires(version != null);
+ this.version = version;
+ }
+
+ #region IMessage Properties
+
+ /// <summary>
+ /// Gets the version of the protocol or extension this message is prepared to implement.
+ /// </summary>
+ /// <remarks>
+ /// Implementations of this interface should ensure that this property never returns null.
+ /// </remarks>
+ Version IMessage.Version {
+ get { return this.version; }
+ }
+
+ /// <summary>
+ /// Gets the extra, non-standard Protocol parameters included in the message.
+ /// </summary>
+ /// <value></value>
+ /// <remarks>
+ /// Implementations of this interface should ensure that this property never returns null.
+ /// </remarks>
+ public IDictionary<string, string> ExtraData {
+ get { return this.extraData; }
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Gets or sets the nonce.
+ /// </summary>
+ /// <value>The nonce.</value>
+ [MessagePart]
+ internal byte[] Nonce { get; set; }
+
+ /// <summary>
+ /// Gets or sets the UTC creation date of this token.
+ /// </summary>
+ /// <value>The UTC creation date.</value>
+ [MessagePart("ts", IsRequired = true, Encoder = typeof(TimestampEncoder))]
+ internal DateTime UtcCreationDate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the signature.
+ /// </summary>
+ /// <value>The signature.</value>
+ internal byte[] Signature { get; set; }
+
+ /// <summary>
+ /// Gets or sets the message that delivered this DataBag instance to this host.
+ /// </summary>
+ protected internal IProtocolMessage ContainingMessage { get; set; }
+
+ /// <summary>
+ /// Gets the type of this instance.
+ /// </summary>
+ /// <value>The type of the bag.</value>
+ /// <remarks>
+ /// This ensures that one token cannot be misused as another kind of token.
+ /// </remarks>
+ [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Accessed by reflection")]
+ [MessagePart("t", IsRequired = true, AllowEmpty = false)]
+ private Type BagType {
+ get { return this.GetType(); }
+ }
+
+ #region IMessage Methods
+
+ /// <summary>
+ /// Checks the message state for conformity to the protocol specification
+ /// and throws an exception if the message is invalid.
+ /// </summary>
+ /// <remarks>
+ /// <para>Some messages have required fields, or combinations of fields that must relate to each other
+ /// in specialized ways. After deserializing a message, this method checks the state of the
+ /// message to see if it conforms to the protocol.</para>
+ /// <para>Note that this property should <i>not</i> check signatures or perform any state checks
+ /// outside this scope of this particular message.</para>
+ /// </remarks>
+ /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception>
+ void IMessage.EnsureValidMessage() {
+ this.EnsureValidMessage();
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Checks the message state for conformity to the protocol specification
+ /// and throws an exception if the message is invalid.
+ /// </summary>
+ /// <remarks>
+ /// <para>Some messages have required fields, or combinations of fields that must relate to each other
+ /// in specialized ways. After deserializing a message, this method checks the state of the
+ /// message to see if it conforms to the protocol.</para>
+ /// <para>Note that this property should <i>not</i> check signatures or perform any state checks
+ /// outside this scope of this particular message.</para>
+ /// </remarks>
+ /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception>
+ protected virtual void EnsureValidMessage() {
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.Core/Messaging/DataBagFormatterBase.cs b/src/DotNetOpenAuth.Core/Messaging/DataBagFormatterBase.cs
new file mode 100644
index 0000000..86ada44
--- /dev/null
+++ b/src/DotNetOpenAuth.Core/Messaging/DataBagFormatterBase.cs
@@ -0,0 +1,354 @@
+//-----------------------------------------------------------------------
+// <copyright file="DataBagFormatterBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.IO;
+ using System.Linq;
+ using System.Security.Cryptography;
+ using System.Text;
+ using System.Web;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+ using DotNetOpenAuth.Messaging.Reflection;
+
+ /// <summary>
+ /// A serializer for <see cref="DataBag"/>-derived types
+ /// </summary>
+ /// <typeparam name="T">The DataBag-derived type that is to be serialized/deserialized.</typeparam>
+ internal abstract class DataBagFormatterBase<T> : IDataBagFormatter<T> where T : DataBag, new() {
+ /// <summary>
+ /// The message description cache to use for data bag types.
+ /// </summary>
+ protected static readonly MessageDescriptionCollection MessageDescriptions = new MessageDescriptionCollection();
+
+ /// <summary>
+ /// The length of the nonce to include in tokens that can be decoded once only.
+ /// </summary>
+ private const int NonceLength = 6;
+
+ /// <summary>
+ /// The minimum allowable lifetime for the key used to encrypt/decrypt or sign this databag.
+ /// </summary>
+ private readonly TimeSpan minimumAge = TimeSpan.FromDays(1);
+
+ /// <summary>
+ /// The symmetric key store with the secret used for signing/encryption of verification codes and refresh tokens.
+ /// </summary>
+ private readonly ICryptoKeyStore cryptoKeyStore;
+
+ /// <summary>
+ /// The bucket for symmetric keys.
+ /// </summary>
+ private readonly string cryptoKeyBucket;
+
+ /// <summary>
+ /// The crypto to use for signing access tokens.
+ /// </summary>
+ private readonly RSACryptoServiceProvider asymmetricSigning;
+
+ /// <summary>
+ /// The crypto to use for encrypting access tokens.
+ /// </summary>
+ private readonly RSACryptoServiceProvider asymmetricEncrypting;
+
+ /// <summary>
+ /// A value indicating whether the data in this instance will be protected against tampering.
+ /// </summary>
+ private readonly bool signed;
+
+ /// <summary>
+ /// The nonce store to use to ensure that this instance is only decoded once.
+ /// </summary>
+ private readonly INonceStore decodeOnceOnly;
+
+ /// <summary>
+ /// The maximum age of a token that can be decoded; useful only when <see cref="decodeOnceOnly"/> is <c>true</c>.
+ /// </summary>
+ private readonly TimeSpan? maximumAge;
+
+ /// <summary>
+ /// A value indicating whether the data in this instance will be protected against eavesdropping.
+ /// </summary>
+ private readonly bool encrypted;
+
+ /// <summary>
+ /// A value indicating whether the data in this instance will be GZip'd.
+ /// </summary>
+ private readonly bool compressed;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DataBagFormatterBase&lt;T&gt;"/> class.
+ /// </summary>
+ /// <param name="signingKey">The crypto service provider with the asymmetric key to use for signing or verifying the token.</param>
+ /// <param name="encryptingKey">The crypto service provider with the asymmetric key to use for encrypting or decrypting the token.</param>
+ /// <param name="compressed">A value indicating whether the data in this instance will be GZip'd.</param>
+ /// <param name="maximumAge">The maximum age of a token that can be decoded; useful only when <paramref name="decodeOnceOnly"/> is <c>true</c>.</param>
+ /// <param name="decodeOnceOnly">The nonce store to use to ensure that this instance is only decoded once.</param>
+ protected DataBagFormatterBase(RSACryptoServiceProvider signingKey = null, RSACryptoServiceProvider encryptingKey = null, bool compressed = false, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null)
+ : this(signingKey != null, encryptingKey != null, compressed, maximumAge, decodeOnceOnly) {
+ this.asymmetricSigning = signingKey;
+ this.asymmetricEncrypting = encryptingKey;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DataBagFormatterBase&lt;T&gt;"/> class.
+ /// </summary>
+ /// <param name="cryptoKeyStore">The crypto key store used when signing or encrypting.</param>
+ /// <param name="bucket">The bucket in which symmetric keys are stored for signing/encrypting data.</param>
+ /// <param name="signed">A value indicating whether the data in this instance will be protected against tampering.</param>
+ /// <param name="encrypted">A value indicating whether the data in this instance will be protected against eavesdropping.</param>
+ /// <param name="compressed">A value indicating whether the data in this instance will be GZip'd.</param>
+ /// <param name="minimumAge">The required minimum lifespan within which this token must be decodable and verifiable; useful only when <paramref name="signed"/> and/or <paramref name="encrypted"/> is true.</param>
+ /// <param name="maximumAge">The maximum age of a token that can be decoded; useful only when <paramref name="decodeOnceOnly"/> is <c>true</c>.</param>
+ /// <param name="decodeOnceOnly">The nonce store to use to ensure that this instance is only decoded once.</param>
+ protected DataBagFormatterBase(ICryptoKeyStore cryptoKeyStore = null, string bucket = null, bool signed = false, bool encrypted = false, bool compressed = false, TimeSpan? minimumAge = null, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null)
+ : this(signed, encrypted, compressed, maximumAge, decodeOnceOnly) {
+ Requires.True(!String.IsNullOrEmpty(bucket) || cryptoKeyStore == null, null);
+ Requires.True(cryptoKeyStore != null || (!signed && !encrypted), null);
+
+ this.cryptoKeyStore = cryptoKeyStore;
+ this.cryptoKeyBucket = bucket;
+ if (minimumAge.HasValue) {
+ this.minimumAge = minimumAge.Value;
+ }
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DataBagFormatterBase&lt;T&gt;"/> class.
+ /// </summary>
+ /// <param name="signed">A value indicating whether the data in this instance will be protected against tampering.</param>
+ /// <param name="encrypted">A value indicating whether the data in this instance will be protected against eavesdropping.</param>
+ /// <param name="compressed">A value indicating whether the data in this instance will be GZip'd.</param>
+ /// <param name="maximumAge">The maximum age of a token that can be decoded; useful only when <paramref name="decodeOnceOnly"/> is <c>true</c>.</param>
+ /// <param name="decodeOnceOnly">The nonce store to use to ensure that this instance is only decoded once.</param>
+ private DataBagFormatterBase(bool signed = false, bool encrypted = false, bool compressed = false, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null) {
+ Requires.True(signed || decodeOnceOnly == null, null);
+ Requires.True(maximumAge.HasValue || decodeOnceOnly == null, null);
+
+ this.signed = signed;
+ this.maximumAge = maximumAge;
+ this.decodeOnceOnly = decodeOnceOnly;
+ this.encrypted = encrypted;
+ this.compressed = compressed;
+ }
+
+ /// <summary>
+ /// Serializes the specified message, including compression, encryption, signing, and nonce handling where applicable.
+ /// </summary>
+ /// <param name="message">The message to serialize. Must not be null.</param>
+ /// <returns>A non-null, non-empty value.</returns>
+ public string Serialize(T message) {
+ message.UtcCreationDate = DateTime.UtcNow;
+
+ if (this.decodeOnceOnly != null) {
+ message.Nonce = MessagingUtilities.GetNonCryptoRandomData(NonceLength);
+ }
+
+ byte[] encoded = this.SerializeCore(message);
+
+ if (this.compressed) {
+ encoded = MessagingUtilities.Compress(encoded);
+ }
+
+ string symmetricSecretHandle = null;
+ if (this.encrypted) {
+ encoded = this.Encrypt(encoded, out symmetricSecretHandle);
+ }
+
+ if (this.signed) {
+ message.Signature = this.CalculateSignature(encoded, symmetricSecretHandle);
+ }
+
+ int capacity = this.signed ? 4 + message.Signature.Length + 4 + encoded.Length : encoded.Length;
+ using (var finalStream = new MemoryStream(capacity)) {
+ var writer = new BinaryWriter(finalStream);
+ if (this.signed) {
+ writer.WriteBuffer(message.Signature);
+ }
+
+ writer.WriteBuffer(encoded);
+ writer.Flush();
+
+ string payload = MessagingUtilities.ConvertToBase64WebSafeString(finalStream.ToArray());
+ string result = payload;
+ if (symmetricSecretHandle != null && (this.signed || this.encrypted)) {
+ result = MessagingUtilities.CombineKeyHandleAndPayload(symmetricSecretHandle, payload);
+ }
+
+ return result;
+ }
+ }
+
+ /// <summary>
+ /// Deserializes a <see cref="DataBag"/>, including decompression, decryption, signature and nonce validation where applicable.
+ /// </summary>
+ /// <param name="containingMessage">The message that contains the <see cref="DataBag"/> serialized value. Must not be nulll.</param>
+ /// <param name="value">The serialized form of the <see cref="DataBag"/> to deserialize. Must not be null or empty.</param>
+ /// <returns>The deserialized value. Never null.</returns>
+ public T Deserialize(IProtocolMessage containingMessage, string value) {
+ string symmetricSecretHandle = null;
+ if (this.encrypted && this.cryptoKeyStore != null) {
+ string valueWithoutHandle;
+ MessagingUtilities.ExtractKeyHandleAndPayload(containingMessage, "<TODO>", value, out symmetricSecretHandle, out valueWithoutHandle);
+ value = valueWithoutHandle;
+ }
+
+ var message = new T { ContainingMessage = containingMessage };
+ byte[] data = MessagingUtilities.FromBase64WebSafeString(value);
+
+ byte[] signature = null;
+ if (this.signed) {
+ using (var dataStream = new MemoryStream(data)) {
+ var dataReader = new BinaryReader(dataStream);
+ signature = dataReader.ReadBuffer();
+ data = dataReader.ReadBuffer();
+ }
+
+ // Verify that the verification code was issued by message authorization server.
+ ErrorUtilities.VerifyProtocol(this.IsSignatureValid(data, signature, symmetricSecretHandle), MessagingStrings.SignatureInvalid);
+ }
+
+ if (this.encrypted) {
+ data = this.Decrypt(data, symmetricSecretHandle);
+ }
+
+ if (this.compressed) {
+ data = MessagingUtilities.Decompress(data);
+ }
+
+ this.DeserializeCore(message, data);
+ message.Signature = signature; // TODO: we don't really need this any more, do we?
+
+ if (this.maximumAge.HasValue) {
+ // Has message verification code expired?
+ DateTime expirationDate = message.UtcCreationDate + this.maximumAge.Value;
+ if (expirationDate < DateTime.UtcNow) {
+ throw new ExpiredMessageException(expirationDate, containingMessage);
+ }
+ }
+
+ // Has message verification code already been used to obtain an access/refresh token?
+ if (this.decodeOnceOnly != null) {
+ ErrorUtilities.VerifyInternal(this.maximumAge.HasValue, "Oops! How can we validate a nonce without a maximum message age?");
+ string context = "{" + GetType().FullName + "}";
+ if (!this.decodeOnceOnly.StoreNonce(context, Convert.ToBase64String(message.Nonce), message.UtcCreationDate)) {
+ Logger.OpenId.ErrorFormat("Replayed nonce detected ({0} {1}). Rejecting message.", message.Nonce, message.UtcCreationDate);
+ throw new ReplayedMessageException(containingMessage);
+ }
+ }
+
+ ((IMessage)message).EnsureValidMessage();
+
+ return message;
+ }
+
+ /// <summary>
+ /// Serializes the <see cref="DataBag"/> instance to a buffer.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <returns>The buffer containing the serialized data.</returns>
+ protected abstract byte[] SerializeCore(T message);
+
+ /// <summary>
+ /// Deserializes the <see cref="DataBag"/> instance from a buffer.
+ /// </summary>
+ /// <param name="message">The message instance to initialize with data from the buffer.</param>
+ /// <param name="data">The data buffer.</param>
+ protected abstract void DeserializeCore(T message, byte[] data);
+
+ /// <summary>
+ /// Determines whether the signature on this instance is valid.
+ /// </summary>
+ /// <param name="signedData">The signed data.</param>
+ /// <param name="signature">The signature.</param>
+ /// <param name="symmetricSecretHandle">The symmetric secret handle. <c>null</c> when using an asymmetric algorithm.</param>
+ /// <returns>
+ /// <c>true</c> if the signature is valid; otherwise, <c>false</c>.
+ /// </returns>
+ private bool IsSignatureValid(byte[] signedData, byte[] signature, string symmetricSecretHandle) {
+ Requires.NotNull(signedData, "signedData");
+ Requires.NotNull(signature, "signature");
+
+ if (this.asymmetricSigning != null) {
+ using (var hasher = new SHA1CryptoServiceProvider()) {
+ return this.asymmetricSigning.VerifyData(signedData, hasher, signature);
+ }
+ } else {
+ return MessagingUtilities.AreEquivalentConstantTime(signature, this.CalculateSignature(signedData, symmetricSecretHandle));
+ }
+ }
+
+ /// <summary>
+ /// Calculates the signature for the data in this verification code.
+ /// </summary>
+ /// <param name="bytesToSign">The bytes to sign.</param>
+ /// <param name="symmetricSecretHandle">The symmetric secret handle. <c>null</c> when using an asymmetric algorithm.</param>
+ /// <returns>
+ /// The calculated signature.
+ /// </returns>
+ private byte[] CalculateSignature(byte[] bytesToSign, string symmetricSecretHandle) {
+ Requires.NotNull(bytesToSign, "bytesToSign");
+ Requires.ValidState(this.asymmetricSigning != null || this.cryptoKeyStore != null);
+ Contract.Ensures(Contract.Result<byte[]>() != null);
+
+ if (this.asymmetricSigning != null) {
+ using (var hasher = new SHA1CryptoServiceProvider()) {
+ return this.asymmetricSigning.SignData(bytesToSign, hasher);
+ }
+ } else {
+ var key = this.cryptoKeyStore.GetKey(this.cryptoKeyBucket, symmetricSecretHandle);
+ ErrorUtilities.VerifyProtocol(key != null, "Missing decryption key.");
+ using (var symmetricHasher = new HMACSHA256(key.Key)) {
+ return symmetricHasher.ComputeHash(bytesToSign);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Encrypts the specified value using either the symmetric or asymmetric encryption algorithm as appropriate.
+ /// </summary>
+ /// <param name="value">The value.</param>
+ /// <param name="symmetricSecretHandle">Receives the symmetric secret handle. <c>null</c> when using an asymmetric algorithm.</param>
+ /// <returns>
+ /// The encrypted value.
+ /// </returns>
+ private byte[] Encrypt(byte[] value, out string symmetricSecretHandle) {
+ Requires.ValidState(this.asymmetricEncrypting != null || this.cryptoKeyStore != null);
+
+ if (this.asymmetricEncrypting != null) {
+ symmetricSecretHandle = null;
+ return this.asymmetricEncrypting.EncryptWithRandomSymmetricKey(value);
+ } else {
+ var cryptoKey = this.cryptoKeyStore.GetCurrentKey(this.cryptoKeyBucket, this.minimumAge);
+ symmetricSecretHandle = cryptoKey.Key;
+ return MessagingUtilities.Encrypt(value, cryptoKey.Value.Key);
+ }
+ }
+
+ /// <summary>
+ /// Decrypts the specified value using either the symmetric or asymmetric encryption algorithm as appropriate.
+ /// </summary>
+ /// <param name="value">The value.</param>
+ /// <param name="symmetricSecretHandle">The symmetric secret handle. <c>null</c> when using an asymmetric algorithm.</param>
+ /// <returns>
+ /// The decrypted value.
+ /// </returns>
+ private byte[] Decrypt(byte[] value, string symmetricSecretHandle) {
+ Requires.ValidState(this.asymmetricEncrypting != null || symmetricSecretHandle != null);
+
+ if (this.asymmetricEncrypting != null) {
+ return this.asymmetricEncrypting.DecryptWithRandomSymmetricKey(value);
+ } else {
+ var key = this.cryptoKeyStore.GetKey(this.cryptoKeyBucket, symmetricSecretHandle);
+ ErrorUtilities.VerifyProtocol(key != null, "Missing decryption key.");
+ return MessagingUtilities.Decrypt(value, key.Key);
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/DirectWebRequestOptions.cs b/src/DotNetOpenAuth.Core/Messaging/DirectWebRequestOptions.cs
index f3ce805..f3ce805 100644
--- a/src/DotNetOpenAuth/Messaging/DirectWebRequestOptions.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/DirectWebRequestOptions.cs
diff --git a/src/DotNetOpenAuth/Messaging/EmptyDictionary.cs b/src/DotNetOpenAuth.Core/Messaging/EmptyDictionary.cs
index 9db5169..9db5169 100644
--- a/src/DotNetOpenAuth/Messaging/EmptyDictionary.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/EmptyDictionary.cs
diff --git a/src/DotNetOpenAuth/Messaging/EmptyEnumerator.cs b/src/DotNetOpenAuth.Core/Messaging/EmptyEnumerator.cs
index f37e3d4..f37e3d4 100644
--- a/src/DotNetOpenAuth/Messaging/EmptyEnumerator.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/EmptyEnumerator.cs
diff --git a/src/DotNetOpenAuth/Messaging/EmptyList.cs b/src/DotNetOpenAuth.Core/Messaging/EmptyList.cs
index 68cdabd..68cdabd 100644
--- a/src/DotNetOpenAuth/Messaging/EmptyList.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/EmptyList.cs
diff --git a/src/DotNetOpenAuth/Messaging/EnumerableCache.cs b/src/DotNetOpenAuth.Core/Messaging/EnumerableCache.cs
index 29ec533..f6ea55e 100644
--- a/src/DotNetOpenAuth/Messaging/EnumerableCache.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/EnumerableCache.cs
@@ -35,7 +35,7 @@ namespace DotNetOpenAuth.Messaging {
/// to avoid double-caching.</para>
/// </remarks>
public static IEnumerable<T> CacheGeneratedResults<T>(this IEnumerable<T> sequence) {
- Contract.Requires<ArgumentNullException>(sequence != null);
+ Requires.NotNull(sequence, "sequence");
// Don't create a cache for types that don't need it.
if (sequence is IList<T> ||
@@ -83,7 +83,7 @@ namespace DotNetOpenAuth.Messaging {
/// </summary>
/// <param name="generator">The generator.</param>
internal EnumerableCache(IEnumerable<T> generator) {
- Contract.Requires<ArgumentNullException>(generator != null);
+ Requires.NotNull(generator, "generator");
this.generator = generator;
}
@@ -137,11 +137,11 @@ namespace DotNetOpenAuth.Messaging {
private int cachePosition = -1;
/// <summary>
- /// Initializes a new instance of the <see cref="EnumeratorCache"/> class.
+ /// Initializes a new instance of the EnumeratorCache class.
/// </summary>
/// <param name="parent">The parent cached enumerable whose GetEnumerator method is calling this constructor.</param>
internal EnumeratorCache(EnumerableCache<T> parent) {
- Contract.Requires<ArgumentNullException>(parent != null);
+ Requires.NotNull(parent, "parent");
this.parent = parent;
}
diff --git a/src/DotNetOpenAuth/Messaging/ErrorUtilities.cs b/src/DotNetOpenAuth.Core/Messaging/ErrorUtilities.cs
index 1807f54..129a03d 100644
--- a/src/DotNetOpenAuth/Messaging/ErrorUtilities.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/ErrorUtilities.cs
@@ -6,6 +6,7 @@
namespace DotNetOpenAuth.Messaging {
using System;
+ using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
@@ -26,7 +27,7 @@ namespace DotNetOpenAuth.Messaging {
/// <returns>The newly constructed (unthrown) exception.</returns>
[Pure]
internal static Exception Wrap(Exception inner, string errorMessage, params object[] args) {
- Contract.Requires<ArgumentNullException>(args != null);
+ Requires.NotNull(args, "args");
Contract.Assume(errorMessage != null);
return new ProtocolException(string.Format(CultureInfo.CurrentCulture, errorMessage, args), inner);
}
@@ -73,7 +74,7 @@ namespace DotNetOpenAuth.Messaging {
/// <exception cref="InternalErrorException">Thrown if <paramref name="condition"/> evaluates to <c>false</c>.</exception>
[Pure]
internal static void VerifyInternal(bool condition, string errorMessage, params object[] args) {
- Contract.Requires<ArgumentNullException>(args != null);
+ Requires.NotNull(args, "args");
Contract.Ensures(condition);
Contract.EnsuresOnThrow<InternalErrorException>(!condition);
Contract.Assume(errorMessage != null);
@@ -122,7 +123,7 @@ namespace DotNetOpenAuth.Messaging {
/// <exception cref="NotSupportedException">Thrown if <paramref name="condition"/> evaluates to <c>false</c>.</exception>
[Pure]
internal static void VerifySupported(bool condition, string errorMessage, params object[] args) {
- Contract.Requires<ArgumentNullException>(args != null);
+ Requires.NotNull(args, "args");
Contract.Ensures(condition);
Contract.EnsuresOnThrow<NotSupportedException>(!condition);
Contract.Assume(errorMessage != null);
@@ -140,7 +141,7 @@ namespace DotNetOpenAuth.Messaging {
/// <exception cref="InvalidOperationException">Thrown if <paramref name="condition"/> evaluates to <c>false</c>.</exception>
[Pure]
internal static void VerifyOperation(bool condition, string errorMessage, params object[] args) {
- Contract.Requires<ArgumentNullException>(args != null);
+ Requires.NotNull(args, "args");
Contract.Ensures(condition);
Contract.EnsuresOnThrow<InvalidOperationException>(!condition);
Contract.Assume(errorMessage != null);
@@ -151,26 +152,6 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
- /// Checks a condition and throws an <see cref="InfoCard.InformationCardException"/>
- /// if it evaluates to false.
- /// </summary>
- /// <param name="condition">The condition to check.</param>
- /// <param name="errorMessage">The message to include in the exception, if created.</param>
- /// <param name="args">The formatting arguments.</param>
- /// <exception cref="InfoCard.InformationCardException">Thrown if <paramref name="condition"/> evaluates to <c>false</c>.</exception>
- [Pure]
- internal static void VerifyInfoCard(bool condition, string errorMessage, params object[] args) {
- Contract.Requires<ArgumentNullException>(args != null);
- Contract.Ensures(condition);
- Contract.EnsuresOnThrow<InfoCard.InformationCardException>(!condition);
- Contract.Assume(errorMessage != null);
- if (!condition) {
- errorMessage = string.Format(CultureInfo.CurrentCulture, errorMessage, args);
- throw new InfoCard.InformationCardException(errorMessage);
- }
- }
-
- /// <summary>
/// Throws a <see cref="HostErrorException"/> if some <paramref name="condition"/> evaluates to false.
/// </summary>
/// <param name="condition">True to do nothing; false to throw the exception.</param>
@@ -179,7 +160,7 @@ namespace DotNetOpenAuth.Messaging {
/// <exception cref="HostErrorException">Thrown if <paramref name="condition"/> evaluates to <c>false</c>.</exception>
[Pure]
internal static void VerifyHost(bool condition, string errorMessage, params object[] args) {
- Contract.Requires<ArgumentNullException>(args != null);
+ Requires.NotNull(args, "args");
Contract.Ensures(condition);
Contract.EnsuresOnThrow<ProtocolException>(!condition);
Contract.Assume(errorMessage != null);
@@ -198,8 +179,8 @@ namespace DotNetOpenAuth.Messaging {
/// <exception cref="ProtocolException">Thrown if <paramref name="condition"/> evaluates to <c>false</c>.</exception>
[Pure]
internal static void VerifyProtocol(bool condition, IProtocolMessage faultedMessage, string errorMessage, params object[] args) {
- Contract.Requires<ArgumentNullException>(args != null);
- Contract.Requires<ArgumentNullException>(faultedMessage != null);
+ Requires.NotNull(args, "args");
+ Requires.NotNull(faultedMessage, "faultedMessage");
Contract.Ensures(condition);
Contract.EnsuresOnThrow<ProtocolException>(!condition);
Contract.Assume(errorMessage != null);
@@ -217,7 +198,7 @@ namespace DotNetOpenAuth.Messaging {
/// <exception cref="ProtocolException">Thrown if <paramref name="condition"/> evaluates to <c>false</c>.</exception>
[Pure]
internal static void VerifyProtocol(bool condition, string message, params object[] args) {
- Contract.Requires<ArgumentNullException>(args != null);
+ Requires.NotNull(args, "args");
Contract.Ensures(condition);
Contract.EnsuresOnThrow<ProtocolException>(!condition);
Contract.Assume(message != null);
@@ -249,7 +230,7 @@ namespace DotNetOpenAuth.Messaging {
/// <exception cref="ProtocolException">Always thrown.</exception>
[Pure]
internal static Exception ThrowProtocol(string message, params object[] args) {
- Contract.Requires<ArgumentNullException>(args != null);
+ Requires.NotNull(args, "args");
Contract.Assume(message != null);
VerifyProtocol(false, message, args);
@@ -265,7 +246,7 @@ namespace DotNetOpenAuth.Messaging {
/// <returns>Nothing. It's just here so the caller can throw this method for C# compilation check.</returns>
[Pure]
internal static Exception ThrowFormat(string message, params object[] args) {
- Contract.Requires<ArgumentNullException>(args != null);
+ Requires.NotNull(args, "args");
Contract.Assume(message != null);
throw new FormatException(string.Format(CultureInfo.CurrentCulture, message, args));
}
@@ -279,7 +260,7 @@ namespace DotNetOpenAuth.Messaging {
/// <exception cref="FormatException">Thrown when <paramref name="condition"/> is <c>false</c>.</exception>
[Pure]
internal static void VerifyFormat(bool condition, string message, params object[] args) {
- Contract.Requires<ArgumentNullException>(args != null);
+ Requires.NotNull(args, "args");
Contract.Ensures(condition);
Contract.EnsuresOnThrow<FormatException>(!condition);
Contract.Assume(message != null);
@@ -297,7 +278,7 @@ namespace DotNetOpenAuth.Messaging {
/// <exception cref="ArgumentException">Thrown if <paramref name="condition"/> evaluates to <c>false</c>.</exception>
[Pure]
internal static void VerifyArgument(bool condition, string message, params object[] args) {
- Contract.Requires<ArgumentNullException>(args != null);
+ Requires.NotNull(args, "args");
Contract.Ensures(condition);
Contract.EnsuresOnThrow<ArgumentException>(!condition);
Contract.Assume(message != null);
@@ -315,7 +296,7 @@ namespace DotNetOpenAuth.Messaging {
/// <returns>Never returns anything. It always throws.</returns>
[Pure]
internal static Exception ThrowArgumentNamed(string parameterName, string message, params object[] args) {
- Contract.Requires<ArgumentNullException>(args != null);
+ Requires.NotNull(args, "args");
Contract.Assume(message != null);
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, message, args), parameterName);
}
@@ -330,7 +311,7 @@ namespace DotNetOpenAuth.Messaging {
/// <exception cref="ArgumentException">Thrown if <paramref name="condition"/> evaluates to <c>false</c>.</exception>
[Pure]
internal static void VerifyArgumentNamed(bool condition, string parameterName, string message, params object[] args) {
- Contract.Requires<ArgumentNullException>(args != null);
+ Requires.NotNull(args, "args");
Contract.Ensures(condition);
Contract.EnsuresOnThrow<ArgumentException>(!condition);
Contract.Assume(message != null);
@@ -381,5 +362,24 @@ namespace DotNetOpenAuth.Messaging {
Contract.Ensures(HttpContext.Current.Request != null);
ErrorUtilities.VerifyOperation(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
}
+
+ /// <summary>
+ /// Obtains a value from the dictionary if possible, or throws a <see cref="ProtocolException"/> if it's missing.
+ /// </summary>
+ /// <typeparam name="TKey">The type of key in the dictionary.</typeparam>
+ /// <typeparam name="TValue">The type of value in the dictionary.</typeparam>
+ /// <param name="dictionary">The dictionary.</param>
+ /// <param name="key">The key to use to look up the value.</param>
+ /// <param name="message">The message to claim is invalid if the key cannot be found.</param>
+ /// <returns>The value for the given key.</returns>
+ [Pure]
+ internal static TValue GetValueOrThrow<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, IMessage message) {
+ Requires.NotNull(dictionary, "dictionary");
+ Requires.NotNull(message, "message");
+
+ TValue value;
+ VerifyProtocol(dictionary.TryGetValue(key, out value), MessagingStrings.ExpectedParameterWasMissing, key, message.GetType().Name);
+ return value;
+ }
}
}
diff --git a/src/DotNetOpenAuth/Messaging/Exceptions.cd b/src/DotNetOpenAuth.Core/Messaging/Exceptions.cd
index 0119753..0119753 100644
--- a/src/DotNetOpenAuth/Messaging/Exceptions.cd
+++ b/src/DotNetOpenAuth.Core/Messaging/Exceptions.cd
diff --git a/src/DotNetOpenAuth/Messaging/HostErrorException.cs b/src/DotNetOpenAuth.Core/Messaging/HostErrorException.cs
index 81691b0..81691b0 100644
--- a/src/DotNetOpenAuth/Messaging/HostErrorException.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/HostErrorException.cs
diff --git a/src/DotNetOpenAuth/Messaging/HttpDeliveryMethods.cs b/src/DotNetOpenAuth.Core/Messaging/HttpDeliveryMethods.cs
index 1443fff..1443fff 100644
--- a/src/DotNetOpenAuth/Messaging/HttpDeliveryMethods.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/HttpDeliveryMethods.cs
diff --git a/src/DotNetOpenAuth/Messaging/HttpRequestInfo.cs b/src/DotNetOpenAuth.Core/Messaging/HttpRequestInfo.cs
index 6ce87a8..0cf37a5 100644
--- a/src/DotNetOpenAuth/Messaging/HttpRequestInfo.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/HttpRequestInfo.cs
@@ -51,7 +51,7 @@ namespace DotNetOpenAuth.Messaging {
/// </summary>
/// <param name="request">The ASP.NET structure to copy from.</param>
public HttpRequestInfo(HttpRequest request) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
Contract.Ensures(this.HttpMethod == request.HttpMethod);
Contract.Ensures(this.Url == request.Url);
Contract.Ensures(this.RawUrl == request.RawUrl);
@@ -88,10 +88,10 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="headers">Headers in the HTTP request.</param>
/// <param name="inputStream">The entity stream, if any. (POST requests typically have these). Use <c>null</c> for GET requests.</param>
public HttpRequestInfo(string httpMethod, Uri requestUrl, string rawUrl, WebHeaderCollection headers, Stream inputStream) {
- Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(httpMethod));
- Contract.Requires<ArgumentNullException>(requestUrl != null);
- Contract.Requires<ArgumentNullException>(rawUrl != null);
- Contract.Requires<ArgumentNullException>(headers != null);
+ Requires.NotNullOrEmpty(httpMethod, "httpMethod");
+ Requires.NotNull(requestUrl, "requestUrl");
+ Requires.NotNull(rawUrl, "rawUrl");
+ Requires.NotNull(headers, "headers");
this.HttpMethod = httpMethod;
this.Url = requestUrl;
@@ -108,7 +108,7 @@ namespace DotNetOpenAuth.Messaging {
/// </summary>
/// <param name="listenerRequest">Details on the incoming HTTP request.</param>
public HttpRequestInfo(HttpListenerRequest listenerRequest) {
- Contract.Requires<ArgumentNullException>(listenerRequest != null);
+ Requires.NotNull(listenerRequest, "listenerRequest");
this.HttpMethod = listenerRequest.HttpMethod;
this.Url = listenerRequest.Url;
@@ -130,8 +130,8 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="request">The WCF incoming request structure to get the HTTP information from.</param>
/// <param name="requestUri">The URI of the service endpoint.</param>
public HttpRequestInfo(HttpRequestMessageProperty request, Uri requestUri) {
- Contract.Requires<ArgumentNullException>(request != null);
- Contract.Requires<ArgumentNullException>(requestUri != null);
+ Requires.NotNull(request, "request");
+ Requires.NotNull(requestUri, "requestUri");
this.HttpMethod = request.Method;
this.Headers = request.Headers;
@@ -158,7 +158,7 @@ namespace DotNetOpenAuth.Messaging {
/// </summary>
/// <param name="request">The HttpWebRequest (that was never used) to copy from.</param>
internal HttpRequestInfo(WebRequest request) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
this.HttpMethod = request.Method;
this.Url = request.RequestUri;
@@ -317,8 +317,8 @@ namespace DotNetOpenAuth.Messaging {
/// is a read-only kind of <see cref="NameValueCollection"/>.
/// </remarks>
internal static Uri GetPublicFacingUrl(HttpRequest request, NameValueCollection serverVariables) {
- Contract.Requires<ArgumentNullException>(request != null);
- Contract.Requires<ArgumentNullException>(serverVariables != null);
+ Requires.NotNull(request, "request");
+ Requires.NotNull(serverVariables, "serverVariables");
// Due to URL rewriting, cloud computing (i.e. Azure)
// and web farms, etc., we have to be VERY careful about what
@@ -370,7 +370,7 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="request">The request.</param>
/// <returns>The URI that the outside world used to create this request.</returns>
private static Uri GetPublicFacingUrl(HttpRequest request) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
return GetPublicFacingUrl(request, request.ServerVariables);
}
@@ -380,7 +380,7 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="url">A full URL.</param>
/// <returns>A raw URL that might have come in on the HTTP verb.</returns>
private static string MakeUpRawUrlFromUrl(Uri url) {
- Contract.Requires<ArgumentNullException>(url != null);
+ Requires.NotNull(url, "url");
return url.AbsolutePath + url.Query + url.Fragment;
}
@@ -390,7 +390,7 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="pairs">The collection a HTTP headers.</param>
/// <returns>A new collection of the given headers.</returns>
private static WebHeaderCollection GetHeaderCollection(NameValueCollection pairs) {
- Contract.Requires<ArgumentNullException>(pairs != null);
+ Requires.NotNull(pairs, "pairs");
WebHeaderCollection headers = new WebHeaderCollection();
foreach (string key in pairs) {
diff --git a/src/DotNetOpenAuth/Messaging/IChannelBindingElement.cs b/src/DotNetOpenAuth.Core/Messaging/IChannelBindingElement.cs
index f502f17..9dac9b3 100644
--- a/src/DotNetOpenAuth/Messaging/IChannelBindingElement.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/IChannelBindingElement.cs
@@ -113,8 +113,8 @@ namespace DotNetOpenAuth.Messaging {
/// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable.
/// </remarks>
MessageProtections? IChannelBindingElement.ProcessOutgoingMessage(IProtocolMessage message) {
- Contract.Requires<ArgumentNullException>(message != null);
- Contract.Requires<InvalidOperationException>(((IChannelBindingElement)this).Channel != null);
+ Requires.NotNull(message, "message");
+ Requires.ValidState(((IChannelBindingElement)this).Channel != null);
throw new NotImplementedException();
}
@@ -136,8 +136,8 @@ namespace DotNetOpenAuth.Messaging {
/// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable.
/// </remarks>
MessageProtections? IChannelBindingElement.ProcessIncomingMessage(IProtocolMessage message) {
- Contract.Requires<ArgumentNullException>(message != null);
- Contract.Requires<InvalidOperationException>(((IChannelBindingElement)this).Channel != null);
+ Requires.NotNull(message, "message");
+ Requires.ValidState(((IChannelBindingElement)this).Channel != null);
throw new NotImplementedException();
}
diff --git a/src/DotNetOpenAuth.Core/Messaging/IDataBagFormatter.cs b/src/DotNetOpenAuth.Core/Messaging/IDataBagFormatter.cs
new file mode 100644
index 0000000..fd1c15d
--- /dev/null
+++ b/src/DotNetOpenAuth.Core/Messaging/IDataBagFormatter.cs
@@ -0,0 +1,75 @@
+//-----------------------------------------------------------------------
+// <copyright file="IDataBagFormatter.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging {
+ using System;
+ using System.Diagnostics.Contracts;
+
+ /// <summary>
+ /// A serializer for <see cref="DataBag"/>-derived types
+ /// </summary>
+ /// <typeparam name="T">The DataBag-derived type that is to be serialized/deserialized.</typeparam>
+ [ContractClass(typeof(IDataBagFormatterContract<>))]
+ internal interface IDataBagFormatter<T> where T : DataBag, new() {
+ /// <summary>
+ /// Serializes the specified message.
+ /// </summary>
+ /// <param name="message">The message to serialize. Must not be null.</param>
+ /// <returns>A non-null, non-empty value.</returns>
+ string Serialize(T message);
+
+ /// <summary>
+ /// Deserializes a <see cref="DataBag"/>.
+ /// </summary>
+ /// <param name="containingMessage">The message that contains the <see cref="DataBag"/> serialized value. Must not be nulll.</param>
+ /// <param name="data">The serialized form of the <see cref="DataBag"/> to deserialize. Must not be null or empty.</param>
+ /// <returns>The deserialized value. Never null.</returns>
+ T Deserialize(IProtocolMessage containingMessage, string data);
+ }
+
+ /// <summary>
+ /// Contract class for the IDataBagFormatter interface.
+ /// </summary>
+ /// <typeparam name="T">The type of DataBag to serialize.</typeparam>
+ [ContractClassFor(typeof(IDataBagFormatter<>))]
+ internal abstract class IDataBagFormatterContract<T> : IDataBagFormatter<T> where T : DataBag, new() {
+ /// <summary>
+ /// Prevents a default instance of the <see cref="IDataBagFormatterContract&lt;T&gt;"/> class from being created.
+ /// </summary>
+ private IDataBagFormatterContract() {
+ }
+
+ #region IDataBagFormatter<T> Members
+
+ /// <summary>
+ /// Serializes the specified message.
+ /// </summary>
+ /// <param name="message">The message to serialize. Must not be null.</param>
+ /// <returns>A non-null, non-empty value.</returns>
+ string IDataBagFormatter<T>.Serialize(T message) {
+ Requires.NotNull(message, "message");
+ Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>()));
+
+ throw new System.NotImplementedException();
+ }
+
+ /// <summary>
+ /// Deserializes a <see cref="DataBag"/>.
+ /// </summary>
+ /// <param name="containingMessage">The message that contains the <see cref="DataBag"/> serialized value. Must not be nulll.</param>
+ /// <param name="data">The serialized form of the <see cref="DataBag"/> to deserialize. Must not be null or empty.</param>
+ /// <returns>The deserialized value. Never null.</returns>
+ T IDataBagFormatter<T>.Deserialize(IProtocolMessage containingMessage, string data) {
+ Requires.NotNull(containingMessage, "containingMessage");
+ Requires.NotNullOrEmpty(data, "data");
+ Contract.Ensures(Contract.Result<T>() != null);
+
+ throw new System.NotImplementedException();
+ }
+
+ #endregion
+ }
+} \ No newline at end of file
diff --git a/src/DotNetOpenAuth/Messaging/IDirectResponseProtocolMessage.cs b/src/DotNetOpenAuth.Core/Messaging/IDirectResponseProtocolMessage.cs
index 3b4da6c..3b4da6c 100644
--- a/src/DotNetOpenAuth/Messaging/IDirectResponseProtocolMessage.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/IDirectResponseProtocolMessage.cs
diff --git a/src/DotNetOpenAuth.Core/Messaging/IDirectWebRequestHandler.cs b/src/DotNetOpenAuth.Core/Messaging/IDirectWebRequestHandler.cs
new file mode 100644
index 0000000..add35f9
--- /dev/null
+++ b/src/DotNetOpenAuth.Core/Messaging/IDirectWebRequestHandler.cs
@@ -0,0 +1,223 @@
+//-----------------------------------------------------------------------
+// <copyright file="IDirectWebRequestHandler.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.IO;
+ using System.Net;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A contract for <see cref="HttpWebRequest"/> handling.
+ /// </summary>
+ /// <remarks>
+ /// Implementations of this interface must be thread safe.
+ /// </remarks>
+ [ContractClass(typeof(IDirectWebRequestHandlerContract))]
+ public interface IDirectWebRequestHandler {
+ /// <summary>
+ /// Determines whether this instance can support the specified options.
+ /// </summary>
+ /// <param name="options">The set of options that might be given in a subsequent web request.</param>
+ /// <returns>
+ /// <c>true</c> if this instance can support the specified options; otherwise, <c>false</c>.
+ /// </returns>
+ [Pure]
+ bool CanSupport(DirectWebRequestOptions options);
+
+ /// <summary>
+ /// Prepares an <see cref="HttpWebRequest"/> that contains an POST entity for sending the entity.
+ /// </summary>
+ /// <param name="request">The <see cref="HttpWebRequest"/> that should contain the entity.</param>
+ /// <returns>
+ /// The stream the caller should write out the entity data to.
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown for any network error.</exception>
+ /// <remarks>
+ /// <para>The caller should have set the <see cref="HttpWebRequest.ContentLength"/>
+ /// and any other appropriate properties <i>before</i> calling this method.
+ /// Callers <i>must</i> close and dispose of the request stream when they are done
+ /// writing to it to avoid taking up the connection too long and causing long waits on
+ /// subsequent requests.</para>
+ /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a
+ /// <see cref="ProtocolException"/> to abstract away the transport and provide
+ /// a single exception type for hosts to catch.</para>
+ /// </remarks>
+ Stream GetRequestStream(HttpWebRequest request);
+
+ /// <summary>
+ /// Prepares an <see cref="HttpWebRequest"/> that contains an POST entity for sending the entity.
+ /// </summary>
+ /// <param name="request">The <see cref="HttpWebRequest"/> that should contain the entity.</param>
+ /// <param name="options">The options to apply to this web request.</param>
+ /// <returns>
+ /// The stream the caller should write out the entity data to.
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown for any network error.</exception>
+ /// <remarks>
+ /// <para>The caller should have set the <see cref="HttpWebRequest.ContentLength"/>
+ /// and any other appropriate properties <i>before</i> calling this method.
+ /// Callers <i>must</i> close and dispose of the request stream when they are done
+ /// writing to it to avoid taking up the connection too long and causing long waits on
+ /// subsequent requests.</para>
+ /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a
+ /// <see cref="ProtocolException"/> to abstract away the transport and provide
+ /// a single exception type for hosts to catch.</para>
+ /// </remarks>
+ Stream GetRequestStream(HttpWebRequest request, DirectWebRequestOptions options);
+
+ /// <summary>
+ /// Processes an <see cref="HttpWebRequest"/> and converts the
+ /// <see cref="HttpWebResponse"/> to a <see cref="IncomingWebResponse"/> instance.
+ /// </summary>
+ /// <param name="request">The <see cref="HttpWebRequest"/> to handle.</param>
+ /// <returns>An instance of <see cref="IncomingWebResponse"/> describing the response.</returns>
+ /// <exception cref="ProtocolException">Thrown for any network error.</exception>
+ /// <remarks>
+ /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a
+ /// <see cref="ProtocolException"/> to abstract away the transport and provide
+ /// a single exception type for hosts to catch. The <see cref="WebException.Response"/>
+ /// value, if set, should be Closed before throwing.</para>
+ /// </remarks>
+ IncomingWebResponse GetResponse(HttpWebRequest request);
+
+ /// <summary>
+ /// Processes an <see cref="HttpWebRequest"/> and converts the
+ /// <see cref="HttpWebResponse"/> to a <see cref="IncomingWebResponse"/> instance.
+ /// </summary>
+ /// <param name="request">The <see cref="HttpWebRequest"/> to handle.</param>
+ /// <param name="options">The options to apply to this web request.</param>
+ /// <returns>An instance of <see cref="IncomingWebResponse"/> describing the response.</returns>
+ /// <exception cref="ProtocolException">Thrown for any network error.</exception>
+ /// <remarks>
+ /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a
+ /// <see cref="ProtocolException"/> to abstract away the transport and provide
+ /// a single exception type for hosts to catch. The <see cref="WebException.Response"/>
+ /// value, if set, should be Closed before throwing.</para>
+ /// </remarks>
+ IncomingWebResponse GetResponse(HttpWebRequest request, DirectWebRequestOptions options);
+ }
+
+ /// <summary>
+ /// Code contract for the <see cref="IDirectWebRequestHandler"/> type.
+ /// </summary>
+ [ContractClassFor(typeof(IDirectWebRequestHandler))]
+ internal abstract class IDirectWebRequestHandlerContract : IDirectWebRequestHandler {
+ #region IDirectWebRequestHandler Members
+
+ /// <summary>
+ /// Determines whether this instance can support the specified options.
+ /// </summary>
+ /// <param name="options">The set of options that might be given in a subsequent web request.</param>
+ /// <returns>
+ /// <c>true</c> if this instance can support the specified options; otherwise, <c>false</c>.
+ /// </returns>
+ bool IDirectWebRequestHandler.CanSupport(DirectWebRequestOptions options) {
+ throw new System.NotImplementedException();
+ }
+
+ /// <summary>
+ /// Prepares an <see cref="HttpWebRequest"/> that contains an POST entity for sending the entity.
+ /// </summary>
+ /// <param name="request">The <see cref="HttpWebRequest"/> that should contain the entity.</param>
+ /// <returns>
+ /// The stream the caller should write out the entity data to.
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown for any network error.</exception>
+ /// <remarks>
+ /// <para>The caller should have set the <see cref="HttpWebRequest.ContentLength"/>
+ /// and any other appropriate properties <i>before</i> calling this method.
+ /// Callers <i>must</i> close and dispose of the request stream when they are done
+ /// writing to it to avoid taking up the connection too long and causing long waits on
+ /// subsequent requests.</para>
+ /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a
+ /// <see cref="ProtocolException"/> to abstract away the transport and provide
+ /// a single exception type for hosts to catch.</para>
+ /// </remarks>
+ Stream IDirectWebRequestHandler.GetRequestStream(HttpWebRequest request) {
+ Requires.NotNull(request, "request");
+ throw new System.NotImplementedException();
+ }
+
+ /// <summary>
+ /// Prepares an <see cref="HttpWebRequest"/> that contains an POST entity for sending the entity.
+ /// </summary>
+ /// <param name="request">The <see cref="HttpWebRequest"/> that should contain the entity.</param>
+ /// <param name="options">The options to apply to this web request.</param>
+ /// <returns>
+ /// The stream the caller should write out the entity data to.
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown for any network error.</exception>
+ /// <remarks>
+ /// <para>The caller should have set the <see cref="HttpWebRequest.ContentLength"/>
+ /// and any other appropriate properties <i>before</i> calling this method.
+ /// Callers <i>must</i> close and dispose of the request stream when they are done
+ /// writing to it to avoid taking up the connection too long and causing long waits on
+ /// subsequent requests.</para>
+ /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a
+ /// <see cref="ProtocolException"/> to abstract away the transport and provide
+ /// a single exception type for hosts to catch.</para>
+ /// </remarks>
+ Stream IDirectWebRequestHandler.GetRequestStream(HttpWebRequest request, DirectWebRequestOptions options) {
+ Requires.NotNull(request, "request");
+ Requires.Support(((IDirectWebRequestHandler)this).CanSupport(options), MessagingStrings.DirectWebRequestOptionsNotSupported);
+ ////ErrorUtilities.VerifySupported(((IDirectWebRequestHandler)this).CanSupport(options), string.Format(MessagingStrings.DirectWebRequestOptionsNotSupported, options, this.GetType().Name));
+ throw new System.NotImplementedException();
+ }
+
+ /// <summary>
+ /// Processes an <see cref="HttpWebRequest"/> and converts the
+ /// <see cref="HttpWebResponse"/> to a <see cref="IncomingWebResponse"/> instance.
+ /// </summary>
+ /// <param name="request">The <see cref="HttpWebRequest"/> to handle.</param>
+ /// <returns>
+ /// An instance of <see cref="IncomingWebResponse"/> describing the response.
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown for any network error.</exception>
+ /// <remarks>
+ /// Implementations should catch <see cref="WebException"/> and wrap it in a
+ /// <see cref="ProtocolException"/> to abstract away the transport and provide
+ /// a single exception type for hosts to catch. The <see cref="WebException.Response"/>
+ /// value, if set, should be Closed before throwing.
+ /// </remarks>
+ IncomingWebResponse IDirectWebRequestHandler.GetResponse(HttpWebRequest request) {
+ Requires.NotNull(request, "request");
+ Contract.Ensures(Contract.Result<IncomingWebResponse>() != null);
+ Contract.Ensures(Contract.Result<IncomingWebResponse>().ResponseStream != null);
+ throw new System.NotImplementedException();
+ }
+
+ /// <summary>
+ /// Processes an <see cref="HttpWebRequest"/> and converts the
+ /// <see cref="HttpWebResponse"/> to a <see cref="IncomingWebResponse"/> instance.
+ /// </summary>
+ /// <param name="request">The <see cref="HttpWebRequest"/> to handle.</param>
+ /// <param name="options">The options to apply to this web request.</param>
+ /// <returns>
+ /// An instance of <see cref="IncomingWebResponse"/> describing the response.
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown for any network error.</exception>
+ /// <remarks>
+ /// Implementations should catch <see cref="WebException"/> and wrap it in a
+ /// <see cref="ProtocolException"/> to abstract away the transport and provide
+ /// a single exception type for hosts to catch. The <see cref="WebException.Response"/>
+ /// value, if set, should be Closed before throwing.
+ /// </remarks>
+ IncomingWebResponse IDirectWebRequestHandler.GetResponse(HttpWebRequest request, DirectWebRequestOptions options) {
+ Requires.NotNull(request, "request");
+ Contract.Ensures(Contract.Result<IncomingWebResponse>() != null);
+ Contract.Ensures(Contract.Result<IncomingWebResponse>().ResponseStream != null);
+ Requires.Support(((IDirectWebRequestHandler)this).CanSupport(options), MessagingStrings.DirectWebRequestOptionsNotSupported);
+
+ ////ErrorUtilities.VerifySupported(((IDirectWebRequestHandler)this).CanSupport(options), string.Format(MessagingStrings.DirectWebRequestOptionsNotSupported, options, this.GetType().Name));
+ throw new System.NotImplementedException();
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/IDirectWebRequestHandler.cs b/src/DotNetOpenAuth.Core/Messaging/IDirectWebRequestHandler.cs.orig
index d47da4a..a17b379 100644
--- a/src/DotNetOpenAuth/Messaging/IDirectWebRequestHandler.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/IDirectWebRequestHandler.cs.orig
@@ -5,9 +5,7 @@
//-----------------------------------------------------------------------
namespace DotNetOpenAuth.Messaging {
- using System;
using System.Collections.Generic;
- using System.Diagnostics.Contracts;
using System.IO;
using System.Net;
using DotNetOpenAuth.Messaging;
@@ -18,7 +16,6 @@ namespace DotNetOpenAuth.Messaging {
/// <remarks>
/// Implementations of this interface must be thread safe.
/// </remarks>
- [ContractClass(typeof(IDirectWebRequestHandlerContract))]
public interface IDirectWebRequestHandler {
/// <summary>
/// Determines whether this instance can support the specified options.
@@ -27,7 +24,6 @@ namespace DotNetOpenAuth.Messaging {
/// <returns>
/// <c>true</c> if this instance can support the specified options; otherwise, <c>false</c>.
/// </returns>
- [Pure]
bool CanSupport(DirectWebRequestOptions options);
/// <summary>
@@ -102,6 +98,8 @@ namespace DotNetOpenAuth.Messaging {
/// </remarks>
IncomingWebResponse GetResponse(HttpWebRequest request, DirectWebRequestOptions options);
}
+<<<<<<< HEAD
+=======
/// <summary>
/// Code contract for the <see cref="IDirectWebRequestHandler"/> type.
@@ -220,4 +218,5 @@ namespace DotNetOpenAuth.Messaging {
#endregion
}
+>>>>>>> 884bcec... Fixed typo in comments.
}
diff --git a/src/DotNetOpenAuth/Messaging/IDirectedProtocolMessage.cs b/src/DotNetOpenAuth.Core/Messaging/IDirectedProtocolMessage.cs
index 4342d45..4342d45 100644
--- a/src/DotNetOpenAuth/Messaging/IDirectedProtocolMessage.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/IDirectedProtocolMessage.cs
diff --git a/src/DotNetOpenAuth/Messaging/IExtensionMessage.cs b/src/DotNetOpenAuth.Core/Messaging/IExtensionMessage.cs
index 5fc05a6..5fc05a6 100644
--- a/src/DotNetOpenAuth/Messaging/IExtensionMessage.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/IExtensionMessage.cs
diff --git a/src/DotNetOpenAuth/Messaging/IHttpDirectResponse.cs b/src/DotNetOpenAuth.Core/Messaging/IHttpDirectResponse.cs
index c0e7803..20c3d6f 100644
--- a/src/DotNetOpenAuth/Messaging/IHttpDirectResponse.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/IHttpDirectResponse.cs
@@ -5,16 +5,24 @@
//-----------------------------------------------------------------------
namespace DotNetOpenAuth.Messaging {
+ using System.Diagnostics.Contracts;
using System.Net;
/// <summary>
/// An interface that allows direct response messages to specify
/// HTTP transport specific properties.
/// </summary>
+ [ContractClass(typeof(IHttpDirectResponseContract))]
public interface IHttpDirectResponse {
/// <summary>
- /// Gets the HTTP status code that the direct respones should be sent with.
+ /// Gets the HTTP status code that the direct response should be sent with.
/// </summary>
HttpStatusCode HttpStatusCode { get; }
+
+ /// <summary>
+ /// Gets the HTTP headers to add to the response.
+ /// </summary>
+ /// <value>May be an empty collection, but must not be <c>null</c>.</value>
+ WebHeaderCollection Headers { get; }
}
}
diff --git a/src/DotNetOpenAuth.Core/Messaging/IHttpDirectResponseContract.cs b/src/DotNetOpenAuth.Core/Messaging/IHttpDirectResponseContract.cs
new file mode 100644
index 0000000..b1ddba2
--- /dev/null
+++ b/src/DotNetOpenAuth.Core/Messaging/IHttpDirectResponseContract.cs
@@ -0,0 +1,43 @@
+//-----------------------------------------------------------------------
+// <copyright file="IHttpDirectResponseContract.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Net;
+ using System.Text;
+
+ /// <summary>
+ /// Contract class for the <see cref="IHttpDirectResponse"/> interface.
+ /// </summary>
+ [ContractClassFor(typeof(IHttpDirectResponse))]
+ public abstract class IHttpDirectResponseContract : IHttpDirectResponse {
+ #region IHttpDirectResponse Members
+
+ /// <summary>
+ /// Gets the HTTP status code that the direct response should be sent with.
+ /// </summary>
+ /// <value></value>
+ HttpStatusCode IHttpDirectResponse.HttpStatusCode {
+ get { throw new NotImplementedException(); }
+ }
+
+ /// <summary>
+ /// Gets the HTTP headers to add to the response.
+ /// </summary>
+ /// <value>May be an empty collection, but must not be <c>null</c>.</value>
+ WebHeaderCollection IHttpDirectResponse.Headers {
+ get {
+ Contract.Ensures(Contract.Result<WebHeaderCollection>() != null);
+ throw new NotImplementedException();
+ }
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth.Core/Messaging/IHttpIndirectResponse.cs b/src/DotNetOpenAuth.Core/Messaging/IHttpIndirectResponse.cs
new file mode 100644
index 0000000..7d0fe0c
--- /dev/null
+++ b/src/DotNetOpenAuth.Core/Messaging/IHttpIndirectResponse.cs
@@ -0,0 +1,22 @@
+//-----------------------------------------------------------------------
+// <copyright file="IHttpIndirectResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging {
+ using System.Diagnostics.Contracts;
+ using System.Net;
+
+ /// <summary>
+ /// An interface that allows indirect response messages to specify
+ /// HTTP transport specific properties.
+ /// </summary>
+ public interface IHttpIndirectResponse {
+ /// <summary>
+ /// Gets a value indicating whether the payload for the message should be included
+ /// in the redirect fragment instead of the query string or POST entity.
+ /// </summary>
+ bool Include301RedirectPayloadInFragment { get; }
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/IMessage.cs b/src/DotNetOpenAuth.Core/Messaging/IMessage.cs
index e91a160..e91a160 100644
--- a/src/DotNetOpenAuth/Messaging/IMessage.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/IMessage.cs
diff --git a/src/DotNetOpenAuth/Messaging/IMessageFactory.cs b/src/DotNetOpenAuth.Core/Messaging/IMessageFactory.cs
index f9ddf3d..b44bbbf 100644
--- a/src/DotNetOpenAuth/Messaging/IMessageFactory.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/IMessageFactory.cs
@@ -66,8 +66,8 @@ namespace DotNetOpenAuth.Messaging {
/// deserialize to. Null if the request isn't recognized as a valid protocol message.
/// </returns>
IDirectedProtocolMessage IMessageFactory.GetNewRequestMessage(MessageReceivingEndpoint recipient, IDictionary<string, string> fields) {
- Contract.Requires<ArgumentNullException>(recipient != null);
- Contract.Requires<ArgumentNullException>(fields != null);
+ Requires.NotNull(recipient, "recipient");
+ Requires.NotNull(fields, "fields");
throw new NotImplementedException();
}
@@ -83,8 +83,8 @@ namespace DotNetOpenAuth.Messaging {
/// deserialize to. Null if the request isn't recognized as a valid protocol message.
/// </returns>
IDirectResponseProtocolMessage IMessageFactory.GetNewResponseMessage(IDirectedProtocolMessage request, IDictionary<string, string> fields) {
- Contract.Requires<ArgumentNullException>(request != null);
- Contract.Requires<ArgumentNullException>(fields != null);
+ Requires.NotNull(request, "request");
+ Requires.NotNull(fields, "fields");
throw new NotImplementedException();
}
diff --git a/src/DotNetOpenAuth/Messaging/IMessageOriginalPayload.cs b/src/DotNetOpenAuth.Core/Messaging/IMessageOriginalPayload.cs
index d18be20..d18be20 100644
--- a/src/DotNetOpenAuth/Messaging/IMessageOriginalPayload.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/IMessageOriginalPayload.cs
diff --git a/src/DotNetOpenAuth/Messaging/IMessageWithBinaryData.cs b/src/DotNetOpenAuth.Core/Messaging/IMessageWithBinaryData.cs
index 32ae227..32ae227 100644
--- a/src/DotNetOpenAuth/Messaging/IMessageWithBinaryData.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/IMessageWithBinaryData.cs
diff --git a/src/DotNetOpenAuth/Messaging/IMessageWithEvents.cs b/src/DotNetOpenAuth.Core/Messaging/IMessageWithEvents.cs
index 51e00fc..51e00fc 100644
--- a/src/DotNetOpenAuth/Messaging/IMessageWithEvents.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/IMessageWithEvents.cs
diff --git a/src/DotNetOpenAuth/Messaging/IProtocolMessage.cs b/src/DotNetOpenAuth.Core/Messaging/IProtocolMessage.cs
index cf43360..cf43360 100644
--- a/src/DotNetOpenAuth/Messaging/IProtocolMessage.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/IProtocolMessage.cs
diff --git a/src/DotNetOpenAuth/Messaging/IProtocolMessageWithExtensions.cs b/src/DotNetOpenAuth.Core/Messaging/IProtocolMessageWithExtensions.cs
index 44c4cbb..44c4cbb 100644
--- a/src/DotNetOpenAuth/Messaging/IProtocolMessageWithExtensions.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/IProtocolMessageWithExtensions.cs
diff --git a/src/DotNetOpenAuth.Core/Messaging/IStreamSerializingDataBag.cs b/src/DotNetOpenAuth.Core/Messaging/IStreamSerializingDataBag.cs
new file mode 100644
index 0000000..2003f9e
--- /dev/null
+++ b/src/DotNetOpenAuth.Core/Messaging/IStreamSerializingDataBag.cs
@@ -0,0 +1,55 @@
+//-----------------------------------------------------------------------
+// <copyright file="IStreamSerializingDataBag.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging {
+ using System;
+ using System.Diagnostics.Contracts;
+ using System.IO;
+
+ /// <summary>
+ /// An interface implemented by <see cref="DataBag"/>-derived types that support binary serialization.
+ /// </summary>
+ [ContractClass(typeof(IStreamSerializingDataBaContract))]
+ internal interface IStreamSerializingDataBag {
+ /// <summary>
+ /// Serializes the instance to the specified stream.
+ /// </summary>
+ /// <param name="stream">The stream.</param>
+ void Serialize(Stream stream);
+
+ /// <summary>
+ /// Initializes the fields on this instance from the specified stream.
+ /// </summary>
+ /// <param name="stream">The stream.</param>
+ void Deserialize(Stream stream);
+ }
+
+ /// <summary>
+ /// Code Contract for the <see cref="IStreamSerializingDataBag"/> interface.
+ /// </summary>
+ [ContractClassFor(typeof(IStreamSerializingDataBag))]
+ internal abstract class IStreamSerializingDataBaContract : IStreamSerializingDataBag {
+ /// <summary>
+ /// Serializes the instance to the specified stream.
+ /// </summary>
+ /// <param name="stream">The stream.</param>
+ void IStreamSerializingDataBag.Serialize(Stream stream) {
+ Contract.Requires(stream != null);
+ Contract.Requires(stream.CanWrite);
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Initializes the fields on this instance from the specified stream.
+ /// </summary>
+ /// <param name="stream">The stream.</param>
+ void IStreamSerializingDataBag.Deserialize(Stream stream) {
+ Contract.Requires(stream != null);
+ Contract.Requires(stream.CanRead);
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/ITamperResistantProtocolMessage.cs b/src/DotNetOpenAuth.Core/Messaging/ITamperResistantProtocolMessage.cs
index 0da6303..0da6303 100644
--- a/src/DotNetOpenAuth/Messaging/ITamperResistantProtocolMessage.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/ITamperResistantProtocolMessage.cs
diff --git a/src/DotNetOpenAuth/Messaging/IncomingWebResponse.cs b/src/DotNetOpenAuth.Core/Messaging/IncomingWebResponse.cs
index 70b1032..90d2f1f 100644
--- a/src/DotNetOpenAuth/Messaging/IncomingWebResponse.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/IncomingWebResponse.cs
@@ -39,8 +39,8 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="requestUri">The original request URI.</param>
/// <param name="response">The response to initialize from. The network stream is used by this class directly.</param>
protected IncomingWebResponse(Uri requestUri, HttpWebResponse response) {
- Contract.Requires<ArgumentNullException>(requestUri != null);
- Contract.Requires<ArgumentNullException>(response != null);
+ Requires.NotNull(requestUri, "requestUri");
+ Requires.NotNull(response, "response");
this.RequestUri = requestUri;
if (!string.IsNullOrEmpty(response.ContentType)) {
@@ -66,7 +66,7 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="contentType">Type of the content.</param>
/// <param name="contentEncoding">The content encoding.</param>
protected IncomingWebResponse(Uri requestUri, Uri responseUri, WebHeaderCollection headers, HttpStatusCode statusCode, string contentType, string contentEncoding) {
- Contract.Requires<ArgumentNullException>(requestUri != null);
+ Requires.NotNull(requestUri, "requestUri");
this.RequestUri = requestUri;
this.Status = statusCode;
diff --git a/src/DotNetOpenAuth/Messaging/IncomingWebResponseContract.cs b/src/DotNetOpenAuth.Core/Messaging/IncomingWebResponseContract.cs
index e9c1941..8c9a6df 100644
--- a/src/DotNetOpenAuth/Messaging/IncomingWebResponseContract.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/IncomingWebResponseContract.cs
@@ -45,8 +45,8 @@ namespace DotNetOpenAuth.Messaging {
/// be the self same instance.
/// </remarks>
internal override CachedDirectWebResponse GetSnapshot(int maximumBytesToCache) {
- Contract.Requires<ArgumentOutOfRangeException>(maximumBytesToCache >= 0);
- Contract.Requires<InvalidOperationException>(this.RequestUri != null);
+ Requires.InRange(maximumBytesToCache >= 0, "maximumBytesToCache");
+ Requires.ValidState(this.RequestUri != null);
Contract.Ensures(Contract.Result<CachedDirectWebResponse>() != null);
throw new NotImplementedException();
}
diff --git a/src/DotNetOpenAuth/Messaging/InternalErrorException.cs b/src/DotNetOpenAuth.Core/Messaging/InternalErrorException.cs
index 32b44f2..32b44f2 100644
--- a/src/DotNetOpenAuth/Messaging/InternalErrorException.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/InternalErrorException.cs
diff --git a/src/DotNetOpenAuth/Messaging/KeyedCollectionDelegate.cs b/src/DotNetOpenAuth.Core/Messaging/KeyedCollectionDelegate.cs
index 5555f9c..c0a08df 100644
--- a/src/DotNetOpenAuth/Messaging/KeyedCollectionDelegate.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/KeyedCollectionDelegate.cs
@@ -27,7 +27,7 @@ namespace DotNetOpenAuth.Messaging {
/// </summary>
/// <param name="getKeyForItemDelegate">The delegate that gets the key for a given item.</param>
internal KeyedCollectionDelegate(Func<TItem, TKey> getKeyForItemDelegate) {
- Contract.Requires<ArgumentNullException>(getKeyForItemDelegate != null);
+ Requires.NotNull(getKeyForItemDelegate, "getKeyForItemDelegate");
this.getKeyForItemDelegate = getKeyForItemDelegate;
}
diff --git a/src/DotNetOpenAuth/Messaging/MessagePartAttribute.cs b/src/DotNetOpenAuth.Core/Messaging/MessagePartAttribute.cs
index 22c660c..22c660c 100644
--- a/src/DotNetOpenAuth/Messaging/MessagePartAttribute.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/MessagePartAttribute.cs
diff --git a/src/DotNetOpenAuth/Messaging/MessageProtections.cs b/src/DotNetOpenAuth.Core/Messaging/MessageProtections.cs
index c78c92f..c78c92f 100644
--- a/src/DotNetOpenAuth/Messaging/MessageProtections.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/MessageProtections.cs
diff --git a/src/DotNetOpenAuth/Messaging/MessageReceivingEndpoint.cs b/src/DotNetOpenAuth.Core/Messaging/MessageReceivingEndpoint.cs
index e39a047..ca7c5df 100644
--- a/src/DotNetOpenAuth/Messaging/MessageReceivingEndpoint.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/MessageReceivingEndpoint.cs
@@ -22,9 +22,9 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="method">The HTTP method(s) allowed.</param>
public MessageReceivingEndpoint(string locationUri, HttpDeliveryMethods method)
: this(new Uri(locationUri), method) {
- Contract.Requires<ArgumentNullException>(locationUri != null);
- Contract.Requires<ArgumentOutOfRangeException>(method != HttpDeliveryMethods.None);
- Contract.Requires<ArgumentOutOfRangeException>((method & HttpDeliveryMethods.HttpVerbMask) != 0, MessagingStrings.GetOrPostFlagsRequired);
+ Requires.NotNull(locationUri, "locationUri");
+ Requires.InRange(method != HttpDeliveryMethods.None, "method");
+ Requires.InRange((method & HttpDeliveryMethods.HttpVerbMask) != 0, "method", MessagingStrings.GetOrPostFlagsRequired);
}
/// <summary>
@@ -33,9 +33,9 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="location">The URL of this endpoint.</param>
/// <param name="method">The HTTP method(s) allowed.</param>
public MessageReceivingEndpoint(Uri location, HttpDeliveryMethods method) {
- Contract.Requires<ArgumentNullException>(location != null);
- Contract.Requires<ArgumentOutOfRangeException>(method != HttpDeliveryMethods.None);
- Contract.Requires<ArgumentOutOfRangeException>((method & HttpDeliveryMethods.HttpVerbMask) != 0, MessagingStrings.GetOrPostFlagsRequired);
+ Requires.NotNull(location, "location");
+ Requires.InRange(method != HttpDeliveryMethods.None, "method");
+ Requires.InRange((method & HttpDeliveryMethods.HttpVerbMask) != 0, "method", MessagingStrings.GetOrPostFlagsRequired);
this.Location = location;
this.AllowedMethods = method;
diff --git a/src/DotNetOpenAuth/Messaging/MessageSerializer.cs b/src/DotNetOpenAuth.Core/Messaging/MessageSerializer.cs
index e1625b9..957ea41 100644
--- a/src/DotNetOpenAuth/Messaging/MessageSerializer.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/MessageSerializer.cs
@@ -12,8 +12,8 @@ namespace DotNetOpenAuth.Messaging {
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Reflection;
+ using System.Xml;
using DotNetOpenAuth.Messaging.Reflection;
- using DotNetOpenAuth.OAuth.ChannelElements;
/// <summary>
/// Serializes/deserializes OAuth messages for/from transit.
@@ -33,8 +33,7 @@ namespace DotNetOpenAuth.Messaging {
/// that will be serialized and deserialized using this class.</param>
[ContractVerification(false)] // bugs/limitations in CC static analysis
private MessageSerializer(Type messageType) {
- Contract.Requires<ArgumentNullException>(messageType != null);
- Contract.Requires<ArgumentException>(typeof(IMessage).IsAssignableFrom(messageType));
+ Requires.NotNullSubtype<IMessage>(messageType, "messageType");
Contract.Ensures(this.messageType != null);
this.messageType = messageType;
}
@@ -46,13 +45,102 @@ namespace DotNetOpenAuth.Messaging {
/// <returns>A message serializer for the given message type.</returns>
[ContractVerification(false)] // bugs/limitations in CC static analysis
internal static MessageSerializer Get(Type messageType) {
- Contract.Requires<ArgumentNullException>(messageType != null);
- Contract.Requires<ArgumentException>(typeof(IMessage).IsAssignableFrom(messageType));
+ Requires.NotNullSubtype<IMessage>(messageType, "messageType");
return new MessageSerializer(messageType);
}
/// <summary>
+ /// Reads JSON as a flat dictionary into a message.
+ /// </summary>
+ /// <param name="messageDictionary">The message dictionary to fill with the JSON-deserialized data.</param>
+ /// <param name="reader">The JSON reader.</param>
+ internal static void DeserializeJsonAsFlatDictionary(IDictionary<string, string> messageDictionary, XmlDictionaryReader reader) {
+ Requires.NotNull(messageDictionary, "messageDictionary");
+ Requires.NotNull(reader, "reader");
+
+ reader.Read(); // one extra one to skip the root node.
+ while (reader.Read()) {
+ if (reader.NodeType == XmlNodeType.EndElement) {
+ // This is likely the closing </root> tag.
+ continue;
+ }
+
+ string key = reader.Name;
+ reader.Read();
+ string value = reader.ReadContentAsString();
+ messageDictionary[key] = value;
+ }
+ }
+
+ /// <summary>
+ /// Reads the data from a message instance and writes a XML/JSON encoding of it.
+ /// </summary>
+ /// <param name="messageDictionary">The message to be serialized.</param>
+ /// <param name="writer">The writer to use for the serialized form.</param>
+ /// <remarks>
+ /// Use <see cref="System.Runtime.Serialization.Json.JsonReaderWriterFactory.CreateJsonWriter(System.IO.Stream)"/>
+ /// to create the <see cref="XmlDictionaryWriter"/> instance capable of emitting JSON.
+ /// </remarks>
+ [Pure]
+ internal static void Serialize(MessageDictionary messageDictionary, XmlDictionaryWriter writer) {
+ Requires.NotNull(messageDictionary, "messageDictionary");
+ Requires.NotNull(writer, "writer");
+
+ writer.WriteStartElement("root");
+ writer.WriteAttributeString("type", "object");
+ foreach (var pair in messageDictionary) {
+ bool include = false;
+ string type = "string";
+ MessagePart partDescription;
+ if (messageDictionary.Description.Mapping.TryGetValue(pair.Key, out partDescription)) {
+ Contract.Assume(partDescription != null);
+ if (partDescription.IsRequired || partDescription.IsNondefaultValueSet(messageDictionary.Message)) {
+ include = true;
+ if (IsNumeric(partDescription.MemberDeclaredType)) {
+ type = "number";
+ } else if (partDescription.MemberDeclaredType.IsAssignableFrom(typeof(bool))) {
+ type = "boolean";
+ }
+ }
+ } else {
+ // This is extra data. We always write it out.
+ include = true;
+ }
+
+ if (include) {
+ writer.WriteStartElement(pair.Key);
+ writer.WriteAttributeString("type", type);
+ writer.WriteString(pair.Value);
+ writer.WriteEndElement();
+ }
+ }
+
+ writer.WriteEndElement();
+ }
+
+ /// <summary>
+ /// Reads XML/JSON into a message dictionary.
+ /// </summary>
+ /// <param name="messageDictionary">The message to deserialize into.</param>
+ /// <param name="reader">The XML/JSON to read into the message.</param>
+ /// <exception cref="ProtocolException">Thrown when protocol rules are broken by the incoming message.</exception>
+ /// <remarks>
+ /// Use <see cref="System.Runtime.Serialization.Json.JsonReaderWriterFactory.CreateJsonReader(System.IO.Stream, System.Xml.XmlDictionaryReaderQuotas)"/>
+ /// to create the <see cref="XmlDictionaryReader"/> instance capable of reading JSON.
+ /// </remarks>
+ internal static void Deserialize(MessageDictionary messageDictionary, XmlDictionaryReader reader) {
+ Requires.NotNull(messageDictionary, "messageDictionary");
+ Requires.NotNull(reader, "reader");
+
+ DeserializeJsonAsFlatDictionary(messageDictionary, reader);
+
+ // Make sure all the required parts are present and valid.
+ messageDictionary.Description.EnsureMessagePartsPassBasicValidation(messageDictionary);
+ messageDictionary.Message.EnsureValidMessage();
+ }
+
+ /// <summary>
/// Reads the data from a message instance and returns a series of name=value pairs for the fields that must be included in the message.
/// </summary>
/// <param name="messageDictionary">The message to be serialized.</param>
@@ -60,13 +148,13 @@ namespace DotNetOpenAuth.Messaging {
[Pure]
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Parallel design with Deserialize method.")]
internal IDictionary<string, string> Serialize(MessageDictionary messageDictionary) {
- Contract.Requires<ArgumentNullException>(messageDictionary != null);
+ Requires.NotNull(messageDictionary, "messageDictionary");
Contract.Ensures(Contract.Result<IDictionary<string, string>>() != null);
// Rather than hand back the whole message dictionary (which
// includes keys with blank values), create a new dictionary
// that only has required keys, and optional keys whose
- // values are not empty.
+ // values are not empty (or default).
var result = new Dictionary<string, string>();
foreach (var pair in messageDictionary) {
MessagePart partDescription;
@@ -91,8 +179,8 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="messageDictionary">The message to deserialize into.</param>
/// <exception cref="ProtocolException">Thrown when protocol rules are broken by the incoming message.</exception>
internal void Deserialize(IDictionary<string, string> fields, MessageDictionary messageDictionary) {
- Contract.Requires<ArgumentNullException>(fields != null);
- Contract.Requires<ArgumentNullException>(messageDictionary != null);
+ Requires.NotNull(fields, "fields");
+ Requires.NotNull(messageDictionary, "messageDictionary");
var messageDescription = messageDictionary.Description;
@@ -115,6 +203,24 @@ namespace DotNetOpenAuth.Messaging {
}
}
+ /// <summary>
+ /// Determines whether the specified type is numeric.
+ /// </summary>
+ /// <param name="type">The type to test.</param>
+ /// <returns>
+ /// <c>true</c> if the specified type is numeric; otherwise, <c>false</c>.
+ /// </returns>
+ private static bool IsNumeric(Type type) {
+ return type.IsAssignableFrom(typeof(double))
+ || type.IsAssignableFrom(typeof(float))
+ || type.IsAssignableFrom(typeof(short))
+ || type.IsAssignableFrom(typeof(int))
+ || type.IsAssignableFrom(typeof(long))
+ || type.IsAssignableFrom(typeof(ushort))
+ || type.IsAssignableFrom(typeof(uint))
+ || type.IsAssignableFrom(typeof(ulong));
+ }
+
#if CONTRACTS_FULL
/// <summary>
/// Verifies conditions that should be true for any valid state of this object.
diff --git a/src/DotNetOpenAuth/Messaging/MessageTransport.cs b/src/DotNetOpenAuth.Core/Messaging/MessageTransport.cs
index ee06c95..ee06c95 100644
--- a/src/DotNetOpenAuth/Messaging/MessageTransport.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/MessageTransport.cs
diff --git a/src/DotNetOpenAuth/Messaging/Messaging.cd b/src/DotNetOpenAuth.Core/Messaging/Messaging.cd
index 0c22565..0c22565 100644
--- a/src/DotNetOpenAuth/Messaging/Messaging.cd
+++ b/src/DotNetOpenAuth.Core/Messaging/Messaging.cd
diff --git a/src/DotNetOpenAuth/Messaging/MessagingStrings.Designer.cs b/src/DotNetOpenAuth.Core/Messaging/MessagingStrings.Designer.cs
index e2638c9..3ad2bdd 100644
--- a/src/DotNetOpenAuth/Messaging/MessagingStrings.Designer.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/MessagingStrings.Designer.cs
@@ -1,7 +1,7 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
-// Runtime Version:4.0.30319.1
+// Runtime Version:4.0.30319.239
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
@@ -133,6 +133,15 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Looks up a localized string similar to Unable to instantiate the message part encoder/decoder type {0}..
+ /// </summary>
+ internal static string EncoderInstantiationFailed {
+ get {
+ return ResourceManager.GetString("EncoderInstantiationFailed", resourceCulture);
+ }
+ }
+
+ /// <summary>
/// Looks up a localized string similar to Error while deserializing message {0}..
/// </summary>
internal static string ErrorDeserializingMessage {
@@ -178,6 +187,15 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Looks up a localized string similar to The message part {0} was expected in the {1} message but was not found..
+ /// </summary>
+ internal static string ExpectedParameterWasMissing {
+ get {
+ return ResourceManager.GetString("ExpectedParameterWasMissing", resourceCulture);
+ }
+ }
+
+ /// <summary>
/// Looks up a localized string similar to The message expired at {0} and it is now {1}..
/// </summary>
internal static string ExpiredMessage {
@@ -367,6 +385,15 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Looks up a localized string similar to The following message parts had constant value requirements that were unsatisfied: {0}.
+ /// </summary>
+ internal static string RequiredMessagePartConstantIncorrect {
+ get {
+ return ResourceManager.GetString("RequiredMessagePartConstantIncorrect", resourceCulture);
+ }
+ }
+
+ /// <summary>
/// Looks up a localized string similar to The following required non-empty parameters were empty in the {0} message: {1}.
/// </summary>
internal static string RequiredNonEmptyParameterWasEmpty {
@@ -439,6 +466,15 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Looks up a localized string similar to This message factory does not support message type(s): {0}.
+ /// </summary>
+ internal static string StandardMessageFactoryUnsupportedMessageType {
+ get {
+ return ResourceManager.GetString("StandardMessageFactoryUnsupportedMessageType", resourceCulture);
+ }
+ }
+
+ /// <summary>
/// Looks up a localized string similar to The stream must have a known length..
/// </summary>
internal static string StreamMustHaveKnownLength {
@@ -601,6 +637,15 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Looks up a localized string similar to This blob is not a recognized encryption format..
+ /// </summary>
+ internal static string UnsupportedEncryptionAlgorithm {
+ get {
+ return ResourceManager.GetString("UnsupportedEncryptionAlgorithm", resourceCulture);
+ }
+ }
+
+ /// <summary>
/// Looks up a localized string similar to The HTTP verb &apos;{0}&apos; is unrecognized and unsupported..
/// </summary>
internal static string UnsupportedHttpVerb {
diff --git a/src/DotNetOpenAuth/Messaging/MessagingStrings.resx b/src/DotNetOpenAuth.Core/Messaging/MessagingStrings.resx
index 30490c7..5f3f79a 100644
--- a/src/DotNetOpenAuth/Messaging/MessagingStrings.resx
+++ b/src/DotNetOpenAuth.Core/Messaging/MessagingStrings.resx
@@ -303,10 +303,25 @@
<data name="SessionRequired" xml:space="preserve">
<value>An HttpContext.Current.Session object is required.</value>
</data>
+ <data name="StandardMessageFactoryUnsupportedMessageType" xml:space="preserve">
+ <value>This message factory does not support message type(s): {0}</value>
+ </data>
+ <data name="RequiredMessagePartConstantIncorrect" xml:space="preserve">
+ <value>The following message parts had constant value requirements that were unsatisfied: {0}</value>
+ </data>
+ <data name="EncoderInstantiationFailed" xml:space="preserve">
+ <value>Unable to instantiate the message part encoder/decoder type {0}.</value>
+ </data>
<data name="MessageTimestampInFuture" xml:space="preserve">
<value>This message has a timestamp of {0}, which is beyond the allowable clock skew for in the future.</value>
</data>
+ <data name="UnsupportedEncryptionAlgorithm" xml:space="preserve">
+ <value>This blob is not a recognized encryption format.</value>
+ </data>
<data name="ExtraParameterAddFailure" xml:space="preserve">
<value>Failed to add extra parameter '{0}' with value '{1}'.</value>
</data>
-</root>
+ <data name="ExpectedParameterWasMissing" xml:space="preserve">
+ <value>The message part {0} was expected in the {1} message but was not found.</value>
+ </data>
+</root> \ No newline at end of file
diff --git a/src/DotNetOpenAuth/Messaging/MessagingStrings.sr.resx b/src/DotNetOpenAuth.Core/Messaging/MessagingStrings.sr.resx
index 5b7b716..5b7b716 100644
--- a/src/DotNetOpenAuth/Messaging/MessagingStrings.sr.resx
+++ b/src/DotNetOpenAuth.Core/Messaging/MessagingStrings.sr.resx
diff --git a/src/DotNetOpenAuth/Messaging/MessagingUtilities.cs b/src/DotNetOpenAuth.Core/Messaging/MessagingUtilities.cs
index 4b20ab8..2a94791 100644
--- a/src/DotNetOpenAuth/Messaging/MessagingUtilities.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/MessagingUtilities.cs
@@ -12,6 +12,7 @@ namespace DotNetOpenAuth.Messaging {
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
+ using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Mime;
@@ -20,11 +21,13 @@ namespace DotNetOpenAuth.Messaging {
using System.Text;
using System.Web;
using System.Web.Mvc;
+ using DotNetOpenAuth.Messaging.Bindings;
using DotNetOpenAuth.Messaging.Reflection;
/// <summary>
/// A grab-bag of utility methods useful for the channel stack of the protocol.
/// </summary>
+ [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Utility class touches lots of surface area")]
public static class MessagingUtilities {
/// <summary>
/// The cryptographically strong random data generator used for creating secrets.
@@ -53,12 +56,57 @@ namespace DotNetOpenAuth.Messaging {
internal const string Digits = "0123456789";
/// <summary>
+ /// The set of digits and alphabetic letters (upper and lowercase).
+ /// </summary>
+ internal const string AlphaNumeric = UppercaseLetters + LowercaseLetters + Digits;
+
+ /// <summary>
+ /// All the characters that are allowed for use as a base64 encoding character.
+ /// </summary>
+ internal const string Base64Characters = AlphaNumeric + "+" + "/";
+
+ /// <summary>
+ /// All the characters that are allowed for use as a base64 encoding character
+ /// in the "web safe" context.
+ /// </summary>
+ internal const string Base64WebSafeCharacters = AlphaNumeric + "-" + "_";
+
+ /// <summary>
/// The set of digits, and alphabetic letters (upper and lowercase) that are clearly
/// visually distinguishable.
/// </summary>
internal const string AlphaNumericNoLookAlikes = "23456789abcdefghjkmnpqrstwxyzABCDEFGHJKMNPQRSTWXYZ";
/// <summary>
+ /// The length of private symmetric secret handles.
+ /// </summary>
+ /// <remarks>
+ /// This value needn't be high, as we only expect to have a small handful of unexpired secrets at a time,
+ /// and handle recycling is permissible.
+ /// </remarks>
+ private const int SymmetricSecretHandleLength = 4;
+
+ /// <summary>
+ /// The default lifetime of a private secret.
+ /// </summary>
+ private static readonly TimeSpan SymmetricSecretKeyLifespan = Configuration.DotNetOpenAuthSection.Messaging.PrivateSecretMaximumAge;
+
+ /// <summary>
+ /// A character array containing just the = character.
+ /// </summary>
+ private static readonly char[] EqualsArray = new char[] { '=' };
+
+ /// <summary>
+ /// A character array containing just the , character.
+ /// </summary>
+ private static readonly char[] CommaArray = new char[] { ',' };
+
+ /// <summary>
+ /// A character array containing just the " character.
+ /// </summary>
+ private static readonly char[] QuoteArray = new char[] { '"' };
+
+ /// <summary>
/// The set of characters that are unreserved in RFC 2396 but are NOT unreserved in RFC 3986.
/// </summary>
private static readonly string[] UriRfc3986CharsToEscape = new[] { "!", "*", "'", "(", ")" };
@@ -92,7 +140,7 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="response">The response to send to the user agent.</param>
/// <returns>The <see cref="ActionResult"/> instance to be returned by the Controller's action method.</returns>
public static ActionResult AsActionResult(this OutgoingWebResponse response) {
- Contract.Requires<ArgumentNullException>(response != null);
+ Requires.NotNull(response, "response");
return new OutgoingWebResponseActionResult(response);
}
@@ -104,7 +152,7 @@ namespace DotNetOpenAuth.Messaging {
[SuppressMessage("Microsoft.Usage", "CA2234:PassSystemUriObjectsInsteadOfStrings", Justification = "The Uri merging requires use of a string value.")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Expensive call should not be a property.")]
public static Uri GetRequestUrlFromContext() {
- Contract.Requires<InvalidOperationException>(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
+ Requires.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
HttpContext context = HttpContext.Current;
return HttpRequestInfo.GetPublicFacingUrl(context.Request, context.Request.ServerVariables);
@@ -117,8 +165,8 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="prefix">The prefix for parameters to remove. A period is NOT automatically appended.</param>
/// <returns>Either a new Uri with the parameters removed if there were any to remove, or the same Uri instance if no parameters needed to be removed.</returns>
public static Uri StripQueryArgumentsWithPrefix(this Uri uri, string prefix) {
- Contract.Requires<ArgumentNullException>(uri != null);
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(prefix));
+ Requires.NotNull(uri, "uri");
+ Requires.NotNullOrEmpty(prefix, "prefix");
NameValueCollection queryArgs = HttpUtility.ParseQueryString(uri.Query);
var matchingKeys = queryArgs.Keys.OfType<string>().Where(key => key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToList();
@@ -142,9 +190,9 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="parts">The parts to include in the POST entity.</param>
/// <returns>The HTTP response.</returns>
public static IncomingWebResponse PostMultipart(this HttpWebRequest request, IDirectWebRequestHandler requestHandler, IEnumerable<MultipartPostPart> parts) {
- Contract.Requires<ArgumentNullException>(request != null);
- Contract.Requires<ArgumentNullException>(requestHandler != null);
- Contract.Requires<ArgumentNullException>(parts != null);
+ Requires.NotNull(request, "request");
+ Requires.NotNull(requestHandler, "requestHandler");
+ Requires.NotNull(parts, "parts");
PostMultipartNoGetResponse(request, requestHandler, parts);
return requestHandler.GetResponse(request);
@@ -193,15 +241,105 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Cuts off precision beyond a second on a DateTime value.
+ /// </summary>
+ /// <param name="value">The value.</param>
+ /// <returns>A DateTime with a 0 millisecond component.</returns>
+ public static DateTime CutToSecond(this DateTime value) {
+ return value - TimeSpan.FromMilliseconds(value.Millisecond);
+ }
+
+ /// <summary>
+ /// Adds a name-value pair to the end of a given URL
+ /// as part of the querystring piece. Prefixes a ? or &amp; before
+ /// first element as necessary.
+ /// </summary>
+ /// <param name="builder">The UriBuilder to add arguments to.</param>
+ /// <param name="name">The name of the parameter to add.</param>
+ /// <param name="value">The value of the argument.</param>
+ /// <remarks>
+ /// If the parameters to add match names of parameters that already are defined
+ /// in the query string, the existing ones are <i>not</i> replaced.
+ /// </remarks>
+ public static void AppendQueryArgument(this UriBuilder builder, string name, string value) {
+ AppendQueryArgs(builder, new[] { new KeyValuePair<string, string>(name, value) });
+ }
+
+ /// <summary>
+ /// Adds a set of values to a collection.
+ /// </summary>
+ /// <typeparam name="T">The type of value kept in the collection.</typeparam>
+ /// <param name="collection">The collection to add to.</param>
+ /// <param name="values">The values to add to the collection.</param>
+ public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> values) {
+ Requires.NotNull(collection, "collection");
+ Requires.NotNull(values, "values");
+
+ foreach (var value in values) {
+ collection.Add(value);
+ }
+ }
+
+ /// <summary>
+ /// Tests whether two timespans are within reasonable approximation of each other.
+ /// </summary>
+ /// <param name="self">One TimeSpan.</param>
+ /// <param name="other">The other TimeSpan.</param>
+ /// <param name="marginOfError">The allowable margin of error.</param>
+ /// <returns><c>true</c> if the two TimeSpans are within <paramref name="marginOfError"/> of each other.</returns>
+ public static bool Equals(this TimeSpan self, TimeSpan other, TimeSpan marginOfError) {
+ return TimeSpan.FromMilliseconds(Math.Abs((self - other).TotalMilliseconds)) < marginOfError;
+ }
+
+ /// <summary>
+ /// Clears any existing elements in a collection and fills the collection with a given set of values.
+ /// </summary>
+ /// <typeparam name="T">The type of value kept in the collection.</typeparam>
+ /// <param name="collection">The collection to modify.</param>
+ /// <param name="values">The new values to fill the collection.</param>
+ internal static void ResetContents<T>(this ICollection<T> collection, IEnumerable<T> values) {
+ Requires.NotNull(collection, "collection");
+
+ collection.Clear();
+ if (values != null) {
+ AddRange(collection, values);
+ }
+ }
+
+ /// <summary>
+ /// Strips any and all URI query parameters that serve as parts of a message.
+ /// </summary>
+ /// <param name="uri">The URI that may contain query parameters to remove.</param>
+ /// <param name="messageDescription">The message description whose parts should be removed from the URL.</param>
+ /// <returns>A cleaned URL.</returns>
+ internal static Uri StripMessagePartsFromQueryString(this Uri uri, MessageDescription messageDescription) {
+ Requires.NotNull(uri, "uri");
+ Requires.NotNull(messageDescription, "messageDescription");
+
+ NameValueCollection queryArgs = HttpUtility.ParseQueryString(uri.Query);
+ var matchingKeys = queryArgs.Keys.OfType<string>().Where(key => messageDescription.Mapping.ContainsKey(key)).ToList();
+ if (matchingKeys.Count > 0) {
+ var builder = new UriBuilder(uri);
+ foreach (string key in matchingKeys) {
+ queryArgs.Remove(key);
+ }
+ builder.Query = CreateQueryString(queryArgs.ToDictionary());
+ return builder.Uri;
+ } else {
+ return uri;
+ }
+ }
+
+ /// <summary>
/// Sends a multipart HTTP POST request (useful for posting files) but doesn't call GetResponse on it.
/// </summary>
/// <param name="request">The HTTP request.</param>
/// <param name="requestHandler">The request handler.</param>
/// <param name="parts">The parts to include in the POST entity.</param>
internal static void PostMultipartNoGetResponse(this HttpWebRequest request, IDirectWebRequestHandler requestHandler, IEnumerable<MultipartPostPart> parts) {
- Contract.Requires<ArgumentNullException>(request != null);
- Contract.Requires<ArgumentNullException>(requestHandler != null);
- Contract.Requires<ArgumentNullException>(parts != null);
+ Requires.NotNull(request, "request");
+ Requires.NotNull(requestHandler, "requestHandler");
+ Requires.NotNull(parts, "parts");
Reporting.RecordFeatureUse("MessagingUtilities.PostMultipart");
parts = parts.CacheGeneratedResults();
@@ -246,6 +384,95 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Assembles the content of the HTTP Authorization or WWW-Authenticate header.
+ /// </summary>
+ /// <param name="scheme">The scheme.</param>
+ /// <param name="fields">The fields to include.</param>
+ /// <returns>A value prepared for an HTTP header.</returns>
+ internal static string AssembleAuthorizationHeader(string scheme, IEnumerable<KeyValuePair<string, string>> fields) {
+ Requires.NotNullOrEmpty(scheme, "scheme");
+ Requires.NotNull(fields, "fields");
+
+ var authorization = new StringBuilder();
+ authorization.Append(scheme);
+ authorization.Append(" ");
+ foreach (var pair in fields) {
+ string key = MessagingUtilities.EscapeUriDataStringRfc3986(pair.Key);
+ string value = MessagingUtilities.EscapeUriDataStringRfc3986(pair.Value);
+ authorization.Append(key);
+ authorization.Append("=\"");
+ authorization.Append(value);
+ authorization.Append("\",");
+ }
+ authorization.Length--; // remove trailing comma
+ return authorization.ToString();
+ }
+
+ /// <summary>
+ /// Parses the authorization header.
+ /// </summary>
+ /// <param name="scheme">The scheme. Must not be null or empty.</param>
+ /// <param name="authorizationHeader">The authorization header. May be null or empty.</param>
+ /// <returns>A sequence of key=value pairs discovered in the header. Never null, but may be empty.</returns>
+ internal static IEnumerable<KeyValuePair<string, string>> ParseAuthorizationHeader(string scheme, string authorizationHeader) {
+ Requires.NotNullOrEmpty(scheme, "scheme");
+ Contract.Ensures(Contract.Result<IEnumerable<KeyValuePair<string, string>>>() != null);
+
+ string prefix = scheme + " ";
+ if (authorizationHeader != null) {
+ // The authorization header may have multiple sections. Look for the appropriate one.
+ string[] authorizationSections = new string[] { authorizationHeader }; // what is the right delimiter, if any?
+ foreach (string authorization in authorizationSections) {
+ string trimmedAuth = authorization.Trim();
+ if (trimmedAuth.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) { // RFC 2617 says this is case INsensitive
+ string data = trimmedAuth.Substring(prefix.Length);
+ return from element in data.Split(CommaArray)
+ let parts = element.Split(EqualsArray, 2)
+ let key = Uri.UnescapeDataString(parts[0])
+ let value = Uri.UnescapeDataString(parts[1].Trim(QuoteArray))
+ select new KeyValuePair<string, string>(key, value);
+ }
+ }
+ }
+
+ return Enumerable.Empty<KeyValuePair<string, string>>();
+ }
+
+ /// <summary>
+ /// Encodes a symmetric key handle and the blob that is encrypted/signed with that key into a single string
+ /// that can be decoded by <see cref="ExtractKeyHandleAndPayload"/>.
+ /// </summary>
+ /// <param name="handle">The cryptographic key handle.</param>
+ /// <param name="payload">The encrypted/signed blob.</param>
+ /// <returns>The combined encoded value.</returns>
+ internal static string CombineKeyHandleAndPayload(string handle, string payload) {
+ Requires.NotNullOrEmpty(handle, "handle");
+ Requires.NotNullOrEmpty(payload, "payload");
+ Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>()));
+
+ return handle + "!" + payload;
+ }
+
+ /// <summary>
+ /// Extracts the key handle and encrypted blob from a string previously returned from <see cref="CombineKeyHandleAndPayload"/>.
+ /// </summary>
+ /// <param name="containingMessage">The containing message.</param>
+ /// <param name="messagePart">The message part.</param>
+ /// <param name="keyHandleAndBlob">The value previously returned from <see cref="CombineKeyHandleAndPayload"/>.</param>
+ /// <param name="handle">The crypto key handle.</param>
+ /// <param name="dataBlob">The encrypted/signed data.</param>
+ internal static void ExtractKeyHandleAndPayload(IProtocolMessage containingMessage, string messagePart, string keyHandleAndBlob, out string handle, out string dataBlob) {
+ Requires.NotNull(containingMessage, "containingMessage");
+ Requires.NotNullOrEmpty(messagePart, "messagePart");
+ Requires.NotNullOrEmpty(keyHandleAndBlob, "keyHandleAndBlob");
+
+ int privateHandleIndex = keyHandleAndBlob.IndexOf('!');
+ ErrorUtilities.VerifyProtocol(privateHandleIndex > 0, MessagingStrings.UnexpectedMessagePartValue, messagePart, keyHandleAndBlob);
+ handle = keyHandleAndBlob.Substring(0, privateHandleIndex);
+ dataBlob = keyHandleAndBlob.Substring(privateHandleIndex + 1);
+ }
+
+ /// <summary>
/// Gets a buffer of random data (not cryptographically strong).
/// </summary>
/// <param name="length">The length of the sequence to generate.</param>
@@ -286,8 +513,8 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="allowableCharacters">The allowable characters.</param>
/// <returns>A random string.</returns>
internal static string GetRandomString(int length, string allowableCharacters) {
- Contract.Requires<ArgumentOutOfRangeException>(length >= 0);
- Contract.Requires<ArgumentException>(allowableCharacters != null && allowableCharacters.Length >= 2);
+ Requires.InRange(length >= 0, "length");
+ Requires.True(allowableCharacters != null && allowableCharacters.Length >= 2, "allowableCharacters");
char[] randomString = new char[length];
for (int i = 0; i < length; i++) {
@@ -298,6 +525,344 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Computes the hash of a string.
+ /// </summary>
+ /// <param name="algorithm">The hash algorithm to use.</param>
+ /// <param name="value">The value to hash.</param>
+ /// <param name="encoding">The encoding to use when converting the string to a byte array.</param>
+ /// <returns>A base64 encoded string.</returns>
+ internal static string ComputeHash(this HashAlgorithm algorithm, string value, Encoding encoding = null) {
+ Requires.NotNull(algorithm, "algorithm");
+ Requires.NotNull(value, "value");
+ Contract.Ensures(Contract.Result<string>() != null);
+
+ encoding = encoding ?? Encoding.UTF8;
+ byte[] bytesToHash = encoding.GetBytes(value);
+ byte[] hash = algorithm.ComputeHash(bytesToHash);
+ string base64Hash = Convert.ToBase64String(hash);
+ return base64Hash;
+ }
+
+ /// <summary>
+ /// Computes the hash of a sequence of key=value pairs.
+ /// </summary>
+ /// <param name="algorithm">The hash algorithm to use.</param>
+ /// <param name="data">The data to hash.</param>
+ /// <param name="encoding">The encoding to use when converting the string to a byte array.</param>
+ /// <returns>A base64 encoded string.</returns>
+ internal static string ComputeHash(this HashAlgorithm algorithm, IDictionary<string, string> data, Encoding encoding = null) {
+ Requires.NotNull(algorithm, "algorithm");
+ Requires.NotNull(data, "data");
+ Contract.Ensures(Contract.Result<string>() != null);
+
+ // Assemble the dictionary to sign, taking care to remove the signature itself
+ // in order to accurately reproduce the original signature (which of course didn't include
+ // the signature).
+ // Also we need to sort the dictionary's keys so that we sign in the same order as we did
+ // the last time.
+ var sortedData = new SortedDictionary<string, string>(data, StringComparer.OrdinalIgnoreCase);
+ return ComputeHash(algorithm, (IEnumerable<KeyValuePair<string, string>>)sortedData, encoding);
+ }
+
+ /// <summary>
+ /// Computes the hash of a sequence of key=value pairs.
+ /// </summary>
+ /// <param name="algorithm">The hash algorithm to use.</param>
+ /// <param name="sortedData">The data to hash.</param>
+ /// <param name="encoding">The encoding to use when converting the string to a byte array.</param>
+ /// <returns>A base64 encoded string.</returns>
+ internal static string ComputeHash(this HashAlgorithm algorithm, IEnumerable<KeyValuePair<string, string>> sortedData, Encoding encoding = null) {
+ Requires.NotNull(algorithm, "algorithm");
+ Requires.NotNull(sortedData, "sortedData");
+ Contract.Ensures(Contract.Result<string>() != null);
+
+ return ComputeHash(algorithm, CreateQueryString(sortedData), encoding);
+ }
+
+ /// <summary>
+ /// Encrypts a byte buffer.
+ /// </summary>
+ /// <param name="buffer">The buffer to encrypt.</param>
+ /// <param name="key">The symmetric secret to use to encrypt the buffer. Allowed values are 128, 192, or 256 bytes in length.</param>
+ /// <returns>The encrypted buffer</returns>
+ internal static byte[] Encrypt(byte[] buffer, byte[] key) {
+ using (SymmetricAlgorithm crypto = CreateSymmetricAlgorithm(key)) {
+ using (var ms = new MemoryStream()) {
+ var binaryWriter = new BinaryWriter(ms);
+ binaryWriter.Write((byte)1); // version of encryption algorithm
+ binaryWriter.Write(crypto.IV);
+ binaryWriter.Flush();
+
+ var cryptoStream = new CryptoStream(ms, crypto.CreateEncryptor(), CryptoStreamMode.Write);
+ cryptoStream.Write(buffer, 0, buffer.Length);
+ cryptoStream.FlushFinalBlock();
+
+ return ms.ToArray();
+ }
+ }
+ }
+
+ /// <summary>
+ /// Decrypts a byte buffer.
+ /// </summary>
+ /// <param name="buffer">The buffer to decrypt.</param>
+ /// <param name="key">The symmetric secret to use to decrypt the buffer. Allowed values are 128, 192, and 256.</param>
+ /// <returns>The encrypted buffer</returns>
+ [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "This Dispose is safe.")]
+ internal static byte[] Decrypt(byte[] buffer, byte[] key) {
+ using (SymmetricAlgorithm crypto = CreateSymmetricAlgorithm(key)) {
+ using (var ms = new MemoryStream(buffer)) {
+ var binaryReader = new BinaryReader(ms);
+ int algorithmVersion = binaryReader.ReadByte();
+ ErrorUtilities.VerifyProtocol(algorithmVersion == 1, MessagingStrings.UnsupportedEncryptionAlgorithm);
+ crypto.IV = binaryReader.ReadBytes(crypto.IV.Length);
+
+ // Allocate space for the decrypted buffer. We don't know how long it will be yet,
+ // but it will never be larger than the encrypted buffer.
+ var decryptedBuffer = new byte[buffer.Length];
+ int actualDecryptedLength;
+
+ using (var cryptoStream = new CryptoStream(ms, crypto.CreateDecryptor(), CryptoStreamMode.Read)) {
+ actualDecryptedLength = cryptoStream.Read(decryptedBuffer, 0, decryptedBuffer.Length);
+ }
+
+ // Create a new buffer with only the decrypted data.
+ var finalDecryptedBuffer = new byte[actualDecryptedLength];
+ Array.Copy(decryptedBuffer, finalDecryptedBuffer, actualDecryptedLength);
+ return finalDecryptedBuffer;
+ }
+ }
+ }
+
+ /// <summary>
+ /// Encrypts a string.
+ /// </summary>
+ /// <param name="plainText">The text to encrypt.</param>
+ /// <param name="key">The symmetric secret to use to encrypt the buffer. Allowed values are 128, 192, and 256.</param>
+ /// <returns>The encrypted buffer</returns>
+ internal static string Encrypt(string plainText, byte[] key) {
+ byte[] buffer = Encoding.UTF8.GetBytes(plainText);
+ byte[] cipher = Encrypt(buffer, key);
+ return Convert.ToBase64String(cipher);
+ }
+
+ /// <summary>
+ /// Decrypts a string previously encrypted with <see cref="Encrypt(string, byte[])"/>.
+ /// </summary>
+ /// <param name="cipherText">The text to decrypt.</param>
+ /// <param name="key">The symmetric secret to use to decrypt the buffer. Allowed values are 128, 192, and 256.</param>
+ /// <returns>The encrypted buffer</returns>
+ internal static string Decrypt(string cipherText, byte[] key) {
+ byte[] cipher = Convert.FromBase64String(cipherText);
+ byte[] plainText = Decrypt(cipher, key);
+ return Encoding.UTF8.GetString(plainText);
+ }
+
+ /// <summary>
+ /// Performs asymmetric encryption of a given buffer.
+ /// </summary>
+ /// <param name="crypto">The asymmetric encryption provider to use for encryption.</param>
+ /// <param name="buffer">The buffer to encrypt.</param>
+ /// <returns>The encrypted data.</returns>
+ internal static byte[] EncryptWithRandomSymmetricKey(this RSACryptoServiceProvider crypto, byte[] buffer) {
+ Requires.NotNull(crypto, "crypto");
+ Requires.NotNull(buffer, "buffer");
+
+ using (var symmetricCrypto = new RijndaelManaged()) {
+ symmetricCrypto.Mode = CipherMode.CBC;
+
+ using (var encryptedStream = new MemoryStream()) {
+ var encryptedStreamWriter = new BinaryWriter(encryptedStream);
+
+ byte[] prequel = new byte[symmetricCrypto.Key.Length + symmetricCrypto.IV.Length];
+ Array.Copy(symmetricCrypto.Key, prequel, symmetricCrypto.Key.Length);
+ Array.Copy(symmetricCrypto.IV, 0, prequel, symmetricCrypto.Key.Length, symmetricCrypto.IV.Length);
+ byte[] encryptedPrequel = crypto.Encrypt(prequel, false);
+
+ encryptedStreamWriter.Write(encryptedPrequel.Length);
+ encryptedStreamWriter.Write(encryptedPrequel);
+ encryptedStreamWriter.Flush();
+
+ var cryptoStream = new CryptoStream(encryptedStream, symmetricCrypto.CreateEncryptor(), CryptoStreamMode.Write);
+ cryptoStream.Write(buffer, 0, buffer.Length);
+ cryptoStream.FlushFinalBlock();
+
+ return encryptedStream.ToArray();
+ }
+ }
+ }
+
+ /// <summary>
+ /// Performs asymmetric decryption of a given buffer.
+ /// </summary>
+ /// <param name="crypto">The asymmetric encryption provider to use for decryption.</param>
+ /// <param name="buffer">The buffer to decrypt.</param>
+ /// <returns>The decrypted data.</returns>
+ [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "This Dispose is safe.")]
+ internal static byte[] DecryptWithRandomSymmetricKey(this RSACryptoServiceProvider crypto, byte[] buffer) {
+ Requires.NotNull(crypto, "crypto");
+ Requires.NotNull(buffer, "buffer");
+
+ using (var encryptedStream = new MemoryStream(buffer)) {
+ var encryptedStreamReader = new BinaryReader(encryptedStream);
+
+ byte[] encryptedPrequel = encryptedStreamReader.ReadBytes(encryptedStreamReader.ReadInt32());
+ byte[] prequel = crypto.Decrypt(encryptedPrequel, false);
+
+ using (var symmetricCrypto = new RijndaelManaged()) {
+ symmetricCrypto.Mode = CipherMode.CBC;
+
+ byte[] symmetricKey = new byte[symmetricCrypto.Key.Length];
+ byte[] symmetricIV = new byte[symmetricCrypto.IV.Length];
+ Array.Copy(prequel, symmetricKey, symmetricKey.Length);
+ Array.Copy(prequel, symmetricKey.Length, symmetricIV, 0, symmetricIV.Length);
+ symmetricCrypto.Key = symmetricKey;
+ symmetricCrypto.IV = symmetricIV;
+
+ // Allocate space for the decrypted buffer. We don't know how long it will be yet,
+ // but it will never be larger than the encrypted buffer.
+ var decryptedBuffer = new byte[encryptedStream.Length - encryptedStream.Position];
+ int actualDecryptedLength;
+
+ using (var cryptoStream = new CryptoStream(encryptedStream, symmetricCrypto.CreateDecryptor(), CryptoStreamMode.Read)) {
+ actualDecryptedLength = cryptoStream.Read(decryptedBuffer, 0, decryptedBuffer.Length);
+ }
+
+ // Create a new buffer with only the decrypted data.
+ var finalDecryptedBuffer = new byte[actualDecryptedLength];
+ Array.Copy(decryptedBuffer, finalDecryptedBuffer, actualDecryptedLength);
+ return finalDecryptedBuffer;
+ }
+ }
+ }
+
+ /// <summary>
+ /// Gets a key from a given bucket with the longest remaining life, or creates a new one if necessary.
+ /// </summary>
+ /// <param name="cryptoKeyStore">The crypto key store.</param>
+ /// <param name="bucket">The bucket where the key should be found or stored.</param>
+ /// <param name="minimumRemainingLife">The minimum remaining life required on the returned key.</param>
+ /// <param name="keySize">The required size of the key, in bits.</param>
+ /// <returns>
+ /// A key-value pair whose key is the secret's handle and whose value is the cryptographic key.
+ /// </returns>
+ internal static KeyValuePair<string, CryptoKey> GetCurrentKey(this ICryptoKeyStore cryptoKeyStore, string bucket, TimeSpan minimumRemainingLife, int keySize = 256) {
+ Requires.NotNull(cryptoKeyStore, "cryptoKeyStore");
+ Requires.NotNullOrEmpty(bucket, "bucket");
+ Requires.True(keySize % 8 == 0, "keySize");
+
+ var cryptoKeyPair = cryptoKeyStore.GetKeys(bucket).FirstOrDefault(pair => pair.Value.Key.Length == keySize / 8);
+ if (cryptoKeyPair.Value == null || cryptoKeyPair.Value.ExpiresUtc < DateTime.UtcNow + minimumRemainingLife) {
+ // No key exists with enough remaining life for the required purpose. Create a new key.
+ ErrorUtilities.VerifyHost(minimumRemainingLife <= SymmetricSecretKeyLifespan, "Unable to create a new symmetric key with the required lifespan of {0} because it is beyond the limit of {1}.", minimumRemainingLife, SymmetricSecretKeyLifespan);
+ byte[] secret = GetCryptoRandomData(keySize / 8);
+ DateTime expires = DateTime.UtcNow + SymmetricSecretKeyLifespan;
+ var cryptoKey = new CryptoKey(secret, expires);
+
+ // Store this key so we can find and use it later.
+ int failedAttempts = 0;
+ tryAgain:
+ try {
+ string handle = GetRandomString(SymmetricSecretHandleLength, Base64WebSafeCharacters);
+ cryptoKeyPair = new KeyValuePair<string, CryptoKey>(handle, cryptoKey);
+ cryptoKeyStore.StoreKey(bucket, handle, cryptoKey);
+ } catch (CryptoKeyCollisionException) {
+ ErrorUtilities.VerifyInternal(++failedAttempts < 3, "Unable to derive a unique handle to a private symmetric key.");
+ goto tryAgain;
+ }
+ }
+
+ return cryptoKeyPair;
+ }
+
+ /// <summary>
+ /// Compresses a given buffer.
+ /// </summary>
+ /// <param name="buffer">The buffer to compress.</param>
+ /// <returns>The compressed data.</returns>
+ [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "This Dispose is safe.")]
+ internal static byte[] Compress(byte[] buffer) {
+ Requires.NotNull(buffer, "buffer");
+ Contract.Ensures(Contract.Result<byte[]>() != null);
+
+ using (var ms = new MemoryStream()) {
+ using (var compressingStream = new DeflateStream(ms, CompressionMode.Compress, true)) {
+ compressingStream.Write(buffer, 0, buffer.Length);
+ }
+
+ return ms.ToArray();
+ }
+ }
+
+ /// <summary>
+ /// Decompresses a given buffer.
+ /// </summary>
+ /// <param name="buffer">The buffer to decompress.</param>
+ /// <returns>The decompressed data.</returns>
+ internal static byte[] Decompress(byte[] buffer) {
+ Requires.NotNull(buffer, "buffer");
+ Contract.Ensures(Contract.Result<byte[]>() != null);
+
+ using (var compressedDataStream = new MemoryStream(buffer)) {
+ using (var decompressedDataStream = new MemoryStream()) {
+ using (var decompressingStream = new DeflateStream(compressedDataStream, CompressionMode.Decompress, true)) {
+ decompressingStream.CopyTo(decompressedDataStream);
+ }
+
+ return decompressedDataStream.ToArray();
+ }
+ }
+ }
+
+ /// <summary>
+ /// Converts to data buffer to a base64-encoded string, using web safe characters and with the padding removed.
+ /// </summary>
+ /// <param name="data">The data buffer.</param>
+ /// <returns>A web-safe base64-encoded string without padding.</returns>
+ internal static string ConvertToBase64WebSafeString(byte[] data) {
+ var builder = new StringBuilder(Convert.ToBase64String(data));
+
+ // Swap out the URL-unsafe characters, and trim the padding characters.
+ builder.Replace('+', '-').Replace('/', '_');
+ while (builder[builder.Length - 1] == '=') { // should happen at most twice.
+ builder.Length -= 1;
+ }
+
+ return builder.ToString();
+ }
+
+ /// <summary>
+ /// Decodes a (web-safe) base64-string back to its binary buffer form.
+ /// </summary>
+ /// <param name="base64WebSafe">The base64-encoded string. May be web-safe encoded.</param>
+ /// <returns>A data buffer.</returns>
+ internal static byte[] FromBase64WebSafeString(string base64WebSafe) {
+ Requires.NotNullOrEmpty(base64WebSafe, "base64WebSafe");
+ Contract.Ensures(Contract.Result<byte[]>() != null);
+
+ // Restore the padding characters and original URL-unsafe characters.
+ int missingPaddingCharacters;
+ switch (base64WebSafe.Length % 4) {
+ case 3:
+ missingPaddingCharacters = 1;
+ break;
+ case 2:
+ missingPaddingCharacters = 2;
+ break;
+ case 0:
+ missingPaddingCharacters = 0;
+ break;
+ default:
+ throw ErrorUtilities.ThrowInternal("No more than two padding characters should be present for base64.");
+ }
+ var builder = new StringBuilder(base64WebSafe, base64WebSafe.Length + missingPaddingCharacters);
+ builder.Replace('-', '+').Replace('_', '/');
+ builder.Append('=', missingPaddingCharacters);
+
+ return Convert.FromBase64String(builder.ToString());
+ }
+
+ /// <summary>
/// Compares to string values for ordinal equality in such a way that its execution time does not depend on how much of the value matches.
/// </summary>
/// <param name="value1">The first value.</param>
@@ -341,9 +906,9 @@ namespace DotNetOpenAuth.Messaging {
/// </summary>
/// <param name="headers">The headers to add.</param>
/// <param name="response">The <see cref="HttpResponse"/> instance to set the appropriate values to.</param>
- internal static void ApplyHeadersToResponse(WebHeaderCollection headers, HttpResponse response) {
- Contract.Requires<ArgumentNullException>(headers != null);
- Contract.Requires<ArgumentNullException>(response != null);
+ internal static void ApplyHeadersToResponse(WebHeaderCollection headers, HttpResponseBase response) {
+ Requires.NotNull(headers, "headers");
+ Requires.NotNull(response, "response");
foreach (string headerName in headers) {
switch (headerName) {
@@ -367,8 +932,8 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="headers">The headers to add.</param>
/// <param name="response">The <see cref="HttpListenerResponse"/> instance to set the appropriate values to.</param>
internal static void ApplyHeadersToResponse(WebHeaderCollection headers, HttpListenerResponse response) {
- Contract.Requires<ArgumentNullException>(headers != null);
- Contract.Requires<ArgumentNullException>(response != null);
+ Requires.NotNull(headers, "headers");
+ Requires.NotNull(response, "response");
foreach (string headerName in headers) {
switch (headerName) {
@@ -396,10 +961,10 @@ namespace DotNetOpenAuth.Messaging {
/// The positions are NOT reset after copying is complete.
/// </remarks>
internal static int CopyTo(this Stream copyFrom, Stream copyTo) {
- Contract.Requires<ArgumentNullException>(copyFrom != null);
- Contract.Requires<ArgumentNullException>(copyTo != null);
- Contract.Requires<ArgumentException>(copyFrom.CanRead, MessagingStrings.StreamUnreadable);
- Contract.Requires<ArgumentException>(copyTo.CanWrite, MessagingStrings.StreamUnwritable);
+ Requires.NotNull(copyFrom, "copyFrom");
+ Requires.NotNull(copyTo, "copyTo");
+ Requires.True(copyFrom.CanRead, "copyFrom", MessagingStrings.StreamUnreadable);
+ Requires.True(copyTo.CanWrite, "copyTo", MessagingStrings.StreamUnwritable);
return CopyUpTo(copyFrom, copyTo, int.MaxValue);
}
#endif
@@ -416,10 +981,10 @@ namespace DotNetOpenAuth.Messaging {
/// The positions are NOT reset after copying is complete.
/// </remarks>
internal static int CopyUpTo(this Stream copyFrom, Stream copyTo, int maximumBytesToCopy) {
- Contract.Requires<ArgumentNullException>(copyFrom != null);
- Contract.Requires<ArgumentNullException>(copyTo != null);
- Contract.Requires<ArgumentException>(copyFrom.CanRead, MessagingStrings.StreamUnreadable);
- Contract.Requires<ArgumentException>(copyTo.CanWrite, MessagingStrings.StreamUnwritable);
+ Requires.NotNull(copyFrom, "copyFrom");
+ Requires.NotNull(copyTo, "copyTo");
+ Requires.True(copyFrom.CanRead, "copyFrom", MessagingStrings.StreamUnreadable);
+ Requires.True(copyTo.CanWrite, "copyTo", MessagingStrings.StreamUnwritable);
byte[] buffer = new byte[1024];
int readBytes;
@@ -440,8 +1005,8 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="copyFrom">The stream to copy bytes from.</param>
/// <returns>A seekable stream with the same contents as the original.</returns>
internal static Stream CreateSnapshot(this Stream copyFrom) {
- Contract.Requires<ArgumentNullException>(copyFrom != null);
- Contract.Requires<ArgumentException>(copyFrom.CanRead);
+ Requires.NotNull(copyFrom, "copyFrom");
+ Requires.True(copyFrom.CanRead, "copyFrom", MessagingStrings.StreamUnreadable);
MemoryStream copyTo = new MemoryStream(copyFrom.CanSeek ? (int)copyFrom.Length : 4 * 1024);
try {
@@ -460,8 +1025,8 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="request">The request to clone.</param>
/// <returns>The newly created instance.</returns>
internal static HttpWebRequest Clone(this HttpWebRequest request) {
- Contract.Requires<ArgumentNullException>(request != null);
- Contract.Requires<ArgumentException>(request.RequestUri != null);
+ Requires.NotNull(request, "request");
+ Requires.True(request.RequestUri != null, "request");
return Clone(request, request.RequestUri);
}
@@ -472,8 +1037,8 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="newRequestUri">The new recipient of the request.</param>
/// <returns>The newly created instance.</returns>
internal static HttpWebRequest Clone(this HttpWebRequest request, Uri newRequestUri) {
- Contract.Requires<ArgumentNullException>(request != null);
- Contract.Requires<ArgumentNullException>(newRequestUri != null);
+ Requires.NotNull(request, "request");
+ Requires.NotNull(newRequestUri, "newRequestUri");
var newRequest = (HttpWebRequest)WebRequest.Create(newRequestUri);
@@ -539,8 +1104,8 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="second">The second array in the comparison. May not be null.</param>
/// <returns>True if the arrays equal; false otherwise.</returns>
internal static bool AreEquivalent<T>(T[] first, T[] second) {
- Contract.Requires<ArgumentNullException>(first != null);
- Contract.Requires<ArgumentNullException>(second != null);
+ Requires.NotNull(first, "first");
+ Requires.NotNull(second, "second");
if (first.Length != second.Length) {
return false;
}
@@ -553,6 +1118,31 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Tests whether two arrays are equal in contents and ordering,
+ /// guaranteeing roughly equivalent execution time regardless of where a signature mismatch may exist.
+ /// </summary>
+ /// <param name="first">The first array in the comparison. May not be null.</param>
+ /// <param name="second">The second array in the comparison. May not be null.</param>
+ /// <returns>True if the arrays equal; false otherwise.</returns>
+ /// <remarks>
+ /// Guaranteeing equal execution time is useful in mitigating against timing attacks on a signature
+ /// or other secret.
+ /// </remarks>
+ internal static bool AreEquivalentConstantTime(byte[] first, byte[] second) {
+ Requires.NotNull(first, "first");
+ Requires.NotNull(second, "second");
+ if (first.Length != second.Length) {
+ return false;
+ }
+
+ int result = 0;
+ for (int i = 0; i < first.Length; i++) {
+ result |= first[i] ^ second[i];
+ }
+ return result == 0;
+ }
+
+ /// <summary>
/// Tests two sequences for same contents and ordering.
/// </summary>
/// <typeparam name="T">The type of elements in the arrays.</typeparam>
@@ -629,8 +1219,8 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="second">The second dictionary in the comparison. May not be null.</param>
/// <returns>True if the arrays equal; false otherwise.</returns>
internal static bool AreEquivalent<TKey, TValue>(IDictionary<TKey, TValue> first, IDictionary<TKey, TValue> second) {
- Contract.Requires<ArgumentNullException>(first != null);
- Contract.Requires<ArgumentNullException>(second != null);
+ Requires.NotNull(first, "first");
+ Requires.NotNull(second, "second");
return AreEquivalent(first.ToArray(), second.ToArray());
}
@@ -642,7 +1232,7 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="args">The dictionary of key/values to read from.</param>
/// <returns>The formulated querystring style string.</returns>
internal static string CreateQueryString(IEnumerable<KeyValuePair<string, string>> args) {
- Contract.Requires<ArgumentNullException>(args != null);
+ Requires.NotNull(args, "args");
Contract.Ensures(Contract.Result<string>() != null);
if (args.Count() == 0) {
@@ -678,7 +1268,7 @@ namespace DotNetOpenAuth.Messaging {
/// in the query string, the existing ones are <i>not</i> replaced.
/// </remarks>
internal static void AppendQueryArgs(this UriBuilder builder, IEnumerable<KeyValuePair<string, string>> args) {
- Contract.Requires<ArgumentNullException>(builder != null);
+ Requires.NotNull(builder, "builder");
if (args != null && args.Count() > 0) {
StringBuilder sb = new StringBuilder(50 + (args.Count() * 10));
@@ -693,6 +1283,35 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Adds a set of name-value pairs to the end of a given URL
+ /// as part of the fragment piece. Prefixes a # or &amp; before
+ /// first element as necessary.
+ /// </summary>
+ /// <param name="builder">The UriBuilder to add arguments to.</param>
+ /// <param name="args">
+ /// The arguments to add to the query.
+ /// If null, <paramref name="builder"/> is not changed.
+ /// </param>
+ /// <remarks>
+ /// If the parameters to add match names of parameters that already are defined
+ /// in the fragment, the existing ones are <i>not</i> replaced.
+ /// </remarks>
+ internal static void AppendFragmentArgs(this UriBuilder builder, IEnumerable<KeyValuePair<string, string>> args) {
+ Requires.NotNull(builder, "builder");
+
+ if (args != null && args.Count() > 0) {
+ StringBuilder sb = new StringBuilder(50 + (args.Count() * 10));
+ if (!string.IsNullOrEmpty(builder.Fragment)) {
+ sb.Append(builder.Fragment);
+ sb.Append('&');
+ }
+ sb.Append(CreateQueryString(args));
+
+ builder.Fragment = sb.ToString();
+ }
+ }
+
+ /// <summary>
/// Adds parameters to a query string, replacing parameters that
/// match ones that already exist in the query string.
/// </summary>
@@ -702,7 +1321,7 @@ namespace DotNetOpenAuth.Messaging {
/// If null, <paramref name="builder"/> is not changed.
/// </param>
internal static void AppendAndReplaceQueryArgs(this UriBuilder builder, IEnumerable<KeyValuePair<string, string>> args) {
- Contract.Requires<ArgumentNullException>(builder != null);
+ Requires.NotNull(builder, "builder");
if (args != null && args.Count() > 0) {
NameValueCollection aggregatedArgs = HttpUtility.ParseQueryString(builder.Query);
@@ -775,7 +1394,7 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="messageDictionary">The message to copy the extra data into.</param>
/// <param name="extraParameters">The extra data to copy into the message. May be null to do nothing.</param>
internal static void AddExtraParameters(this MessageDictionary messageDictionary, IDictionary<string, string> extraParameters) {
- Contract.Requires<ArgumentNullException>(messageDictionary != null);
+ Requires.NotNull(messageDictionary, "messageDictionary");
if (extraParameters != null) {
foreach (var pair in extraParameters) {
@@ -789,6 +1408,18 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Collects a sequence of key=value pairs into a dictionary.
+ /// </summary>
+ /// <typeparam name="TKey">The type of the key.</typeparam>
+ /// <typeparam name="TValue">The type of the value.</typeparam>
+ /// <param name="sequence">The sequence.</param>
+ /// <returns>A dictionary.</returns>
+ internal static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> sequence) {
+ Requires.NotNull(sequence, "sequence");
+ return sequence.ToDictionary(pair => pair.Key, pair => pair.Value);
+ }
+
+ /// <summary>
/// Converts a <see cref="NameValueCollection"/> to an IDictionary&lt;string, string&gt;.
/// </summary>
/// <param name="nvc">The NameValueCollection to convert. May be null.</param>
@@ -849,9 +1480,9 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="comparer">A comparison function to compare keys.</param>
/// <returns>An System.Linq.IOrderedEnumerable&lt;TElement&gt; whose elements are sorted according to a key.</returns>
internal static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Comparison<TKey> comparer) {
- Contract.Requires<ArgumentNullException>(source != null);
- Contract.Requires<ArgumentNullException>(comparer != null);
- Contract.Requires<ArgumentNullException>(keySelector != null);
+ Requires.NotNull(source, "source");
+ Requires.NotNull(comparer, "comparer");
+ Requires.NotNull(keySelector, "keySelector");
Contract.Ensures(Contract.Result<IOrderedEnumerable<TSource>>() != null);
return System.Linq.Enumerable.OrderBy<TSource, TKey>(source, keySelector, new ComparisonHelper<TKey>(comparer));
}
@@ -869,7 +1500,7 @@ namespace DotNetOpenAuth.Messaging {
/// if their <see cref="IDirectedProtocolMessage.Recipient"/> property is non-null.
/// </remarks>
internal static bool IsRequest(this IDirectedProtocolMessage message) {
- Contract.Requires<ArgumentNullException>(message != null);
+ Requires.NotNull(message, "message");
return message.Recipient != null;
}
@@ -887,11 +1518,36 @@ namespace DotNetOpenAuth.Messaging {
/// <see cref="IDirectResponseProtocolMessage.OriginatingRequest"/> property is non-null.
/// </remarks>
internal static bool IsDirectResponse(this IDirectResponseProtocolMessage message) {
- Contract.Requires<ArgumentNullException>(message != null);
+ Requires.NotNull(message, "message");
return message.OriginatingRequest != null;
}
/// <summary>
+ /// Writes a buffer, prefixed with its own length.
+ /// </summary>
+ /// <param name="writer">The binary writer.</param>
+ /// <param name="buffer">The buffer.</param>
+ internal static void WriteBuffer(this BinaryWriter writer, byte[] buffer) {
+ Requires.NotNull(writer, "writer");
+ Requires.NotNull(buffer, "buffer");
+ writer.Write(buffer.Length);
+ writer.Write(buffer, 0, buffer.Length);
+ }
+
+ /// <summary>
+ /// Reads a buffer that is prefixed with its own length.
+ /// </summary>
+ /// <param name="reader">The binary reader positioned at the buffer length.</param>
+ /// <returns>The read buffer.</returns>
+ internal static byte[] ReadBuffer(this BinaryReader reader) {
+ Requires.NotNull(reader, "reader");
+ int length = reader.ReadInt32();
+ byte[] buffer = new byte[length];
+ ErrorUtilities.VerifyProtocol(reader.Read(buffer, 0, length) == length, "Unexpected buffer length.");
+ return buffer;
+ }
+
+ /// <summary>
/// Constructs a Javascript expression that will create an object
/// on the user agent when assigned to a variable.
/// </summary>
@@ -950,7 +1606,7 @@ namespace DotNetOpenAuth.Messaging {
/// host actually having this configuration element present.
/// </remarks>
internal static string EscapeUriDataStringRfc3986(string value) {
- Contract.Requires<ArgumentNullException>(value != null);
+ Requires.NotNull(value, "value");
// Start with RFC 2396 escaping by calling the .NET method to do the work.
// This MAY sometimes exhibit RFC 3986 behavior (according to the documentation).
@@ -994,6 +1650,28 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Creates a symmetric algorithm for use in encryption/decryption.
+ /// </summary>
+ /// <param name="key">The symmetric key to use for encryption/decryption.</param>
+ /// <returns>A symmetric algorithm.</returns>
+ private static SymmetricAlgorithm CreateSymmetricAlgorithm(byte[] key) {
+ SymmetricAlgorithm result = null;
+ try {
+ result = new RijndaelManaged();
+ result.Mode = CipherMode.CBC;
+ result.Key = key;
+ return result;
+ } catch {
+ IDisposable disposableResult = result;
+ if (disposableResult != null) {
+ disposableResult.Dispose();
+ }
+
+ throw;
+ }
+ }
+
+ /// <summary>
/// A class to convert a <see cref="Comparison&lt;T&gt;"/> into an <see cref="IComparer&lt;T&gt;"/>.
/// </summary>
/// <typeparam name="T">The type of objects being compared.</typeparam>
@@ -1008,7 +1686,7 @@ namespace DotNetOpenAuth.Messaging {
/// </summary>
/// <param name="comparison">The comparison method to use.</param>
internal ComparisonHelper(Comparison<T> comparison) {
- Contract.Requires<ArgumentNullException>(comparison != null);
+ Requires.NotNull(comparison, "comparison");
this.comparison = comparison;
}
diff --git a/src/DotNetOpenAuth/Messaging/MultipartPostPart.cs b/src/DotNetOpenAuth.Core/Messaging/MultipartPostPart.cs
index eff40dd..f72ad6c 100644
--- a/src/DotNetOpenAuth/Messaging/MultipartPostPart.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/MultipartPostPart.cs
@@ -32,7 +32,7 @@ namespace DotNetOpenAuth.Messaging {
/// </summary>
/// <param name="contentDisposition">The content disposition of the part.</param>
public MultipartPostPart(string contentDisposition) {
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(contentDisposition));
+ Requires.NotNullOrEmpty(contentDisposition, "contentDisposition");
this.ContentDisposition = contentDisposition;
this.ContentAttributes = new Dictionary<string, string>();
@@ -99,8 +99,8 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="value">The value.</param>
/// <returns>The constructed part.</returns>
public static MultipartPostPart CreateFormPart(string name, string value) {
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(name));
- Contract.Requires<ArgumentException>(value != null);
+ Requires.NotNullOrEmpty(name, "name");
+ Requires.NotNull(value, "value");
var part = new MultipartPostPart("form-data");
try {
@@ -121,9 +121,9 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="contentType">Type of the content in HTTP Content-Type format.</param>
/// <returns>The constructed part.</returns>
public static MultipartPostPart CreateFormFilePart(string name, string filePath, string contentType) {
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(name));
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(filePath));
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(contentType));
+ Requires.NotNullOrEmpty(name, "name");
+ Requires.NotNullOrEmpty(filePath, "filePath");
+ Requires.NotNullOrEmpty(contentType, "contentType");
string fileName = Path.GetFileName(filePath);
var fileStream = File.OpenRead(filePath);
@@ -144,10 +144,10 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="content">The content of the file.</param>
/// <returns>The constructed part.</returns>
public static MultipartPostPart CreateFormFilePart(string name, string fileName, string contentType, Stream content) {
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(name));
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(fileName));
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(contentType));
- Contract.Requires<ArgumentException>(content != null);
+ Requires.NotNullOrEmpty(name, "name");
+ Requires.NotNullOrEmpty(fileName, "fileName");
+ Requires.NotNullOrEmpty(contentType, "contentType");
+ Requires.NotNull(content, "content");
var part = new MultipartPostPart("file");
try {
diff --git a/src/DotNetOpenAuth/Messaging/NetworkDirectWebResponse.cs b/src/DotNetOpenAuth.Core/Messaging/NetworkDirectWebResponse.cs
index 800d2ba..8fb69a1 100644
--- a/src/DotNetOpenAuth/Messaging/NetworkDirectWebResponse.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/NetworkDirectWebResponse.cs
@@ -42,8 +42,8 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="response">The response.</param>
internal NetworkDirectWebResponse(Uri requestUri, HttpWebResponse response)
: base(requestUri, response) {
- Contract.Requires<ArgumentNullException>(requestUri != null);
- Contract.Requires<ArgumentNullException>(response != null);
+ Requires.NotNull(requestUri, "requestUri");
+ Requires.NotNull(response, "response");
this.httpWebResponse = response;
this.responseStream = response.GetResponseStream();
}
diff --git a/src/DotNetOpenAuth/Messaging/OutgoingWebResponse.cs b/src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponse.cs
index cc655cf..026b7c2 100644
--- a/src/DotNetOpenAuth/Messaging/OutgoingWebResponse.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponse.cs
@@ -6,6 +6,7 @@
namespace DotNetOpenAuth.Messaging {
using System;
+ using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.IO;
@@ -50,7 +51,7 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="response">The <see cref="HttpWebResponse"/> to clone.</param>
/// <param name="maximumBytesToRead">The maximum bytes to read from the response stream.</param>
protected internal OutgoingWebResponse(HttpWebResponse response, int maximumBytesToRead) {
- Contract.Requires<ArgumentNullException>(response != null);
+ Requires.NotNull(response, "response");
this.Status = response.StatusCode;
this.Headers = response.Headers;
@@ -125,8 +126,9 @@ namespace DotNetOpenAuth.Messaging {
/// <remarks>
/// Requires a current HttpContext.
/// </remarks>
+ [EditorBrowsable(EditorBrowsableState.Never)]
public virtual void Send() {
- Contract.Requires<InvalidOperationException>(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
+ Requires.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
this.Send(HttpContext.Current);
}
@@ -138,27 +140,76 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="context">The context of the HTTP request whose response should be set.
/// Typically this is <see cref="HttpContext.Current"/>.</param>
/// <exception cref="ThreadAbortException">Typically thrown by ASP.NET in order to prevent additional data from the page being sent to the client and corrupting the response.</exception>
+ [EditorBrowsable(EditorBrowsableState.Never)]
public virtual void Send(HttpContext context) {
- Contract.Requires<ArgumentNullException>(context != null);
+ this.Respond(new HttpContextWrapper(context), true);
+ }
- context.Response.Clear();
- context.Response.StatusCode = (int)this.Status;
- MessagingUtilities.ApplyHeadersToResponse(this.Headers, context.Response);
- if (this.ResponseStream != null) {
- try {
- this.ResponseStream.CopyTo(context.Response.OutputStream);
- } catch (HttpException ex) {
- if (ex.ErrorCode == -2147467259 && context.Response.Output != null) {
- // Test scenarios can generate this, since the stream is being spoofed:
- // System.Web.HttpException: OutputStream is not available when a custom TextWriter is used.
- context.Response.Output.Write(this.Body);
- } else {
- throw;
- }
- }
- }
+ /// <summary>
+ /// Automatically sends the appropriate response to the user agent
+ /// and ends execution on the current page or handler.
+ /// </summary>
+ /// <param name="context">The context of the HTTP request whose response should be set.
+ /// Typically this is <see cref="HttpContext.Current"/>.</param>
+ /// <exception cref="ThreadAbortException">Typically thrown by ASP.NET in order to prevent additional data from the page being sent to the client and corrupting the response.</exception>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public virtual void Send(HttpContextBase context) {
+ this.Respond(context, true);
+ }
+
+ /// <summary>
+ /// Automatically sends the appropriate response to the user agent
+ /// and signals ASP.NET to short-circuit the page execution pipeline
+ /// now that the response has been completed.
+ /// Not safe to call from ASP.NET web forms.
+ /// </summary>
+ /// <remarks>
+ /// Requires a current HttpContext.
+ /// This call is not safe to make from an ASP.NET web form (.aspx file or code-behind) because
+ /// ASP.NET will render HTML after the protocol message has been sent, which will corrupt the response.
+ /// Use the <see cref="Send()"/> method instead for web forms.
+ /// </remarks>
+ public virtual void Respond() {
+ Requires.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
+
+ this.Respond(HttpContext.Current);
+ }
+
+ /// <summary>
+ /// Automatically sends the appropriate response to the user agent
+ /// and signals ASP.NET to short-circuit the page execution pipeline
+ /// now that the response has been completed.
+ /// Not safe to call from ASP.NET web forms.
+ /// </summary>
+ /// <param name="context">The context of the HTTP request whose response should be set.
+ /// Typically this is <see cref="HttpContext.Current"/>.</param>
+ /// <remarks>
+ /// This call is not safe to make from an ASP.NET web form (.aspx file or code-behind) because
+ /// ASP.NET will render HTML after the protocol message has been sent, which will corrupt the response.
+ /// Use the <see cref="Send()"/> method instead for web forms.
+ /// </remarks>
+ public void Respond(HttpContext context) {
+ Requires.NotNull(context, "context");
+ this.Respond(new HttpContextWrapper(context));
+ }
- context.Response.End();
+ /// <summary>
+ /// Automatically sends the appropriate response to the user agent
+ /// and signals ASP.NET to short-circuit the page execution pipeline
+ /// now that the response has been completed.
+ /// Not safe to call from ASP.NET web forms.
+ /// </summary>
+ /// <param name="context">The context of the HTTP request whose response should be set.
+ /// Typically this is <see cref="HttpContext.Current"/>.</param>
+ /// <remarks>
+ /// This call is not safe to make from an ASP.NET web form (.aspx file or code-behind) because
+ /// ASP.NET will render HTML after the protocol message has been sent, which will corrupt the response.
+ /// Use the <see cref="Send()"/> method instead for web forms.
+ /// </remarks>
+ public virtual void Respond(HttpContextBase context) {
+ Requires.NotNull(context, "context");
+
+ this.Respond(context, false);
}
/// <summary>
@@ -166,7 +217,7 @@ namespace DotNetOpenAuth.Messaging {
/// </summary>
/// <param name="response">The response to set to this message.</param>
public virtual void Send(HttpListenerResponse response) {
- Contract.Requires<ArgumentNullException>(response != null);
+ Requires.NotNull(response, "response");
response.StatusCode = (int)this.Status;
MessagingUtilities.ApplyHeadersToResponse(this.Headers, response);
@@ -192,7 +243,7 @@ namespace DotNetOpenAuth.Messaging {
/// rather than cause a redirect.
/// </remarks>
internal Uri GetDirectUriRequest(Channel channel) {
- Contract.Requires<ArgumentNullException>(channel != null);
+ Requires.NotNull(channel, "channel");
var message = this.OriginalMessage as IDirectedProtocolMessage;
if (message == null) {
@@ -232,5 +283,62 @@ namespace DotNetOpenAuth.Messaging {
writer.Flush();
this.ResponseStream.Seek(0, SeekOrigin.Begin);
}
+
+ /// <summary>
+ /// Automatically sends the appropriate response to the user agent
+ /// and signals ASP.NET to short-circuit the page execution pipeline
+ /// now that the response has been completed.
+ /// </summary>
+ /// <param name="context">The context of the HTTP request whose response should be set.
+ /// Typically this is <see cref="HttpContext.Current"/>.</param>
+ /// <param name="endRequest">If set to <c>false</c>, this method calls
+ /// <see cref="HttpApplication.CompleteRequest"/> rather than <see cref="HttpResponse.End"/>
+ /// to avoid a <see cref="ThreadAbortException"/>.</param>
+ protected internal void Respond(HttpContext context, bool endRequest) {
+ this.Respond(new HttpContextWrapper(context), endRequest);
+ }
+
+ /// <summary>
+ /// Automatically sends the appropriate response to the user agent
+ /// and signals ASP.NET to short-circuit the page execution pipeline
+ /// now that the response has been completed.
+ /// </summary>
+ /// <param name="context">The context of the HTTP request whose response should be set.
+ /// Typically this is <see cref="HttpContext.Current"/>.</param>
+ /// <param name="endRequest">If set to <c>false</c>, this method calls
+ /// <see cref="HttpApplication.CompleteRequest"/> rather than <see cref="HttpResponse.End"/>
+ /// to avoid a <see cref="ThreadAbortException"/>.</param>
+ protected internal virtual void Respond(HttpContextBase context, bool endRequest) {
+ Requires.NotNull(context, "context");
+
+ context.Response.Clear();
+ context.Response.StatusCode = (int)this.Status;
+ MessagingUtilities.ApplyHeadersToResponse(this.Headers, context.Response);
+ if (this.ResponseStream != null) {
+ try {
+ this.ResponseStream.CopyTo(context.Response.OutputStream);
+ } catch (HttpException ex) {
+ if (ex.ErrorCode == -2147467259 && context.Response.Output != null) {
+ // Test scenarios can generate this, since the stream is being spoofed:
+ // System.Web.HttpException: OutputStream is not available when a custom TextWriter is used.
+ context.Response.Output.Write(this.Body);
+ } else {
+ throw;
+ }
+ }
+ }
+
+ if (endRequest) {
+ // This approach throws an exception in order that
+ // no more code is executed in the calling page.
+ // Microsoft no longer recommends this approach.
+ context.Response.End();
+ } else if (context.ApplicationInstance != null) {
+ // This approach doesn't throw an exception, but
+ // still tells ASP.NET to short-circuit most of the
+ // request handling pipeline to speed things up.
+ context.ApplicationInstance.CompleteRequest();
+ }
+ }
}
}
diff --git a/src/DotNetOpenAuth/Messaging/OutgoingWebResponseActionResult.cs b/src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponseActionResult.cs
index 1cfc638..86dbb58 100644
--- a/src/DotNetOpenAuth/Messaging/OutgoingWebResponseActionResult.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponseActionResult.cs
@@ -25,7 +25,7 @@ namespace DotNetOpenAuth.Messaging {
/// </summary>
/// <param name="response">The response.</param>
internal OutgoingWebResponseActionResult(OutgoingWebResponse response) {
- Contract.Requires<ArgumentNullException>(response != null);
+ Requires.NotNull(response, "response");
this.response = response;
}
@@ -34,7 +34,7 @@ namespace DotNetOpenAuth.Messaging {
/// </summary>
/// <param name="context">The context in which to set the response.</param>
public override void ExecuteResult(ControllerContext context) {
- this.response.Send();
+ this.response.Respond();
}
}
}
diff --git a/src/DotNetOpenAuth/Messaging/ProtocolException.cs b/src/DotNetOpenAuth.Core/Messaging/ProtocolException.cs
index fb9ec6d..cf3ccb8 100644
--- a/src/DotNetOpenAuth/Messaging/ProtocolException.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/ProtocolException.cs
@@ -45,7 +45,7 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="faultedMessage">The message that was the cause of the exception. Must not be null.</param>
protected internal ProtocolException(string message, IProtocolMessage faultedMessage)
: base(message) {
- Contract.Requires<ArgumentNullException>(faultedMessage != null);
+ Requires.NotNull(faultedMessage, "faultedMessage");
this.FaultedMessage = faultedMessage;
}
diff --git a/src/DotNetOpenAuth/Messaging/Reflection/IMessagePartEncoder.cs b/src/DotNetOpenAuth.Core/Messaging/Reflection/IMessagePartEncoder.cs
index 03534f2..bbb3737 100644
--- a/src/DotNetOpenAuth/Messaging/Reflection/IMessagePartEncoder.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/Reflection/IMessagePartEncoder.cs
@@ -56,7 +56,7 @@ namespace DotNetOpenAuth.Messaging.Reflection {
/// The <paramref name="value"/> in string form, ready for message transport.
/// </returns>
string IMessagePartEncoder.Encode(object value) {
- Contract.Requires<ArgumentNullException>(value != null);
+ Requires.NotNull(value, "value");
throw new NotImplementedException();
}
@@ -69,7 +69,7 @@ namespace DotNetOpenAuth.Messaging.Reflection {
/// </returns>
/// <exception cref="FormatException">Thrown when the string value given cannot be decoded into the required object type.</exception>
object IMessagePartEncoder.Decode(string value) {
- Contract.Requires<ArgumentNullException>(value != null);
+ Requires.NotNull(value, "value");
throw new NotImplementedException();
}
diff --git a/src/DotNetOpenAuth/Messaging/Reflection/IMessagePartNullEncoder.cs b/src/DotNetOpenAuth.Core/Messaging/Reflection/IMessagePartNullEncoder.cs
index 7581550..7581550 100644
--- a/src/DotNetOpenAuth/Messaging/Reflection/IMessagePartNullEncoder.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/Reflection/IMessagePartNullEncoder.cs
diff --git a/src/DotNetOpenAuth/Messaging/Reflection/IMessagePartOriginalEncoder.cs b/src/DotNetOpenAuth.Core/Messaging/Reflection/IMessagePartOriginalEncoder.cs
index 9ad55c9..9ad55c9 100644
--- a/src/DotNetOpenAuth/Messaging/Reflection/IMessagePartOriginalEncoder.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/Reflection/IMessagePartOriginalEncoder.cs
diff --git a/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDescription.cs b/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDescription.cs
new file mode 100644
index 0000000..6e16478
--- /dev/null
+++ b/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDescription.cs
@@ -0,0 +1,284 @@
+//-----------------------------------------------------------------------
+// <copyright file="MessageDescription.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging.Reflection {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics;
+ using System.Diagnostics.Contracts;
+ using System.Globalization;
+ using System.Linq;
+ using System.Reflection;
+
+ /// <summary>
+ /// A mapping between serialized key names and <see cref="MessagePart"/> instances describing
+ /// those key/values pairs.
+ /// </summary>
+ internal class MessageDescription {
+ /// <summary>
+ /// A mapping between the serialized key names and their
+ /// describing <see cref="MessagePart"/> instances.
+ /// </summary>
+ private Dictionary<string, MessagePart> mapping;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MessageDescription"/> class.
+ /// </summary>
+ /// <param name="messageType">Type of the message.</param>
+ /// <param name="messageVersion">The message version.</param>
+ internal MessageDescription(Type messageType, Version messageVersion) {
+ Requires.NotNullSubtype<IMessage>(messageType, "messageType");
+ Requires.NotNull(messageVersion, "messageVersion");
+
+ this.MessageType = messageType;
+ this.MessageVersion = messageVersion;
+ this.ReflectMessageType();
+ }
+
+ /// <summary>
+ /// Gets the mapping between the serialized key names and their describing
+ /// <see cref="MessagePart"/> instances.
+ /// </summary>
+ internal IDictionary<string, MessagePart> Mapping {
+ get { return this.mapping; }
+ }
+
+ /// <summary>
+ /// Gets the message version this instance was generated from.
+ /// </summary>
+ internal Version MessageVersion { get; private set; }
+
+ /// <summary>
+ /// Gets the type of message this instance was generated from.
+ /// </summary>
+ /// <value>The type of the described message.</value>
+ internal Type MessageType { get; private set; }
+
+ /// <summary>
+ /// Gets the constructors available on the message type.
+ /// </summary>
+ internal ConstructorInfo[] Constructors { get; private set; }
+
+ /// <summary>
+ /// Returns a <see cref="System.String"/> that represents this instance.
+ /// </summary>
+ /// <returns>
+ /// A <see cref="System.String"/> that represents this instance.
+ /// </returns>
+ public override string ToString() {
+ return this.MessageType.Name + " (" + this.MessageVersion + ")";
+ }
+
+ /// <summary>
+ /// Gets a dictionary that provides read/write access to a message.
+ /// </summary>
+ /// <param name="message">The message the dictionary should provide access to.</param>
+ /// <returns>The dictionary accessor to the message</returns>
+ [Pure]
+ internal MessageDictionary GetDictionary(IMessage message) {
+ Requires.NotNull(message, "message");
+ Contract.Ensures(Contract.Result<MessageDictionary>() != null);
+ return this.GetDictionary(message, false);
+ }
+
+ /// <summary>
+ /// Gets a dictionary that provides read/write access to a message.
+ /// </summary>
+ /// <param name="message">The message the dictionary should provide access to.</param>
+ /// <param name="getOriginalValues">A value indicating whether this message dictionary will retrieve original values instead of normalized ones.</param>
+ /// <returns>The dictionary accessor to the message</returns>
+ [Pure]
+ internal MessageDictionary GetDictionary(IMessage message, bool getOriginalValues) {
+ Requires.NotNull(message, "message");
+ Contract.Ensures(Contract.Result<MessageDictionary>() != null);
+ return new MessageDictionary(message, this, getOriginalValues);
+ }
+
+ /// <summary>
+ /// Ensures the message parts pass basic validation.
+ /// </summary>
+ /// <param name="parts">The key/value pairs of the serialized message.</param>
+ internal void EnsureMessagePartsPassBasicValidation(IDictionary<string, string> parts) {
+ try {
+ this.CheckRequiredMessagePartsArePresent(parts.Keys, true);
+ this.CheckRequiredProtocolMessagePartsAreNotEmpty(parts, true);
+ this.CheckMessagePartsConstantValues(parts, true);
+ } catch (ProtocolException) {
+ Logger.Messaging.ErrorFormat(
+ "Error while performing basic validation of {0} ({3}) with these message parts:{1}{2}",
+ this.MessageType.Name,
+ Environment.NewLine,
+ parts.ToStringDeferred(),
+ this.messageVersion);
+ throw;
+ }
+ }
+
+ /// <summary>
+ /// Tests whether all the required message parts pass basic validation for the given data.
+ /// </summary>
+ /// <param name="parts">The key/value pairs of the serialized message.</param>
+ /// <returns>A value indicating whether the provided data fits the message's basic requirements.</returns>
+ internal bool CheckMessagePartsPassBasicValidation(IDictionary<string, string> parts) {
+ Requires.NotNull(parts, "parts");
+
+ return this.CheckRequiredMessagePartsArePresent(parts.Keys, false) &&
+ this.CheckRequiredProtocolMessagePartsAreNotEmpty(parts, false) &&
+ this.CheckMessagePartsConstantValues(parts, false);
+ }
+
+ /// <summary>
+ /// Verifies that a given set of keys include all the required parameters
+ /// for this message type or throws an exception.
+ /// </summary>
+ /// <param name="keys">The names of all parameters included in a message.</param>
+ /// <param name="throwOnFailure">if set to <c>true</c> an exception is thrown on failure with details.</param>
+ /// <returns>A value indicating whether the provided data fits the message's basic requirements.</returns>
+ /// <exception cref="ProtocolException">
+ /// Thrown when required parts of a message are not in <paramref name="keys"/>
+ /// if <paramref name="throwOnFailure"/> is <c>true</c>.
+ /// </exception>
+ private bool CheckRequiredMessagePartsArePresent(IEnumerable<string> keys, bool throwOnFailure) {
+ Requires.NotNull(keys, "keys");
+
+ var missingKeys = (from part in this.Mapping.Values
+ where part.IsRequired && !keys.Contains(part.Name)
+ select part.Name).ToArray();
+ if (missingKeys.Length > 0) {
+ if (throwOnFailure) {
+ ErrorUtilities.ThrowProtocol(
+ MessagingStrings.RequiredParametersMissing,
+ this.MessageType.FullName,
+ string.Join(", ", missingKeys));
+ } else {
+ Logger.Messaging.DebugFormat(
+ MessagingStrings.RequiredParametersMissing,
+ this.MessageType.FullName,
+ missingKeys.ToStringDeferred());
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /// <summary>
+ /// Ensures the protocol message parts that must not be empty are in fact not empty.
+ /// </summary>
+ /// <param name="partValues">A dictionary of key/value pairs that make up the serialized message.</param>
+ /// <param name="throwOnFailure">if set to <c>true</c> an exception is thrown on failure with details.</param>
+ /// <returns>A value indicating whether the provided data fits the message's basic requirements.</returns>
+ /// <exception cref="ProtocolException">
+ /// Thrown when required parts of a message are not in <paramref name="partValues"/>
+ /// if <paramref name="throwOnFailure"/> is <c>true</c>.
+ /// </exception>
+ private bool CheckRequiredProtocolMessagePartsAreNotEmpty(IDictionary<string, string> partValues, bool throwOnFailure) {
+ Requires.NotNull(partValues, "partValues");
+
+ string value;
+ var emptyValuedKeys = (from part in this.Mapping.Values
+ where !part.AllowEmpty && partValues.TryGetValue(part.Name, out value) && value != null && value.Length == 0
+ select part.Name).ToArray();
+ if (emptyValuedKeys.Length > 0) {
+ if (throwOnFailure) {
+ ErrorUtilities.ThrowProtocol(
+ MessagingStrings.RequiredNonEmptyParameterWasEmpty,
+ this.MessageType.FullName,
+ string.Join(", ", emptyValuedKeys));
+ } else {
+ Logger.Messaging.DebugFormat(
+ MessagingStrings.RequiredNonEmptyParameterWasEmpty,
+ this.MessageType.FullName,
+ emptyValuedKeys.ToStringDeferred());
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /// <summary>
+ /// Checks that a bunch of message part values meet the constant value requirements of this message description.
+ /// </summary>
+ /// <param name="partValues">The part values.</param>
+ /// <param name="throwOnFailure">if set to <c>true</c>, this method will throw on failure.</param>
+ /// <returns>A value indicating whether all the requirements are met.</returns>
+ private bool CheckMessagePartsConstantValues(IDictionary<string, string> partValues, bool throwOnFailure) {
+ Requires.NotNull(partValues, "partValues");
+
+ var badConstantValues = (from part in this.Mapping.Values
+ where part.IsConstantValueAvailableStatically
+ where partValues.ContainsKey(part.Name)
+ where !string.Equals(partValues[part.Name], part.StaticConstantValue, StringComparison.Ordinal)
+ select part.Name).ToArray();
+ if (badConstantValues.Length > 0) {
+ if (throwOnFailure) {
+ ErrorUtilities.ThrowProtocol(
+ MessagingStrings.RequiredMessagePartConstantIncorrect,
+ this.MessageType.FullName,
+ string.Join(", ", badConstantValues));
+ } else {
+ Logger.Messaging.DebugFormat(
+ MessagingStrings.RequiredMessagePartConstantIncorrect,
+ this.MessageType.FullName,
+ badConstantValues.ToStringDeferred());
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /// <summary>
+ /// Reflects over some <see cref="IMessage"/>-implementing type
+ /// and prepares to serialize/deserialize instances of that type.
+ /// </summary>
+ private void ReflectMessageType() {
+ this.mapping = new Dictionary<string, MessagePart>();
+
+ Type currentType = this.MessageType;
+ do {
+ foreach (MemberInfo member in currentType.GetMembers(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)) {
+ if (member is PropertyInfo || member is FieldInfo) {
+ MessagePartAttribute partAttribute =
+ (from a in member.GetCustomAttributes(typeof(MessagePartAttribute), true).OfType<MessagePartAttribute>()
+ orderby a.MinVersionValue descending
+ where a.MinVersionValue <= this.MessageVersion
+ where a.MaxVersionValue >= this.MessageVersion
+ select a).FirstOrDefault();
+ if (partAttribute != null) {
+ MessagePart part = new MessagePart(member, partAttribute);
+ if (this.mapping.ContainsKey(part.Name)) {
+ Logger.Messaging.WarnFormat(
+ "Message type {0} has more than one message part named {1}. Inherited members will be hidden.",
+ this.MessageType.Name,
+ part.Name);
+ } else {
+ this.mapping.Add(part.Name, part);
+ }
+ }
+ }
+ }
+ currentType = currentType.BaseType;
+ } while (currentType != null);
+
+ BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
+ this.Constructors = this.MessageType.GetConstructors(flags);
+ }
+
+#if CONTRACTS_FULL
+ /// <summary>
+ /// Describes traits of this class that are always true.
+ /// </summary>
+ [ContractInvariantMethod]
+ private void Invariant() {
+ Contract.Invariant(this.MessageType != null);
+ Contract.Invariant(this.MessageVersion != null);
+ Contract.Invariant(this.Constructors != null);
+ }
+#endif
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/Reflection/MessageDescriptionCollection.cs b/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDescriptionCollection.cs
index 26d088b..79ef172 100644
--- a/src/DotNetOpenAuth/Messaging/Reflection/MessageDescriptionCollection.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDescriptionCollection.cs
@@ -14,7 +14,7 @@ namespace DotNetOpenAuth.Messaging.Reflection {
/// A cache of <see cref="MessageDescription"/> instances.
/// </summary>
[ContractVerification(true)]
- internal class MessageDescriptionCollection {
+ internal class MessageDescriptionCollection : IEnumerable<MessageDescription> {
/// <summary>
/// A dictionary of reflected message types and the generated reflection information.
/// </summary>
@@ -23,9 +23,37 @@ namespace DotNetOpenAuth.Messaging.Reflection {
/// <summary>
/// Initializes a new instance of the <see cref="MessageDescriptionCollection"/> class.
/// </summary>
- public MessageDescriptionCollection() {
+ internal MessageDescriptionCollection() {
}
+ #region IEnumerable<MessageDescription> Members
+
+ /// <summary>
+ /// Returns an enumerator that iterates through a collection.
+ /// </summary>
+ /// <returns>
+ /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
+ /// </returns>
+ public IEnumerator<MessageDescription> GetEnumerator() {
+ return this.reflectedMessageTypes.Values.GetEnumerator();
+ }
+
+ #endregion
+
+ #region IEnumerable Members
+
+ /// <summary>
+ /// Returns an enumerator that iterates through a collection.
+ /// </summary>
+ /// <returns>
+ /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
+ /// </returns>
+ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
+ return this.reflectedMessageTypes.Values.GetEnumerator();
+ }
+
+ #endregion
+
/// <summary>
/// Gets a <see cref="MessageDescription"/> instance prepared for the
/// given message type.
@@ -36,9 +64,8 @@ namespace DotNetOpenAuth.Messaging.Reflection {
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Diagnostics.Contracts.__ContractsRuntime.Assume(System.Boolean,System.String,System.String)", Justification = "No localization required.")]
[Pure]
internal MessageDescription Get(Type messageType, Version messageVersion) {
- Contract.Requires<ArgumentNullException>(messageType != null);
- Contract.Requires<ArgumentException>(typeof(IMessage).IsAssignableFrom(messageType));
- Contract.Requires<ArgumentNullException>(messageVersion != null);
+ Requires.NotNullSubtype<IMessage>(messageType, "messageType");
+ Requires.NotNull(messageVersion, "messageVersion");
Contract.Ensures(Contract.Result<MessageDescription>() != null);
MessageTypeAndVersion key = new MessageTypeAndVersion(messageType, messageVersion);
@@ -66,7 +93,7 @@ namespace DotNetOpenAuth.Messaging.Reflection {
/// </returns>
[Pure]
internal MessageDescription Get(IMessage message) {
- Contract.Requires<ArgumentNullException>(message != null);
+ Requires.NotNull(message, "message");
Contract.Ensures(Contract.Result<MessageDescription>() != null);
return this.Get(message.GetType(), message.Version);
}
@@ -78,7 +105,7 @@ namespace DotNetOpenAuth.Messaging.Reflection {
/// <returns>The dictionary.</returns>
[Pure]
internal MessageDictionary GetAccessor(IMessage message) {
- Contract.Requires<ArgumentNullException>(message != null);
+ Requires.NotNull(message, "message");
return this.GetAccessor(message, false);
}
@@ -90,7 +117,7 @@ namespace DotNetOpenAuth.Messaging.Reflection {
/// <returns>The dictionary.</returns>
[Pure]
internal MessageDictionary GetAccessor(IMessage message, bool getOriginalValues) {
- Contract.Requires<ArgumentNullException>(message != null);
+ Requires.NotNull(message, "message");
return this.Get(message).GetDictionary(message, getOriginalValues);
}
@@ -115,8 +142,8 @@ namespace DotNetOpenAuth.Messaging.Reflection {
/// <param name="messageType">Type of the message.</param>
/// <param name="messageVersion">The message version.</param>
internal MessageTypeAndVersion(Type messageType, Version messageVersion) {
- Contract.Requires<ArgumentNullException>(messageType != null);
- Contract.Requires<ArgumentNullException>(messageVersion != null);
+ Requires.NotNull(messageType, "messageType");
+ Requires.NotNull(messageVersion, "messageVersion");
this.type = messageType;
this.version = messageVersion;
diff --git a/src/DotNetOpenAuth/Messaging/Reflection/MessageDictionary.cs b/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDictionary.cs
index 2b60a9c..54e2dd5 100644
--- a/src/DotNetOpenAuth/Messaging/Reflection/MessageDictionary.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDictionary.cs
@@ -42,8 +42,8 @@ namespace DotNetOpenAuth.Messaging.Reflection {
/// <param name="getOriginalValues">A value indicating whether this message dictionary will retrieve original values instead of normalized ones.</param>
[Pure]
internal MessageDictionary(IMessage message, MessageDescription description, bool getOriginalValues) {
- Contract.Requires<ArgumentNullException>(message != null);
- Contract.Requires<ArgumentNullException>(description != null);
+ Requires.NotNull(message, "message");
+ Requires.NotNull(description, "description");
this.message = message;
this.description = description;
@@ -389,7 +389,7 @@ namespace DotNetOpenAuth.Messaging.Reflection {
/// </summary>
/// <param name="fields">The data to load into the message.</param>
public void Deserialize(IDictionary<string, string> fields) {
- Contract.Requires<ArgumentNullException>(fields != null);
+ Requires.NotNull(fields, "fields");
this.Serializer.Deserialize(fields, this);
}
diff --git a/src/DotNetOpenAuth/Messaging/Reflection/MessagePart.cs b/src/DotNetOpenAuth.Core/Messaging/Reflection/MessagePart.cs
index 088aa05..f439c4d 100644
--- a/src/DotNetOpenAuth/Messaging/Reflection/MessagePart.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/Reflection/MessagePart.cs
@@ -16,7 +16,6 @@ namespace DotNetOpenAuth.Messaging.Reflection {
using System.Reflection;
using System.Xml;
using DotNetOpenAuth.Configuration;
- using DotNetOpenAuth.OpenId;
/// <summary>
/// Describes an individual member of a message and assists in its serialization.
@@ -74,11 +73,7 @@ namespace DotNetOpenAuth.Messaging.Reflection {
Contract.Assume(str != null);
return bool.Parse(str);
};
- Func<string, Identifier> safeIdentifier = str => {
- Contract.Assume(str != null);
- ErrorUtilities.VerifyFormat(str.Length > 0, MessagingStrings.NonEmptyStringExpected);
- return Identifier.Parse(str, true);
- };
+
Func<byte[], string> safeFromByteArray = bytes => {
Contract.Assume(bytes != null);
return Convert.ToBase64String(bytes);
@@ -87,18 +82,14 @@ namespace DotNetOpenAuth.Messaging.Reflection {
Contract.Assume(str != null);
return Convert.FromBase64String(str);
};
- Func<string, Realm> safeRealm = str => {
- Contract.Assume(str != null);
- return new Realm(str);
- };
Map<Uri>(uri => uri.AbsoluteUri, uri => uri.OriginalString, safeUri);
Map<DateTime>(dt => XmlConvert.ToString(dt, XmlDateTimeSerializationMode.Utc), null, str => XmlConvert.ToDateTime(str, XmlDateTimeSerializationMode.Utc));
+ Map<TimeSpan>(ts => ts.ToString(), null, str => TimeSpan.Parse(str));
Map<byte[]>(safeFromByteArray, null, safeToByteArray);
- Map<Realm>(realm => realm.ToString(), realm => realm.OriginalString, safeRealm);
- Map<Identifier>(id => id.SerializedString, id => id.OriginalString, safeIdentifier);
Map<bool>(value => value.ToString().ToLowerInvariant(), null, safeBool);
Map<CultureInfo>(c => c.Name, null, str => new CultureInfo(str));
Map<CultureInfo[]>(cs => string.Join(",", cs.Select(c => c.Name).ToArray()), null, str => str.Split(',').Select(s => new CultureInfo(s)).ToArray());
+ Map<Type>(t => t.FullName, null, str => Type.GetType(str));
}
/// <summary>
@@ -114,9 +105,9 @@ namespace DotNetOpenAuth.Messaging.Reflection {
/// </param>
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Unavoidable"), SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "Code contracts requires it.")]
internal MessagePart(MemberInfo member, MessagePartAttribute attribute) {
- Contract.Requires<ArgumentNullException>(member != null);
- Contract.Requires<ArgumentException>(member is FieldInfo || member is PropertyInfo);
- Contract.Requires<ArgumentNullException>(attribute != null);
+ Requires.NotNull(member, "member");
+ Requires.True(member is FieldInfo || member is PropertyInfo, "member");
+ Requires.NotNull(attribute, "attribute");
this.field = member as FieldInfo;
this.property = member as PropertyInfo;
@@ -163,6 +154,7 @@ namespace DotNetOpenAuth.Messaging.Reflection {
(this.field.Attributes & FieldAttributes.InitOnly) == FieldAttributes.InitOnly ||
(this.field.Attributes & constAttributes) == constAttributes)) {
this.IsConstantValue = true;
+ this.IsConstantValueAvailableStatically = this.field.IsStatic;
} else if (this.property != null && !this.property.CanWrite) {
this.IsConstantValue = true;
}
@@ -198,18 +190,62 @@ namespace DotNetOpenAuth.Messaging.Reflection {
internal bool IsConstantValue { get; set; }
/// <summary>
+ /// Gets or sets a value indicating whether this part is defined as a constant field and can be read without a message instance.
+ /// </summary>
+ internal bool IsConstantValueAvailableStatically { get; set; }
+
+ /// <summary>
+ /// Gets the static constant value for this message part without a message instance.
+ /// </summary>
+ internal string StaticConstantValue {
+ get {
+ Requires.ValidState(this.IsConstantValueAvailableStatically);
+ return this.ToString(this.field.GetValue(null), false);
+ }
+ }
+
+ /// <summary>
+ /// Gets the type of the declared member.
+ /// </summary>
+ internal Type MemberDeclaredType {
+ get { return this.memberDeclaredType; }
+ }
+
+ /// <summary>
+ /// Adds a pair of type conversion functions to the static conversion map.
+ /// </summary>
+ /// <typeparam name="T">The custom type to convert to and from strings.</typeparam>
+ /// <param name="toString">The function to convert the custom type to a string.</param>
+ /// <param name="toOriginalString">The mapping function that converts some custom value to its original (non-normalized) string. May be null if the same as the <paramref name="toString"/> function.</param>
+ /// <param name="toValue">The function to convert a string to the custom type.</param>
+ [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Diagnostics.Contracts.__ContractsRuntime.Requires<System.ArgumentNullException>(System.Boolean,System.String,System.String)", Justification = "Code contracts"), SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "toString", Justification = "Code contracts"), SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "toValue", Justification = "Code contracts")]
+ internal static void Map<T>(Func<T, string> toString, Func<T, string> toOriginalString, Func<string, T> toValue) {
+ Requires.NotNull(toString, "toString");
+ Requires.NotNull(toValue, "toValue");
+
+ if (toOriginalString == null) {
+ toOriginalString = toString;
+ }
+
+ Func<object, string> safeToString = obj => obj != null ? toString((T)obj) : null;
+ Func<object, string> safeToOriginalString = obj => obj != null ? toOriginalString((T)obj) : null;
+ Func<string, object> safeToT = str => str != null ? toValue(str) : default(T);
+ converters.Add(typeof(T), new ValueMapping(safeToString, safeToOriginalString, safeToT));
+ }
+
+ /// <summary>
/// Sets the member of a given message to some given value.
/// Used in deserialization.
/// </summary>
/// <param name="message">The message instance containing the member whose value should be set.</param>
/// <param name="value">The string representation of the value to set.</param>
internal void SetValue(IMessage message, string value) {
- Contract.Requires<ArgumentNullException>(message != null);
+ Requires.NotNull(message, "message");
try {
if (this.IsConstantValue) {
string constantValue = this.GetValue(message);
- var caseSensitivity = DotNetOpenAuthSection.Configuration.Messaging.Strict ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
+ var caseSensitivity = DotNetOpenAuthSection.Messaging.Strict ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
if (!string.Equals(constantValue, value, caseSensitivity)) {
throw new ArgumentException(string.Format(
CultureInfo.CurrentCulture,
@@ -220,11 +256,7 @@ namespace DotNetOpenAuth.Messaging.Reflection {
value));
}
} else {
- if (this.property != null) {
- this.property.SetValue(message, this.ToValue(value), null);
- } else {
- this.field.SetValue(message, this.ToValue(value));
- }
+ this.SetValueAsObject(message, this.ToValue(value));
}
} catch (Exception ex) {
throw ErrorUtilities.Wrap(ex, MessagingStrings.MessagePartReadFailure, message.GetType(), this.Name, value);
@@ -289,28 +321,6 @@ namespace DotNetOpenAuth.Messaging.Reflection {
}
/// <summary>
- /// Adds a pair of type conversion functions to the static conversion map.
- /// </summary>
- /// <typeparam name="T">The custom type to convert to and from strings.</typeparam>
- /// <param name="toString">The function to convert the custom type to a string.</param>
- /// <param name="toOriginalString">The mapping function that converts some custom value to its original (non-normalized) string. May be null if the same as the <paramref name="toString"/> function.</param>
- /// <param name="toValue">The function to convert a string to the custom type.</param>
- [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Diagnostics.Contracts.__ContractsRuntime.Requires<System.ArgumentNullException>(System.Boolean,System.String,System.String)", Justification = "Code contracts"), SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "toString", Justification = "Code contracts"), SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "toValue", Justification = "Code contracts")]
- private static void Map<T>(Func<T, string> toString, Func<T, string> toOriginalString, Func<string, T> toValue) {
- Contract.Requires<ArgumentNullException>(toString != null, "toString");
- Contract.Requires<ArgumentNullException>(toValue != null, "toValue");
-
- if (toOriginalString == null) {
- toOriginalString = toString;
- }
-
- Func<object, string> safeToString = obj => obj != null ? toString((T)obj) : null;
- Func<object, string> safeToOriginalString = obj => obj != null ? toOriginalString((T)obj) : null;
- Func<string, object> safeToT = str => str != null ? toValue(str) : default(T);
- converters.Add(typeof(T), new ValueMapping(safeToString, safeToOriginalString, safeToT));
- }
-
- /// <summary>
/// Checks whether a type is a nullable value type (i.e. int?)
/// </summary>
/// <param name="type">The type in question.</param>
@@ -333,18 +343,48 @@ namespace DotNetOpenAuth.Messaging.Reflection {
/// <param name="messagePartEncoder">The message part encoder type.</param>
/// <returns>An instance of the desired encoder.</returns>
private static IMessagePartEncoder GetEncoder(Type messagePartEncoder) {
- Contract.Requires<ArgumentNullException>(messagePartEncoder != null);
+ Requires.NotNull(messagePartEncoder, "messagePartEncoder");
Contract.Ensures(Contract.Result<IMessagePartEncoder>() != null);
IMessagePartEncoder encoder;
if (!encoders.TryGetValue(messagePartEncoder, out encoder)) {
- encoder = encoders[messagePartEncoder] = (IMessagePartEncoder)Activator.CreateInstance(messagePartEncoder);
+ try {
+ encoder = encoders[messagePartEncoder] = (IMessagePartEncoder)Activator.CreateInstance(messagePartEncoder);
+ } catch (MissingMethodException ex) {
+ throw ErrorUtilities.Wrap(ex, MessagingStrings.EncoderInstantiationFailed, messagePartEncoder.FullName);
+ }
}
return encoder;
}
/// <summary>
+ /// Gets the value of the message part, without converting it to/from a string.
+ /// </summary>
+ /// <param name="message">The message instance to read from.</param>
+ /// <returns>The value of the member.</returns>
+ private object GetValueAsObject(IMessage message) {
+ if (this.property != null) {
+ return this.property.GetValue(message, null);
+ } else {
+ return this.field.GetValue(message);
+ }
+ }
+
+ /// <summary>
+ /// Sets the value of a message part directly with a given value.
+ /// </summary>
+ /// <param name="message">The message instance to read from.</param>
+ /// <param name="value">The value to set on the this part.</param>
+ private void SetValueAsObject(IMessage message, object value) {
+ if (this.property != null) {
+ this.property.SetValue(message, value, null);
+ } else {
+ this.field.SetValue(message, value);
+ }
+ }
+
+ /// <summary>
/// Converts a string representation of the member's value to the appropriate type.
/// </summary>
/// <param name="value">The string representation of the member's value.</param>
@@ -368,19 +408,6 @@ namespace DotNetOpenAuth.Messaging.Reflection {
}
/// <summary>
- /// Gets the value of the message part, without converting it to/from a string.
- /// </summary>
- /// <param name="message">The message instance to read from.</param>
- /// <returns>The value of the member.</returns>
- private object GetValueAsObject(IMessage message) {
- if (this.property != null) {
- return this.property.GetValue(message, null);
- } else {
- return this.field.GetValue(message);
- }
- }
-
- /// <summary>
/// Validates that the message part and its attribute have agreeable settings.
/// </summary>
/// <exception cref="ArgumentException">
diff --git a/src/DotNetOpenAuth/Messaging/Reflection/ValueMapping.cs b/src/DotNetOpenAuth.Core/Messaging/Reflection/ValueMapping.cs
index b0b8b47..9c0fa83 100644
--- a/src/DotNetOpenAuth/Messaging/Reflection/ValueMapping.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/Reflection/ValueMapping.cs
@@ -36,8 +36,8 @@ namespace DotNetOpenAuth.Messaging.Reflection {
/// <param name="toOriginalString">The mapping function that converts some custom value to its original (non-normalized) string. May be null if the same as the <paramref name="toString"/> function.</param>
/// <param name="toValue">The mapping function that converts a string to some custom value.</param>
internal ValueMapping(Func<object, string> toString, Func<object, string> toOriginalString, Func<string, object> toValue) {
- Contract.Requires<ArgumentNullException>(toString != null);
- Contract.Requires<ArgumentNullException>(toValue != null);
+ Requires.NotNull(toString, "toString");
+ Requires.NotNull(toValue, "toValue");
this.ValueToString = toString;
this.ValueToOriginalString = toOriginalString ?? toString;
@@ -49,7 +49,7 @@ namespace DotNetOpenAuth.Messaging.Reflection {
/// </summary>
/// <param name="encoder">The encoder.</param>
internal ValueMapping(IMessagePartEncoder encoder) {
- Contract.Requires<ArgumentNullException>(encoder != null);
+ Requires.NotNull(encoder, "encoder");
var nullEncoder = encoder as IMessagePartNullEncoder;
string nullString = nullEncoder != null ? nullEncoder.EncodedNullValue : null;
diff --git a/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactory.cs b/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactory.cs
new file mode 100644
index 0000000..5db206e
--- /dev/null
+++ b/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactory.cs
@@ -0,0 +1,298 @@
+//-----------------------------------------------------------------------
+// <copyright file="StandardMessageFactory.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Reflection;
+ using System.Text;
+ using DotNetOpenAuth.Messaging.Reflection;
+
+ /// <summary>
+ /// A message factory that automatically selects the message type based on the incoming data.
+ /// </summary>
+ internal class StandardMessageFactory : IMessageFactory {
+ /// <summary>
+ /// The request message types and their constructors to use for instantiating the messages.
+ /// </summary>
+ private readonly Dictionary<MessageDescription, ConstructorInfo> requestMessageTypes = new Dictionary<MessageDescription, ConstructorInfo>();
+
+ /// <summary>
+ /// The response message types and their constructors to use for instantiating the messages.
+ /// </summary>
+ /// <value>
+ /// The value is a dictionary, whose key is the type of the constructor's lone parameter.
+ /// </value>
+ private readonly Dictionary<MessageDescription, Dictionary<Type, ConstructorInfo>> responseMessageTypes = new Dictionary<MessageDescription, Dictionary<Type, ConstructorInfo>>();
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="StandardMessageFactory"/> class.
+ /// </summary>
+ internal StandardMessageFactory() {
+ }
+
+ /// <summary>
+ /// Adds message types to the set that this factory can create.
+ /// </summary>
+ /// <param name="messageTypes">The message types that this factory may instantiate.</param>
+ public virtual void AddMessageTypes(IEnumerable<MessageDescription> messageTypes) {
+ Requires.NotNull(messageTypes, "messageTypes");
+ Requires.True(messageTypes.All(msg => msg != null), "messageTypes");
+
+ var unsupportedMessageTypes = new List<MessageDescription>(0);
+ foreach (MessageDescription messageDescription in messageTypes) {
+ bool supportedMessageType = false;
+
+ // First see whether this message fits the recognized pattern for request messages.
+ if (typeof(IDirectedProtocolMessage).IsAssignableFrom(messageDescription.MessageType)) {
+ foreach (ConstructorInfo ctor in messageDescription.Constructors) {
+ ParameterInfo[] parameters = ctor.GetParameters();
+ if (parameters.Length == 2 && parameters[0].ParameterType == typeof(Uri) && parameters[1].ParameterType == typeof(Version)) {
+ supportedMessageType = true;
+ this.requestMessageTypes.Add(messageDescription, ctor);
+ break;
+ }
+ }
+ }
+
+ // Also see if this message fits the recognized pattern for response messages.
+ if (typeof(IDirectResponseProtocolMessage).IsAssignableFrom(messageDescription.MessageType)) {
+ var responseCtors = new Dictionary<Type, ConstructorInfo>(messageDescription.Constructors.Length);
+ foreach (ConstructorInfo ctor in messageDescription.Constructors) {
+ ParameterInfo[] parameters = ctor.GetParameters();
+ if (parameters.Length == 1 && typeof(IDirectedProtocolMessage).IsAssignableFrom(parameters[0].ParameterType)) {
+ responseCtors.Add(parameters[0].ParameterType, ctor);
+ }
+ }
+
+ if (responseCtors.Count > 0) {
+ supportedMessageType = true;
+ this.responseMessageTypes.Add(messageDescription, responseCtors);
+ }
+ }
+
+ if (!supportedMessageType) {
+ unsupportedMessageTypes.Add(messageDescription);
+ }
+ }
+
+ ErrorUtilities.VerifySupported(
+ !unsupportedMessageTypes.Any(),
+ MessagingStrings.StandardMessageFactoryUnsupportedMessageType,
+ unsupportedMessageTypes.ToStringDeferred());
+ }
+
+ #region IMessageFactory Members
+
+ /// <summary>
+ /// Analyzes an incoming request message payload to discover what kind of
+ /// message is embedded in it and returns the type, or null if no match is found.
+ /// </summary>
+ /// <param name="recipient">The intended or actual recipient of the request message.</param>
+ /// <param name="fields">The name/value pairs that make up the message payload.</param>
+ /// <returns>
+ /// A newly instantiated <see cref="IProtocolMessage"/>-derived object that this message can
+ /// deserialize to. Null if the request isn't recognized as a valid protocol message.
+ /// </returns>
+ public virtual IDirectedProtocolMessage GetNewRequestMessage(MessageReceivingEndpoint recipient, IDictionary<string, string> fields) {
+ MessageDescription matchingType = this.GetMessageDescription(recipient, fields);
+ if (matchingType != null) {
+ return this.InstantiateAsRequest(matchingType, recipient);
+ } else {
+ return null;
+ }
+ }
+
+ /// <summary>
+ /// Analyzes an incoming request message payload to discover what kind of
+ /// message is embedded in it and returns the type, or null if no match is found.
+ /// </summary>
+ /// <param name="request">The message that was sent as a request that resulted in the response.</param>
+ /// <param name="fields">The name/value pairs that make up the message payload.</param>
+ /// <returns>
+ /// A newly instantiated <see cref="IProtocolMessage"/>-derived object that this message can
+ /// deserialize to. Null if the request isn't recognized as a valid protocol message.
+ /// </returns>
+ public virtual IDirectResponseProtocolMessage GetNewResponseMessage(IDirectedProtocolMessage request, IDictionary<string, string> fields) {
+ MessageDescription matchingType = this.GetMessageDescription(request, fields);
+ if (matchingType != null) {
+ return this.InstantiateAsResponse(matchingType, request);
+ } else {
+ return null;
+ }
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Gets the message type that best fits the given incoming request data.
+ /// </summary>
+ /// <param name="recipient">The recipient of the incoming data. Typically not used, but included just in case.</param>
+ /// <param name="fields">The data of the incoming message.</param>
+ /// <returns>
+ /// The message type that matches the incoming data; or <c>null</c> if no match.
+ /// </returns>
+ /// <exception cref="ProtocolException">May be thrown if the incoming data is ambiguous.</exception>
+ protected virtual MessageDescription GetMessageDescription(MessageReceivingEndpoint recipient, IDictionary<string, string> fields) {
+ Requires.NotNull(recipient, "recipient");
+ Requires.NotNull(fields, "fields");
+
+ var matches = this.requestMessageTypes.Keys
+ .Where(message => message.CheckMessagePartsPassBasicValidation(fields))
+ .OrderByDescending(message => CountInCommon(message.Mapping.Keys, fields.Keys))
+ .ThenByDescending(message => message.Mapping.Count)
+ .CacheGeneratedResults();
+ var match = matches.FirstOrDefault();
+ if (match != null) {
+ if (Logger.Messaging.IsWarnEnabled && matches.Count() > 1) {
+ Logger.Messaging.WarnFormat(
+ "Multiple message types seemed to fit the incoming data: {0}",
+ matches.ToStringDeferred());
+ }
+
+ return match;
+ } else {
+ // No message type matches the incoming data.
+ return null;
+ }
+ }
+
+ /// <summary>
+ /// Gets the message type that best fits the given incoming direct response data.
+ /// </summary>
+ /// <param name="request">The request message that prompted the response data.</param>
+ /// <param name="fields">The data of the incoming message.</param>
+ /// <returns>
+ /// The message type that matches the incoming data; or <c>null</c> if no match.
+ /// </returns>
+ /// <exception cref="ProtocolException">May be thrown if the incoming data is ambiguous.</exception>
+ protected virtual MessageDescription GetMessageDescription(IDirectedProtocolMessage request, IDictionary<string, string> fields) {
+ Requires.NotNull(request, "request");
+ Requires.NotNull(fields, "fields");
+
+ var matches = (from responseMessageType in this.responseMessageTypes
+ let message = responseMessageType.Key
+ where message.CheckMessagePartsPassBasicValidation(fields)
+ let ctors = this.FindMatchingResponseConstructors(message, request.GetType())
+ where ctors.Any()
+ orderby GetDerivationDistance(ctors.First().GetParameters()[0].ParameterType, request.GetType()),
+ CountInCommon(message.Mapping.Keys, fields.Keys) descending,
+ message.Mapping.Count descending
+ select message).CacheGeneratedResults();
+ var match = matches.FirstOrDefault();
+ if (match != null) {
+ if (Logger.Messaging.IsWarnEnabled && matches.Count() > 1) {
+ Logger.Messaging.WarnFormat(
+ "Multiple message types seemed to fit the incoming data: {0}",
+ matches.ToStringDeferred());
+ }
+
+ return match;
+ } else {
+ // No message type matches the incoming data.
+ return null;
+ }
+ }
+
+ /// <summary>
+ /// Instantiates the given request message type.
+ /// </summary>
+ /// <param name="messageDescription">The message description.</param>
+ /// <param name="recipient">The recipient.</param>
+ /// <returns>The instantiated message. Never null.</returns>
+ protected virtual IDirectedProtocolMessage InstantiateAsRequest(MessageDescription messageDescription, MessageReceivingEndpoint recipient) {
+ Requires.NotNull(messageDescription, "messageDescription");
+ Requires.NotNull(recipient, "recipient");
+ Contract.Ensures(Contract.Result<IDirectedProtocolMessage>() != null);
+
+ ConstructorInfo ctor = this.requestMessageTypes[messageDescription];
+ return (IDirectedProtocolMessage)ctor.Invoke(new object[] { recipient.Location, messageDescription.MessageVersion });
+ }
+
+ /// <summary>
+ /// Instantiates the given request message type.
+ /// </summary>
+ /// <param name="messageDescription">The message description.</param>
+ /// <param name="request">The request that resulted in this response.</param>
+ /// <returns>The instantiated message. Never null.</returns>
+ protected virtual IDirectResponseProtocolMessage InstantiateAsResponse(MessageDescription messageDescription, IDirectedProtocolMessage request) {
+ Requires.NotNull(messageDescription, "messageDescription");
+ Requires.NotNull(request, "request");
+ Contract.Ensures(Contract.Result<IDirectResponseProtocolMessage>() != null);
+
+ Type requestType = request.GetType();
+ var ctors = this.FindMatchingResponseConstructors(messageDescription, requestType);
+ ConstructorInfo ctor = null;
+ try {
+ ctor = ctors.Single();
+ } catch (InvalidOperationException) {
+ if (ctors.Any()) {
+ ErrorUtilities.ThrowInternal("More than one matching constructor for request type " + requestType.Name + " and response type " + messageDescription.MessageType.Name);
+ } else {
+ ErrorUtilities.ThrowInternal("Unexpected request message type " + requestType.FullName + " for response type " + messageDescription.MessageType.Name);
+ }
+ }
+ return (IDirectResponseProtocolMessage)ctor.Invoke(new object[] { request });
+ }
+
+ /// <summary>
+ /// Gets the hierarchical distance between a type and a type it derives from or implements.
+ /// </summary>
+ /// <param name="assignableType">The base type or interface.</param>
+ /// <param name="derivedType">The concrete class that implements the <paramref name="assignableType"/>.</param>
+ /// <returns>The distance between the two types. 0 if the types are equivalent, 1 if the type immediately derives from or implements the base type, or progressively higher integers.</returns>
+ private static int GetDerivationDistance(Type assignableType, Type derivedType) {
+ Requires.NotNull(assignableType, "assignableType");
+ Requires.NotNull(derivedType, "derivedType");
+ Requires.True(assignableType.IsAssignableFrom(derivedType), "assignableType");
+
+ // If this is the two types are equivalent...
+ if (derivedType.IsAssignableFrom(assignableType))
+ {
+ return 0;
+ }
+
+ int steps;
+ derivedType = derivedType.BaseType;
+ for (steps = 1; assignableType.IsAssignableFrom(derivedType); steps++)
+ {
+ derivedType = derivedType.BaseType;
+ }
+
+ return steps;
+ }
+
+ /// <summary>
+ /// Counts how many strings are in the intersection of two collections.
+ /// </summary>
+ /// <param name="collection1">The first collection.</param>
+ /// <param name="collection2">The second collection.</param>
+ /// <param name="comparison">The string comparison method to use.</param>
+ /// <returns>A non-negative integer no greater than the count of elements in the smallest collection.</returns>
+ private static int CountInCommon(ICollection<string> collection1, ICollection<string> collection2, StringComparison comparison = StringComparison.Ordinal) {
+ Requires.NotNull(collection1, "collection1");
+ Requires.NotNull(collection2, "collection2");
+ Contract.Ensures(Contract.Result<int>() >= 0 && Contract.Result<int>() <= Math.Min(collection1.Count, collection2.Count));
+
+ return collection1.Count(value1 => collection2.Any(value2 => string.Equals(value1, value2, comparison)));
+ }
+
+ /// <summary>
+ /// Finds constructors for response messages that take a given request message type.
+ /// </summary>
+ /// <param name="messageDescription">The message description.</param>
+ /// <param name="requestType">Type of the request message.</param>
+ /// <returns>A sequence of matching constructors.</returns>
+ private IEnumerable<ConstructorInfo> FindMatchingResponseConstructors(MessageDescription messageDescription, Type requestType) {
+ Requires.NotNull(messageDescription, "messageDescription");
+ Requires.NotNull(requestType, "requestType");
+
+ return this.responseMessageTypes[messageDescription].Where(pair => pair.Key.IsAssignableFrom(requestType)).Select(pair => pair.Value);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactoryChannel.cs b/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactoryChannel.cs
new file mode 100644
index 0000000..acfc004
--- /dev/null
+++ b/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactoryChannel.cs
@@ -0,0 +1,111 @@
+//-----------------------------------------------------------------------
+// <copyright file="StandardMessageFactoryChannel.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using Reflection;
+
+ /// <summary>
+ /// A channel that uses the standard message factory.
+ /// </summary>
+ public abstract class StandardMessageFactoryChannel : Channel {
+ /// <summary>
+ /// The message types receivable by this channel.
+ /// </summary>
+ private readonly ICollection<Type> messageTypes;
+
+ /// <summary>
+ /// The protocol versions supported by this channel.
+ /// </summary>
+ private readonly ICollection<Version> versions;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="StandardMessageFactoryChannel"/> class.
+ /// </summary>
+ /// <param name="messageTypes">The message types that might be encountered.</param>
+ /// <param name="versions">All the possible message versions that might be encountered.</param>
+ /// <param name="bindingElements">The binding elements to apply to the channel.</param>
+ protected StandardMessageFactoryChannel(ICollection<Type> messageTypes, ICollection<Version> versions, params IChannelBindingElement[] bindingElements)
+ : base(new StandardMessageFactory(), bindingElements) {
+ Requires.NotNull(messageTypes, "messageTypes");
+ Requires.NotNull(versions, "versions");
+
+ this.messageTypes = messageTypes;
+ this.versions = versions;
+ this.StandardMessageFactory.AddMessageTypes(GetMessageDescriptions(this.messageTypes, this.versions, this.MessageDescriptions));
+ }
+
+ /// <summary>
+ /// Gets or sets a tool that can figure out what kind of message is being received
+ /// so it can be deserialized.
+ /// </summary>
+ internal StandardMessageFactory StandardMessageFactory {
+ get { return (Messaging.StandardMessageFactory)this.MessageFactory; }
+ set { this.MessageFactory = value; }
+ }
+
+ /// <summary>
+ /// Gets or sets the message descriptions.
+ /// </summary>
+ internal sealed override MessageDescriptionCollection MessageDescriptions {
+ get {
+ return base.MessageDescriptions;
+ }
+
+ set {
+ base.MessageDescriptions = value;
+
+ // We must reinitialize the message factory so it can use the new message descriptions.
+ var factory = new StandardMessageFactory();
+ factory.AddMessageTypes(GetMessageDescriptions(this.messageTypes, this.versions, value));
+ this.MessageFactory = factory;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets a tool that can figure out what kind of message is being received
+ /// so it can be deserialized.
+ /// </summary>
+ protected sealed override IMessageFactory MessageFactory {
+ get {
+ return (StandardMessageFactory)base.MessageFactory;
+ }
+
+ set {
+ StandardMessageFactory newValue = (StandardMessageFactory)value;
+ base.MessageFactory = newValue;
+ }
+ }
+
+ /// <summary>
+ /// Generates all the message descriptions for a given set of message types and versions.
+ /// </summary>
+ /// <param name="messageTypes">The message types.</param>
+ /// <param name="versions">The message versions.</param>
+ /// <param name="descriptionsCache">The cache to use when obtaining the message descriptions.</param>
+ /// <returns>The generated/retrieved message descriptions.</returns>
+ private static IEnumerable<MessageDescription> GetMessageDescriptions(ICollection<Type> messageTypes, ICollection<Version> versions, MessageDescriptionCollection descriptionsCache)
+ {
+ Requires.NotNull(messageTypes, "messageTypes");
+ Requires.NotNull(descriptionsCache, "descriptionsCache");
+ Contract.Ensures(Contract.Result<IEnumerable<MessageDescription>>() != null);
+
+ // Get all the MessageDescription objects through the standard cache,
+ // so that perhaps it will be a quick lookup, or at least it will be
+ // stored there for a quick lookup later.
+ var messageDescriptions = new List<MessageDescription>(messageTypes.Count * versions.Count);
+ messageDescriptions.AddRange(from version in versions
+ from messageType in messageTypes
+ select descriptionsCache.Get(messageType, version));
+
+ return messageDescriptions;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/StandardWebRequestHandler.cs b/src/DotNetOpenAuth.Core/Messaging/StandardWebRequestHandler.cs
index 48cc6e6..6c6a7bb 100644
--- a/src/DotNetOpenAuth/Messaging/StandardWebRequestHandler.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/StandardWebRequestHandler.cs
@@ -6,6 +6,7 @@
namespace DotNetOpenAuth.Messaging {
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Net;
@@ -225,10 +226,18 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="request">The request.</param>
/// <param name="preparingPost"><c>true</c> if this is a POST request whose headers have not yet been sent out; <c>false</c> otherwise.</param>
private static void PrepareRequest(HttpWebRequest request, bool preparingPost) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
// Be careful to not try to change the HTTP headers that have already gone out.
if (preparingPost || request.Method == "GET") {
+ // Set/override a few properties of the request to apply our policies for requests.
+ if (Debugger.IsAttached) {
+ // Since a debugger is attached, requests may be MUCH slower,
+ // so give ourselves huge timeouts.
+ request.ReadWriteTimeout = (int)TimeSpan.FromHours(1).TotalMilliseconds;
+ request.Timeout = (int)TimeSpan.FromHours(1).TotalMilliseconds;
+ }
+
// Some sites, such as Technorati, return 403 Forbidden on identity
// pages unless a User-Agent header is included.
if (string.IsNullOrEmpty(request.UserAgent)) {
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/TimespanSecondsEncoder.cs b/src/DotNetOpenAuth.Core/Messaging/TimespanSecondsEncoder.cs
index cc3f7cc..b28e5a8 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/TimespanSecondsEncoder.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/TimespanSecondsEncoder.cs
@@ -4,7 +4,7 @@
// </copyright>
//-----------------------------------------------------------------------
-namespace DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy {
+namespace DotNetOpenAuth.Messaging {
using System;
using System.Globalization;
using DotNetOpenAuth.Messaging.Reflection;
@@ -13,6 +13,13 @@ namespace DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy {
/// Encodes and decodes the <see cref="TimeSpan"/> as an integer of total seconds.
/// </summary>
internal class TimespanSecondsEncoder : IMessagePartEncoder {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TimespanSecondsEncoder"/> class.
+ /// </summary>
+ public TimespanSecondsEncoder() {
+ // Note that this constructor is public so it can be instantiated via Activator.
+ }
+
#region IMessagePartEncoder Members
/// <summary>
diff --git a/src/DotNetOpenAuth.Core/Messaging/TimestampEncoder.cs b/src/DotNetOpenAuth.Core/Messaging/TimestampEncoder.cs
new file mode 100644
index 0000000..b83a426
--- /dev/null
+++ b/src/DotNetOpenAuth.Core/Messaging/TimestampEncoder.cs
@@ -0,0 +1,61 @@
+//-----------------------------------------------------------------------
+// <copyright file="TimestampEncoder.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging {
+ using System;
+ using System.Globalization;
+ using DotNetOpenAuth.Messaging.Reflection;
+
+ /// <summary>
+ /// Translates between a <see cref="DateTime"/> and the number of seconds between it and 1/1/1970 12 AM
+ /// </summary>
+ internal class TimestampEncoder : IMessagePartEncoder {
+ /// <summary>
+ /// The reference date and time for calculating time stamps.
+ /// </summary>
+ internal static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TimestampEncoder"/> class.
+ /// </summary>
+ public TimestampEncoder() {
+ }
+
+ /// <summary>
+ /// Encodes the specified value.
+ /// </summary>
+ /// <param name="value">The value. Guaranteed to never be null.</param>
+ /// <returns>
+ /// The <paramref name="value"/> in string form, ready for message transport.
+ /// </returns>
+ public string Encode(object value) {
+ if (value == null) {
+ return null;
+ }
+
+ var timestamp = (DateTime)value;
+ TimeSpan secondsSinceEpoch = timestamp - Epoch;
+ return ((int)secondsSinceEpoch.TotalSeconds).ToString(CultureInfo.InvariantCulture);
+ }
+
+ /// <summary>
+ /// Decodes the specified value.
+ /// </summary>
+ /// <param name="value">The string value carried by the transport. Guaranteed to never be null, although it may be empty.</param>
+ /// <returns>
+ /// The deserialized form of the given string.
+ /// </returns>
+ /// <exception cref="FormatException">Thrown when the string value given cannot be decoded into the required object type.</exception>
+ public object Decode(string value) {
+ if (value == null) {
+ return null;
+ }
+
+ var secondsSinceEpoch = int.Parse(value, CultureInfo.InvariantCulture);
+ return Epoch.AddSeconds(secondsSinceEpoch);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/UnprotectedMessageException.cs b/src/DotNetOpenAuth.Core/Messaging/UnprotectedMessageException.cs
index 2f21184..2f21184 100644
--- a/src/DotNetOpenAuth/Messaging/UnprotectedMessageException.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/UnprotectedMessageException.cs
diff --git a/src/DotNetOpenAuth/Messaging/UntrustedWebRequestHandler.cs b/src/DotNetOpenAuth.Core/Messaging/UntrustedWebRequestHandler.cs
index 838b7e8..2d94130 100644
--- a/src/DotNetOpenAuth/Messaging/UntrustedWebRequestHandler.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/UntrustedWebRequestHandler.cs
@@ -88,7 +88,7 @@ namespace DotNetOpenAuth.Messaging {
/// </summary>
/// <param name="chainedWebRequestHandler">The chained web request handler.</param>
public UntrustedWebRequestHandler(IDirectWebRequestHandler chainedWebRequestHandler) {
- Contract.Requires<ArgumentNullException>(chainedWebRequestHandler != null);
+ Requires.NotNull(chainedWebRequestHandler, "chainedWebRequestHandler");
this.chainedWebRequestHandler = chainedWebRequestHandler;
if (Debugger.IsAttached) {
@@ -112,7 +112,7 @@ namespace DotNetOpenAuth.Messaging {
}
set {
- Contract.Requires<ArgumentOutOfRangeException>(value >= 2048);
+ Requires.InRange(value >= 2048, "value");
this.maximumBytesToRead = value;
}
}
@@ -127,7 +127,7 @@ namespace DotNetOpenAuth.Messaging {
}
set {
- Contract.Requires<ArgumentOutOfRangeException>(value >= 0);
+ Requires.InRange(value >= 0, "value");
this.maximumRedirections = value;
}
}
@@ -174,7 +174,7 @@ namespace DotNetOpenAuth.Messaging {
/// Gets the configuration for this class that is specified in the host's .config file.
/// </summary>
private static UntrustedWebRequestElement Configuration {
- get { return DotNetOpenAuthSection.Configuration.Messaging.UntrustedWebRequest; }
+ get { return DotNetOpenAuthSection.Messaging.UntrustedWebRequest; }
}
#region IDirectWebRequestHandler Members
@@ -314,7 +314,7 @@ namespace DotNetOpenAuth.Messaging {
/// <c>true</c> if this is a loopback IP address; <c>false</c> otherwise.
/// </returns>
private static bool IsIPv6Loopback(IPAddress ip) {
- Contract.Requires<ArgumentNullException>(ip != null);
+ Requires.NotNull(ip, "ip");
byte[] addressBytes = ip.GetAddressBytes();
for (int i = 0; i < addressBytes.Length - 1; i++) {
if (addressBytes[i] != 0) {
@@ -337,9 +337,9 @@ namespace DotNetOpenAuth.Messaging {
/// <c>true</c> if the specified host falls within at least one of the given lists; otherwise, <c>false</c>.
/// </returns>
private static bool IsHostInList(string host, ICollection<string> stringList, ICollection<Regex> regexList) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(host));
- Contract.Requires<ArgumentNullException>(stringList != null);
- Contract.Requires<ArgumentNullException>(regexList != null);
+ Requires.NotNullOrEmpty(host, "host");
+ Requires.NotNull(stringList, "stringList");
+ Requires.NotNull(regexList, "regexList");
foreach (string testHost in stringList) {
if (string.Equals(host, testHost, StringComparison.OrdinalIgnoreCase)) {
return true;
@@ -395,7 +395,7 @@ namespace DotNetOpenAuth.Messaging {
/// <c>true</c> if [is URI allowable] [the specified URI]; otherwise, <c>false</c>.
/// </returns>
private bool IsUriAllowable(Uri uri) {
- Contract.Requires<ArgumentNullException>(uri != null);
+ Requires.NotNull(uri, "uri");
if (!this.allowableSchemes.Contains(uri.Scheme)) {
Logger.Http.WarnFormat("Rejecting URL {0} because it uses a disallowed scheme.", uri);
return false;
@@ -455,7 +455,7 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="request">The request to prepare.</param>
/// <param name="preparingPost"><c>true</c> if this is a POST request whose headers have not yet been sent out; <c>false</c> otherwise.</param>
private void PrepareRequest(HttpWebRequest request, bool preparingPost) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
// Be careful to not try to change the HTTP headers that have already gone out.
if (preparingPost || request.Method == "GET") {
diff --git a/src/DotNetOpenAuth.Core/Messaging/UriStyleMessageFormatter.cs b/src/DotNetOpenAuth.Core/Messaging/UriStyleMessageFormatter.cs
new file mode 100644
index 0000000..2c653d0
--- /dev/null
+++ b/src/DotNetOpenAuth.Core/Messaging/UriStyleMessageFormatter.cs
@@ -0,0 +1,77 @@
+//-----------------------------------------------------------------------
+// <copyright file="UriStyleMessageFormatter.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Security.Cryptography;
+ using System.Text;
+ using System.Web;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+ using DotNetOpenAuth.Messaging.Reflection;
+
+ /// <summary>
+ /// A serializer for <see cref="DataBag"/>-derived types
+ /// </summary>
+ /// <typeparam name="T">The DataBag-derived type that is to be serialized/deserialized.</typeparam>
+ internal class UriStyleMessageFormatter<T> : DataBagFormatterBase<T> where T : DataBag, new() {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UriStyleMessageFormatter&lt;T&gt;"/> class.
+ /// </summary>
+ /// <param name="signingKey">The crypto service provider with the asymmetric key to use for signing or verifying the token.</param>
+ /// <param name="encryptingKey">The crypto service provider with the asymmetric key to use for encrypting or decrypting the token.</param>
+ /// <param name="compressed">A value indicating whether the data in this instance will be GZip'd.</param>
+ /// <param name="maximumAge">The maximum age of a token that can be decoded; useful only when <paramref name="decodeOnceOnly"/> is <c>true</c>.</param>
+ /// <param name="decodeOnceOnly">The nonce store to use to ensure that this instance is only decoded once.</param>
+ protected internal UriStyleMessageFormatter(RSACryptoServiceProvider signingKey = null, RSACryptoServiceProvider encryptingKey = null, bool compressed = false, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null)
+ : base(signingKey, encryptingKey, compressed, maximumAge, decodeOnceOnly) {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UriStyleMessageFormatter&lt;T&gt;"/> class.
+ /// </summary>
+ /// <param name="cryptoKeyStore">The crypto key store used when signing or encrypting.</param>
+ /// <param name="bucket">The bucket in which symmetric keys are stored for signing/encrypting data.</param>
+ /// <param name="signed">A value indicating whether the data in this instance will be protected against tampering.</param>
+ /// <param name="encrypted">A value indicating whether the data in this instance will be protected against eavesdropping.</param>
+ /// <param name="compressed">A value indicating whether the data in this instance will be GZip'd.</param>
+ /// <param name="minimumAge">The minimum age.</param>
+ /// <param name="maximumAge">The maximum age of a token that can be decoded; useful only when <paramref name="decodeOnceOnly"/> is <c>true</c>.</param>
+ /// <param name="decodeOnceOnly">The nonce store to use to ensure that this instance is only decoded once.</param>
+ protected internal UriStyleMessageFormatter(ICryptoKeyStore cryptoKeyStore = null, string bucket = null, bool signed = false, bool encrypted = false, bool compressed = false, TimeSpan? minimumAge = null, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null)
+ : base(cryptoKeyStore, bucket, signed, encrypted, compressed, minimumAge, maximumAge, decodeOnceOnly) {
+ Requires.True((cryptoKeyStore != null && !String.IsNullOrEmpty(bucket)) || (!signed && !encrypted), null);
+ }
+
+ /// <summary>
+ /// Serializes the <see cref="DataBag"/> instance to a buffer.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <returns>The buffer containing the serialized data.</returns>
+ protected override byte[] SerializeCore(T message) {
+ var fields = MessageSerializer.Get(message.GetType()).Serialize(MessageDescriptions.GetAccessor(message));
+ string value = MessagingUtilities.CreateQueryString(fields);
+ return Encoding.UTF8.GetBytes(value);
+ }
+
+ /// <summary>
+ /// Deserializes the <see cref="DataBag"/> instance from a buffer.
+ /// </summary>
+ /// <param name="message">The message instance to initialize with data from the buffer.</param>
+ /// <param name="data">The data buffer.</param>
+ protected override void DeserializeCore(T message, byte[] data) {
+ string value = Encoding.UTF8.GetString(data);
+
+ // Deserialize into message newly created instance.
+ var serializer = MessageSerializer.Get(message.GetType());
+ var fields = MessageDescriptions.GetAccessor(message);
+ serializer.Deserialize(HttpUtility.ParseQueryString(value).ToDictionary(), fields);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/Migrated rules for DotNetOpenAuth.ruleset b/src/DotNetOpenAuth.Core/Migrated rules for DotNetOpenAuth.ruleset
index 0ba4e6e..0ba4e6e 100644
--- a/src/DotNetOpenAuth/Migrated rules for DotNetOpenAuth.ruleset
+++ b/src/DotNetOpenAuth.Core/Migrated rules for DotNetOpenAuth.ruleset
diff --git a/src/DotNetOpenAuth.Core/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth.Core/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..205d331
--- /dev/null
+++ b/src/DotNetOpenAuth.Core/Properties/AssemblyInfo.cs
@@ -0,0 +1,88 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssemblyInfo.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+// We DON'T put an AssemblyVersionAttribute in here because it is generated in the build.
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Net;
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Security.Permissions;
+using System.Web.UI;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("DotNetOpenAuth")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DotNetOpenAuth")]
+[assembly: AssemblyCopyright("Copyright © 2008")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+[assembly: NeutralResourcesLanguage("en-US")]
+[assembly: CLSCompliant(true)]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("7d73990c-47c0-4256-9f20-a893add9e289")]
+
+[assembly: ContractVerification(true)]
+
+#if StrongNameSigned
+// See comment at top of this file. We need this so that strong-naming doesn't
+// keep this assembly from being useful to shared host (medium trust) web sites.
+[assembly: AllowPartiallyTrustedCallers]
+
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Core.UI, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.InfoCard, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.InfoCard.UI, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.UI, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.RelyingParty, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.RelyingParty.UI, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider.UI, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenIdInfoCard.UI, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth.Consumer, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth.ServiceProvider, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2.AuthorizationServer, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2.ResourceServer, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2.Client, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2.Client.UI, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
+#else
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.InfoCard")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.InfoCard.UI")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.UI")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.RelyingParty")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.RelyingParty.UI")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider.UI")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenIdInfoCard.UI")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth.Consumer")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth.ServiceProvider")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2.AuthorizationServer")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2.ResourceServer")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2.Client")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
+#endif
diff --git a/src/DotNetOpenAuth/Reporting.cs b/src/DotNetOpenAuth.Core/Reporting.cs
index 2f93416..0bbbcec 100644
--- a/src/DotNetOpenAuth/Reporting.cs
+++ b/src/DotNetOpenAuth.Core/Reporting.cs
@@ -23,14 +23,12 @@ namespace DotNetOpenAuth {
using DotNetOpenAuth.Configuration;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.Messaging.Bindings;
- using DotNetOpenAuth.OAuth;
- using DotNetOpenAuth.OAuth.ChannelElements;
/// <summary>
/// The statistical reporting mechanism used so this library's project authors
/// know what versions and features are in use.
/// </summary>
- public static class Reporting {
+ public class Reporting {
/// <summary>
/// A UTF8 encoder that doesn't emit the preamble. Used for mid-stream writers.
/// </summary>
@@ -117,7 +115,7 @@ namespace DotNetOpenAuth {
[SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "We do more than field initialization here.")]
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Reporting MUST NOT cause unhandled exceptions.")]
static Reporting() {
- Enabled = DotNetOpenAuthSection.Configuration.Reporting.Enabled;
+ Enabled = DotNetOpenAuthSection.Reporting.Enabled;
}
/// <summary>
@@ -145,10 +143,17 @@ namespace DotNetOpenAuth {
}
/// <summary>
+ /// Gets the observed features.
+ /// </summary>
+ internal static PersistentHashSet ObservedFeatures {
+ get { return observedFeatures; }
+ }
+
+ /// <summary>
/// Gets the configuration to use for reporting.
/// </summary>
- private static ReportingElement Configuration {
- get { return DotNetOpenAuthSection.Configuration.Reporting; }
+ internal static ReportingElement Configuration {
+ get { return DotNetOpenAuthSection.Reporting; }
}
/// <summary>
@@ -237,8 +242,7 @@ namespace DotNetOpenAuth {
/// </summary>
/// <param name="value">The object whose type is the feature to set as used.</param>
/// <param name="dependency1">Some dependency used by <paramref name="value"/>.</param>
- /// <param name="dependency2">Some dependency used by <paramref name="value"/>.</param>
- internal static void RecordFeatureAndDependencyUse(object value, object dependency1, object dependency2) {
+ internal static void RecordFeatureAndDependencyUse(object value, object dependency1) {
Contract.Requires(value != null);
// In release builds, just quietly return.
@@ -251,27 +255,22 @@ namespace DotNetOpenAuth {
builder.Append(value.GetType().Name);
builder.Append(" ");
builder.Append(dependency1 != null ? dependency1.GetType().Name : "(null)");
- builder.Append(" ");
- builder.Append(dependency2 != null ? dependency2.GetType().Name : "(null)");
observedFeatures.Add(builder.ToString());
Touch();
}
}
/// <summary>
- /// Records the feature and dependency use.
+ /// Records the use of a feature by object type.
/// </summary>
- /// <param name="value">The consumer or service provider.</param>
- /// <param name="service">The service.</param>
- /// <param name="tokenManager">The token manager.</param>
- /// <param name="nonceStore">The nonce store.</param>
- internal static void RecordFeatureAndDependencyUse(object value, ServiceProviderDescription service, ITokenManager tokenManager, INonceStore nonceStore) {
+ /// <param name="value">The object whose type is the feature to set as used.</param>
+ /// <param name="dependency1">Some dependency used by <paramref name="value"/>.</param>
+ /// <param name="dependency2">Some dependency used by <paramref name="value"/>.</param>
+ internal static void RecordFeatureAndDependencyUse(object value, object dependency1, object dependency2) {
Contract.Requires(value != null);
- Contract.Requires(service != null);
- Contract.Requires(tokenManager != null);
// In release builds, just quietly return.
- if (value == null || service == null || tokenManager == null) {
+ if (value == null) {
return;
}
@@ -279,15 +278,9 @@ namespace DotNetOpenAuth {
StringBuilder builder = new StringBuilder();
builder.Append(value.GetType().Name);
builder.Append(" ");
- builder.Append(tokenManager.GetType().Name);
- if (nonceStore != null) {
- builder.Append(" ");
- builder.Append(nonceStore.GetType().Name);
- }
- builder.Append(" ");
- builder.Append(service.Version);
+ builder.Append(dependency1 != null ? dependency1.GetType().Name : "(null)");
builder.Append(" ");
- builder.Append(service.UserAuthorizationEndpoint);
+ builder.Append(dependency2 != null ? dependency2.GetType().Name : "(null)");
observedFeatures.Add(builder.ToString());
Touch();
}
@@ -322,6 +315,20 @@ namespace DotNetOpenAuth {
}
/// <summary>
+ /// Called by every internal/public method on this class to give
+ /// periodic operations a chance to run.
+ /// </summary>
+ protected static void Touch() {
+ // Publish stats if it's time to do so.
+ lock (publishingConsiderationLock) {
+ if (DateTime.Now - lastPublished > Configuration.MinimumReportingInterval) {
+ lastPublished = DateTime.Now;
+ SendStatsAsync();
+ }
+ }
+ }
+
+ /// <summary>
/// Initializes Reporting if it has not been initialized yet.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "This method must never throw.")]
@@ -493,20 +500,6 @@ namespace DotNetOpenAuth {
}
/// <summary>
- /// Called by every internal/public method on this class to give
- /// periodic operations a chance to run.
- /// </summary>
- private static void Touch() {
- // Publish stats if it's time to do so.
- lock (publishingConsiderationLock) {
- if (DateTime.Now - lastPublished > Configuration.MinimumReportingInterval) {
- lastPublished = DateTime.Now;
- SendStatsAsync();
- }
- }
- }
-
- /// <summary>
/// Sends the stats report asynchronously, and careful to not throw any unhandled exceptions.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Unhandled exceptions MUST NOT be thrown from here.")]
@@ -561,7 +554,7 @@ namespace DotNetOpenAuth {
/// If an existing identifier is not found, a new one is created, persisted, and returned.
/// </remarks>
private static Guid GetOrCreateOriginIdentity() {
- Contract.Requires<InvalidOperationException>(file != null);
+ Requires.ValidState(file != null);
Contract.Ensures(Contract.Result<Guid>() != Guid.Empty);
Guid identityGuid = Guid.Empty;
@@ -591,7 +584,7 @@ namespace DotNetOpenAuth {
/// <param name="fileName">The filename to sanitize.</param>
/// <returns>The filename, with any and all invalid filename characters replaced with the hyphen (-) character.</returns>
private static string SanitizeFileName(string fileName) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(fileName));
+ Requires.NotNullOrEmpty(fileName, "fileName");
char[] invalidCharacters = Path.GetInvalidFileNameChars();
if (fileName.IndexOfAny(invalidCharacters) < 0) {
return fileName; // nothing invalid about this filename.
@@ -610,7 +603,7 @@ namespace DotNetOpenAuth {
/// <summary>
/// A set of values that persist the set to disk.
/// </summary>
- private class PersistentHashSet : IDisposable {
+ internal class PersistentHashSet : IDisposable {
/// <summary>
/// The isolated persistent storage.
/// </summary>
@@ -658,8 +651,8 @@ namespace DotNetOpenAuth {
/// <param name="fileName">Name of the file.</param>
/// <param name="maximumElements">The maximum number of elements to track.</param>
internal PersistentHashSet(IsolatedStorageFile storage, string fileName, int maximumElements) {
- Contract.Requires<ArgumentNullException>(storage != null);
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(fileName));
+ Requires.NotNull(storage, "storage");
+ Requires.NotNullOrEmpty(fileName, "fileName");
this.FileName = fileName;
this.maximumElements = maximumElements;
@@ -803,8 +796,8 @@ namespace DotNetOpenAuth {
/// <param name="storage">The storage location.</param>
/// <param name="fileName">Name of the file.</param>
internal PersistentCounter(IsolatedStorageFile storage, string fileName) {
- Contract.Requires<ArgumentNullException>(storage != null);
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(fileName));
+ Requires.NotNull(storage, "storage");
+ Requires.NotNullOrEmpty(fileName, "fileName");
this.FileName = fileName;
// Load the file into memory.
diff --git a/src/DotNetOpenAuth.Core/Requires.cs b/src/DotNetOpenAuth.Core/Requires.cs
new file mode 100644
index 0000000..4be6da0
--- /dev/null
+++ b/src/DotNetOpenAuth.Core/Requires.cs
@@ -0,0 +1,250 @@
+//-----------------------------------------------------------------------
+// <copyright file="Requires.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics;
+ using System.Diagnostics.Contracts;
+ using System.Globalization;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// Argument validation checks that throw some kind of ArgumentException when they fail (unless otherwise noted).
+ /// </summary>
+ internal static class Requires {
+ /// <summary>
+ /// Validates that a given parameter is not null.
+ /// </summary>
+ /// <typeparam name="T">The type of the parameter</typeparam>
+ /// <param name="value">The value.</param>
+ /// <param name="parameterName">Name of the parameter.</param>
+#if !CLR4
+ [ContractArgumentValidator]
+#endif
+ [Pure, DebuggerStepThrough]
+ internal static void NotNull<T>(T value, string parameterName) where T : class {
+ if (value == null) {
+ throw new ArgumentNullException(parameterName);
+ }
+
+ Contract.EndContractBlock();
+ }
+
+ /// <summary>
+ /// Validates that a parameter is not null or empty.
+ /// </summary>
+ /// <param name="value">The value.</param>
+ /// <param name="parameterName">Name of the parameter.</param>
+#if !CLR4
+ [ContractArgumentValidator]
+#endif
+ [Pure, DebuggerStepThrough]
+ internal static void NotNullOrEmpty(string value, string parameterName) {
+ NotNull(value, parameterName);
+ True(value.Length > 0, parameterName, Strings.EmptyStringNotAllowed);
+ Contract.EndContractBlock();
+ }
+
+ /// <summary>
+ /// Validates that an array is not null or empty.
+ /// </summary>
+ /// <typeparam name="T">The type of the elements in the sequence.</typeparam>
+ /// <param name="value">The value.</param>
+ /// <param name="parameterName">Name of the parameter.</param>
+#if !CLR4
+ [ContractArgumentValidator]
+#endif
+ [Pure, DebuggerStepThrough]
+ internal static void NotNullOrEmpty<T>(IEnumerable<T> value, string parameterName) {
+ NotNull(value, parameterName);
+ True(value.Any(), parameterName, Strings.InvalidArgument);
+ Contract.EndContractBlock();
+ }
+
+ /// <summary>
+ /// Validates that an argument is either null or is a sequence with no null elements.
+ /// </summary>
+ /// <typeparam name="T">The type of elements in the sequence.</typeparam>
+ /// <param name="sequence">The sequence.</param>
+ /// <param name="parameterName">Name of the parameter.</param>
+#if !CLR4
+ [ContractArgumentValidator]
+#endif
+ [Pure, DebuggerStepThrough]
+ internal static void NullOrWithNoNullElements<T>(IEnumerable<T> sequence, string parameterName) where T : class {
+ if (sequence != null) {
+ if (sequence.Any(e => e == null)) {
+ throw new ArgumentException(MessagingStrings.SequenceContainsNullElement, parameterName);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Validates some expression describing the acceptable range for an argument evaluates to true.
+ /// </summary>
+ /// <param name="condition">The expression that must evaluate to true to avoid an <see cref="ArgumentOutOfRangeException"/>.</param>
+ /// <param name="parameterName">Name of the parameter.</param>
+ /// <param name="message">The message to include with the exception.</param>
+#if !CLR4
+ [ContractArgumentValidator]
+#endif
+ [Pure, DebuggerStepThrough]
+ internal static void InRange(bool condition, string parameterName, string message = null) {
+ if (!condition) {
+ throw new ArgumentOutOfRangeException(parameterName, message);
+ }
+
+ Contract.EndContractBlock();
+ }
+
+ /// <summary>
+ /// Validates some expression describing the acceptable condition for an argument evaluates to true.
+ /// </summary>
+ /// <param name="condition">The expression that must evaluate to true to avoid an <see cref="ArgumentException"/>.</param>
+ /// <param name="parameterName">Name of the parameter.</param>
+ /// <param name="message">The message to include with the exception.</param>
+#if !CLR4
+ [ContractArgumentValidator]
+#endif
+ [Pure, DebuggerStepThrough]
+ internal static void True(bool condition, string parameterName = null, string message = null) {
+ if (!condition) {
+ throw new ArgumentException(message ?? Strings.InvalidArgument, parameterName);
+ }
+
+ Contract.EndContractBlock();
+ }
+
+ /// <summary>
+ /// Validates some expression describing the acceptable condition for an argument evaluates to true.
+ /// </summary>
+ /// <param name="condition">The expression that must evaluate to true to avoid an <see cref="ArgumentException"/>.</param>
+ /// <param name="parameterName">Name of the parameter.</param>
+ /// <param name="unformattedMessage">The unformatted message.</param>
+ /// <param name="args">Formatting arguments.</param>
+#if !CLR4
+ [ContractArgumentValidator]
+#endif
+ [Pure, DebuggerStepThrough]
+ internal static void True(bool condition, string parameterName, string unformattedMessage, params object[] args) {
+ if (!condition) {
+ throw new ArgumentException(String.Format(unformattedMessage, args), parameterName);
+ }
+
+ Contract.EndContractBlock();
+ }
+
+ /// <summary>
+ /// Validates some expression describing the acceptable condition for an argument evaluates to true.
+ /// </summary>
+ /// <param name="condition">The expression that must evaluate to true to avoid an <see cref="InvalidOperationException"/>.</param>
+#if !CLR4
+ [ContractArgumentValidator]
+#endif
+ [Pure, DebuggerStepThrough]
+ internal static void ValidState(bool condition) {
+ if (!condition) {
+ throw new InvalidOperationException();
+ }
+
+ Contract.EndContractBlock();
+ }
+
+ /// <summary>
+ /// Validates some expression describing the acceptable condition for an argument evaluates to true.
+ /// </summary>
+ /// <param name="condition">The expression that must evaluate to true to avoid an <see cref="InvalidOperationException"/>.</param>
+ /// <param name="message">The message to include with the exception.</param>
+#if !CLR4
+ [ContractArgumentValidator]
+#endif
+ [Pure, DebuggerStepThrough]
+ internal static void ValidState(bool condition, string message) {
+ if (!condition) {
+ throw new InvalidOperationException(message);
+ }
+
+ Contract.EndContractBlock();
+ }
+
+ /// <summary>
+ /// Validates some expression describing the acceptable condition for an argument evaluates to true.
+ /// </summary>
+ /// <param name="condition">The expression that must evaluate to true to avoid an <see cref="InvalidOperationException"/>.</param>
+ /// <param name="unformattedMessage">The unformatted message.</param>
+ /// <param name="args">Formatting arguments.</param>
+#if !CLR4
+ [ContractArgumentValidator]
+#endif
+ [Pure, DebuggerStepThrough]
+ internal static void ValidState(bool condition, string unformattedMessage, params object[] args) {
+ if (!condition) {
+ throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, unformattedMessage, args));
+ }
+
+ Contract.EndContractBlock();
+ }
+
+ /// <summary>
+ /// Validates that some argument describes a type that is or derives from a required type.
+ /// </summary>
+ /// <typeparam name="T">The type that the argument must be or derive from.</typeparam>
+ /// <param name="type">The type given in the argument.</param>
+ /// <param name="parameterName">Name of the parameter.</param>
+#if !CLR4
+ [ContractArgumentValidator]
+#endif
+ [Pure, DebuggerStepThrough]
+ internal static void NotNullSubtype<T>(Type type, string parameterName) {
+ NotNull(type, parameterName);
+ True(typeof(T).IsAssignableFrom(type), parameterName, MessagingStrings.UnexpectedType, typeof(T).FullName, type.FullName);
+
+ Contract.EndContractBlock();
+ }
+
+ /// <summary>
+ /// Validates some expression describing the acceptable condition for an argument evaluates to true.
+ /// </summary>
+ /// <param name="condition">The expression that must evaluate to true to avoid an <see cref="FormatException"/>.</param>
+ /// <param name="message">The message.</param>
+#if !CLR4
+ [ContractArgumentValidator]
+#endif
+ [Pure, DebuggerStepThrough]
+ internal static void Format(bool condition, string message) {
+ if (!condition) {
+ throw new FormatException(message);
+ }
+
+ Contract.EndContractBlock();
+ }
+
+ /// <summary>
+ /// Throws an <see cref="NotSupportedException"/> if a condition does not evaluate to <c>true</c>.
+ /// </summary>
+ /// <param name="condition">The expression that must evaluate to true to avoid an <see cref="NotSupportedException"/>.</param>
+ /// <param name="message">The message.</param>
+ [Pure, DebuggerStepThrough]
+ internal static void Support(bool condition, string message) {
+ if (!condition) {
+ throw new NotSupportedException(message);
+ }
+ }
+
+ /// <summary>
+ /// Throws an <see cref="ArgumentException"/>
+ /// </summary>
+ /// <param name="parameterName">Name of the parameter.</param>
+ /// <param name="message">The message.</param>
+ [Pure, DebuggerStepThrough]
+ internal static void Fail(string parameterName, string message) {
+ throw new ArgumentException(message, parameterName);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/Settings.StyleCop b/src/DotNetOpenAuth.Core/Settings.StyleCop
index 017d610..017d610 100644
--- a/src/DotNetOpenAuth/Settings.StyleCop
+++ b/src/DotNetOpenAuth.Core/Settings.StyleCop
diff --git a/src/DotNetOpenAuth/Strings.Designer.cs b/src/DotNetOpenAuth.Core/Strings.Designer.cs
index 1461f83..21411a1 100644
--- a/src/DotNetOpenAuth/Strings.Designer.cs
+++ b/src/DotNetOpenAuth.Core/Strings.Designer.cs
@@ -1,7 +1,7 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
-// Runtime Version:4.0.30319.1
+// Runtime Version:4.0.30319.17291
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
@@ -88,6 +88,24 @@ namespace DotNetOpenAuth {
}
/// <summary>
+ /// Looks up a localized string similar to The empty string is not allowed..
+ /// </summary>
+ internal static string EmptyStringNotAllowed {
+ get {
+ return ResourceManager.GetString("EmptyStringNotAllowed", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to The argument has an unexpected value..
+ /// </summary>
+ internal static string InvalidArgument {
+ get {
+ return ResourceManager.GetString("InvalidArgument", resourceCulture);
+ }
+ }
+
+ /// <summary>
/// Looks up a localized string similar to No current HttpContext was detected, so an {0} instance must be explicitly provided or specified in the .config file. Call the constructor overload that takes an {0}..
/// </summary>
internal static string StoreRequiredWhenNoHttpContextAvailable {
diff --git a/src/DotNetOpenAuth/Strings.resx b/src/DotNetOpenAuth.Core/Strings.resx
index 4b78664..1c69ef7 100644
--- a/src/DotNetOpenAuth/Strings.resx
+++ b/src/DotNetOpenAuth.Core/Strings.resx
@@ -129,4 +129,10 @@
<data name="EmbeddedResourceUrlProviderRequired" xml:space="preserve">
<value>The current IHttpHandler is not one of types: {0}. An embedded resource URL provider must be set in your .config file.</value>
</data>
+ <data name="EmptyStringNotAllowed" xml:space="preserve">
+ <value>The empty string is not allowed.</value>
+ </data>
+ <data name="InvalidArgument" xml:space="preserve">
+ <value>The argument has an unexpected value.</value>
+ </data>
</root> \ No newline at end of file
diff --git a/src/DotNetOpenAuth/Strings.sr.resx b/src/DotNetOpenAuth.Core/Strings.sr.resx
index 5112265..5112265 100644
--- a/src/DotNetOpenAuth/Strings.sr.resx
+++ b/src/DotNetOpenAuth.Core/Strings.sr.resx
diff --git a/src/DotNetOpenAuth/UriUtil.cs b/src/DotNetOpenAuth.Core/UriUtil.cs
index 819c406..57360f5 100644
--- a/src/DotNetOpenAuth/UriUtil.cs
+++ b/src/DotNetOpenAuth.Core/UriUtil.cs
@@ -30,7 +30,7 @@ namespace DotNetOpenAuth {
/// </returns>
[ContractVerification(false)] // bugs/limitations in CC static analysis
internal static bool QueryStringContainPrefixedParameters(this Uri uri, string prefix) {
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(prefix));
+ Requires.NotNullOrEmpty(prefix, "prefix");
if (uri == null) {
return false;
}
@@ -48,7 +48,7 @@ namespace DotNetOpenAuth {
/// <c>true</c> if the URI represents an encrypted request; otherwise, <c>false</c>.
/// </returns>
internal static bool IsTransportSecure(this Uri uri) {
- Contract.Requires<ArgumentNullException>(uri != null);
+ Requires.NotNull(uri, "uri");
return string.Equals(uri.Scheme, "https", StringComparison.OrdinalIgnoreCase);
}
@@ -59,7 +59,7 @@ namespace DotNetOpenAuth {
/// <param name="builder">The UriBuilder to render as a string.</param>
/// <returns>The string version of the Uri.</returns>
internal static string ToStringWithImpliedPorts(this UriBuilder builder) {
- Contract.Requires<ArgumentNullException>(builder != null);
+ Requires.NotNull(builder, "builder");
Contract.Ensures(Contract.Result<string>() != null);
// We only check for implied ports on HTTP and HTTPS schemes since those
diff --git a/src/DotNetOpenAuth/Util.cs b/src/DotNetOpenAuth.Core/Util.cs
index 0317c4d..6b63a36 100644
--- a/src/DotNetOpenAuth/Util.cs
+++ b/src/DotNetOpenAuth.Core/Util.cs
@@ -30,7 +30,7 @@ namespace DotNetOpenAuth {
/// <summary>
/// The web.config file-specified provider of web resource URLs.
/// </summary>
- private static IEmbeddedResourceRetrieval embeddedResourceRetrieval = DotNetOpenAuthSection.Configuration.EmbeddedResourceRetrievalProvider.CreateInstance(null, false);
+ private static IEmbeddedResourceRetrieval embeddedResourceRetrieval = MessagingElement.Configuration.EmbeddedResourceRetrievalProvider.CreateInstance(null, false);
/// <summary>
/// Gets a human-readable description of the library name and version, including
@@ -209,7 +209,7 @@ namespace DotNetOpenAuth {
/// <param name="obj">The object that may be serialized to string form.</param>
/// <param name="toString">The method that will serialize the object if called upon.</param>
public DelayedToString(T obj, Func<T, string> toString) {
- Contract.Requires<ArgumentNullException>(toString != null);
+ Requires.NotNull(toString, "toString");
this.obj = obj;
this.toString = toString;
diff --git a/src/DotNetOpenAuth/ComponentModel/IssuersSuggestions.cs b/src/DotNetOpenAuth.InfoCard.UI/ComponentModel/IssuersSuggestions.cs
index dc41843..dc41843 100644
--- a/src/DotNetOpenAuth/ComponentModel/IssuersSuggestions.cs
+++ b/src/DotNetOpenAuth.InfoCard.UI/ComponentModel/IssuersSuggestions.cs
diff --git a/src/DotNetOpenAuth/ComponentModel/UriConverter.cs b/src/DotNetOpenAuth.InfoCard.UI/ComponentModel/UriConverter.cs
index 5e7c22b..5111846 100644
--- a/src/DotNetOpenAuth/ComponentModel/UriConverter.cs
+++ b/src/DotNetOpenAuth.InfoCard.UI/ComponentModel/UriConverter.cs
@@ -108,7 +108,7 @@ namespace DotNetOpenAuth.ComponentModel {
let value = (string)prop.GetValue(null, null)
where value != null
select new Uri(value);
- return (fields.Concat(properties)).ToArray();
+ return fields.Concat(properties).ToArray();
} else {
return new Uri[0];
}
diff --git a/src/DotNetOpenAuth.InfoCard.UI/DotNetOpenAuth.InfoCard.UI.csproj b/src/DotNetOpenAuth.InfoCard.UI/DotNetOpenAuth.InfoCard.UI.csproj
new file mode 100644
index 0000000..f1aac54
--- /dev/null
+++ b/src/DotNetOpenAuth.InfoCard.UI/DotNetOpenAuth.InfoCard.UI.csproj
@@ -0,0 +1,68 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))\EnlistmentInfo.props" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))' != '' " />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" />
+ <PropertyGroup>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{E040EB58-B4D2-457B-A023-AE6EF3BD34DE}</ProjectGuid>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <AssemblyName>DotNetOpenAuth.InfoCard.UI</AssemblyName>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" />
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="ComponentModel\IssuersSuggestions.cs" />
+ <Compile Include="ComponentModel\UriConverter.cs" />
+ <Compile Include="InfoCard\ClaimType.cs" />
+ <Compile Include="InfoCard\InfoCardImage.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ </ItemGroup>
+ <ItemGroup Condition=" '$(NoUIControls)' != 'true' ">
+ <Compile Include="InfoCard\ReceivingTokenEventArgs.cs" />
+ <Compile Include="InfoCard\TokenProcessingErrorEventArgs.cs" />
+ <Compile Include="InfoCard\InfoCardSelector.cs" />
+ <Compile Include="InfoCard\ReceivedTokenEventArgs.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <EmbeddedResource Include="InfoCard\infocard_114x80.png" />
+ <EmbeddedResource Include="InfoCard\infocard_14x10.png" />
+ <EmbeddedResource Include="InfoCard\infocard_214x150.png" />
+ <EmbeddedResource Include="InfoCard\infocard_23x16.png" />
+ <EmbeddedResource Include="InfoCard\infocard_300x210.png" />
+ <EmbeddedResource Include="InfoCard\infocard_34x24.png" />
+ <EmbeddedResource Include="InfoCard\infocard_365x256.png" />
+ <EmbeddedResource Include="InfoCard\infocard_41x29.png" />
+ <EmbeddedResource Include="InfoCard\infocard_50x35.png" />
+ <EmbeddedResource Include="InfoCard\infocard_60x42.png" />
+ <EmbeddedResource Include="InfoCard\infocard_71x50.png" />
+ <EmbeddedResource Include="InfoCard\infocard_81x57.png" />
+ <EmbeddedResource Include="InfoCard\infocard_92x64.png" />
+ <EmbeddedResource Include="InfoCard\SupportingScript.js">
+ <Copyright>$(StandardCopyright)</Copyright>
+ </EmbeddedResource>
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\DotNetOpenAuth.InfoCard\DotNetOpenAuth.InfoCard.csproj">
+ <Project>{408D10B8-34BA-4CBD-B7AA-FEB1907ABA4C}</Project>
+ <Name>DotNetOpenAuth.InfoCard</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.Core.UI\DotNetOpenAuth.Core.UI.csproj">
+ <Project>{173E7B8D-E751-46E2-A133-F72297C0D2F4}</Project>
+ <Name>DotNetOpenAuth.Core.UI</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.Core\DotNetOpenAuth.Core.csproj">
+ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project>
+ <Name>DotNetOpenAuth.Core</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
+</Project> \ No newline at end of file
diff --git a/src/DotNetOpenAuth/InfoCard/ClaimType.cs b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/ClaimType.cs
index 9d3056a..9d3056a 100644
--- a/src/DotNetOpenAuth/InfoCard/ClaimType.cs
+++ b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/ClaimType.cs
diff --git a/src/DotNetOpenAuth/InfoCard/InfoCardImage.cs b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/InfoCardImage.cs
index 247f461..247f461 100644
--- a/src/DotNetOpenAuth/InfoCard/InfoCardImage.cs
+++ b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/InfoCardImage.cs
diff --git a/src/DotNetOpenAuth/InfoCard/InfoCardSelector.cs b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/InfoCardSelector.cs
index ae45229..b1d5bfd 100644
--- a/src/DotNetOpenAuth/InfoCard/InfoCardSelector.cs
+++ b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/InfoCardSelector.cs
@@ -454,7 +454,7 @@ namespace DotNetOpenAuth.InfoCard {
/// <returns>The event arguments sent to the event handlers.</returns>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "decryptor", Justification = "By design")]
protected virtual ReceivingTokenEventArgs OnReceivingToken(string tokenXml) {
- Contract.Requires<ArgumentNullException>(tokenXml != null);
+ Requires.NotNull(tokenXml, "tokenXml");
var args = new ReceivingTokenEventArgs(tokenXml);
var receivingToken = this.ReceivingToken;
@@ -470,7 +470,7 @@ namespace DotNetOpenAuth.InfoCard {
/// </summary>
/// <param name="token">The token, if it was decrypted.</param>
protected virtual void OnReceivedToken(Token token) {
- Contract.Requires<ArgumentNullException>(token != null);
+ Requires.NotNull(token, "token");
var receivedInfoCard = this.ReceivedToken;
if (receivedInfoCard != null) {
@@ -484,8 +484,8 @@ namespace DotNetOpenAuth.InfoCard {
/// <param name="unprocessedToken">The unprocessed token.</param>
/// <param name="ex">The exception generated while processing the token.</param>
protected virtual void OnTokenProcessingError(string unprocessedToken, Exception ex) {
- Contract.Requires<ArgumentNullException>(unprocessedToken != null);
- Contract.Requires<ArgumentNullException>(ex != null);
+ Requires.NotNull(unprocessedToken, "unprocessedToken");
+ Requires.NotNull(ex, "ex");
var tokenProcessingError = this.TokenProcessingError;
if (tokenProcessingError != null) {
@@ -516,7 +516,7 @@ namespace DotNetOpenAuth.InfoCard {
protected override void CreateChildControls() {
base.CreateChildControls();
- this.Page.ClientScript.RegisterHiddenField(this.HiddenFieldName, "");
+ this.Page.ClientScript.RegisterHiddenField(this.HiddenFieldName, string.Empty);
this.Controls.Add(this.infoCardSupportedPanel = this.CreateInfoCardSupportedPanel());
this.Controls.Add(this.infoCardNotSupportedPanel = this.CreateInfoCardUnsupportedPanel());
@@ -724,7 +724,7 @@ namespace DotNetOpenAuth.InfoCard {
/// <param name="optional">A space-delimited list of claim type URIs for claims that may optionally be included in a submitted Information Card.</param>
[Pure]
private void GetRequestedClaims(out string required, out string optional) {
- Contract.Requires<InvalidOperationException>(this.ClaimsRequested != null);
+ Requires.ValidState(this.ClaimsRequested != null);
Contract.Ensures(Contract.ValueAtReturn<string>(out required) != null);
Contract.Ensures(Contract.ValueAtReturn<string>(out optional) != null);
@@ -750,7 +750,7 @@ namespace DotNetOpenAuth.InfoCard {
/// or to downgrade gracefully if the user agent lacks an Information Card selector.
/// </summary>
private void RenderSupportingScript() {
- Contract.Requires<InvalidOperationException>(this.infoCardSupportedPanel != null);
+ Requires.ValidState(this.infoCardSupportedPanel != null);
this.Page.ClientScript.RegisterClientScriptResource(typeof(InfoCardSelector), ScriptResourceName);
diff --git a/src/DotNetOpenAuth/InfoCard/ReceivedTokenEventArgs.cs b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/ReceivedTokenEventArgs.cs
index f325ff9..f325ff9 100644
--- a/src/DotNetOpenAuth/InfoCard/ReceivedTokenEventArgs.cs
+++ b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/ReceivedTokenEventArgs.cs
diff --git a/src/DotNetOpenAuth/InfoCard/ReceivingTokenEventArgs.cs b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/ReceivingTokenEventArgs.cs
index 3dd892a..d831a84 100644
--- a/src/DotNetOpenAuth/InfoCard/ReceivingTokenEventArgs.cs
+++ b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/ReceivingTokenEventArgs.cs
@@ -21,7 +21,7 @@ namespace DotNetOpenAuth.InfoCard {
/// </summary>
/// <param name="tokenXml">The raw token XML, prior to any decryption.</param>
internal ReceivingTokenEventArgs(string tokenXml) {
- Contract.Requires<ArgumentNullException>(tokenXml != null);
+ Requires.NotNull(tokenXml, "tokenXml");
this.TokenXml = tokenXml;
this.IsEncrypted = Token.IsEncrypted(this.TokenXml);
@@ -63,7 +63,7 @@ namespace DotNetOpenAuth.InfoCard {
/// </summary>
/// <param name="securityToken">The security token.</param>
public void AddDecryptingToken(SecurityToken securityToken) {
- Contract.Requires<ArgumentNullException>(securityToken != null);
+ Requires.NotNull(securityToken, "securityToken");
this.DecryptingTokens.Add(securityToken);
}
@@ -73,8 +73,8 @@ namespace DotNetOpenAuth.InfoCard {
/// <param name="certificate">The certificate.</param>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "False positive")]
public void AddDecryptingToken(X509Certificate2 certificate) {
- Contract.Requires<ArgumentNullException>(certificate != null);
- Contract.Requires<ArgumentException>(certificate.HasPrivateKey);
+ Requires.NotNull(certificate, "certificate");
+ Requires.True(certificate.HasPrivateKey, "certificate");
var cert = new X509SecurityToken(certificate);
try {
this.AddDecryptingToken(cert);
diff --git a/src/DotNetOpenAuth/InfoCard/SupportingScript.js b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/SupportingScript.js
index a883cd7..a883cd7 100644
--- a/src/DotNetOpenAuth/InfoCard/SupportingScript.js
+++ b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/SupportingScript.js
diff --git a/src/DotNetOpenAuth/InfoCard/TokenProcessingErrorEventArgs.cs b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/TokenProcessingErrorEventArgs.cs
index 0f17b63..3ce9f40 100644
--- a/src/DotNetOpenAuth/InfoCard/TokenProcessingErrorEventArgs.cs
+++ b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/TokenProcessingErrorEventArgs.cs
@@ -18,8 +18,8 @@ namespace DotNetOpenAuth.InfoCard {
/// <param name="tokenXml">The token XML.</param>
/// <param name="exception">The exception.</param>
internal TokenProcessingErrorEventArgs(string tokenXml, Exception exception) {
- Contract.Requires<ArgumentNullException>(tokenXml != null);
- Contract.Requires<ArgumentNullException>(exception != null);
+ Requires.NotNull(tokenXml, "tokenXml");
+ Requires.NotNull(exception, "exception");
this.TokenXml = tokenXml;
this.Exception = exception;
}
diff --git a/src/DotNetOpenAuth/InfoCard/infocard_114x80.png b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_114x80.png
index 6dba25f..6dba25f 100644
--- a/src/DotNetOpenAuth/InfoCard/infocard_114x80.png
+++ b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_114x80.png
Binary files differ
diff --git a/src/DotNetOpenAuth/InfoCard/infocard_14x10.png b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_14x10.png
index d63575d..d63575d 100644
--- a/src/DotNetOpenAuth/InfoCard/infocard_14x10.png
+++ b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_14x10.png
Binary files differ
diff --git a/src/DotNetOpenAuth/InfoCard/infocard_214x150.png b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_214x150.png
index 71ebc7e..71ebc7e 100644
--- a/src/DotNetOpenAuth/InfoCard/infocard_214x150.png
+++ b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_214x150.png
Binary files differ
diff --git a/src/DotNetOpenAuth/InfoCard/infocard_23x16.png b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_23x16.png
index 9dbea9f..9dbea9f 100644
--- a/src/DotNetOpenAuth/InfoCard/infocard_23x16.png
+++ b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_23x16.png
Binary files differ
diff --git a/src/DotNetOpenAuth/InfoCard/infocard_300x210.png b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_300x210.png
index e805b9d..e805b9d 100644
--- a/src/DotNetOpenAuth/InfoCard/infocard_300x210.png
+++ b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_300x210.png
Binary files differ
diff --git a/src/DotNetOpenAuth/InfoCard/infocard_34x24.png b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_34x24.png
index b863f64..b863f64 100644
--- a/src/DotNetOpenAuth/InfoCard/infocard_34x24.png
+++ b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_34x24.png
Binary files differ
diff --git a/src/DotNetOpenAuth/InfoCard/infocard_365x256.png b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_365x256.png
index 30092c5..30092c5 100644
--- a/src/DotNetOpenAuth/InfoCard/infocard_365x256.png
+++ b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_365x256.png
Binary files differ
diff --git a/src/DotNetOpenAuth/InfoCard/infocard_41x29.png b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_41x29.png
index d3c71ae..d3c71ae 100644
--- a/src/DotNetOpenAuth/InfoCard/infocard_41x29.png
+++ b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_41x29.png
Binary files differ
diff --git a/src/DotNetOpenAuth/InfoCard/infocard_50x35.png b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_50x35.png
index 62ff78b..62ff78b 100644
--- a/src/DotNetOpenAuth/InfoCard/infocard_50x35.png
+++ b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_50x35.png
Binary files differ
diff --git a/src/DotNetOpenAuth/InfoCard/infocard_60x42.png b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_60x42.png
index 8e920c5..8e920c5 100644
--- a/src/DotNetOpenAuth/InfoCard/infocard_60x42.png
+++ b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_60x42.png
Binary files differ
diff --git a/src/DotNetOpenAuth/InfoCard/infocard_71x50.png b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_71x50.png
index 9e8f7fb..9e8f7fb 100644
--- a/src/DotNetOpenAuth/InfoCard/infocard_71x50.png
+++ b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_71x50.png
Binary files differ
diff --git a/src/DotNetOpenAuth/InfoCard/infocard_81x57.png b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_81x57.png
index 48d62b2..48d62b2 100644
--- a/src/DotNetOpenAuth/InfoCard/infocard_81x57.png
+++ b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_81x57.png
Binary files differ
diff --git a/src/DotNetOpenAuth/InfoCard/infocard_92x64.png b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_92x64.png
index 388e497..388e497 100644
--- a/src/DotNetOpenAuth/InfoCard/infocard_92x64.png
+++ b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/infocard_92x64.png
Binary files differ
diff --git a/src/DotNetOpenAuth.InfoCard.UI/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth.InfoCard.UI/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..63faf9a
--- /dev/null
+++ b/src/DotNetOpenAuth.InfoCard.UI/Properties/AssemblyInfo.cs
@@ -0,0 +1,56 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssemblyInfo.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+// We DON'T put an AssemblyVersionAttribute in here because it is generated in the build.
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Net;
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Security.Permissions;
+using System.Web.UI;
+
+[assembly: TagPrefix("DotNetOpenAuth.InfoCard", "ic")]
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("DotNetOpenAuth InfoCard")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DotNetOpenAuth")]
+[assembly: AssemblyCopyright("Copyright © 2008")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+[assembly: NeutralResourcesLanguage("en-US")]
+[assembly: CLSCompliant(true)]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("7d73990c-47c0-4256-9f20-a893add9e289")]
+
+[assembly: ContractVerification(true)]
+
+#if StrongNameSigned
+// See comment at top of this file. We need this so that strong-naming doesn't
+// keep this assembly from being useful to shared host (medium trust) web sites.
+[assembly: AllowPartiallyTrustedCallers]
+
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
+#else
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
+#endif
diff --git a/src/DotNetOpenAuth.InfoCard/DotNetOpenAuth.InfoCard.csproj b/src/DotNetOpenAuth.InfoCard/DotNetOpenAuth.InfoCard.csproj
new file mode 100644
index 0000000..09371f1
--- /dev/null
+++ b/src/DotNetOpenAuth.InfoCard/DotNetOpenAuth.InfoCard.csproj
@@ -0,0 +1,52 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))\EnlistmentInfo.props" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))' != '' " />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" />
+ <PropertyGroup>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{408D10B8-34BA-4CBD-B7AA-FEB1907ABA4C}</ProjectGuid>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <AssemblyName>DotNetOpenAuth.InfoCard</AssemblyName>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" />
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="InfoCardErrorUtilities.cs" />
+ <Compile Include="InfoCard\InfoCardStrings.Designer.cs">
+ <AutoGen>True</AutoGen>
+ <DesignTime>True</DesignTime>
+ <DependentUpon>InfoCardStrings.resx</DependentUpon>
+ </Compile>
+ <Compile Include="InfoCard\Token\InformationCardException.cs" />
+ <Compile Include="InfoCard\Token\Token.cs" />
+ <Compile Include="InfoCard\Token\TokenUtility.cs" />
+ <Compile Include="InfoCard\Token\TokenDecryptor.cs" />
+ <Compile Include="InfoCard\WellKnownIssuers.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <EmbeddedResource Include="InfoCard\InfoCardStrings.resx">
+ <Generator>ResXFileCodeGenerator</Generator>
+ <LastGenOutput>InfoCardStrings.Designer.cs</LastGenOutput>
+ </EmbeddedResource>
+ </ItemGroup>
+ <ItemGroup>
+ <EmbeddedResource Include="InfoCard\InfoCardStrings.sr.resx" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\DotNetOpenAuth.Core\DotNetOpenAuth.Core.csproj">
+ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project>
+ <Name>DotNetOpenAuth.Core</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
+</Project> \ No newline at end of file
diff --git a/src/DotNetOpenAuth/InfoCard/InfoCardStrings.Designer.cs b/src/DotNetOpenAuth.InfoCard/InfoCard/InfoCardStrings.Designer.cs
index a6d3dcf..a6d3dcf 100644
--- a/src/DotNetOpenAuth/InfoCard/InfoCardStrings.Designer.cs
+++ b/src/DotNetOpenAuth.InfoCard/InfoCard/InfoCardStrings.Designer.cs
diff --git a/src/DotNetOpenAuth/InfoCard/InfoCardStrings.resx b/src/DotNetOpenAuth.InfoCard/InfoCard/InfoCardStrings.resx
index 956b321..956b321 100644
--- a/src/DotNetOpenAuth/InfoCard/InfoCardStrings.resx
+++ b/src/DotNetOpenAuth.InfoCard/InfoCard/InfoCardStrings.resx
diff --git a/src/DotNetOpenAuth/InfoCard/InfoCardStrings.sr.resx b/src/DotNetOpenAuth.InfoCard/InfoCard/InfoCardStrings.sr.resx
index 9df0429..9df0429 100644
--- a/src/DotNetOpenAuth/InfoCard/InfoCardStrings.sr.resx
+++ b/src/DotNetOpenAuth.InfoCard/InfoCard/InfoCardStrings.sr.resx
diff --git a/src/DotNetOpenAuth/InfoCard/Token/InformationCardException.cs b/src/DotNetOpenAuth.InfoCard/InfoCard/Token/InformationCardException.cs
index ff08be8..ff08be8 100644
--- a/src/DotNetOpenAuth/InfoCard/Token/InformationCardException.cs
+++ b/src/DotNetOpenAuth.InfoCard/InfoCard/Token/InformationCardException.cs
diff --git a/src/DotNetOpenAuth/InfoCard/Token/Token.cs b/src/DotNetOpenAuth.InfoCard/InfoCard/Token/Token.cs
index 3b6f573..fc7683d 100644
--- a/src/DotNetOpenAuth/InfoCard/Token/Token.cs
+++ b/src/DotNetOpenAuth.InfoCard/InfoCard/Token/Token.cs
@@ -43,8 +43,8 @@ namespace DotNetOpenAuth.InfoCard {
/// <exception cref="InformationCardException">Thrown for any problem decoding or decrypting the token.</exception>
[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "Not a problem for this type."), SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "False positive")]
private Token(string tokenXml, Uri audience, TokenDecryptor decryptor) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(tokenXml));
- Contract.Requires<ArgumentException>(decryptor != null || !IsEncrypted(tokenXml));
+ Requires.NotNullOrEmpty(tokenXml, "tokenXml");
+ Requires.True(decryptor != null || !IsEncrypted(tokenXml), null);
Contract.Ensures(this.AuthorizationContext != null);
byte[] decryptedBytes;
@@ -117,7 +117,7 @@ namespace DotNetOpenAuth.InfoCard {
/// </summary>
public string SiteSpecificId {
get {
- Contract.Requires<InvalidOperationException>(this.Claims.ContainsKey(ClaimTypes.PPID) && !string.IsNullOrEmpty(this.Claims[ClaimTypes.PPID]));
+ Requires.ValidState(this.Claims.ContainsKey(ClaimTypes.PPID) && !string.IsNullOrEmpty(this.Claims[ClaimTypes.PPID]));
string ppidValue;
ErrorUtilities.VerifyOperation(this.Claims.TryGetValue(ClaimTypes.PPID, out ppidValue) && ppidValue != null, InfoCardStrings.PpidClaimRequired);
return TokenUtility.CalculateSiteSpecificID(ppidValue);
@@ -143,7 +143,7 @@ namespace DotNetOpenAuth.InfoCard {
/// <param name="tokenXml">The token XML.</param>
/// <returns>The deserialized token.</returns>
public static Token Read(string tokenXml) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(tokenXml));
+ Requires.NotNullOrEmpty(tokenXml, "tokenXml");
return Read(tokenXml, (Uri)null);
}
@@ -154,7 +154,7 @@ namespace DotNetOpenAuth.InfoCard {
/// <param name="audience">The URI that this token must have been crafted to be sent to. Use <c>null</c> to accept any intended audience.</param>
/// <returns>The deserialized token.</returns>
public static Token Read(string tokenXml, Uri audience) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(tokenXml));
+ Requires.NotNullOrEmpty(tokenXml, "tokenXml");
return Read(tokenXml, audience, Enumerable.Empty<SecurityToken>());
}
@@ -165,8 +165,8 @@ namespace DotNetOpenAuth.InfoCard {
/// <param name="decryptionTokens">Any X.509 certificates that may be used to decrypt the token, if necessary.</param>
/// <returns>The deserialized token.</returns>
public static Token Read(string tokenXml, IEnumerable<SecurityToken> decryptionTokens) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(tokenXml));
- Contract.Requires<ArgumentNullException>(decryptionTokens != null);
+ Requires.NotNullOrEmpty(tokenXml, "tokenXml");
+ Requires.NotNull(decryptionTokens, "decryptionTokens");
return Read(tokenXml, null, decryptionTokens);
}
@@ -178,8 +178,8 @@ namespace DotNetOpenAuth.InfoCard {
/// <param name="decryptionTokens">Any X.509 certificates that may be used to decrypt the token, if necessary.</param>
/// <returns>The deserialized token.</returns>
public static Token Read(string tokenXml, Uri audience, IEnumerable<SecurityToken> decryptionTokens) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(tokenXml));
- Contract.Requires<ArgumentNullException>(decryptionTokens != null);
+ Requires.NotNullOrEmpty(tokenXml, "tokenXml");
+ Requires.NotNull(decryptionTokens, "decryptionTokens");
Contract.Ensures(Contract.Result<Token>() != null);
TokenDecryptor decryptor = null;
@@ -201,7 +201,7 @@ namespace DotNetOpenAuth.InfoCard {
/// </returns>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "False positive"), Pure]
internal static bool IsEncrypted(string tokenXml) {
- Contract.Requires<ArgumentNullException>(tokenXml != null);
+ Requires.NotNull(tokenXml, "tokenXml");
var stringReader = new StringReader(tokenXml);
XmlReader tokenReader;
@@ -230,7 +230,7 @@ namespace DotNetOpenAuth.InfoCard {
/// <c>true</c> if the specified token XML is encrypted; otherwise, <c>false</c>.
/// </returns>
private static bool IsEncrypted(XmlReader tokenXmlReader) {
- Contract.Requires<ArgumentNullException>(tokenXmlReader != null);
+ Requires.NotNull(tokenXmlReader, "tokenXmlReader");
return tokenXmlReader.IsStartElement(TokenDecryptor.XmlEncryptionStrings.EncryptedData, TokenDecryptor.XmlEncryptionStrings.Namespace);
}
diff --git a/src/DotNetOpenAuth/InfoCard/Token/TokenDecryptor.cs b/src/DotNetOpenAuth.InfoCard/InfoCard/Token/TokenDecryptor.cs
index 9424480..e9199c7 100644
--- a/src/DotNetOpenAuth/InfoCard/Token/TokenDecryptor.cs
+++ b/src/DotNetOpenAuth.InfoCard/InfoCard/Token/TokenDecryptor.cs
@@ -89,7 +89,7 @@ namespace DotNetOpenAuth.InfoCard {
/// <param name="reader">The encrypted token XML reader.</param>
/// <returns>A byte array of the contents of the encrypted token</returns>
internal byte[] DecryptToken(XmlReader reader) {
- Contract.Requires<ArgumentNullException>(reader != null);
+ Requires.NotNull(reader, "reader");
Contract.Ensures(Contract.Result<byte[]>() != null);
byte[] securityTokenData;
@@ -101,7 +101,7 @@ namespace DotNetOpenAuth.InfoCard {
reader.Read(); // get started
// if it's not an encryption method, something is dreadfully wrong.
- ErrorUtilities.VerifyInfoCard(reader.IsStartElement(XmlEncryptionStrings.EncryptionMethod, XmlEncryptionStrings.Namespace), InfoCardStrings.EncryptionAlgorithmNotFound);
+ InfoCardErrorUtilities.VerifyInfoCard(reader.IsStartElement(XmlEncryptionStrings.EncryptionMethod, XmlEncryptionStrings.Namespace), InfoCardStrings.EncryptionAlgorithmNotFound);
// Looks good, let's grab the alg.
isEmptyElement = reader.IsEmptyElement;
diff --git a/src/DotNetOpenAuth/InfoCard/Token/TokenUtility.cs b/src/DotNetOpenAuth.InfoCard/InfoCard/Token/TokenUtility.cs
index 4ac871a..5daffa8 100644
--- a/src/DotNetOpenAuth/InfoCard/Token/TokenUtility.cs
+++ b/src/DotNetOpenAuth.InfoCard/InfoCard/Token/TokenUtility.cs
@@ -35,7 +35,7 @@ namespace DotNetOpenAuth.InfoCard {
/// Gets the maximum amount the token can be out of sync with time.
/// </summary>
internal static TimeSpan MaximumClockSkew {
- get { return DotNetOpenAuth.Configuration.DotNetOpenAuthSection.Configuration.Messaging.MaximumClockSkew; }
+ get { return DotNetOpenAuth.Configuration.DotNetOpenAuthSection.Messaging.MaximumClockSkew; }
}
/// <summary>
@@ -60,8 +60,9 @@ namespace DotNetOpenAuth.InfoCard {
throw new InformationCardException("Unable to read security token");
}
- ////if (null != token.SecurityKeys && token.SecurityKeys.Count > 0)
- //// throw new InformationCardException("Token Security Keys Exist");
+ if (null != token.SecurityKeys && token.SecurityKeys.Count > 0) {
+ throw new InformationCardException("Token Security Keys Exist");
+ }
if (audience == null) {
Logger.InfoCard.Warn("SAML token Audience checking will be skipped.");
@@ -82,7 +83,7 @@ namespace DotNetOpenAuth.InfoCard {
// The token is invalid if any condition is not valid.
// An audience restriction condition is valid if any audience
// matches the Relying Party.
- ErrorUtilities.VerifyInfoCard(match, InfoCardStrings.AudienceMismatch);
+ InfoCardErrorUtilities.VerifyInfoCard(match, InfoCardStrings.AudienceMismatch);
}
}
}
@@ -149,7 +150,7 @@ namespace DotNetOpenAuth.InfoCard {
return null;
}
- return ComputeCombinedId(rsa, "");
+ return ComputeCombinedId(rsa, string.Empty);
}
}
@@ -162,7 +163,7 @@ namespace DotNetOpenAuth.InfoCard {
/// <param name="authzContext">The Authorization Context</param>
/// <returns>A unique ID for this user at this web site.</returns>
internal static string GetUniqueName(AuthorizationContext authzContext) {
- Contract.Requires<ArgumentNullException>(authzContext != null);
+ Requires.NotNull(authzContext, "authzContext");
Claim uniqueIssuerClaim = null;
Claim uniqueUserClaim = null;
@@ -218,7 +219,7 @@ namespace DotNetOpenAuth.InfoCard {
/// <param name="ppid">The personal private identifier.</param>
/// <returns>A string containing the XXX-XXXX-XXX cosmetic value.</returns>
internal static string CalculateSiteSpecificID(string ppid) {
- Contract.Requires<ArgumentNullException>(ppid != null);
+ Requires.NotNull(ppid, "ppid");
Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()));
int callSignChars = 10;
@@ -248,7 +249,7 @@ namespace DotNetOpenAuth.InfoCard {
/// <param name="cs">the claimset which contains the claim</param>
/// <returns>a RSA claim</returns>
private static Claim GetUniqueRsaClaim(ClaimSet cs) {
- Contract.Requires<ArgumentNullException>(cs != null);
+ Requires.NotNull(cs, "cs");
Claim rsa = null;
@@ -270,8 +271,8 @@ namespace DotNetOpenAuth.InfoCard {
/// <param name="claimValue">the claim value to hash with.</param>
/// <returns>A base64 representation of the combined ID.</returns>
private static string ComputeCombinedId(RSA issuerKey, string claimValue) {
- Contract.Requires<ArgumentNullException>(issuerKey != null);
- Contract.Requires<ArgumentNullException>(claimValue != null);
+ Requires.NotNull(issuerKey, "issuerKey");
+ Requires.NotNull(claimValue, "claimValue");
Contract.Ensures(Contract.Result<string>() != null);
int nameLength = Encoding.UTF8.GetByteCount(claimValue);
diff --git a/src/DotNetOpenAuth/InfoCard/WellKnownClaimTypes.cs b/src/DotNetOpenAuth.InfoCard/InfoCard/WellKnownClaimTypes.cs
index 94ebae8..94ebae8 100644
--- a/src/DotNetOpenAuth/InfoCard/WellKnownClaimTypes.cs
+++ b/src/DotNetOpenAuth.InfoCard/InfoCard/WellKnownClaimTypes.cs
diff --git a/src/DotNetOpenAuth/InfoCard/WellKnownIssuers.cs b/src/DotNetOpenAuth.InfoCard/InfoCard/WellKnownIssuers.cs
index 8c63287..8c63287 100644
--- a/src/DotNetOpenAuth/InfoCard/WellKnownIssuers.cs
+++ b/src/DotNetOpenAuth.InfoCard/InfoCard/WellKnownIssuers.cs
diff --git a/src/DotNetOpenAuth.InfoCard/InfoCardErrorUtilities.cs b/src/DotNetOpenAuth.InfoCard/InfoCardErrorUtilities.cs
new file mode 100644
index 0000000..da1c7ff
--- /dev/null
+++ b/src/DotNetOpenAuth.InfoCard/InfoCardErrorUtilities.cs
@@ -0,0 +1,39 @@
+//-----------------------------------------------------------------------
+// <copyright file="InfoCardErrorUtilities.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Globalization;
+ using System.Linq;
+ using System.Text;
+
+ /// <summary>
+ /// Error reporting methods specific to InfoCard validation.
+ /// </summary>
+ internal static class InfoCardErrorUtilities {
+ /// <summary>
+ /// Checks a condition and throws an <see cref="InfoCard.InformationCardException"/>
+ /// if it evaluates to false.
+ /// </summary>
+ /// <param name="condition">The condition to check.</param>
+ /// <param name="errorMessage">The message to include in the exception, if created.</param>
+ /// <param name="args">The formatting arguments.</param>
+ /// <exception cref="InfoCard.InformationCardException">Thrown if <paramref name="condition"/> evaluates to <c>false</c>.</exception>
+ [Pure]
+ internal static void VerifyInfoCard(bool condition, string errorMessage, params object[] args) {
+ Requires.NotNull(args, "args");
+ Contract.Ensures(condition);
+ Contract.EnsuresOnThrow<InfoCard.InformationCardException>(!condition);
+ Contract.Assume(errorMessage != null);
+ if (!condition) {
+ errorMessage = string.Format(CultureInfo.CurrentCulture, errorMessage, args);
+ throw new InfoCard.InformationCardException(errorMessage);
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.InfoCard/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth.InfoCard/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..7260f4b
--- /dev/null
+++ b/src/DotNetOpenAuth.InfoCard/Properties/AssemblyInfo.cs
@@ -0,0 +1,56 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssemblyInfo.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+// We DON'T put an AssemblyVersionAttribute in here because it is generated in the build.
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Net;
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Security.Permissions;
+using System.Web.UI;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("DotNetOpenAuth InfoCard")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DotNetOpenAuth")]
+[assembly: AssemblyCopyright("Copyright © 2008")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+[assembly: NeutralResourcesLanguage("en-US")]
+[assembly: CLSCompliant(true)]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("7d73990c-47c0-4256-9f20-a893add9e289")]
+
+[assembly: ContractVerification(true)]
+
+#if StrongNameSigned
+// See comment at top of this file. We need this so that strong-naming doesn't
+// keep this assembly from being useful to shared host (medium trust) web sites.
+[assembly: AllowPartiallyTrustedCallers]
+
+[assembly: InternalsVisibleTo("DotNetOpenAuth.InfoCard.UI, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
+#else
+[assembly: InternalsVisibleTo("DotNetOpenAuth.InfoCard.UI")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
+#endif
diff --git a/src/DotNetOpenAuth.OAuth.Consumer/DotNetOpenAuth.OAuth.Consumer.csproj b/src/DotNetOpenAuth.OAuth.Consumer/DotNetOpenAuth.OAuth.Consumer.csproj
new file mode 100644
index 0000000..2478187
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth.Consumer/DotNetOpenAuth.OAuth.Consumer.csproj
@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))\EnlistmentInfo.props" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))' != '' " />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" />
+ <PropertyGroup>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{B202E40D-4663-4A2B-ACDA-865F88FF7CAA}</ProjectGuid>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <AssemblyName>DotNetOpenAuth.OAuth.Consumer</AssemblyName>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" />
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="OAuth\ChannelElements\IConsumerTokenManager.cs" />
+ <Compile Include="OAuth\ChannelElements\OAuthConsumerChannel.cs" />
+ <Compile Include="OAuth\ChannelElements\OAuthConsumerMessageFactory.cs" />
+ <Compile Include="OAuth\ChannelElements\RsaSha1ConsumerSigningBindingElement.cs" />
+ <Compile Include="OAuth\ConsumerBase.cs" />
+ <Compile Include="OAuth\DesktopConsumer.cs" />
+ <Compile Include="OAuth\WebConsumer.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs">
+ <SubType>
+ </SubType>
+ </Compile>
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\DotNetOpenAuth.Core\DotNetOpenAuth.Core.csproj">
+ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project>
+ <Name>DotNetOpenAuth.Core</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OAuth\DotNetOpenAuth.OAuth.csproj">
+ <Project>{A288FCC8-6FCF-46DA-A45E-5F9281556361}</Project>
+ <Name>DotNetOpenAuth.OAuth</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OpenId\DotNetOpenAuth.OpenId.csproj">
+ <Project>{3896A32A-E876-4C23-B9B8-78E17D134CD3}</Project>
+ <Name>DotNetOpenAuth.OpenId</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
+</Project> \ No newline at end of file
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/IConsumerTokenManager.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/IConsumerTokenManager.cs
index f16be64..f16be64 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/IConsumerTokenManager.cs
+++ b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/IConsumerTokenManager.cs
diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/OAuthConsumerChannel.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/OAuthConsumerChannel.cs
new file mode 100644
index 0000000..553d6c6
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/OAuthConsumerChannel.cs
@@ -0,0 +1,70 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuthConsumerChannel.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+
+ /// <summary>
+ /// The messaging channel for OAuth 1.0(a) Consumers.
+ /// </summary>
+ internal class OAuthConsumerChannel : OAuthChannel {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="OAuthConsumerChannel"/> class.
+ /// </summary>
+ /// <param name="signingBindingElement">The binding element to use for signing.</param>
+ /// <param name="store">The web application store to use for nonces.</param>
+ /// <param name="tokenManager">The token manager instance to use.</param>
+ /// <param name="securitySettings">The security settings.</param>
+ /// <param name="messageFactory">The message factory.</param>
+ [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Diagnostics.Contracts.__ContractsRuntime.Requires<System.ArgumentNullException>(System.Boolean,System.String,System.String)", Justification = "Code contracts"), SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "securitySettings", Justification = "Code contracts")]
+ internal OAuthConsumerChannel(ITamperProtectionChannelBindingElement signingBindingElement, INonceStore store, IConsumerTokenManager tokenManager, ConsumerSecuritySettings securitySettings, IMessageFactory messageFactory = null)
+ : base(
+ signingBindingElement,
+ store,
+ tokenManager,
+ securitySettings,
+ messageFactory ?? new OAuthConsumerMessageFactory(),
+ InitializeBindingElements(signingBindingElement, store, tokenManager, securitySettings)) {
+ Requires.NotNull(tokenManager, "tokenManager");
+ Requires.NotNull(securitySettings, "securitySettings");
+ Requires.NotNull(signingBindingElement, "signingBindingElement");
+ }
+
+ /// <summary>
+ /// Gets the consumer secret for a given consumer key.
+ /// </summary>
+ /// <param name="consumerKey">The consumer key.</param>
+ /// <returns>The consumer secret.</returns>
+ protected override string GetConsumerSecret(string consumerKey) {
+ var consumerTokenManager = (IConsumerTokenManager)this.TokenManager;
+ ErrorUtilities.VerifyInternal(consumerKey == consumerTokenManager.ConsumerKey, "The token manager consumer key and the consumer key set earlier do not match!");
+ return consumerTokenManager.ConsumerSecret;
+ }
+
+ /// <summary>
+ /// Initializes the binding elements for the OAuth channel.
+ /// </summary>
+ /// <param name="signingBindingElement">The signing binding element.</param>
+ /// <param name="store">The nonce store.</param>
+ /// <param name="tokenManager">The token manager.</param>
+ /// <param name="securitySettings">The security settings.</param>
+ /// <returns>
+ /// An array of binding elements used to initialize the channel.
+ /// </returns>
+ private static new IChannelBindingElement[] InitializeBindingElements(ITamperProtectionChannelBindingElement signingBindingElement, INonceStore store, ITokenManager tokenManager, SecuritySettings securitySettings) {
+ Contract.Requires(securitySettings != null);
+
+ return OAuthChannel.InitializeBindingElements(signingBindingElement, store, tokenManager, securitySettings).ToArray();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthConsumerMessageFactory.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/OAuthConsumerMessageFactory.cs
index 327b923..327b923 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthConsumerMessageFactory.cs
+++ b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/OAuthConsumerMessageFactory.cs
diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/RsaSha1ConsumerSigningBindingElement.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/RsaSha1ConsumerSigningBindingElement.cs
new file mode 100644
index 0000000..7a7998e
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/RsaSha1ConsumerSigningBindingElement.cs
@@ -0,0 +1,74 @@
+//-----------------------------------------------------------------------
+// <copyright file="RsaSha1ConsumerSigningBindingElement.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth.ChannelElements {
+ using System;
+ using System.Diagnostics.Contracts;
+ using System.Security.Cryptography;
+ using System.Security.Cryptography.X509Certificates;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A binding element that signs outgoing messages and verifies the signature on incoming messages.
+ /// </summary>
+ public class RsaSha1ConsumerSigningBindingElement : RsaSha1SigningBindingElement {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RsaSha1ConsumerSigningBindingElement"/> class.
+ /// </summary>
+ /// <param name="signingCertificate">The certificate used to sign outgoing messages.</param>
+ public RsaSha1ConsumerSigningBindingElement(X509Certificate2 signingCertificate) {
+ Requires.NotNull(signingCertificate, "signingCertificate");
+
+ this.SigningCertificate = signingCertificate;
+ }
+
+ /// <summary>
+ /// Gets or sets the certificate used to sign outgoing messages. Used only by Consumers.
+ /// </summary>
+ public X509Certificate2 SigningCertificate { get; set; }
+
+ /// <summary>
+ /// Determines whether the signature on some message is valid.
+ /// </summary>
+ /// <param name="message">The message to check the signature on.</param>
+ /// <returns>
+ /// <c>true</c> if the signature on the message is valid; otherwise, <c>false</c>.
+ /// </returns>
+ protected override bool IsSignatureValid(ITamperResistantOAuthMessage message) {
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Calculates a signature for a given message.
+ /// </summary>
+ /// <param name="message">The message to sign.</param>
+ /// <returns>The signature for the message.</returns>
+ /// <remarks>
+ /// This method signs the message per OAuth 1.0 section 9.3.
+ /// </remarks>
+ protected override string GetSignature(ITamperResistantOAuthMessage message) {
+ ErrorUtilities.VerifyOperation(this.SigningCertificate != null, OAuthStrings.X509CertificateNotProvidedForSigning);
+
+ string signatureBaseString = ConstructSignatureBaseString(message, this.Channel.MessageDescriptions.GetAccessor(message));
+ byte[] data = Encoding.ASCII.GetBytes(signatureBaseString);
+ var provider = (RSACryptoServiceProvider)this.SigningCertificate.PrivateKey;
+ byte[] binarySignature = provider.SignData(data, "SHA1");
+ string base64Signature = Convert.ToBase64String(binarySignature);
+ return base64Signature;
+ }
+
+ /// <summary>
+ /// Creates a new object that is a copy of the current instance.
+ /// </summary>
+ /// <returns>
+ /// A new object that is a copy of this instance.
+ /// </returns>
+ protected override ITamperProtectionChannelBindingElement Clone() {
+ return new RsaSha1ConsumerSigningBindingElement(this.SigningCertificate);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth/ConsumerBase.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ConsumerBase.cs
index ad4e317..0366f0a 100644
--- a/src/DotNetOpenAuth/OAuth/ConsumerBase.cs
+++ b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ConsumerBase.cs
@@ -27,16 +27,16 @@ namespace DotNetOpenAuth.OAuth {
/// <param name="serviceDescription">The endpoints and behavior of the Service Provider.</param>
/// <param name="tokenManager">The host's method of storing and recalling tokens and secrets.</param>
protected ConsumerBase(ServiceProviderDescription serviceDescription, IConsumerTokenManager tokenManager) {
- Contract.Requires<ArgumentNullException>(serviceDescription != null);
- Contract.Requires<ArgumentNullException>(tokenManager != null);
+ Requires.NotNull(serviceDescription, "serviceDescription");
+ Requires.NotNull(tokenManager, "tokenManager");
ITamperProtectionChannelBindingElement signingElement = serviceDescription.CreateTamperProtectionElement();
INonceStore store = new NonceMemoryStore(StandardExpirationBindingElement.MaximumMessageAge);
- this.SecuritySettings = DotNetOpenAuthSection.Configuration.OAuth.Consumer.SecuritySettings.CreateSecuritySettings();
- this.OAuthChannel = new OAuthChannel(signingElement, store, tokenManager, this.SecuritySettings);
+ this.SecuritySettings = OAuthElement.Configuration.Consumer.SecuritySettings.CreateSecuritySettings();
+ this.OAuthChannel = new OAuthConsumerChannel(signingElement, store, tokenManager, this.SecuritySettings);
this.ServiceProvider = serviceDescription;
- Reporting.RecordFeatureAndDependencyUse(this, serviceDescription, tokenManager, null);
+ OAuthReporting.RecordFeatureAndDependencyUse(this, serviceDescription, tokenManager, null);
}
/// <summary>
@@ -111,8 +111,8 @@ namespace DotNetOpenAuth.OAuth {
/// <param name="accessToken">The access token that permits access to the protected resource.</param>
/// <returns>The initialized WebRequest object.</returns>
public HttpWebRequest PrepareAuthorizedRequest(MessageReceivingEndpoint endpoint, string accessToken) {
- Contract.Requires<ArgumentNullException>(endpoint != null);
- Contract.Requires<ArgumentNullException>(!String.IsNullOrEmpty(accessToken));
+ Requires.NotNull(endpoint, "endpoint");
+ Requires.NotNullOrEmpty(accessToken, "accessToken");
return this.PrepareAuthorizedRequest(endpoint, accessToken, EmptyDictionary<string, string>.Instance);
}
@@ -126,9 +126,9 @@ namespace DotNetOpenAuth.OAuth {
/// <param name="extraData">Extra parameters to include in the message. Must not be null, but may be empty.</param>
/// <returns>The initialized WebRequest object.</returns>
public HttpWebRequest PrepareAuthorizedRequest(MessageReceivingEndpoint endpoint, string accessToken, IDictionary<string, string> extraData) {
- Contract.Requires<ArgumentNullException>(endpoint != null);
- Contract.Requires<ArgumentNullException>(!String.IsNullOrEmpty(accessToken));
- Contract.Requires<ArgumentNullException>(extraData != null);
+ Requires.NotNull(endpoint, "endpoint");
+ Requires.NotNullOrEmpty(accessToken, "accessToken");
+ Requires.NotNull(extraData, "extraData");
IDirectedProtocolMessage message = this.CreateAuthorizingMessage(endpoint, accessToken);
foreach (var pair in extraData) {
@@ -147,9 +147,9 @@ namespace DotNetOpenAuth.OAuth {
/// <param name="binaryData">Extra parameters to include in the message. Must not be null, but may be empty.</param>
/// <returns>The initialized WebRequest object.</returns>
public HttpWebRequest PrepareAuthorizedRequest(MessageReceivingEndpoint endpoint, string accessToken, IEnumerable<MultipartPostPart> binaryData) {
- Contract.Requires<ArgumentNullException>(endpoint != null);
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(accessToken));
- Contract.Requires<ArgumentNullException>(binaryData != null);
+ Requires.NotNull(endpoint, "endpoint");
+ Requires.NotNullOrEmpty(accessToken, "accessToken");
+ Requires.NotNull(binaryData, "binaryData");
AccessProtectedResourceRequest message = this.CreateAuthorizingMessage(endpoint, accessToken);
foreach (MultipartPostPart part in binaryData) {
@@ -177,7 +177,7 @@ namespace DotNetOpenAuth.OAuth {
/// </remarks>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Type of parameter forces the method to apply only to specific scenario.")]
public HttpWebRequest PrepareAuthorizedRequest(AccessProtectedResourceRequest message) {
- Contract.Requires<ArgumentNullException>(message != null);
+ Requires.NotNull(message, "message");
return this.OAuthChannel.InitializeRequest(message);
}
@@ -215,8 +215,8 @@ namespace DotNetOpenAuth.OAuth {
/// <param name="accessToken">The access token that permits access to the protected resource.</param>
/// <returns>The initialized WebRequest object.</returns>
protected internal AccessProtectedResourceRequest CreateAuthorizingMessage(MessageReceivingEndpoint endpoint, string accessToken) {
- Contract.Requires<ArgumentNullException>(endpoint != null);
- Contract.Requires<ArgumentNullException>(!String.IsNullOrEmpty(accessToken));
+ Requires.NotNull(endpoint, "endpoint");
+ Requires.NotNullOrEmpty(accessToken, "accessToken");
AccessProtectedResourceRequest message = new AccessProtectedResourceRequest(endpoint, this.ServiceProvider.Version) {
AccessToken = accessToken,
@@ -277,7 +277,7 @@ namespace DotNetOpenAuth.OAuth {
/// The access token assigned by the Service Provider.
/// </returns>
protected AuthorizedTokenResponse ProcessUserAuthorization(string requestToken, string verifier) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(requestToken));
+ Requires.NotNullOrEmpty(requestToken, "requestToken");
Contract.Ensures(Contract.Result<AuthorizedTokenResponse>() != null);
var requestAccess = new AuthorizedTokenRequest(this.ServiceProvider.AccessTokenEndpoint, this.ServiceProvider.Version) {
diff --git a/src/DotNetOpenAuth/OAuth/DesktopConsumer.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/DesktopConsumer.cs
index f9c1a94..f9c1a94 100644
--- a/src/DotNetOpenAuth/OAuth/DesktopConsumer.cs
+++ b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/DesktopConsumer.cs
diff --git a/src/DotNetOpenAuth/OAuth/WebConsumer.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/WebConsumer.cs
index de37b80..e7d7f4f 100644
--- a/src/DotNetOpenAuth/OAuth/WebConsumer.cs
+++ b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/WebConsumer.cs
@@ -79,7 +79,7 @@ namespace DotNetOpenAuth.OAuth {
/// <param name="openIdAuthenticationRequest">The OpenID authentication request.</param>
/// <param name="scope">The scope of access that is requested of the service provider.</param>
public void AttachAuthorizationRequest(IAuthenticationRequest openIdAuthenticationRequest, string scope) {
- Contract.Requires<ArgumentNullException>(openIdAuthenticationRequest != null);
+ Requires.NotNull(openIdAuthenticationRequest, "openIdAuthenticationRequest");
var authorizationRequest = new AuthorizationRequest {
Consumer = this.ConsumerKey,
@@ -101,8 +101,8 @@ namespace DotNetOpenAuth.OAuth {
/// 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);
+ 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);
@@ -140,7 +140,7 @@ namespace DotNetOpenAuth.OAuth {
/// <param name="request">The incoming HTTP request.</param>
/// <returns>The access token, or null if no incoming authorization message was recognized.</returns>
public AuthorizedTokenResponse ProcessUserAuthorization(HttpRequestInfo request) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
UserAuthorizationResponse authorizationMessage;
if (this.Channel.TryReadFromRequest<UserAuthorizationResponse>(request, out authorizationMessage)) {
diff --git a/src/DotNetOpenAuth.OAuth.Consumer/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth.OAuth.Consumer/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..fd29585
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth.Consumer/Properties/AssemblyInfo.cs
@@ -0,0 +1,58 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssemblyInfo.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+// We DON'T put an AssemblyVersionAttribute in here because it is generated in the build.
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Net;
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Security.Permissions;
+using System.Web.UI;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("DotNetOpenAuth OAuth")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DotNetOpenAuth")]
+[assembly: AssemblyCopyright("Copyright © 2008")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+[assembly: NeutralResourcesLanguage("en-US")]
+[assembly: CLSCompliant(true)]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("7d73990c-47c0-4256-9f20-a893add9e289")]
+
+[assembly: ContractVerification(true)]
+
+#if StrongNameSigned
+// See comment at top of this file. We need this so that strong-naming doesn't
+// keep this assembly from being useful to shared host (medium trust) web sites.
+[assembly: AllowPartiallyTrustedCallers]
+
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
+#else
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth.Consumer")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth.ServiceProvider")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
+#endif
diff --git a/src/DotNetOpenAuth.OAuth.Consumer/Properties/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth.OAuth.Consumer/Properties/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..d402b02
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth.Consumer/Properties/Properties/AssemblyInfo.cs
@@ -0,0 +1,58 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssemblyInfo.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+// We DON'T put an AssemblyVersionAttribute in here because it is generated in the build.
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Net;
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Security.Permissions;
+using System.Web.UI;
+
+[assembly: TagPrefix("DotNetOpenAuth.OAuth", "oauth")]
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("DotNetOpenAuth OAuth")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DotNetOpenAuth")]
+[assembly: AssemblyCopyright("Copyright © 2008")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+[assembly: NeutralResourcesLanguage("en-US")]
+[assembly: CLSCompliant(true)]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("7d73990c-47c0-4256-9f20-a893add9e289")]
+
+[assembly: ContractVerification(true)]
+
+#if StrongNameSigned
+// See comment at top of this file. We need this so that strong-naming doesn't
+// keep this assembly from being useful to shared host (medium trust) web sites.
+[assembly: AllowPartiallyTrustedCallers]
+
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
+#else
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
+#endif
diff --git a/src/DotNetOpenAuth.OAuth.ServiceProvider/DotNetOpenAuth.OAuth.ServiceProvider.csproj b/src/DotNetOpenAuth.OAuth.ServiceProvider/DotNetOpenAuth.OAuth.ServiceProvider.csproj
new file mode 100644
index 0000000..4e99b4a
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/DotNetOpenAuth.OAuth.ServiceProvider.csproj
@@ -0,0 +1,57 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))\EnlistmentInfo.props" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))' != '' " />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" />
+ <PropertyGroup>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{FED1923A-6D70-49B5-A37A-FB744FEC1C86}</ProjectGuid>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <AssemblyName>DotNetOpenAuth.OAuth.ServiceProvider</AssemblyName>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" />
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="OAuth\ChannelElements\IConsumerDescription.cs" />
+ <Compile Include="OAuth\ChannelElements\IServiceProviderAccessToken.cs" />
+ <Compile Include="OAuth\ChannelElements\IServiceProviderRequestToken.cs" />
+ <Compile Include="OAuth\ChannelElements\IServiceProviderTokenManager.cs" />
+ <Compile Include="OAuth\ChannelElements\ITokenGenerator.cs" />
+ <Compile Include="OAuth\ChannelElements\OAuthServiceProviderChannel.cs" />
+ <Compile Include="OAuth\ChannelElements\OAuthServiceProviderMessageFactory.cs" />
+ <Compile Include="OAuth\ChannelElements\OAuthIdentity.cs" />
+ <Compile Include="OAuth\ChannelElements\OAuthPrincipal.cs" />
+ <Compile Include="OAuth\ChannelElements\RsaSha1ServiceProviderSigningBindingElement.cs" />
+ <Compile Include="OAuth\ChannelElements\StandardTokenGenerator.cs" />
+ <Compile Include="OAuth\ChannelElements\TokenHandlingBindingElement.cs" />
+ <Compile Include="OAuth\ServiceProvider.cs" />
+ <Compile Include="OAuth\VerificationCodeFormat.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs">
+ <SubType>
+ </SubType>
+ </Compile>
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\DotNetOpenAuth.Core\DotNetOpenAuth.Core.csproj">
+ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project>
+ <Name>DotNetOpenAuth.Core</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OAuth\DotNetOpenAuth.OAuth.csproj">
+ <Project>{A288FCC8-6FCF-46DA-A45E-5F9281556361}</Project>
+ <Name>DotNetOpenAuth.OAuth</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OpenId\DotNetOpenAuth.OpenId.csproj">
+ <Project>{3896A32A-E876-4C23-B9B8-78E17D134CD3}</Project>
+ <Name>DotNetOpenAuth.OpenId</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
+</Project> \ No newline at end of file
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/IConsumerDescription.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/IConsumerDescription.cs
index db505d5..db505d5 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/IConsumerDescription.cs
+++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/IConsumerDescription.cs
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/IServiceProviderAccessToken.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/IServiceProviderAccessToken.cs
index 35ba52d..35ba52d 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/IServiceProviderAccessToken.cs
+++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/IServiceProviderAccessToken.cs
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/IServiceProviderRequestToken.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/IServiceProviderRequestToken.cs
index 6dfa416..6dfa416 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/IServiceProviderRequestToken.cs
+++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/IServiceProviderRequestToken.cs
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/IServiceProviderTokenManager.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/IServiceProviderTokenManager.cs
index 7df67ce..13320b3 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/IServiceProviderTokenManager.cs
+++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/IServiceProviderTokenManager.cs
@@ -102,7 +102,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// </returns>
/// <exception cref="KeyNotFoundException">Thrown if the consumer key cannot be found.</exception>
IConsumerDescription IServiceProviderTokenManager.GetConsumer(string consumerKey) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(consumerKey));
+ Requires.NotNullOrEmpty(consumerKey, "consumerKey");
Contract.Ensures(Contract.Result<IConsumerDescription>() != null);
throw new NotImplementedException();
}
@@ -118,7 +118,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// been authorized, has expired or does not exist.
/// </returns>
bool IServiceProviderTokenManager.IsRequestTokenAuthorized(string requestToken) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(requestToken));
+ Requires.NotNullOrEmpty(requestToken, "requestToken");
throw new NotImplementedException();
}
@@ -135,7 +135,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// log and throw the appropriate error.
/// </remarks>
IServiceProviderRequestToken IServiceProviderTokenManager.GetRequestToken(string token) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(token));
+ Requires.NotNullOrEmpty(token, "token");
Contract.Ensures(Contract.Result<IServiceProviderRequestToken>() != null);
throw new NotImplementedException();
}
@@ -153,7 +153,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// log and throw the appropriate error.
/// </remarks>
IServiceProviderAccessToken IServiceProviderTokenManager.GetAccessToken(string token) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(token));
+ Requires.NotNullOrEmpty(token, "token");
Contract.Ensures(Contract.Result<IServiceProviderAccessToken>() != null);
throw new NotImplementedException();
}
@@ -171,7 +171,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// will automatically be saved without any extra handling).
/// </remarks>
void IServiceProviderTokenManager.UpdateToken(IServiceProviderRequestToken token) {
- Contract.Requires<ArgumentNullException>(token != null);
+ Requires.NotNull(token, "token");
throw new NotImplementedException();
}
@@ -226,8 +226,8 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// <see cref="System.Web.HttpContext.User">HttpContext.Current.User</see> may be
/// useful in an ASP.NET web application within the implementation of this method.
/// Alternatively you may store the access token here without associating with a user account,
- /// and wait until <see cref="WebConsumer.ProcessUserAuthorization()"/> or
- /// <see cref="DesktopConsumer.ProcessUserAuthorization(string, string)"/> return the access
+ /// and wait until WebConsumer.ProcessUserAuthorization or
+ /// DesktopConsumer.ProcessUserAuthorization return the access
/// token to associate the access token with a user account at that point.
/// </para>
/// </remarks>
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/ITokenGenerator.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/ITokenGenerator.cs
index ce22479..ce22479 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/ITokenGenerator.cs
+++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/ITokenGenerator.cs
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthIdentity.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthIdentity.cs
index 65bde20..6865f79 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthIdentity.cs
+++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthIdentity.cs
@@ -24,7 +24,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// </summary>
/// <param name="username">The username.</param>
internal OAuthIdentity(string username) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(username));
+ Requires.NotNullOrEmpty(username, "username");
this.Name = username;
}
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthPrincipal.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthPrincipal.cs
index 025ef09..f4d167d 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthPrincipal.cs
+++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthPrincipal.cs
@@ -7,6 +7,7 @@
namespace DotNetOpenAuth.OAuth.ChannelElements {
using System;
using System.Collections.Generic;
+ using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
@@ -28,10 +29,19 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// <summary>
/// Initializes a new instance of the <see cref="OAuthPrincipal"/> class.
/// </summary>
+ /// <param name="userName">The username.</param>
+ /// <param name="roles">The roles this user belongs to.</param>
+ public OAuthPrincipal(string userName, string[] roles)
+ : this(new OAuthIdentity(userName), roles) {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="OAuthPrincipal"/> class.
+ /// </summary>
/// <param name="token">The access token.</param>
internal OAuthPrincipal(IServiceProviderAccessToken token)
: this(token.Username, token.Roles) {
- Contract.Requires<ArgumentNullException>(token != null);
+ Requires.NotNull(token, "token");
this.AccessToken = token.Token;
}
@@ -47,20 +57,19 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
}
/// <summary>
- /// Initializes a new instance of the <see cref="OAuthPrincipal"/> class.
- /// </summary>
- /// <param name="username">The username.</param>
- /// <param name="roles">The roles this user belongs to.</param>
- internal OAuthPrincipal(string username, string[] roles)
- : this(new OAuthIdentity(username), roles) {
- }
-
- /// <summary>
/// Gets the access token used to create this principal.
/// </summary>
/// <value>A non-empty string.</value>
public string AccessToken { get; private set; }
+ /// <summary>
+ /// Gets the roles that this principal has as a ReadOnlyCollection.
+ /// </summary>
+ public ReadOnlyCollection<string> Roles
+ {
+ get { return new ReadOnlyCollection<string>(this.roles.ToList()); }
+ }
+
#region IPrincipal Members
/// <summary>
@@ -87,5 +96,14 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
}
#endregion
+
+ /// <summary>
+ /// Creates a new instance of GenericPrincipal based on this OAuthPrincipal.
+ /// </summary>
+ /// <returns>A new instance of GenericPrincipal with a GenericIdentity, having the same username and roles as this OAuthPrincipal and OAuthIdentity</returns>
+ public GenericPrincipal CreateGenericPrincipal()
+ {
+ return new GenericPrincipal(new GenericIdentity(this.Identity.Name), this.roles.ToArray());
+ }
}
}
diff --git a/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthServiceProviderChannel.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthServiceProviderChannel.cs
new file mode 100644
index 0000000..43e7902
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthServiceProviderChannel.cs
@@ -0,0 +1,74 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuthServiceProviderChannel.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+
+ /// <summary>
+ /// The messaging channel for OAuth 1.0(a) Service Providers.
+ /// </summary>
+ internal class OAuthServiceProviderChannel : OAuthChannel {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="OAuthServiceProviderChannel"/> class.
+ /// </summary>
+ /// <param name="signingBindingElement">The binding element to use for signing.</param>
+ /// <param name="store">The web application store to use for nonces.</param>
+ /// <param name="tokenManager">The token manager instance to use.</param>
+ /// <param name="securitySettings">The security settings.</param>
+ /// <param name="messageTypeProvider">The message type provider.</param>
+ [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Diagnostics.Contracts.__ContractsRuntime.Requires<System.ArgumentNullException>(System.Boolean,System.String,System.String)", Justification = "Code contracts"), SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "securitySettings", Justification = "Code contracts")]
+ internal OAuthServiceProviderChannel(ITamperProtectionChannelBindingElement signingBindingElement, INonceStore store, IServiceProviderTokenManager tokenManager, ServiceProviderSecuritySettings securitySettings, IMessageFactory messageTypeProvider = null)
+ : base(
+ signingBindingElement,
+ store,
+ tokenManager,
+ securitySettings,
+ messageTypeProvider ?? new OAuthServiceProviderMessageFactory(tokenManager),
+ InitializeBindingElements(signingBindingElement, store, tokenManager, securitySettings)) {
+ Requires.NotNull(tokenManager, "tokenManager");
+ Requires.NotNull(securitySettings, "securitySettings");
+ Requires.NotNull(signingBindingElement, "signingBindingElement");
+ }
+
+ /// <summary>
+ /// Gets the consumer secret for a given consumer key.
+ /// </summary>
+ /// <param name="consumerKey">The consumer key.</param>
+ /// <returns>The consumer secret.</returns>
+ protected override string GetConsumerSecret(string consumerKey) {
+ return ((IServiceProviderTokenManager)this.TokenManager).GetConsumer(consumerKey).Secret;
+ }
+
+ /// <summary>
+ /// Initializes the binding elements for the OAuth channel.
+ /// </summary>
+ /// <param name="signingBindingElement">The signing binding element.</param>
+ /// <param name="store">The nonce store.</param>
+ /// <param name="tokenManager">The token manager.</param>
+ /// <param name="securitySettings">The security settings.</param>
+ /// <returns>
+ /// An array of binding elements used to initialize the channel.
+ /// </returns>
+ private static new IChannelBindingElement[] InitializeBindingElements(ITamperProtectionChannelBindingElement signingBindingElement, INonceStore store, ITokenManager tokenManager, SecuritySettings securitySettings) {
+ Contract.Requires(securitySettings != null);
+
+ var bindingElements = OAuthChannel.InitializeBindingElements(signingBindingElement, store, tokenManager, securitySettings);
+
+ var spTokenManager = tokenManager as IServiceProviderTokenManager;
+ var serviceProviderSecuritySettings = securitySettings as ServiceProviderSecuritySettings;
+ bindingElements.Insert(0, new TokenHandlingBindingElement(spTokenManager, serviceProviderSecuritySettings));
+
+ return bindingElements.ToArray();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthServiceProviderMessageFactory.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthServiceProviderMessageFactory.cs
index 5b3c918..565756b 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthServiceProviderMessageFactory.cs
+++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthServiceProviderMessageFactory.cs
@@ -26,7 +26,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// </summary>
/// <param name="tokenManager">The token manager instance to use.</param>
public OAuthServiceProviderMessageFactory(IServiceProviderTokenManager tokenManager) {
- Contract.Requires<ArgumentNullException>(tokenManager != null);
+ Requires.NotNull(tokenManager, "tokenManager");
this.tokenManager = tokenManager;
}
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/RsaSha1SigningBindingElement.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/RsaSha1ServiceProviderSigningBindingElement.cs
index f7b8370..06a005b 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/RsaSha1SigningBindingElement.cs
+++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/RsaSha1ServiceProviderSigningBindingElement.cs
@@ -1,5 +1,5 @@
//-----------------------------------------------------------------------
-// <copyright file="RsaSha1SigningBindingElement.cs" company="Andrew Arnott">
+// <copyright file="RsaSha1ServiceProviderSigningBindingElement.cs" company="Andrew Arnott">
// Copyright (c) Andrew Arnott. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
@@ -15,66 +15,23 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// <summary>
/// A binding element that signs outgoing messages and verifies the signature on incoming messages.
/// </summary>
- public class RsaSha1SigningBindingElement : SigningBindingElementBase {
- /// <summary>
- /// The name of the hash algorithm to use.
- /// </summary>
- private const string HashAlgorithmName = "RSA-SHA1";
-
+ public class RsaSha1ServiceProviderSigningBindingElement : RsaSha1SigningBindingElement {
/// <summary>
/// The token manager for the service provider.
/// </summary>
private IServiceProviderTokenManager tokenManager;
/// <summary>
- /// Initializes a new instance of the <see cref="RsaSha1SigningBindingElement"/> class
- /// for use by Consumers.
- /// </summary>
- /// <param name="signingCertificate">The certificate used to sign outgoing messages.</param>
- public RsaSha1SigningBindingElement(X509Certificate2 signingCertificate)
- : base(HashAlgorithmName) {
- Contract.Requires<ArgumentNullException>(signingCertificate != null);
-
- this.SigningCertificate = signingCertificate;
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="RsaSha1SigningBindingElement"/> class
- /// for use by Service Providers.
+ /// Initializes a new instance of the <see cref="RsaSha1ServiceProviderSigningBindingElement"/> class.
/// </summary>
/// <param name="tokenManager">The token manager.</param>
- public RsaSha1SigningBindingElement(IServiceProviderTokenManager tokenManager)
- : base(HashAlgorithmName) {
- Contract.Requires<ArgumentNullException>(tokenManager != null);
+ public RsaSha1ServiceProviderSigningBindingElement(IServiceProviderTokenManager tokenManager) {
+ Requires.NotNull(tokenManager, "tokenManager");
this.tokenManager = tokenManager;
}
/// <summary>
- /// Gets or sets the certificate used to sign outgoing messages. Used only by Consumers.
- /// </summary>
- public X509Certificate2 SigningCertificate { get; set; }
-
- /// <summary>
- /// Calculates a signature for a given message.
- /// </summary>
- /// <param name="message">The message to sign.</param>
- /// <returns>The signature for the message.</returns>
- /// <remarks>
- /// This method signs the message per OAuth 1.0 section 9.3.
- /// </remarks>
- protected override string GetSignature(ITamperResistantOAuthMessage message) {
- ErrorUtilities.VerifyOperation(this.SigningCertificate != null, OAuthStrings.X509CertificateNotProvidedForSigning);
-
- string signatureBaseString = ConstructSignatureBaseString(message, this.Channel.MessageDescriptions.GetAccessor(message));
- byte[] data = Encoding.ASCII.GetBytes(signatureBaseString);
- var provider = (RSACryptoServiceProvider)this.SigningCertificate.PrivateKey;
- byte[] binarySignature = provider.SignData(data, "SHA1");
- string base64Signature = Convert.ToBase64String(binarySignature);
- return base64Signature;
- }
-
- /// <summary>
/// Determines whether the signature on some message is valid.
/// </summary>
/// <param name="message">The message to check the signature on.</param>
@@ -101,15 +58,24 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
}
/// <summary>
+ /// Calculates a signature for a given message.
+ /// </summary>
+ /// <param name="message">The message to sign.</param>
+ /// <returns>
+ /// The signature for the message.
+ /// </returns>
+ protected override string GetSignature(ITamperResistantOAuthMessage message) {
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
/// Clones this instance.
/// </summary>
- /// <returns>A new instance of the binding element.</returns>
+ /// <returns>
+ /// A new instance of the binding element.
+ /// </returns>
protected override ITamperProtectionChannelBindingElement Clone() {
- if (this.tokenManager != null) {
- return new RsaSha1SigningBindingElement(this.tokenManager);
- } else {
- return new RsaSha1SigningBindingElement(this.SigningCertificate);
- }
+ return new RsaSha1ServiceProviderSigningBindingElement(this.tokenManager);
}
}
}
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/StandardTokenGenerator.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/StandardTokenGenerator.cs
index d18f5fe..d18f5fe 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/StandardTokenGenerator.cs
+++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/StandardTokenGenerator.cs
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/TokenHandlingBindingElement.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/TokenHandlingBindingElement.cs
index bfebd8b..596336a 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/TokenHandlingBindingElement.cs
+++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/TokenHandlingBindingElement.cs
@@ -37,8 +37,8 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// <param name="securitySettings">The security settings.</param>
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Diagnostics.Contracts.__ContractsRuntime.Requires<System.ArgumentNullException>(System.Boolean,System.String,System.String)", Justification = "Code contract"), SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "securitySettings", Justification = "Code contracts")]
internal TokenHandlingBindingElement(IServiceProviderTokenManager tokenManager, ServiceProviderSecuritySettings securitySettings) {
- Contract.Requires<ArgumentNullException>(tokenManager != null);
- Contract.Requires<ArgumentNullException>(securitySettings != null, "securitySettings");
+ Requires.NotNull(tokenManager, "tokenManager");
+ Requires.NotNull(securitySettings, "securitySettings");
this.tokenManager = tokenManager;
this.securitySettings = securitySettings;
@@ -153,7 +153,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// </summary>
/// <param name="message">The incoming message carrying the access token.</param>
private void VerifyThrowTokenNotExpired(AccessProtectedResourceRequest message) {
- Contract.Requires<ArgumentNullException>(message != null);
+ Requires.NotNull(message, "message");
try {
IServiceProviderAccessToken token = this.tokenManager.GetAccessToken(message.AccessToken);
diff --git a/src/DotNetOpenAuth/OAuth/ServiceProvider.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ServiceProvider.cs
index ec9206e..719e84e 100644
--- a/src/DotNetOpenAuth/OAuth/ServiceProvider.cs
+++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ServiceProvider.cs
@@ -68,10 +68,10 @@ namespace DotNetOpenAuth.OAuth {
/// <param name="tokenManager">The host's method of storing and recalling tokens and secrets.</param>
/// <param name="messageTypeProvider">An object that can figure out what type of message is being received for deserialization.</param>
public ServiceProvider(ServiceProviderDescription serviceDescription, IServiceProviderTokenManager tokenManager, OAuthServiceProviderMessageFactory messageTypeProvider)
- : this(serviceDescription, tokenManager, DotNetOpenAuthSection.Configuration.OAuth.ServiceProvider.ApplicationStore.CreateInstance(HttpApplicationStore), messageTypeProvider) {
- Contract.Requires<ArgumentNullException>(serviceDescription != null);
- Contract.Requires<ArgumentNullException>(tokenManager != null);
- Contract.Requires<ArgumentNullException>(messageTypeProvider != null);
+ : this(serviceDescription, tokenManager, OAuthElement.Configuration.ServiceProvider.ApplicationStore.CreateInstance(HttpApplicationStore), messageTypeProvider) {
+ Requires.NotNull(serviceDescription, "serviceDescription");
+ Requires.NotNull(tokenManager, "tokenManager");
+ Requires.NotNull(messageTypeProvider, "messageTypeProvider");
}
/// <summary>
@@ -92,18 +92,18 @@ namespace DotNetOpenAuth.OAuth {
/// <param name="nonceStore">The nonce store.</param>
/// <param name="messageTypeProvider">An object that can figure out what type of message is being received for deserialization.</param>
public ServiceProvider(ServiceProviderDescription serviceDescription, IServiceProviderTokenManager tokenManager, INonceStore nonceStore, OAuthServiceProviderMessageFactory messageTypeProvider) {
- Contract.Requires<ArgumentNullException>(serviceDescription != null);
- Contract.Requires<ArgumentNullException>(tokenManager != null);
- Contract.Requires<ArgumentNullException>(nonceStore != null);
- Contract.Requires<ArgumentNullException>(messageTypeProvider != null);
+ Requires.NotNull(serviceDescription, "serviceDescription");
+ Requires.NotNull(tokenManager, "tokenManager");
+ Requires.NotNull(nonceStore, "nonceStore");
+ Requires.NotNull(messageTypeProvider, "messageTypeProvider");
var signingElement = serviceDescription.CreateTamperProtectionElement();
this.ServiceDescription = serviceDescription;
- this.SecuritySettings = DotNetOpenAuthSection.Configuration.OAuth.ServiceProvider.SecuritySettings.CreateSecuritySettings();
- this.OAuthChannel = new OAuthChannel(signingElement, nonceStore, tokenManager, this.SecuritySettings, messageTypeProvider);
+ this.SecuritySettings = OAuthElement.Configuration.ServiceProvider.SecuritySettings.CreateSecuritySettings();
+ this.OAuthChannel = new OAuthServiceProviderChannel(signingElement, nonceStore, tokenManager, this.SecuritySettings, messageTypeProvider);
this.TokenGenerator = new StandardTokenGenerator();
- Reporting.RecordFeatureAndDependencyUse(this, serviceDescription, tokenManager, nonceStore);
+ OAuthReporting.RecordFeatureAndDependencyUse(this, serviceDescription, tokenManager, nonceStore);
}
/// <summary>
@@ -171,7 +171,7 @@ namespace DotNetOpenAuth.OAuth {
}
set {
- Contract.Requires<ArgumentNullException>(value != null);
+ Requires.NotNull(value, "value");
this.channel = value;
}
}
@@ -186,7 +186,7 @@ namespace DotNetOpenAuth.OAuth {
/// length of the final string.</param>
/// <returns>The verification code.</returns>
public static string CreateVerificationCode(VerificationCodeFormat format, int length) {
- Contract.Requires<ArgumentOutOfRangeException>(length >= 0);
+ Requires.InRange(length >= 0, "length");
switch (format) {
case VerificationCodeFormat.IncludedInCallback:
@@ -257,7 +257,7 @@ namespace DotNetOpenAuth.OAuth {
/// <param name="request">The token request message the Consumer sent that the Service Provider is now responding to.</param>
/// <returns>The response message to send using the <see cref="Channel"/>, after optionally adding extra data to it.</returns>
public UnauthorizedTokenResponse PrepareUnauthorizedTokenMessage(UnauthorizedTokenRequest request) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
string token = this.TokenGenerator.GenerateRequestToken(request.ConsumerKey);
string secret = this.TokenGenerator.GenerateSecret();
@@ -307,8 +307,8 @@ namespace DotNetOpenAuth.OAuth {
/// security measures that are required are taken.</para>
/// </remarks>
public AuthorizationRequest ReadAuthorizationRequest(IHostProcessedRequest openIdRequest) {
- Contract.Requires<ArgumentNullException>(openIdRequest != null);
- Contract.Requires<InvalidOperationException>(this.TokenManager is ICombinedOpenIdProviderTokenManager);
+ Requires.NotNull(openIdRequest, "openIdRequest");
+ Requires.ValidState(this.TokenManager is ICombinedOpenIdProviderTokenManager);
var openidTokenManager = this.TokenManager as ICombinedOpenIdProviderTokenManager;
ErrorUtilities.VerifyOperation(openidTokenManager != null, OAuthStrings.OpenIdOAuthExtensionRequiresSpecialTokenManagerInterface, typeof(IOpenIdOAuthTokenManager).FullName);
@@ -328,7 +328,7 @@ namespace DotNetOpenAuth.OAuth {
return authzRequest;
}
- /// <summary>
+ /// <summary>
/// Attaches the authorization response to an OpenID authentication response.
/// </summary>
/// <param name="openIdAuthenticationRequest">The OpenID authentication request.</param>
@@ -337,9 +337,9 @@ namespace DotNetOpenAuth.OAuth {
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "We want to take IAuthenticationRequest because that's the only supported use case.")]
[Obsolete("Call the overload that doesn't take a consumerKey instead.")]
public void AttachAuthorizationResponse(IHostProcessedRequest openIdAuthenticationRequest, string consumerKey, string scope) {
- Contract.Requires<ArgumentNullException>(openIdAuthenticationRequest != null);
- Contract.Requires<ArgumentException>((consumerKey == null) == (scope == null));
- Contract.Requires<InvalidOperationException>(this.TokenManager is ICombinedOpenIdProviderTokenManager);
+ Requires.NotNull(openIdAuthenticationRequest, "openIdAuthenticationRequest");
+ Requires.True((consumerKey == null) == (scope == null), null);
+ Requires.ValidState(this.TokenManager is ICombinedOpenIdProviderTokenManager);
var openidTokenManager = (ICombinedOpenIdProviderTokenManager)this.TokenManager;
ErrorUtilities.VerifyArgument(consumerKey == null || consumerKey == openidTokenManager.GetConsumerKey(openIdAuthenticationRequest.Realm), OAuthStrings.OpenIdOAuthRealmConsumerKeyDoNotMatch);
@@ -353,8 +353,8 @@ namespace DotNetOpenAuth.OAuth {
/// <param name="scope">The approved access scope. Use <c>null</c> to indicate no access was granted. The empty string will be interpreted as some default level of access is granted.</param>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "We want to take IAuthenticationRequest because that's the only supported use case.")]
public void AttachAuthorizationResponse(IHostProcessedRequest openIdAuthenticationRequest, string scope) {
- Contract.Requires<ArgumentNullException>(openIdAuthenticationRequest != null);
- Contract.Requires<InvalidOperationException>(this.TokenManager is ICombinedOpenIdProviderTokenManager);
+ Requires.NotNull(openIdAuthenticationRequest, "openIdAuthenticationRequest");
+ Requires.ValidState(this.TokenManager is ICombinedOpenIdProviderTokenManager);
var openidTokenManager = this.TokenManager as ICombinedOpenIdProviderTokenManager;
IOpenIdMessageExtension response;
@@ -385,7 +385,7 @@ namespace DotNetOpenAuth.OAuth {
/// </returns>
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Consistent user experience with instance.")]
public UserAuthorizationResponse PrepareAuthorizationResponse(UserAuthorizationRequest request) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
// It is very important for us to ignore the oauth_callback argument in the
// UserAuthorizationRequest if the Consumer is a 1.0a consumer or else we
@@ -422,8 +422,8 @@ namespace DotNetOpenAuth.OAuth {
/// </returns>
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Consistent user experience with instance.")]
public UserAuthorizationResponse PrepareAuthorizationResponse(UserAuthorizationRequest request, Uri callback) {
- Contract.Requires<ArgumentNullException>(request != null);
- Contract.Requires<ArgumentNullException>(callback != null);
+ Requires.NotNull(request, "request");
+ Requires.NotNull(callback, "callback");
var authorization = new UserAuthorizationResponse(callback, request.Version) {
RequestToken = request.RequestToken,
@@ -466,7 +466,7 @@ namespace DotNetOpenAuth.OAuth {
/// <param name="request">The Consumer's message requesting an access token.</param>
/// <returns>The HTTP response to actually send to the Consumer.</returns>
public AuthorizedTokenResponse PrepareAccessTokenMessage(AuthorizedTokenRequest request) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
ErrorUtilities.VerifyProtocol(this.TokenManager.IsRequestTokenAuthorized(request.RequestToken), OAuthStrings.AccessTokenNotAuthorized, request.RequestToken);
@@ -523,7 +523,7 @@ namespace DotNetOpenAuth.OAuth {
/// </remarks>
/// <exception cref="ProtocolException">Thrown if an unexpected message is attached to the request.</exception>
public AccessProtectedResourceRequest ReadProtectedResourceAuthorization(HttpRequestInfo request) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
AccessProtectedResourceRequest accessMessage;
if (this.Channel.TryReadFromRequest<AccessProtectedResourceRequest>(request, out accessMessage)) {
@@ -545,7 +545,7 @@ namespace DotNetOpenAuth.OAuth {
/// <param name="request">The request.</param>
/// <returns>The <see cref="IPrincipal"/> instance that can be used for access control of resources.</returns>
public OAuthPrincipal CreatePrincipal(AccessProtectedResourceRequest request) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
IServiceProviderAccessToken accessToken = this.TokenManager.GetAccessToken(request.AccessToken);
return new OAuthPrincipal(accessToken);
diff --git a/src/DotNetOpenAuth/OAuth/VerificationCodeFormat.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/VerificationCodeFormat.cs
index a6560d8..a6560d8 100644
--- a/src/DotNetOpenAuth/OAuth/VerificationCodeFormat.cs
+++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/VerificationCodeFormat.cs
diff --git a/src/DotNetOpenAuth.OAuth.ServiceProvider/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..d038290
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/Properties/AssemblyInfo.cs
@@ -0,0 +1,56 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssemblyInfo.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+// We DON'T put an AssemblyVersionAttribute in here because it is generated in the build.
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Net;
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Security.Permissions;
+using System.Web.UI;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("DotNetOpenAuth OAuth")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DotNetOpenAuth")]
+[assembly: AssemblyCopyright("Copyright © 2008")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+[assembly: NeutralResourcesLanguage("en-US")]
+[assembly: CLSCompliant(true)]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("7d73990c-47c0-4256-9f20-a893add9e289")]
+
+[assembly: ContractVerification(true)]
+
+#if StrongNameSigned
+// See comment at top of this file. We need this so that strong-naming doesn't
+// keep this assembly from being useful to shared host (medium trust) web sites.
+[assembly: AllowPartiallyTrustedCallers]
+
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
+#else
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
+#endif
diff --git a/src/DotNetOpenAuth/Configuration/OAuthConsumerElement.cs b/src/DotNetOpenAuth.OAuth/Configuration/OAuthConsumerElement.cs
index b15c3e3..b15c3e3 100644
--- a/src/DotNetOpenAuth/Configuration/OAuthConsumerElement.cs
+++ b/src/DotNetOpenAuth.OAuth/Configuration/OAuthConsumerElement.cs
diff --git a/src/DotNetOpenAuth/Configuration/OAuthConsumerSecuritySettingsElement.cs b/src/DotNetOpenAuth.OAuth/Configuration/OAuthConsumerSecuritySettingsElement.cs
index 38a183a..38a183a 100644
--- a/src/DotNetOpenAuth/Configuration/OAuthConsumerSecuritySettingsElement.cs
+++ b/src/DotNetOpenAuth.OAuth/Configuration/OAuthConsumerSecuritySettingsElement.cs
diff --git a/src/DotNetOpenAuth/Configuration/OAuthElement.cs b/src/DotNetOpenAuth.OAuth/Configuration/OAuthElement.cs
index 282bdba..59c5851 100644
--- a/src/DotNetOpenAuth/Configuration/OAuthElement.cs
+++ b/src/DotNetOpenAuth.OAuth/Configuration/OAuthElement.cs
@@ -6,11 +6,17 @@
namespace DotNetOpenAuth.Configuration {
using System.Configuration;
+ using System.Diagnostics.Contracts;
/// <summary>
/// Represents the &lt;oauth&gt; element in the host's .config file.
/// </summary>
- internal class OAuthElement : ConfigurationElement {
+ internal class OAuthElement : ConfigurationSection {
+ /// <summary>
+ /// The name of the oauth section.
+ /// </summary>
+ private const string SectionName = DotNetOpenAuthSection.SectionName + "/oauth";
+
/// <summary>
/// The name of the &lt;consumer&gt; sub-element.
/// </summary>
@@ -28,6 +34,16 @@ namespace DotNetOpenAuth.Configuration {
}
/// <summary>
+ /// Gets the configuration section from the .config file.
+ /// </summary>
+ public static OAuthElement Configuration {
+ get {
+ Contract.Ensures(Contract.Result<OAuthElement>() != null);
+ return (OAuthElement)ConfigurationManager.GetSection(SectionName) ?? new OAuthElement();
+ }
+ }
+
+ /// <summary>
/// Gets or sets the configuration specific for Consumers.
/// </summary>
[ConfigurationProperty(ConsumerElementName)]
diff --git a/src/DotNetOpenAuth/Configuration/OAuthServiceProviderElement.cs b/src/DotNetOpenAuth.OAuth/Configuration/OAuthServiceProviderElement.cs
index 8e910a0..8e910a0 100644
--- a/src/DotNetOpenAuth/Configuration/OAuthServiceProviderElement.cs
+++ b/src/DotNetOpenAuth.OAuth/Configuration/OAuthServiceProviderElement.cs
diff --git a/src/DotNetOpenAuth/Configuration/OAuthServiceProviderSecuritySettingsElement.cs b/src/DotNetOpenAuth.OAuth/Configuration/OAuthServiceProviderSecuritySettingsElement.cs
index 723b607..723b607 100644
--- a/src/DotNetOpenAuth/Configuration/OAuthServiceProviderSecuritySettingsElement.cs
+++ b/src/DotNetOpenAuth.OAuth/Configuration/OAuthServiceProviderSecuritySettingsElement.cs
diff --git a/src/DotNetOpenAuth.OAuth/DotNetOpenAuth.OAuth.csproj b/src/DotNetOpenAuth.OAuth/DotNetOpenAuth.OAuth.csproj
new file mode 100644
index 0000000..20d6643
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth/DotNetOpenAuth.OAuth.csproj
@@ -0,0 +1,94 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))\EnlistmentInfo.props" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))' != '' " />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" />
+ <PropertyGroup>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{A288FCC8-6FCF-46DA-A45E-5F9281556361}</ProjectGuid>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <AssemblyName>DotNetOpenAuth.OAuth</AssemblyName>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" />
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="Configuration\OAuthConsumerElement.cs" />
+ <Compile Include="Configuration\OAuthConsumerSecuritySettingsElement.cs" />
+ <Compile Include="Configuration\OAuthElement.cs" />
+ <Compile Include="Configuration\OAuthServiceProviderElement.cs" />
+ <Compile Include="Configuration\OAuthServiceProviderSecuritySettingsElement.cs" />
+ <Compile Include="Messaging\ITamperProtectionChannelBindingElement.cs" />
+ <Compile Include="OAuthReporting.cs" />
+ <Compile Include="OAuth\ChannelElements\ICombinedOpenIdProviderTokenManager.cs" />
+ <Compile Include="OAuth\ChannelElements\IOpenIdOAuthTokenManager.cs" />
+ <Compile Include="OAuth\ChannelElements\ITokenManager.cs" />
+ <Compile Include="OAuth\ChannelElements\OAuthHttpMethodBindingElement.cs" />
+ <Compile Include="OAuth\ChannelElements\PlaintextSigningBindingElement.cs" />
+ <Compile Include="OAuth\ChannelElements\HmacSha1SigningBindingElement.cs" />
+ <Compile Include="OAuth\ChannelElements\SigningBindingElementBaseContract.cs" />
+ <Compile Include="OAuth\ChannelElements\SigningBindingElementChain.cs" />
+ <Compile Include="OAuth\ChannelElements\TokenType.cs" />
+ <Compile Include="OAuth\ChannelElements\UriOrOobEncoding.cs" />
+ <Compile Include="OAuth\ConsumerSecuritySettings.cs" />
+ <Compile Include="OAuth\Messages\ITokenSecretContainingMessage.cs" />
+ <Compile Include="OAuth\OAuthStrings.Designer.cs">
+ <AutoGen>True</AutoGen>
+ <DesignTime>True</DesignTime>
+ <DependentUpon>OAuthStrings.resx</DependentUpon>
+ </Compile>
+ <Compile Include="OAuth\SecuritySettings.cs" />
+ <Compile Include="OAuth\ServiceProviderDescription.cs" />
+ <Compile Include="OAuth\Messages\ITokenContainingMessage.cs" />
+ <Compile Include="OAuth\Messages\SignedMessageBase.cs" />
+ <Compile Include="OAuth\ChannelElements\SigningBindingElementBase.cs" />
+ <Compile Include="OAuth\ServiceProviderSecuritySettings.cs" />
+ <Compile Include="OAuth\ChannelElements\ITamperResistantOAuthMessage.cs" />
+ <Compile Include="OAuth\Messages\MessageBase.cs" />
+ <Compile Include="OAuth\Messages\AuthorizedTokenRequest.cs" />
+ <Compile Include="OAuth\Messages\AccessProtectedResourceRequest.cs" />
+ <Compile Include="OAuth\Messages\AuthorizedTokenResponse.cs" />
+ <Compile Include="OAuth\Messages\UserAuthorizationResponse.cs" />
+ <Compile Include="OAuth\Messages\UserAuthorizationRequest.cs" />
+ <Compile Include="OAuth\Messages\UnauthorizedTokenResponse.cs" />
+ <Compile Include="OAuth\ChannelElements\OAuthChannel.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs">
+ <SubType>
+ </SubType>
+ </Compile>
+ <Compile Include="OAuth\Messages\UnauthorizedTokenRequest.cs" />
+ <Compile Include="OAuth\ChannelElements\RsaSha1SigningBindingElement.cs" />
+ <Compile Include="OAuth\Protocol.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="OAuth\ClassDiagram.cd" />
+ <None Include="OAuth\Messages\OAuth Messages.cd" />
+ </ItemGroup>
+ <ItemGroup>
+ <EmbeddedResource Include="OAuth\OAuthStrings.resx">
+ <Generator>ResXFileCodeGenerator</Generator>
+ <LastGenOutput>OAuthStrings.Designer.cs</LastGenOutput>
+ </EmbeddedResource>
+ </ItemGroup>
+ <ItemGroup>
+ <EmbeddedResource Include="OAuth\OAuthStrings.sr.resx" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\DotNetOpenAuth.Core\DotNetOpenAuth.Core.csproj">
+ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project>
+ <Name>DotNetOpenAuth.Core</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OpenId\DotNetOpenAuth.OpenId.csproj">
+ <Project>{3896A32A-E876-4C23-B9B8-78E17D134CD3}</Project>
+ <Name>DotNetOpenAuth.OpenId</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
+</Project> \ No newline at end of file
diff --git a/src/DotNetOpenAuth/Messaging/ITamperProtectionChannelBindingElement.cs b/src/DotNetOpenAuth.OAuth/Messaging/ITamperProtectionChannelBindingElement.cs
index e177dd9..e177dd9 100644
--- a/src/DotNetOpenAuth/Messaging/ITamperProtectionChannelBindingElement.cs
+++ b/src/DotNetOpenAuth.OAuth/Messaging/ITamperProtectionChannelBindingElement.cs
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/HmacSha1SigningBindingElement.cs b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/HmacSha1SigningBindingElement.cs
index 5828428..5828428 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/HmacSha1SigningBindingElement.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/HmacSha1SigningBindingElement.cs
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/ICombinedOpenIdProviderTokenManager.cs b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/ICombinedOpenIdProviderTokenManager.cs
index dd28e71..dd28e71 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/ICombinedOpenIdProviderTokenManager.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/ICombinedOpenIdProviderTokenManager.cs
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/IOpenIdOAuthTokenManager.cs b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/IOpenIdOAuthTokenManager.cs
index b3ee320..b3ee320 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/IOpenIdOAuthTokenManager.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/IOpenIdOAuthTokenManager.cs
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/ITamperResistantOAuthMessage.cs b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/ITamperResistantOAuthMessage.cs
index a95001d..a95001d 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/ITamperResistantOAuthMessage.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/ITamperResistantOAuthMessage.cs
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/ITokenManager.cs b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/ITokenManager.cs
index 459cd28..7d68b63 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/ITokenManager.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/ITokenManager.cs
@@ -60,8 +60,8 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// <see cref="System.Web.HttpContext.User">HttpContext.Current.User</see> may be
/// useful in an ASP.NET web application within the implementation of this method.
/// Alternatively you may store the access token here without associating with a user account,
- /// and wait until <see cref="WebConsumer.ProcessUserAuthorization()"/> or
- /// <see cref="DesktopConsumer.ProcessUserAuthorization(string, string)"/> return the access
+ /// and wait until WebConsumer.ProcessUserAuthorization or
+ /// DesktopConsumer.ProcessUserAuthorization return the access
/// token to associate the access token with a user account at that point.
/// </para>
/// </remarks>
@@ -97,7 +97,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// </returns>
/// <exception cref="ArgumentException">Thrown if the secret cannot be found for the given token.</exception>
string ITokenManager.GetTokenSecret(string token) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(token));
+ Requires.NotNullOrEmpty(token, "token");
Contract.Ensures(Contract.Result<string>() != null);
throw new NotImplementedException();
}
@@ -116,8 +116,8 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// method.
/// </remarks>
void ITokenManager.StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response) {
- Contract.Requires<ArgumentNullException>(request != null);
- Contract.Requires<ArgumentNullException>(response != null);
+ Requires.NotNull(request, "request");
+ Requires.NotNull(response, "response");
throw new NotImplementedException();
}
@@ -139,16 +139,16 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// <see cref="System.Web.HttpContext.User">HttpContext.Current.User</see> may be
/// useful in an ASP.NET web application within the implementation of this method.
/// Alternatively you may store the access token here without associating with a user account,
- /// and wait until <see cref="WebConsumer.ProcessUserAuthorization()"/> or
- /// <see cref="DesktopConsumer.ProcessUserAuthorization(string, string)"/> return the access
+ /// and wait until WebConsumer.ProcessUserAuthorization or
+ /// DesktopConsumer.ProcessUserAuthorization return the access
/// token to associate the access token with a user account at that point.
/// </para>
/// </remarks>
void ITokenManager.ExpireRequestTokenAndStoreNewAccessToken(string consumerKey, string requestToken, string accessToken, string accessTokenSecret) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(consumerKey));
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(requestToken));
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(accessToken));
- Contract.Requires<ArgumentNullException>(accessTokenSecret != null);
+ Requires.NotNullOrEmpty(consumerKey, "consumerKey");
+ Requires.NotNullOrEmpty(requestToken, "requestToken");
+ Requires.NotNullOrEmpty(accessToken, "accessToken");
+ Requires.NotNull(accessTokenSecret, "accessTokenSecret");
throw new NotImplementedException();
}
@@ -160,7 +160,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// Request or Access token, or invalid if the token is not recognized.
/// </returns>
TokenType ITokenManager.GetTokenType(string token) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(token));
+ Requires.NotNullOrEmpty(token, "token");
throw new NotImplementedException();
}
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthChannel.cs b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/OAuthChannel.cs
index 2b1bea5..32b57d0 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthChannel.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/OAuthChannel.cs
@@ -25,49 +25,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// <summary>
/// An OAuth-specific implementation of the <see cref="Channel"/> class.
/// </summary>
- internal class OAuthChannel : Channel {
- /// <summary>
- /// Initializes a new instance of the <see cref="OAuthChannel"/> class.
- /// </summary>
- /// <param name="signingBindingElement">The binding element to use for signing.</param>
- /// <param name="store">The web application store to use for nonces.</param>
- /// <param name="tokenManager">The token manager instance to use.</param>
- /// <param name="securitySettings">The security settings.</param>
- [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Diagnostics.Contracts.__ContractsRuntime.Requires<System.ArgumentNullException>(System.Boolean,System.String,System.String)", Justification = "Code contracts"), SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "securitySettings", Justification = "Code contracts")]
- internal OAuthChannel(ITamperProtectionChannelBindingElement signingBindingElement, INonceStore store, IConsumerTokenManager tokenManager, ConsumerSecuritySettings securitySettings)
- : this(
- signingBindingElement,
- store,
- tokenManager,
- securitySettings,
- new OAuthConsumerMessageFactory()) {
- Contract.Requires<ArgumentNullException>(tokenManager != null);
- Contract.Requires<ArgumentNullException>(securitySettings != null, "securitySettings");
- Contract.Requires<ArgumentNullException>(signingBindingElement != null);
- Contract.Requires<ArgumentException>(signingBindingElement.SignatureCallback == null, OAuthStrings.SigningElementAlreadyAssociatedWithChannel);
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="OAuthChannel"/> class.
- /// </summary>
- /// <param name="signingBindingElement">The binding element to use for signing.</param>
- /// <param name="store">The web application store to use for nonces.</param>
- /// <param name="tokenManager">The token manager instance to use.</param>
- /// <param name="securitySettings">The security settings.</param>
- [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Diagnostics.Contracts.__ContractsRuntime.Requires<System.ArgumentNullException>(System.Boolean,System.String,System.String)", Justification = "Code contracts"), SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "securitySettings", Justification = "Code contracts")]
- internal OAuthChannel(ITamperProtectionChannelBindingElement signingBindingElement, INonceStore store, IServiceProviderTokenManager tokenManager, ServiceProviderSecuritySettings securitySettings)
- : this(
- signingBindingElement,
- store,
- tokenManager,
- securitySettings,
- new OAuthServiceProviderMessageFactory(tokenManager)) {
- Contract.Requires<ArgumentNullException>(tokenManager != null);
- Contract.Requires<ArgumentNullException>(securitySettings != null, "securitySettings");
- Contract.Requires<ArgumentNullException>(signingBindingElement != null);
- Contract.Requires<ArgumentException>(signingBindingElement.SignatureCallback == null, OAuthStrings.SigningElementAlreadyAssociatedWithChannel);
- }
-
+ internal abstract class OAuthChannel : Channel {
/// <summary>
/// Initializes a new instance of the <see cref="OAuthChannel"/> class.
/// </summary>
@@ -77,14 +35,16 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// <param name="securitySettings">The security settings.</param>
/// <param name="messageTypeProvider">An injected message type provider instance.
/// Except for mock testing, this should always be one of
- /// <see cref="OAuthConsumerMessageFactory"/> or <see cref="OAuthServiceProviderMessageFactory"/>.</param>
+ /// OAuthConsumerMessageFactory or OAuthServiceProviderMessageFactory.</param>
+ /// <param name="bindingElements">The binding elements.</param>
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Diagnostics.Contracts.__ContractsRuntime.Requires<System.ArgumentNullException>(System.Boolean,System.String,System.String)", Justification = "Code contracts"), SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "securitySettings", Justification = "Code contracts")]
- internal OAuthChannel(ITamperProtectionChannelBindingElement signingBindingElement, INonceStore store, ITokenManager tokenManager, SecuritySettings securitySettings, IMessageFactory messageTypeProvider)
- : base(messageTypeProvider, InitializeBindingElements(signingBindingElement, store, tokenManager, securitySettings)) {
- Contract.Requires<ArgumentNullException>(tokenManager != null);
- Contract.Requires<ArgumentNullException>(securitySettings != null, "securitySettings");
- Contract.Requires<ArgumentNullException>(signingBindingElement != null);
- Contract.Requires<ArgumentException>(signingBindingElement.SignatureCallback == null, OAuthStrings.SigningElementAlreadyAssociatedWithChannel);
+ protected OAuthChannel(ITamperProtectionChannelBindingElement signingBindingElement, INonceStore store, ITokenManager tokenManager, SecuritySettings securitySettings, IMessageFactory messageTypeProvider, IChannelBindingElement[] bindingElements)
+ : base(messageTypeProvider, bindingElements) {
+ Requires.NotNull(tokenManager, "tokenManager");
+ Requires.NotNull(securitySettings, "securitySettings");
+ Requires.NotNull(signingBindingElement, "signingBindingElement");
+ Requires.True(signingBindingElement.SignatureCallback == null, "signingBindingElement", OAuthStrings.SigningElementAlreadyAssociatedWithChannel);
+ Requires.NotNull(bindingElements, "bindingElements");
this.TokenManager = tokenManager;
signingBindingElement.SignatureCallback = this.SignatureCallback;
@@ -119,49 +79,50 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// <param name="request">The message to attach.</param>
/// <returns>The initialized web request.</returns>
internal HttpWebRequest InitializeRequest(IDirectedProtocolMessage request) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
ProcessOutgoingMessage(request);
return this.CreateHttpRequest(request);
}
/// <summary>
+ /// Initializes the binding elements for the OAuth channel.
+ /// </summary>
+ /// <param name="signingBindingElement">The signing binding element.</param>
+ /// <param name="store">The nonce store.</param>
+ /// <param name="tokenManager">The token manager.</param>
+ /// <param name="securitySettings">The security settings.</param>
+ /// <returns>
+ /// An array of binding elements used to initialize the channel.
+ /// </returns>
+ protected static List<IChannelBindingElement> InitializeBindingElements(ITamperProtectionChannelBindingElement signingBindingElement, INonceStore store, ITokenManager tokenManager, SecuritySettings securitySettings) {
+ Contract.Requires(securitySettings != null);
+
+ var bindingElements = new List<IChannelBindingElement> {
+ new OAuthHttpMethodBindingElement(),
+ signingBindingElement,
+ new StandardExpirationBindingElement(),
+ new StandardReplayProtectionBindingElement(store),
+ };
+
+ return bindingElements;
+ }
+
+ /// <summary>
/// Searches an incoming HTTP request for data that could be used to assemble
/// a protocol request message.
/// </summary>
/// <param name="request">The HTTP request to search.</param>
/// <returns>The deserialized message, if one is found. Null otherwise.</returns>
protected override IDirectedProtocolMessage ReadFromRequestCore(HttpRequestInfo request) {
- var fields = new Dictionary<string, string>();
-
// First search the Authorization header.
string authorization = request.Headers[HttpRequestHeader.Authorization];
- if (authorization != null) {
- string[] authorizationSections = authorization.Split(';'); // TODO: is this the right delimiter?
- string oauthPrefix = Protocol.AuthorizationHeaderScheme + " ";
-
- // The Authorization header may have multiple uses, and OAuth may be just one of them.
- // Go through each one looking for an OAuth one.
- foreach (string auth in authorizationSections) {
- string trimmedAuth = auth.Trim();
- if (trimmedAuth.StartsWith(oauthPrefix, StringComparison.Ordinal)) {
- // We found an Authorization: OAuth header.
- // Parse it according to the rules in section 5.4.1 of the V1.0 spec.
- foreach (string stringPair in trimmedAuth.Substring(oauthPrefix.Length).Split(',')) {
- string[] keyValueStringPair = stringPair.Trim().Split('=');
- string key = Uri.UnescapeDataString(keyValueStringPair[0]);
- string value = Uri.UnescapeDataString(keyValueStringPair[1].Trim('"'));
- fields.Add(key, value);
- }
- }
- }
-
- fields.Remove("realm"); // ignore the realm parameter, since we don't use it, and it must be omitted from signature base string.
- }
+ var fields = MessagingUtilities.ParseAuthorizationHeader(Protocol.AuthorizationHeaderScheme, authorization).ToDictionary();
+ fields.Remove("realm"); // ignore the realm parameter, since we don't use it, and it must be omitted from signature base string.
// Scrape the entity
if (!string.IsNullOrEmpty(request.Headers[HttpRequestHeader.ContentType])) {
- ContentType contentType = new ContentType(request.Headers[HttpRequestHeader.ContentType]);
+ var contentType = new ContentType(request.Headers[HttpRequestHeader.ContentType]);
if (string.Equals(contentType.MediaType, HttpFormUrlEncoded, StringComparison.Ordinal)) {
foreach (string key in request.Form) {
if (key != null) {
@@ -276,33 +237,11 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
}
/// <summary>
- /// Initializes the binding elements for the OAuth channel.
+ /// Gets the consumer secret for a given consumer key.
/// </summary>
- /// <param name="signingBindingElement">The signing binding element.</param>
- /// <param name="store">The nonce store.</param>
- /// <param name="tokenManager">The token manager.</param>
- /// <param name="securitySettings">The security settings.</param>
- /// <returns>
- /// An array of binding elements used to initialize the channel.
- /// </returns>
- private static IChannelBindingElement[] InitializeBindingElements(ITamperProtectionChannelBindingElement signingBindingElement, INonceStore store, ITokenManager tokenManager, SecuritySettings securitySettings) {
- Contract.Requires(securitySettings != null);
-
- var bindingElements = new List<IChannelBindingElement> {
- new OAuthHttpMethodBindingElement(),
- signingBindingElement,
- new StandardExpirationBindingElement(),
- new StandardReplayProtectionBindingElement(store),
- };
-
- var spTokenManager = tokenManager as IServiceProviderTokenManager;
- var serviceProviderSecuritySettings = securitySettings as ServiceProviderSecuritySettings;
- if (spTokenManager != null && serviceProviderSecuritySettings != null) {
- bindingElements.Insert(0, new TokenHandlingBindingElement(spTokenManager, serviceProviderSecuritySettings));
- }
-
- return bindingElements.ToArray();
- }
+ /// <param name="consumerKey">The consumer key.</param>
+ /// <returns>A consumer secret.</returns>
+ protected abstract string GetConsumerSecret(string consumerKey);
/// <summary>
/// Uri-escapes the names and values in a dictionary per OAuth 1.0 section 5.1.
@@ -310,8 +249,8 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// <param name="source">The dictionary with names and values to encode.</param>
/// <param name="destination">The dictionary to add the encoded pairs to.</param>
private static void UriEscapeParameters(IEnumerable<KeyValuePair<string, string>> source, IDictionary<string, string> destination) {
- Contract.Requires<ArgumentNullException>(source != null);
- Contract.Requires<ArgumentNullException>(destination != null);
+ Requires.NotNull(source, "source");
+ Requires.NotNull(destination, "destination");
foreach (var pair in source) {
var key = MessagingUtilities.EscapeUriDataStringRfc3986(pair.Key);
@@ -326,7 +265,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// <param name="message">The message.</param>
/// <returns>"POST", "GET" or some other similar http verb.</returns>
private static string GetHttpMethod(IDirectedProtocolMessage message) {
- Contract.Requires<ArgumentNullException>(message != null);
+ Requires.NotNull(message, "message");
var signedMessage = message as ITamperResistantOAuthMessage;
if (signedMessage != null) {
@@ -368,20 +307,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
httpRequest = (HttpWebRequest)WebRequest.Create(recipientBuilder.Uri);
httpRequest.Method = GetHttpMethod(requestMessage);
- StringBuilder authorization = new StringBuilder();
- authorization.Append(Protocol.AuthorizationHeaderScheme);
- authorization.Append(" ");
- foreach (var pair in fields) {
- string key = MessagingUtilities.EscapeUriDataStringRfc3986(pair.Key);
- string value = MessagingUtilities.EscapeUriDataStringRfc3986(pair.Value);
- authorization.Append(key);
- authorization.Append("=\"");
- authorization.Append(value);
- authorization.Append("\",");
- }
- authorization.Length--; // remove trailing comma
-
- httpRequest.Headers.Add(HttpRequestHeader.Authorization, authorization.ToString());
+ httpRequest.Headers.Add(HttpRequestHeader.Authorization, MessagingUtilities.AssembleAuthorizationHeader(Protocol.AuthorizationHeaderScheme, fields));
if (hasEntity) {
// WARNING: We only set up the request stream for the caller if there is
@@ -426,20 +352,5 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
throw new ProtocolException(OAuthStrings.ConsumerOrTokenSecretNotFound, ex);
}
}
-
- /// <summary>
- /// Gets the consumer secret for a given consumer key.
- /// </summary>
- /// <param name="consumerKey">The consumer key.</param>
- /// <returns>The consumer secret.</returns>
- private string GetConsumerSecret(string consumerKey) {
- var consumerTokenManager = this.TokenManager as IConsumerTokenManager;
- if (consumerTokenManager != null) {
- ErrorUtilities.VerifyInternal(consumerKey == consumerTokenManager.ConsumerKey, "The token manager consumer key and the consumer key set earlier do not match!");
- return consumerTokenManager.ConsumerSecret;
- } else {
- return ((IServiceProviderTokenManager)this.TokenManager).GetConsumer(consumerKey).Secret;
- }
- }
}
}
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthHttpMethodBindingElement.cs b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/OAuthHttpMethodBindingElement.cs
index 37fb80b..37fb80b 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthHttpMethodBindingElement.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/OAuthHttpMethodBindingElement.cs
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/PlaintextSigningBindingElement.cs b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/PlaintextSigningBindingElement.cs
index 22e5f20..22e5f20 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/PlaintextSigningBindingElement.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/PlaintextSigningBindingElement.cs
diff --git a/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/RsaSha1SigningBindingElement.cs b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/RsaSha1SigningBindingElement.cs
new file mode 100644
index 0000000..83be094
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/RsaSha1SigningBindingElement.cs
@@ -0,0 +1,31 @@
+//-----------------------------------------------------------------------
+// <copyright file="RsaSha1SigningBindingElement.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth.ChannelElements {
+ using System;
+ using System.Diagnostics.Contracts;
+ using System.Security.Cryptography;
+ using System.Security.Cryptography.X509Certificates;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A binding element that signs outgoing messages and verifies the signature on incoming messages.
+ /// </summary>
+ public abstract class RsaSha1SigningBindingElement : SigningBindingElementBase {
+ /// <summary>
+ /// The name of the hash algorithm to use.
+ /// </summary>
+ protected const string HashAlgorithmName = "RSA-SHA1";
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RsaSha1SigningBindingElement"/> class.
+ /// </summary>
+ protected RsaSha1SigningBindingElement()
+ : base(HashAlgorithmName) {
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/SigningBindingElementBase.cs b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementBase.cs
index 31b5149..2c47453 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/SigningBindingElementBase.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementBase.cs
@@ -151,10 +151,10 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// </remarks>
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Unavoidable")]
internal static string ConstructSignatureBaseString(ITamperResistantOAuthMessage message, MessageDictionary messageDictionary) {
- Contract.Requires<ArgumentNullException>(message != null);
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(message.HttpMethod));
- Contract.Requires<ArgumentNullException>(messageDictionary != null);
- Contract.Requires<ArgumentException>(messageDictionary.Message == message);
+ Requires.NotNull(message, "message");
+ Requires.NotNullOrEmpty(message.HttpMethod, "message.HttpMethod");
+ Requires.NotNull(messageDictionary, "messageDictionary");
+ ErrorUtilities.VerifyArgument(messageDictionary.Message == message, "Message references are not equal.");
List<string> signatureBaseStringElements = new List<string>(3);
@@ -279,7 +279,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// <c>true</c> if the signature on the message is valid; otherwise, <c>false</c>.
/// </returns>
protected virtual bool IsSignatureValid(ITamperResistantOAuthMessage message) {
- Contract.Requires<ArgumentNullException>(message != null);
+ Requires.NotNull(message, "message");
string signature = this.GetSignature(message);
return MessagingUtilities.EqualsConstantTime(message.Signature, signature);
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/SigningBindingElementBaseContract.cs b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementBaseContract.cs
index 4ff52fd..4450fb5 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/SigningBindingElementBaseContract.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementBaseContract.cs
@@ -39,8 +39,8 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// <param name="message">The message to sign.</param>
/// <returns>The signature for the message.</returns>
protected override string GetSignature(ITamperResistantOAuthMessage message) {
- Contract.Requires<ArgumentNullException>(message != null);
- Contract.Requires<InvalidOperationException>(this.Channel != null);
+ Requires.NotNull(message, "message");
+ Requires.ValidState(this.Channel != null);
throw new NotImplementedException();
}
}
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/SigningBindingElementChain.cs b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementChain.cs
index 67c5205..849ad5e 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/SigningBindingElementChain.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementChain.cs
@@ -30,10 +30,9 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// in preferred use order.
/// </param>
internal SigningBindingElementChain(ITamperProtectionChannelBindingElement[] signers) {
- Contract.Requires<ArgumentNullException>(signers != null);
- Contract.Requires<ArgumentException>(signers.Length > 0);
- Contract.Requires<ArgumentException>(!signers.Contains(null), MessagingStrings.SequenceContainsNullElement);
- Contract.Requires<ArgumentException>(signers.Select(s => s.Protection).Distinct().Count() == 1, OAuthStrings.SigningElementsMustShareSameProtection);
+ Requires.NotNullOrEmpty(signers, "signers");
+ Requires.NullOrWithNoNullElements(signers, "signers");
+ Requires.True(signers.Select(s => s.Protection).Distinct().Count() == 1, "signers", OAuthStrings.SigningElementsMustShareSameProtection);
this.signers = signers;
}
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/TokenType.cs b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/TokenType.cs
index 46c2bd9..46c2bd9 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/TokenType.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/TokenType.cs
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/UriOrOobEncoding.cs b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/UriOrOobEncoding.cs
index 287ef01..287ef01 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/UriOrOobEncoding.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/UriOrOobEncoding.cs
diff --git a/src/DotNetOpenAuth/OAuth/ClassDiagram.cd b/src/DotNetOpenAuth.OAuth/OAuth/ClassDiagram.cd
index f56fd83..f56fd83 100644
--- a/src/DotNetOpenAuth/OAuth/ClassDiagram.cd
+++ b/src/DotNetOpenAuth.OAuth/OAuth/ClassDiagram.cd
diff --git a/src/DotNetOpenAuth/OAuth/ConsumerSecuritySettings.cs b/src/DotNetOpenAuth.OAuth/OAuth/ConsumerSecuritySettings.cs
index bb2fbaa..bb2fbaa 100644
--- a/src/DotNetOpenAuth/OAuth/ConsumerSecuritySettings.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/ConsumerSecuritySettings.cs
diff --git a/src/DotNetOpenAuth/OAuth/Messages/AccessProtectedResourceRequest.cs b/src/DotNetOpenAuth.OAuth/OAuth/Messages/AccessProtectedResourceRequest.cs
index f3231f0..f3231f0 100644
--- a/src/DotNetOpenAuth/OAuth/Messages/AccessProtectedResourceRequest.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/Messages/AccessProtectedResourceRequest.cs
diff --git a/src/DotNetOpenAuth/OAuth/Messages/AuthorizedTokenRequest.cs b/src/DotNetOpenAuth.OAuth/OAuth/Messages/AuthorizedTokenRequest.cs
index 02c6c1d..02c6c1d 100644
--- a/src/DotNetOpenAuth/OAuth/Messages/AuthorizedTokenRequest.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/Messages/AuthorizedTokenRequest.cs
diff --git a/src/DotNetOpenAuth/OAuth/Messages/AuthorizedTokenResponse.cs b/src/DotNetOpenAuth.OAuth/OAuth/Messages/AuthorizedTokenResponse.cs
index 0b14819..0b14819 100644
--- a/src/DotNetOpenAuth/OAuth/Messages/AuthorizedTokenResponse.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/Messages/AuthorizedTokenResponse.cs
diff --git a/src/DotNetOpenAuth/OAuth/Messages/ITokenContainingMessage.cs b/src/DotNetOpenAuth.OAuth/OAuth/Messages/ITokenContainingMessage.cs
index 832b754..832b754 100644
--- a/src/DotNetOpenAuth/OAuth/Messages/ITokenContainingMessage.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/Messages/ITokenContainingMessage.cs
diff --git a/src/DotNetOpenAuth/OAuth/Messages/ITokenSecretContainingMessage.cs b/src/DotNetOpenAuth.OAuth/OAuth/Messages/ITokenSecretContainingMessage.cs
index 95809ec..95809ec 100644
--- a/src/DotNetOpenAuth/OAuth/Messages/ITokenSecretContainingMessage.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/Messages/ITokenSecretContainingMessage.cs
diff --git a/src/DotNetOpenAuth/OAuth/Messages/MessageBase.cs b/src/DotNetOpenAuth.OAuth/OAuth/Messages/MessageBase.cs
index 1a0ba23..faa4345 100644
--- a/src/DotNetOpenAuth/OAuth/Messages/MessageBase.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/Messages/MessageBase.cs
@@ -65,8 +65,8 @@ namespace DotNetOpenAuth.OAuth.Messages {
/// <param name="originatingRequest">The request that asked for this direct response.</param>
/// <param name="version">The OAuth version.</param>
protected MessageBase(MessageProtections protectionRequired, IDirectedProtocolMessage originatingRequest, Version version) {
- Contract.Requires<ArgumentNullException>(originatingRequest != null);
- Contract.Requires<ArgumentNullException>(version != null);
+ Requires.NotNull(originatingRequest, "originatingRequest");
+ Requires.NotNull(version, "version");
this.protectionRequired = protectionRequired;
this.transport = MessageTransport.Direct;
@@ -82,8 +82,8 @@ namespace DotNetOpenAuth.OAuth.Messages {
/// <param name="recipient">The URI that a directed message will be delivered to.</param>
/// <param name="version">The OAuth version.</param>
protected MessageBase(MessageProtections protectionRequired, MessageTransport transport, MessageReceivingEndpoint recipient, Version version) {
- Contract.Requires<ArgumentNullException>(recipient != null);
- Contract.Requires<ArgumentNullException>(version != null);
+ Requires.NotNull(recipient, "recipient");
+ Requires.NotNull(version, "version");
this.protectionRequired = protectionRequired;
this.transport = transport;
@@ -242,7 +242,7 @@ namespace DotNetOpenAuth.OAuth.Messages {
/// The string representation of this object.
/// </returns>
internal virtual string ToString(Channel channel) {
- Contract.Requires<ArgumentNullException>(channel != null);
+ Requires.NotNull(channel, "channel");
StringBuilder builder = new StringBuilder();
builder.AppendFormat(CultureInfo.InvariantCulture, "{0} message", GetType().Name);
diff --git a/src/DotNetOpenAuth/OAuth/Messages/OAuth Messages.cd b/src/DotNetOpenAuth.OAuth/OAuth/Messages/OAuth Messages.cd
index f5526d2..f5526d2 100644
--- a/src/DotNetOpenAuth/OAuth/Messages/OAuth Messages.cd
+++ b/src/DotNetOpenAuth.OAuth/OAuth/Messages/OAuth Messages.cd
diff --git a/src/DotNetOpenAuth/OAuth/Messages/SignedMessageBase.cs b/src/DotNetOpenAuth.OAuth/OAuth/Messages/SignedMessageBase.cs
index 6084fc0..6084fc0 100644
--- a/src/DotNetOpenAuth/OAuth/Messages/SignedMessageBase.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/Messages/SignedMessageBase.cs
diff --git a/src/DotNetOpenAuth/OAuth/Messages/UnauthorizedTokenRequest.cs b/src/DotNetOpenAuth.OAuth/OAuth/Messages/UnauthorizedTokenRequest.cs
index 9214d91..9214d91 100644
--- a/src/DotNetOpenAuth/OAuth/Messages/UnauthorizedTokenRequest.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/Messages/UnauthorizedTokenRequest.cs
diff --git a/src/DotNetOpenAuth/OAuth/Messages/UnauthorizedTokenResponse.cs b/src/DotNetOpenAuth.OAuth/OAuth/Messages/UnauthorizedTokenResponse.cs
index 0be9f63..04dee88 100644
--- a/src/DotNetOpenAuth/OAuth/Messages/UnauthorizedTokenResponse.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/Messages/UnauthorizedTokenResponse.cs
@@ -27,8 +27,8 @@ namespace DotNetOpenAuth.OAuth.Messages {
/// </remarks>
protected internal UnauthorizedTokenResponse(UnauthorizedTokenRequest requestMessage, string requestToken, string tokenSecret)
: this(requestMessage, requestMessage.Version) {
- Contract.Requires<ArgumentNullException>(requestToken != null);
- Contract.Requires<ArgumentNullException>(tokenSecret != null);
+ Requires.NotNull(requestToken, "requestToken");
+ Requires.NotNull(tokenSecret, "tokenSecret");
this.RequestToken = requestToken;
this.TokenSecret = tokenSecret;
diff --git a/src/DotNetOpenAuth/OAuth/Messages/UserAuthorizationRequest.cs b/src/DotNetOpenAuth.OAuth/OAuth/Messages/UserAuthorizationRequest.cs
index a5823bb..a5823bb 100644
--- a/src/DotNetOpenAuth/OAuth/Messages/UserAuthorizationRequest.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/Messages/UserAuthorizationRequest.cs
diff --git a/src/DotNetOpenAuth/OAuth/Messages/UserAuthorizationResponse.cs b/src/DotNetOpenAuth.OAuth/OAuth/Messages/UserAuthorizationResponse.cs
index 73fddc7..73fddc7 100644
--- a/src/DotNetOpenAuth/OAuth/Messages/UserAuthorizationResponse.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/Messages/UserAuthorizationResponse.cs
diff --git a/src/DotNetOpenAuth/OAuth/OAuthStrings.Designer.cs b/src/DotNetOpenAuth.OAuth/OAuth/OAuthStrings.Designer.cs
index 723839d..723839d 100644
--- a/src/DotNetOpenAuth/OAuth/OAuthStrings.Designer.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/OAuthStrings.Designer.cs
diff --git a/src/DotNetOpenAuth/OAuth/OAuthStrings.resx b/src/DotNetOpenAuth.OAuth/OAuth/OAuthStrings.resx
index 34b314b..34b314b 100644
--- a/src/DotNetOpenAuth/OAuth/OAuthStrings.resx
+++ b/src/DotNetOpenAuth.OAuth/OAuth/OAuthStrings.resx
diff --git a/src/DotNetOpenAuth/OAuth/OAuthStrings.sr.resx b/src/DotNetOpenAuth.OAuth/OAuth/OAuthStrings.sr.resx
index ef9ce60..ef9ce60 100644
--- a/src/DotNetOpenAuth/OAuth/OAuthStrings.sr.resx
+++ b/src/DotNetOpenAuth.OAuth/OAuth/OAuthStrings.sr.resx
diff --git a/src/DotNetOpenAuth/OAuth/Protocol.cs b/src/DotNetOpenAuth.OAuth/OAuth/Protocol.cs
index 6eecd8e..0b7aaa9 100644
--- a/src/DotNetOpenAuth/OAuth/Protocol.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/Protocol.cs
@@ -100,7 +100,7 @@ namespace DotNetOpenAuth.OAuth {
}
/// <summary>
- /// Gets the version used to represent OAuth 1.0a.
+ /// Gets the OAuth version this instance represents.
/// </summary>
internal Version Version { get; private set; }
@@ -140,8 +140,8 @@ namespace DotNetOpenAuth.OAuth {
/// <param name="version">The OAuth version to get.</param>
/// <returns>A matching <see cref="Protocol"/> instance.</returns>
internal static Protocol Lookup(Version version) {
- Contract.Requires<ArgumentNullException>(version != null);
- Contract.Requires<ArgumentOutOfRangeException>(AllVersions.Any(p => p.Version == version));
+ Requires.NotNull(version, "version");
+ Requires.InRange(AllVersions.Any(p => p.Version == version), "version");
return AllVersions.First(p => p.Version == version);
}
}
diff --git a/src/DotNetOpenAuth/OAuth/SecuritySettings.cs b/src/DotNetOpenAuth.OAuth/OAuth/SecuritySettings.cs
index 3329f09..3329f09 100644
--- a/src/DotNetOpenAuth/OAuth/SecuritySettings.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/SecuritySettings.cs
diff --git a/src/DotNetOpenAuth/OAuth/ServiceProviderDescription.cs b/src/DotNetOpenAuth.OAuth/OAuth/ServiceProviderDescription.cs
index 6205f55..6205f55 100644
--- a/src/DotNetOpenAuth/OAuth/ServiceProviderDescription.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/ServiceProviderDescription.cs
diff --git a/src/DotNetOpenAuth/OAuth/ServiceProviderSecuritySettings.cs b/src/DotNetOpenAuth.OAuth/OAuth/ServiceProviderSecuritySettings.cs
index 701e36c..701e36c 100644
--- a/src/DotNetOpenAuth/OAuth/ServiceProviderSecuritySettings.cs
+++ b/src/DotNetOpenAuth.OAuth/OAuth/ServiceProviderSecuritySettings.cs
diff --git a/src/DotNetOpenAuth.OAuth/OAuthReporting.cs b/src/DotNetOpenAuth.OAuth/OAuthReporting.cs
new file mode 100644
index 0000000..c6f8841
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth/OAuthReporting.cs
@@ -0,0 +1,56 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuthReporting.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging.Bindings;
+ using DotNetOpenAuth.OAuth;
+ using DotNetOpenAuth.OAuth.ChannelElements;
+
+ /// <summary>
+ /// Utility methods specific to OAuth feature reporting.
+ /// </summary>
+ internal class OAuthReporting : Reporting {
+ /// <summary>
+ /// Records the feature and dependency use.
+ /// </summary>
+ /// <param name="value">The consumer or service provider.</param>
+ /// <param name="service">The service.</param>
+ /// <param name="tokenManager">The token manager.</param>
+ /// <param name="nonceStore">The nonce store.</param>
+ internal static void RecordFeatureAndDependencyUse(object value, ServiceProviderDescription service, ITokenManager tokenManager, INonceStore nonceStore) {
+ Contract.Requires(value != null);
+ Contract.Requires(service != null);
+ Contract.Requires(tokenManager != null);
+
+ // In release builds, just quietly return.
+ if (value == null || service == null || tokenManager == null) {
+ return;
+ }
+
+ if (Reporting.Enabled && Reporting.Configuration.IncludeFeatureUsage) {
+ StringBuilder builder = new StringBuilder();
+ builder.Append(value.GetType().Name);
+ builder.Append(" ");
+ builder.Append(tokenManager.GetType().Name);
+ if (nonceStore != null) {
+ builder.Append(" ");
+ builder.Append(nonceStore.GetType().Name);
+ }
+ builder.Append(" ");
+ builder.Append(service.Version);
+ builder.Append(" ");
+ builder.Append(service.UserAuthorizationEndpoint);
+ Reporting.ObservedFeatures.Add(builder.ToString());
+ Reporting.Touch();
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth.OAuth/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..49ef570
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth/Properties/AssemblyInfo.cs
@@ -0,0 +1,62 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssemblyInfo.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+// We DON'T put an AssemblyVersionAttribute in here because it is generated in the build.
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Net;
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Security.Permissions;
+using System.Web.UI;
+
+[assembly: TagPrefix("DotNetOpenAuth.OAuth", "oauth")]
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("DotNetOpenAuth OAuth")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DotNetOpenAuth")]
+[assembly: AssemblyCopyright("Copyright © 2008")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+[assembly: NeutralResourcesLanguage("en-US")]
+[assembly: CLSCompliant(true)]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("7d73990c-47c0-4256-9f20-a893add9e289")]
+
+[assembly: ContractVerification(true)]
+
+#if StrongNameSigned
+// See comment at top of this file. We need this so that strong-naming doesn't
+// keep this assembly from being useful to shared host (medium trust) web sites.
+[assembly: AllowPartiallyTrustedCallers]
+
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth.Consumer, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth.ServiceProvider, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
+#else
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth.Consumer")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth.ServiceProvider")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
+#endif
diff --git a/src/DotNetOpenAuth.OAuth2.AuthorizationServer/DotNetOpenAuth.OAuth2.AuthorizationServer.csproj b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/DotNetOpenAuth.OAuth2.AuthorizationServer.csproj
new file mode 100644
index 0000000..e28c158
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/DotNetOpenAuth.OAuth2.AuthorizationServer.csproj
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))\EnlistmentInfo.props" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))' != '' " />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" />
+ <PropertyGroup>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{99BB7543-EA16-43EE-A7BC-D7A25A3B22F6}</ProjectGuid>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <AssemblyName>DotNetOpenAuth.OAuth2.AuthorizationServer</AssemblyName>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" />
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="OAuth2\AuthorizationServer.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\DotNetOpenAuth.Core\DotNetOpenAuth.Core.csproj">
+ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project>
+ <Name>DotNetOpenAuth.Core</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OAuth2\DotNetOpenAuth.OAuth2.csproj">
+ <Project>{56459A6C-6BA2-4BAC-A9C0-27E3BD961FA6}</Project>
+ <Name>DotNetOpenAuth.OAuth2</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OAuth\DotNetOpenAuth.OAuth.csproj">
+ <Project>{A288FCC8-6FCF-46DA-A45E-5F9281556361}</Project>
+ <Name>DotNetOpenAuth.OAuth</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
+</Project> \ No newline at end of file
diff --git a/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/AuthorizationServer.cs b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/AuthorizationServer.cs
new file mode 100644
index 0000000..73c2bd6
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/AuthorizationServer.cs
@@ -0,0 +1,258 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthorizationServer.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Security.Cryptography;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+ using DotNetOpenAuth.OAuth2.Messages;
+
+ /// <summary>
+ /// Authorization Server supporting the web server flow.
+ /// </summary>
+ public class AuthorizationServer {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthorizationServer"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ public AuthorizationServer(IAuthorizationServer authorizationServer) {
+ Requires.NotNull(authorizationServer, "authorizationServer");
+ this.OAuthChannel = new OAuth2AuthorizationServerChannel(authorizationServer);
+ }
+
+ /// <summary>
+ /// Gets the channel.
+ /// </summary>
+ /// <value>The channel.</value>
+ public Channel Channel {
+ get { return this.OAuthChannel; }
+ }
+
+ /// <summary>
+ /// Gets the authorization server.
+ /// </summary>
+ /// <value>The authorization server.</value>
+ public IAuthorizationServer AuthorizationServerServices {
+ get { return this.OAuthChannel.AuthorizationServer; }
+ }
+
+ /// <summary>
+ /// Gets the channel.
+ /// </summary>
+ internal OAuth2AuthorizationServerChannel OAuthChannel { get; private set; }
+
+ /// <summary>
+ /// Reads in a client's request for the Authorization Server to obtain permission from
+ /// the user to authorize the Client's access of some protected resource(s).
+ /// </summary>
+ /// <param name="request">The HTTP request to read from.</param>
+ /// <returns>The incoming request, or null if no OAuth message was attached.</returns>
+ /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception>
+ public EndUserAuthorizationRequest ReadAuthorizationRequest(HttpRequestInfo request = null) {
+ if (request == null) {
+ request = this.Channel.GetRequestFromContext();
+ }
+
+ EndUserAuthorizationRequest message;
+ if (this.Channel.TryReadFromRequest(request, out message)) {
+ if (message.ResponseType == EndUserAuthorizationResponseType.AuthorizationCode) {
+ // Clients with no secrets can only request implicit grant types.
+ var client = this.AuthorizationServerServices.GetClientOrThrow(message.ClientIdentifier);
+ ErrorUtilities.VerifyProtocol(!String.IsNullOrEmpty(client.Secret), Protocol.unauthorized_client);
+ }
+ }
+
+ return message;
+ }
+
+ /// <summary>
+ /// Approves an authorization request and sends an HTTP response to the user agent to redirect the user back to the Client.
+ /// </summary>
+ /// <param name="authorizationRequest">The authorization request to approve.</param>
+ /// <param name="userName">The username of the account that approved the request (or whose data will be accessed by the client).</param>
+ /// <param name="scopes">The scope of access the client should be granted. If <c>null</c>, all scopes in the original request will be granted.</param>
+ /// <param name="callback">The Client callback URL to use when formulating the redirect to send the user agent back to the Client.</param>
+ public void ApproveAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, string userName, IEnumerable<string> scopes = null, Uri callback = null) {
+ Requires.NotNull(authorizationRequest, "authorizationRequest");
+
+ var response = this.PrepareApproveAuthorizationRequest(authorizationRequest, userName, scopes, callback);
+ this.Channel.Respond(response);
+ }
+
+ /// <summary>
+ /// Rejects an authorization request and sends an HTTP response to the user agent to redirect the user back to the Client.
+ /// </summary>
+ /// <param name="authorizationRequest">The authorization request to disapprove.</param>
+ /// <param name="callback">The Client callback URL to use when formulating the redirect to send the user agent back to the Client.</param>
+ public void RejectAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, Uri callback = null) {
+ Requires.NotNull(authorizationRequest, "authorizationRequest");
+
+ var response = this.PrepareRejectAuthorizationRequest(authorizationRequest, callback);
+ this.Channel.Respond(response);
+ }
+
+ /// <summary>
+ /// Checks the incoming HTTP request for an access token request and prepares a response if the request message was found.
+ /// </summary>
+ /// <param name="response">The formulated response, or <c>null</c> if the request was not found..</param>
+ /// <returns>A value indicating whether any access token request was found in the HTTP request.</returns>
+ /// <remarks>
+ /// This method assumes that the authorization server and the resource server are the same and that they share a single
+ /// asymmetric key for signing and encrypting the access token. If this is not true, use the <see cref="ReadAccessTokenRequest"/> method instead.
+ /// </remarks>
+ public bool TryPrepareAccessTokenResponse(out IDirectResponseProtocolMessage response) {
+ return this.TryPrepareAccessTokenResponse(this.Channel.GetRequestFromContext(), out response);
+ }
+
+ /// <summary>
+ /// Checks the incoming HTTP request for an access token request and prepares a response if the request message was found.
+ /// </summary>
+ /// <param name="httpRequestInfo">The HTTP request info.</param>
+ /// <param name="response">The formulated response, or <c>null</c> if the request was not found..</param>
+ /// <returns>A value indicating whether any access token request was found in the HTTP request.</returns>
+ /// <remarks>
+ /// This method assumes that the authorization server and the resource server are the same and that they share a single
+ /// asymmetric key for signing and encrypting the access token. If this is not true, use the <see cref="ReadAccessTokenRequest"/> method instead.
+ /// </remarks>
+ public bool TryPrepareAccessTokenResponse(HttpRequestInfo httpRequestInfo, out IDirectResponseProtocolMessage response) {
+ Requires.NotNull(httpRequestInfo, "httpRequestInfo");
+ Contract.Ensures(Contract.Result<bool>() == (Contract.ValueAtReturn<IDirectResponseProtocolMessage>(out response) != null));
+
+ var request = this.ReadAccessTokenRequest(httpRequestInfo);
+ if (request != null) {
+ response = this.PrepareAccessTokenResponse(request);
+ return true;
+ }
+
+ response = null;
+ return false;
+ }
+
+ /// <summary>
+ /// Reads the access token request.
+ /// </summary>
+ /// <param name="requestInfo">The request info.</param>
+ /// <returns>The Client's request for an access token; or <c>null</c> if no such message was found in the request.</returns>
+ public AccessTokenRequestBase ReadAccessTokenRequest(HttpRequestInfo requestInfo = null) {
+ if (requestInfo == null) {
+ requestInfo = this.Channel.GetRequestFromContext();
+ }
+
+ AccessTokenRequestBase request;
+ this.Channel.TryReadFromRequest(requestInfo, out request);
+ return request;
+ }
+
+ /// <summary>
+ /// Prepares a response to inform the Client that the user has rejected the Client's authorization request.
+ /// </summary>
+ /// <param name="authorizationRequest">The authorization request.</param>
+ /// <param name="callback">The Client callback URL to use when formulating the redirect to send the user agent back to the Client.</param>
+ /// <returns>The authorization response message to send to the Client.</returns>
+ public EndUserAuthorizationFailedResponse PrepareRejectAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, Uri callback = null) {
+ Requires.NotNull(authorizationRequest, "authorizationRequest");
+ Contract.Ensures(Contract.Result<EndUserAuthorizationFailedResponse>() != null);
+
+ if (callback == null) {
+ callback = this.GetCallback(authorizationRequest);
+ }
+
+ var response = new EndUserAuthorizationFailedResponse(callback, authorizationRequest);
+ return response;
+ }
+
+ /// <summary>
+ /// Approves an authorization request.
+ /// </summary>
+ /// <param name="authorizationRequest">The authorization request to approve.</param>
+ /// <param name="userName">The username of the account that approved the request (or whose data will be accessed by the client).</param>
+ /// <param name="scopes">The scope of access the client should be granted. If <c>null</c>, all scopes in the original request will be granted.</param>
+ /// <param name="callback">The Client callback URL to use when formulating the redirect to send the user agent back to the Client.</param>
+ /// <returns>The authorization response message to send to the Client.</returns>
+ public EndUserAuthorizationSuccessResponseBase PrepareApproveAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, string userName, IEnumerable<string> scopes = null, Uri callback = null) {
+ Requires.NotNull(authorizationRequest, "authorizationRequest");
+ Requires.NotNullOrEmpty(userName, "userName");
+ Contract.Ensures(Contract.Result<EndUserAuthorizationSuccessResponseBase>() != null);
+
+ if (callback == null) {
+ callback = this.GetCallback(authorizationRequest);
+ }
+
+ var client = this.AuthorizationServerServices.GetClientOrThrow(authorizationRequest.ClientIdentifier);
+ EndUserAuthorizationSuccessResponseBase response;
+ switch (authorizationRequest.ResponseType) {
+ case EndUserAuthorizationResponseType.AccessToken:
+ var accessTokenResponse = new EndUserAuthorizationSuccessAccessTokenResponse(callback, authorizationRequest);
+ accessTokenResponse.Lifetime = this.AuthorizationServerServices.GetAccessTokenLifetime(authorizationRequest);
+ response = accessTokenResponse;
+ break;
+ case EndUserAuthorizationResponseType.AuthorizationCode:
+ response = new EndUserAuthorizationSuccessAuthCodeResponse(callback, authorizationRequest);
+ break;
+ default:
+ throw ErrorUtilities.ThrowInternal("Unexpected response type.");
+ }
+
+ response.AuthorizingUsername = userName;
+
+ // Customize the approved scope if the authorization server has decided to do so.
+ if (scopes != null) {
+ response.Scope.ResetContents(scopes);
+ }
+
+ return response;
+ }
+
+ /// <summary>
+ /// Prepares the response to an access token request.
+ /// </summary>
+ /// <param name="request">The request for an access token.</param>
+ /// <param name="includeRefreshToken">If set to <c>true</c>, the response will include a long-lived refresh token.</param>
+ /// <returns>The response message to send to the client.</returns>
+ public virtual IDirectResponseProtocolMessage PrepareAccessTokenResponse(AccessTokenRequestBase request, bool includeRefreshToken = true) {
+ Requires.NotNull(request, "request");
+
+ var tokenRequest = (IAuthorizationCarryingRequest)request;
+ var response = new AccessTokenSuccessResponse(request) {
+ Lifetime = this.AuthorizationServerServices.GetAccessTokenLifetime(request),
+ HasRefreshToken = includeRefreshToken,
+ };
+ response.Scope.ResetContents(tokenRequest.AuthorizationDescription.Scope);
+ return response;
+ }
+
+ /// <summary>
+ /// Gets the redirect URL to use for a particular authorization request.
+ /// </summary>
+ /// <param name="authorizationRequest">The authorization request.</param>
+ /// <returns>The URL to redirect to. Never <c>null</c>.</returns>
+ /// <exception cref="ProtocolException">Thrown if no callback URL could be determined.</exception>
+ protected Uri GetCallback(EndUserAuthorizationRequest authorizationRequest) {
+ Requires.NotNull(authorizationRequest, "authorizationRequest");
+ Contract.Ensures(Contract.Result<Uri>() != null);
+
+ var client = this.AuthorizationServerServices.GetClientOrThrow(authorizationRequest.ClientIdentifier);
+
+ // Prefer a request-specific callback to the pre-registered one (if any).
+ if (authorizationRequest.Callback != null) {
+ // The OAuth channel has already validated the callback parameter against
+ // the authorization server's whitelist for this client.
+ return authorizationRequest.Callback;
+ }
+
+ // Since the request didn't include a callback URL, look up the callback from
+ // the client's preregistration with this authorization server.
+ Uri defaultCallback = client.DefaultCallback;
+ ErrorUtilities.VerifyProtocol(defaultCallback != null, OAuthStrings.NoCallback);
+ return defaultCallback;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2.AuthorizationServer/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..54db6cf
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/Properties/AssemblyInfo.cs
@@ -0,0 +1,54 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssemblyInfo.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+// We DON'T put an AssemblyVersionAttribute in here because it is generated in the build.
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Net;
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Security.Permissions;
+using System.Web.UI;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("DotNetOpenAuth OAuth 2.0")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DotNetOpenAuth")]
+[assembly: AssemblyCopyright("Copyright © 2008")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+[assembly: NeutralResourcesLanguage("en-US")]
+[assembly: CLSCompliant(true)]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("7d73990c-47c0-4256-9f20-a893add9e289")]
+
+[assembly: ContractVerification(true)]
+
+#if StrongNameSigned
+// See comment at top of this file. We need this so that strong-naming doesn't
+// keep this assembly from being useful to shared host (medium trust) web sites.
+[assembly: AllowPartiallyTrustedCallers]
+
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
+#else
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
+#endif
diff --git a/src/DotNetOpenAuth.OAuth2.Client.UI/DotNetOpenAuth.OAuth2.Client.UI.csproj b/src/DotNetOpenAuth.OAuth2.Client.UI/DotNetOpenAuth.OAuth2.Client.UI.csproj
new file mode 100644
index 0000000..7c35a50
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2.Client.UI/DotNetOpenAuth.OAuth2.Client.UI.csproj
@@ -0,0 +1,55 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))\EnlistmentInfo.props" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))' != '' " />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" />
+ <PropertyGroup>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{ADC2CC8C-541E-4F86-ACB1-DD504A36FA4B}</ProjectGuid>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <AssemblyName>DotNetOpenAuth.OAuth2.Client.UI</AssemblyName>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" />
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="OAuth2\ClientAuthorizationView.cs">
+ <SubType>UserControl</SubType>
+ </Compile>
+ <Compile Include="OAuth2\ClientAuthorizationView.Designer.cs">
+ <DependentUpon>ClientAuthorizationView.cs</DependentUpon>
+ </Compile>
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\DotNetOpenAuth.Core\DotNetOpenAuth.Core.csproj">
+ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project>
+ <Name>DotNetOpenAuth.Core</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OAuth2.Client\DotNetOpenAuth.OAuth2.Client.csproj">
+ <Project>{CDEDD439-7F35-4E6E-8605-4E70BDC4CC99}</Project>
+ <Name>DotNetOpenAuth.OAuth2.Client</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OAuth2\DotNetOpenAuth.OAuth2.csproj">
+ <Project>{56459A6C-6BA2-4BAC-A9C0-27E3BD961FA6}</Project>
+ <Name>DotNetOpenAuth.OAuth2</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OAuth\DotNetOpenAuth.OAuth.csproj">
+ <Project>{A288FCC8-6FCF-46DA-A45E-5F9281556361}</Project>
+ <Name>DotNetOpenAuth.OAuth</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <ItemGroup>
+ <EmbeddedResource Include="OAuth2\ClientAuthorizationView.resx">
+ <DependentUpon>ClientAuthorizationView.cs</DependentUpon>
+ </EmbeddedResource>
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
+</Project> \ No newline at end of file
diff --git a/src/DotNetOpenAuth.OAuth2.Client.UI/OAuth2/ClientAuthorizationView.Designer.cs b/src/DotNetOpenAuth.OAuth2.Client.UI/OAuth2/ClientAuthorizationView.Designer.cs
new file mode 100644
index 0000000..c05a4b8
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2.Client.UI/OAuth2/ClientAuthorizationView.Designer.cs
@@ -0,0 +1,56 @@
+namespace DotNetOpenAuth.OAuth2 {
+ partial class ClientAuthorizationView {
+ /// <summary>
+ /// Required designer variable.
+ /// </summary>
+ private System.ComponentModel.IContainer components = null;
+
+ /// <summary>
+ /// Clean up any resources being used.
+ /// </summary>
+ /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
+ protected override void Dispose(bool disposing) {
+ if (disposing && (components != null)) {
+ components.Dispose();
+ }
+ base.Dispose(disposing);
+ }
+
+ #region Component Designer generated code
+
+ /// <summary>
+ /// Required method for Designer support - do not modify
+ /// the contents of this method with the code editor.
+ /// </summary>
+ private void InitializeComponent() {
+ this.webBrowser1 = new System.Windows.Forms.WebBrowser();
+ this.SuspendLayout();
+ //
+ // webBrowser1
+ //
+ this.webBrowser1.AllowWebBrowserDrop = false;
+ this.webBrowser1.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.webBrowser1.IsWebBrowserContextMenuEnabled = false;
+ this.webBrowser1.Location = new System.Drawing.Point(0, 0);
+ this.webBrowser1.Name = "webBrowser1";
+ this.webBrowser1.Size = new System.Drawing.Size(150, 150);
+ this.webBrowser1.TabIndex = 0;
+ this.webBrowser1.Navigated += new System.Windows.Forms.WebBrowserNavigatedEventHandler(this.WebBrowser1_Navigated);
+ this.webBrowser1.Navigating += new System.Windows.Forms.WebBrowserNavigatingEventHandler(this.WebBrowser1_Navigating);
+ this.webBrowser1.LocationChanged += new System.EventHandler(this.WebBrowser1_LocationChanged);
+ //
+ // ClientAuthorizationView
+ //
+ this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
+ this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
+ this.Controls.Add(this.webBrowser1);
+ this.Name = "ClientAuthorizationView";
+ this.ResumeLayout(false);
+
+ }
+
+ #endregion
+
+ private System.Windows.Forms.WebBrowser webBrowser1;
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2.Client.UI/OAuth2/ClientAuthorizationView.cs b/src/DotNetOpenAuth.OAuth2.Client.UI/OAuth2/ClientAuthorizationView.cs
new file mode 100644
index 0000000..acd8fb3
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2.Client.UI/OAuth2/ClientAuthorizationView.cs
@@ -0,0 +1,192 @@
+//-----------------------------------------------------------------------
+// <copyright file="ClientAuthorizationView.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.ComponentModel;
+ using System.Data;
+ using System.Diagnostics.Contracts;
+ using System.Drawing;
+ using System.Linq;
+ using System.Text;
+ using System.Windows.Forms;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A WinForms control that hosts a mini-browser for hosting by native applications to
+ /// allow the user to authorize the client without leaving the application.
+ /// </summary>
+ public partial class ClientAuthorizationView : UserControl {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ClientAuthorizationView"/> class.
+ /// </summary>
+ public ClientAuthorizationView() {
+ this.InitializeComponent();
+
+ this.Authorization = new AuthorizationState();
+ }
+
+ /// <summary>
+ /// Occurs when the authorization flow has completed.
+ /// </summary>
+ public event EventHandler<ClientAuthorizationCompleteEventArgs> Completed;
+
+ /// <summary>
+ /// Gets the authorization tracking object.
+ /// </summary>
+ public IAuthorizationState Authorization { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the client used to coordinate the authorization flow.
+ /// </summary>
+ public UserAgentClient Client { get; set; }
+
+ /// <summary>
+ /// Gets the set of scopes that describe the requested level of access.
+ /// </summary>
+ public HashSet<string> Scope {
+ get { return this.Authorization.Scope; }
+ }
+
+ /// <summary>
+ /// Gets or sets the callback URL used to indicate the flow has completed.
+ /// </summary>
+ public Uri Callback {
+ get { return this.Authorization.Callback; }
+ set { this.Authorization.Callback = value; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the authorization flow has been completed.
+ /// </summary>
+ public bool IsCompleted {
+ get { return this.Authorization == null || this.Authorization.AccessToken != null; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether authorization has been granted.
+ /// </summary>
+ /// <value>Null if <see cref="IsCompleted"/> is <c>false</c></value>
+ public bool? IsGranted {
+ get {
+ if (this.Authorization == null) {
+ return false;
+ }
+
+ return this.Authorization.AccessToken != null ? (bool?)true : null;
+ }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether authorization has been rejected.
+ /// </summary>
+ /// <value>Null if <see cref="IsCompleted"/> is <c>false</c></value>
+ public bool? IsRejected {
+ get {
+ bool? granted = this.IsGranted;
+ return granted.HasValue ? (bool?)(!granted.Value) : null;
+ }
+ }
+
+ /// <summary>
+ /// Called when the authorization flow has been completed.
+ /// </summary>
+ protected virtual void OnCompleted() {
+ var completed = this.Completed;
+ if (completed != null) {
+ completed(this, new ClientAuthorizationCompleteEventArgs(this.Authorization));
+ }
+ }
+
+ /// <summary>
+ /// Raises the <see cref="E:System.Windows.Forms.UserControl.Load"/> event.
+ /// </summary>
+ /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
+ protected override void OnLoad(EventArgs e) {
+ base.OnLoad(e);
+
+ Uri authorizationUrl = this.Client.RequestUserAuthorization(this.Authorization);
+ this.webBrowser1.Navigate(authorizationUrl.AbsoluteUri); // use AbsoluteUri to workaround bug in WebBrowser that calls Uri.ToString instead of Uri.AbsoluteUri leading to escaping errors.
+ }
+
+ /// <summary>
+ /// Tests whether two URLs are equal for purposes of detecting the conclusion of authorization.
+ /// </summary>
+ /// <param name="location1">The first location.</param>
+ /// <param name="location2">The second location.</param>
+ /// <param name="components">The components to compare.</param>
+ /// <returns><c>true</c> if the given components are equal.</returns>
+ private static bool SignificantlyEqual(Uri location1, Uri location2, UriComponents components) {
+ string value1 = location1.GetComponents(components, UriFormat.Unescaped);
+ string value2 = location2.GetComponents(components, UriFormat.Unescaped);
+ return string.Equals(value1, value2, StringComparison.Ordinal);
+ }
+
+ /// <summary>
+ /// Handles the Navigating event of the webBrowser1 control.
+ /// </summary>
+ /// <param name="sender">The source of the event.</param>
+ /// <param name="e">The <see cref="System.Windows.Forms.WebBrowserNavigatingEventArgs"/> instance containing the event data.</param>
+ private void WebBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e) {
+ this.ProcessLocationChanged(e.Url);
+ }
+
+ /// <summary>
+ /// Processes changes in the URL the browser has navigated to.
+ /// </summary>
+ /// <param name="location">The location.</param>
+ private void ProcessLocationChanged(Uri location) {
+ if (SignificantlyEqual(location, this.Authorization.Callback, UriComponents.SchemeAndServer | UriComponents.Path)) {
+ try {
+ this.Client.ProcessUserAuthorization(location, this.Authorization);
+ } catch (ProtocolException ex) {
+ MessageBox.Show(ex.ToStringDescriptive());
+ } finally {
+ this.OnCompleted();
+ }
+ }
+ }
+
+ /// <summary>
+ /// Handles the Navigated event of the webBrowser1 control.
+ /// </summary>
+ /// <param name="sender">The source of the event.</param>
+ /// <param name="e">The <see cref="System.Windows.Forms.WebBrowserNavigatedEventArgs"/> instance containing the event data.</param>
+ private void WebBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e) {
+ this.ProcessLocationChanged(e.Url);
+ }
+
+ /// <summary>
+ /// Handles the LocationChanged event of the webBrowser1 control.
+ /// </summary>
+ /// <param name="sender">The source of the event.</param>
+ /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
+ private void WebBrowser1_LocationChanged(object sender, EventArgs e) {
+ this.ProcessLocationChanged(this.webBrowser1.Url);
+ }
+
+ /// <summary>
+ /// Describes the results of a completed authorization flow.
+ /// </summary>
+ public class ClientAuthorizationCompleteEventArgs : EventArgs {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ClientAuthorizationCompleteEventArgs"/> class.
+ /// </summary>
+ /// <param name="authorization">The authorization.</param>
+ public ClientAuthorizationCompleteEventArgs(IAuthorizationState authorization) {
+ Requires.NotNull(authorization, "authorization");
+ this.Authorization = authorization;
+ }
+
+ /// <summary>
+ /// Gets the authorization tracking object.
+ /// </summary>
+ /// <value>Null if authorization was rejected by the user.</value>
+ public IAuthorizationState Authorization { get; private set; }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2.Client.UI/OAuth2/ClientAuthorizationView.resx b/src/DotNetOpenAuth.OAuth2.Client.UI/OAuth2/ClientAuthorizationView.resx
new file mode 100644
index 0000000..7080a7d
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2.Client.UI/OAuth2/ClientAuthorizationView.resx
@@ -0,0 +1,120 @@
+<?xml version="1.0" encoding="utf-8"?>
+<root>
+ <!--
+ Microsoft ResX Schema
+
+ Version 2.0
+
+ The primary goals of this format is to allow a simple XML format
+ that is mostly human readable. The generation and parsing of the
+ various data types are done through the TypeConverter classes
+ associated with the data types.
+
+ Example:
+
+ ... ado.net/XML headers & schema ...
+ <resheader name="resmimetype">text/microsoft-resx</resheader>
+ <resheader name="version">2.0</resheader>
+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+ <value>[base64 mime encoded serialized .NET Framework object]</value>
+ </data>
+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+ <comment>This is a comment</comment>
+ </data>
+
+ There are any number of "resheader" rows that contain simple
+ name/value pairs.
+
+ Each data row contains a name, and value. The row also contains a
+ type or mimetype. Type corresponds to a .NET class that support
+ text/value conversion through the TypeConverter architecture.
+ Classes that don't support this are serialized and stored with the
+ mimetype set.
+
+ The mimetype is used for serialized objects, and tells the
+ ResXResourceReader how to depersist the object. This is currently not
+ extensible. For a given mimetype the value must be set accordingly:
+
+ Note - application/x-microsoft.net.object.binary.base64 is the format
+ that the ResXResourceWriter will generate, however the reader can
+ read any of the formats listed below.
+
+ mimetype: application/x-microsoft.net.object.binary.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.soap.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.bytearray.base64
+ value : The object must be serialized into a byte array
+ : using a System.ComponentModel.TypeConverter
+ : and then encoded with base64 encoding.
+ -->
+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
+ <xsd:element name="root" msdata:IsDataSet="true">
+ <xsd:complexType>
+ <xsd:choice maxOccurs="unbounded">
+ <xsd:element name="metadata">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" />
+ </xsd:sequence>
+ <xsd:attribute name="name" use="required" type="xsd:string" />
+ <xsd:attribute name="type" type="xsd:string" />
+ <xsd:attribute name="mimetype" type="xsd:string" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="assembly">
+ <xsd:complexType>
+ <xsd:attribute name="alias" type="xsd:string" />
+ <xsd:attribute name="name" type="xsd:string" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="data">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="resheader">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" />
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:choice>
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:schema>
+ <resheader name="resmimetype">
+ <value>text/microsoft-resx</value>
+ </resheader>
+ <resheader name="version">
+ <value>2.0</value>
+ </resheader>
+ <resheader name="reader">
+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <resheader name="writer">
+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+</root> \ No newline at end of file
diff --git a/src/DotNetOpenAuth.OAuth2.Client.UI/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth.OAuth2.Client.UI/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..54db6cf
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2.Client.UI/Properties/AssemblyInfo.cs
@@ -0,0 +1,54 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssemblyInfo.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+// We DON'T put an AssemblyVersionAttribute in here because it is generated in the build.
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Net;
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Security.Permissions;
+using System.Web.UI;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("DotNetOpenAuth OAuth 2.0")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DotNetOpenAuth")]
+[assembly: AssemblyCopyright("Copyright © 2008")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+[assembly: NeutralResourcesLanguage("en-US")]
+[assembly: CLSCompliant(true)]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("7d73990c-47c0-4256-9f20-a893add9e289")]
+
+[assembly: ContractVerification(true)]
+
+#if StrongNameSigned
+// See comment at top of this file. We need this so that strong-naming doesn't
+// keep this assembly from being useful to shared host (medium trust) web sites.
+[assembly: AllowPartiallyTrustedCallers]
+
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
+#else
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
+#endif
diff --git a/src/DotNetOpenAuth.OAuth2.Client/DotNetOpenAuth.OAuth2.Client.csproj b/src/DotNetOpenAuth.OAuth2.Client/DotNetOpenAuth.OAuth2.Client.csproj
new file mode 100644
index 0000000..8cfec0e
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2.Client/DotNetOpenAuth.OAuth2.Client.csproj
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))\EnlistmentInfo.props" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))' != '' " />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" />
+ <PropertyGroup>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{CDEDD439-7F35-4E6E-8605-4E70BDC4CC99}</ProjectGuid>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <AssemblyName>DotNetOpenAuth.OAuth2.Client</AssemblyName>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" />
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="OAuth2\UserAgentClient.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ <Compile Include="OAuth2\ClientBase.cs" />
+ <Compile Include="OAuth2\WebServerClient.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\DotNetOpenAuth.Core\DotNetOpenAuth.Core.csproj">
+ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project>
+ <Name>DotNetOpenAuth.Core</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OAuth2\DotNetOpenAuth.OAuth2.csproj">
+ <Project>{56459A6C-6BA2-4BAC-A9C0-27E3BD961FA6}</Project>
+ <Name>DotNetOpenAuth.OAuth2</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OAuth\DotNetOpenAuth.OAuth.csproj">
+ <Project>{A288FCC8-6FCF-46DA-A45E-5F9281556361}</Project>
+ <Name>DotNetOpenAuth.OAuth</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
+</Project> \ No newline at end of file
diff --git a/src/DotNetOpenAuth.OAuth2.Client/OAuth2/ClientBase.cs b/src/DotNetOpenAuth.OAuth2.Client/OAuth2/ClientBase.cs
new file mode 100644
index 0000000..2465182
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2.Client/OAuth2/ClientBase.cs
@@ -0,0 +1,256 @@
+//-----------------------------------------------------------------------
+// <copyright file="ClientBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Globalization;
+ using System.Linq;
+ using System.Net;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+ using DotNetOpenAuth.OAuth2.Messages;
+
+ /// <summary>
+ /// A base class for common OAuth Client behaviors.
+ /// </summary>
+ public class ClientBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ClientBase"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The token issuer.</param>
+ /// <param name="clientIdentifier">The client identifier.</param>
+ /// <param name="clientSecret">The client secret.</param>
+ protected ClientBase(AuthorizationServerDescription authorizationServer, string clientIdentifier = null, string clientSecret = null) {
+ Requires.NotNull(authorizationServer, "authorizationServer");
+ this.AuthorizationServer = authorizationServer;
+ this.Channel = new OAuth2ClientChannel();
+ this.ClientIdentifier = clientIdentifier;
+ this.ClientSecret = clientSecret;
+ }
+
+ /// <summary>
+ /// Gets the token issuer.
+ /// </summary>
+ /// <value>The token issuer.</value>
+ public AuthorizationServerDescription AuthorizationServer { get; private set; }
+
+ /// <summary>
+ /// Gets the OAuth channel.
+ /// </summary>
+ /// <value>The channel.</value>
+ public Channel Channel { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the identifier by which this client is known to the Authorization Server.
+ /// </summary>
+ public string ClientIdentifier { get; set; }
+
+ /// <summary>
+ /// Gets or sets the client secret shared with the Authorization Server.
+ /// </summary>
+ public string ClientSecret { get; set; }
+
+ /// <summary>
+ /// Adds the necessary HTTP Authorization header to an HTTP request for protected resources
+ /// so that the Service Provider will allow the request through.
+ /// </summary>
+ /// <param name="request">The request for protected resources from the service provider.</param>
+ /// <param name="accessToken">The access token previously obtained from the Authorization Server.</param>
+ public static void AuthorizeRequest(HttpWebRequest request, string accessToken) {
+ Requires.NotNull(request, "request");
+ Requires.NotNullOrEmpty(accessToken, "accessToken");
+
+ OAuthUtilities.AuthorizeWithBearerToken(request, accessToken);
+ }
+
+ /// <summary>
+ /// Adds the OAuth authorization token to an outgoing HTTP request, renewing a
+ /// (nearly) expired access token if necessary.
+ /// </summary>
+ /// <param name="request">The request for protected resources from the service provider.</param>
+ /// <param name="authorization">The authorization for this request previously obtained via OAuth.</param>
+ public void AuthorizeRequest(HttpWebRequest request, IAuthorizationState authorization) {
+ Requires.NotNull(request, "request");
+ Requires.NotNull(authorization, "authorization");
+ Requires.True(!string.IsNullOrEmpty(authorization.AccessToken), "authorization");
+ ErrorUtilities.VerifyProtocol(!authorization.AccessTokenExpirationUtc.HasValue || authorization.AccessTokenExpirationUtc < DateTime.UtcNow || authorization.RefreshToken != null, "authorization has expired");
+
+ if (authorization.AccessTokenExpirationUtc.HasValue && authorization.AccessTokenExpirationUtc.Value < DateTime.UtcNow) {
+ ErrorUtilities.VerifyProtocol(authorization.RefreshToken != null, "Access token has expired and cannot be automatically refreshed.");
+ this.RefreshAuthorization(authorization);
+ }
+
+ AuthorizeRequest(request, authorization.AccessToken);
+ }
+
+ /// <summary>
+ /// Refreshes a short-lived access token using a longer-lived refresh token
+ /// with a new access token that has the same scope as the refresh token.
+ /// The refresh token itself may also be refreshed.
+ /// </summary>
+ /// <param name="authorization">The authorization to update.</param>
+ /// <param name="skipIfUsefulLifeExceeds">If given, the access token will <em>not</em> be refreshed if its remaining lifetime exceeds this value.</param>
+ /// <returns>A value indicating whether the access token was actually renewed; <c>true</c> if it was renewed, or <c>false</c> if it still had useful life remaining.</returns>
+ /// <remarks>
+ /// This method may modify the value of the <see cref="IAuthorizationState.RefreshToken"/> property on
+ /// the <paramref name="authorization"/> parameter if the authorization server has cycled out your refresh token.
+ /// If the parameter value was updated, this method calls <see cref="IAuthorizationState.SaveChanges"/> on that instance.
+ /// </remarks>
+ public bool RefreshAuthorization(IAuthorizationState authorization, TimeSpan? skipIfUsefulLifeExceeds = null) {
+ Requires.NotNull(authorization, "authorization");
+ Requires.True(!string.IsNullOrEmpty(authorization.RefreshToken), "authorization");
+
+ if (skipIfUsefulLifeExceeds.HasValue && authorization.AccessTokenExpirationUtc.HasValue) {
+ TimeSpan usefulLifeRemaining = authorization.AccessTokenExpirationUtc.Value - DateTime.UtcNow;
+ if (usefulLifeRemaining > skipIfUsefulLifeExceeds.Value) {
+ // There is useful life remaining in the access token. Don't refresh.
+ Logger.OAuth.DebugFormat("Skipping token refresh step because access token's remaining life is {0}, which exceeds {1}.", usefulLifeRemaining, skipIfUsefulLifeExceeds.Value);
+ return false;
+ }
+ }
+
+ var request = new AccessTokenRefreshRequest(this.AuthorizationServer) {
+ ClientIdentifier = this.ClientIdentifier,
+ ClientSecret = this.ClientSecret,
+ RefreshToken = authorization.RefreshToken,
+ };
+
+ var response = this.Channel.Request<AccessTokenSuccessResponse>(request);
+ UpdateAuthorizationWithResponse(authorization, response);
+ return true;
+ }
+
+ /// <summary>
+ /// Gets an access token that may be used for only a subset of the scope for which a given
+ /// refresh token is authorized.
+ /// </summary>
+ /// <param name="refreshToken">The refresh token.</param>
+ /// <param name="scope">The scope subset desired in the access token.</param>
+ /// <returns>A description of the obtained access token, and possibly a new refresh token.</returns>
+ /// <remarks>
+ /// If the return value includes a new refresh token, the old refresh token should be discarded and
+ /// replaced with the new one.
+ /// </remarks>
+ public IAuthorizationState GetScopedAccessToken(string refreshToken, HashSet<string> scope) {
+ Requires.NotNullOrEmpty(refreshToken, "refreshToken");
+ Requires.NotNull(scope, "scope");
+ Contract.Ensures(Contract.Result<IAuthorizationState>() != null);
+
+ var request = new AccessTokenRefreshRequest(this.AuthorizationServer) {
+ ClientIdentifier = this.ClientIdentifier,
+ ClientSecret = this.ClientSecret,
+ RefreshToken = refreshToken,
+ };
+
+ var response = this.Channel.Request<AccessTokenSuccessResponse>(request);
+ var authorization = new AuthorizationState();
+ UpdateAuthorizationWithResponse(authorization, response);
+
+ return authorization;
+ }
+
+ /// <summary>
+ /// Updates the authorization state maintained by the client with the content of an outgoing response.
+ /// </summary>
+ /// <param name="authorizationState">The authorization state maintained by the client.</param>
+ /// <param name="accessTokenSuccess">The access token containing response message.</param>
+ internal static void UpdateAuthorizationWithResponse(IAuthorizationState authorizationState, AccessTokenSuccessResponse accessTokenSuccess) {
+ Requires.NotNull(authorizationState, "authorizationState");
+ Requires.NotNull(accessTokenSuccess, "accessTokenSuccess");
+
+ authorizationState.AccessToken = accessTokenSuccess.AccessToken;
+ authorizationState.AccessTokenExpirationUtc = DateTime.UtcNow + accessTokenSuccess.Lifetime;
+ authorizationState.AccessTokenIssueDateUtc = DateTime.UtcNow;
+
+ // The authorization server MAY choose to renew the refresh token itself.
+ if (accessTokenSuccess.RefreshToken != null) {
+ authorizationState.RefreshToken = accessTokenSuccess.RefreshToken;
+ }
+
+ // An included scope parameter in the response only describes the access token's scope.
+ // Don't update the whole authorization state object with that scope because that represents
+ // the refresh token's original scope.
+ if ((authorizationState.Scope == null || authorizationState.Scope.Count == 0) && accessTokenSuccess.Scope != null) {
+ authorizationState.Scope.ResetContents(accessTokenSuccess.Scope);
+ }
+
+ authorizationState.SaveChanges();
+ }
+
+ /// <summary>
+ /// Updates the authorization state maintained by the client with the content of an outgoing response.
+ /// </summary>
+ /// <param name="authorizationState">The authorization state maintained by the client.</param>
+ /// <param name="accessTokenSuccess">The access token containing response message.</param>
+ internal static void UpdateAuthorizationWithResponse(IAuthorizationState authorizationState, EndUserAuthorizationSuccessAccessTokenResponse accessTokenSuccess) {
+ Requires.NotNull(authorizationState, "authorizationState");
+ Requires.NotNull(accessTokenSuccess, "accessTokenSuccess");
+
+ authorizationState.AccessToken = accessTokenSuccess.AccessToken;
+ authorizationState.AccessTokenExpirationUtc = DateTime.UtcNow + accessTokenSuccess.Lifetime;
+ authorizationState.AccessTokenIssueDateUtc = DateTime.UtcNow;
+ if (accessTokenSuccess.Scope != null && accessTokenSuccess.Scope != authorizationState.Scope) {
+ if (authorizationState.Scope != null) {
+ Logger.OAuth.InfoFormat(
+ "Requested scope of \"{0}\" changed to \"{1}\" by authorization server.",
+ authorizationState.Scope,
+ accessTokenSuccess.Scope);
+ }
+
+ authorizationState.Scope.ResetContents(accessTokenSuccess.Scope);
+ }
+
+ authorizationState.SaveChanges();
+ }
+
+ /// <summary>
+ /// Updates authorization state with a success response from the Authorization Server.
+ /// </summary>
+ /// <param name="authorizationState">The authorization state to update.</param>
+ /// <param name="authorizationSuccess">The authorization success message obtained from the authorization server.</param>
+ internal void UpdateAuthorizationWithResponse(IAuthorizationState authorizationState, EndUserAuthorizationSuccessAuthCodeResponse authorizationSuccess) {
+ Requires.NotNull(authorizationState, "authorizationState");
+ Requires.NotNull(authorizationSuccess, "authorizationSuccess");
+
+ var accessTokenRequest = new AccessTokenAuthorizationCodeRequest(this.AuthorizationServer) {
+ ClientIdentifier = this.ClientIdentifier,
+ ClientSecret = this.ClientSecret,
+ Callback = authorizationState.Callback,
+ AuthorizationCode = authorizationSuccess.AuthorizationCode,
+ };
+ IProtocolMessage accessTokenResponse = this.Channel.Request(accessTokenRequest);
+ var accessTokenSuccess = accessTokenResponse as AccessTokenSuccessResponse;
+ var failedAccessTokenResponse = accessTokenResponse as AccessTokenFailedResponse;
+ if (accessTokenSuccess != null) {
+ UpdateAuthorizationWithResponse(authorizationState, accessTokenSuccess);
+ } else {
+ authorizationState.Delete();
+ string error = failedAccessTokenResponse != null ? failedAccessTokenResponse.Error : "(unknown)";
+ ErrorUtilities.ThrowProtocol(OAuthStrings.CannotObtainAccessTokenWithReason, error);
+ }
+ }
+
+ /// <summary>
+ /// Calculates the fraction of life remaining in an access token.
+ /// </summary>
+ /// <param name="authorization">The authorization to measure.</param>
+ /// <returns>A fractional number no greater than 1. Could be negative if the access token has already expired.</returns>
+ private static double ProportionalLifeRemaining(IAuthorizationState authorization) {
+ Requires.NotNull(authorization, "authorization");
+ Requires.True(authorization.AccessTokenIssueDateUtc.HasValue, "authorization");
+ Requires.True(authorization.AccessTokenExpirationUtc.HasValue, "authorization");
+
+ // Calculate what % of the total life this access token has left.
+ TimeSpan totalLifetime = authorization.AccessTokenExpirationUtc.Value - authorization.AccessTokenIssueDateUtc.Value;
+ TimeSpan elapsedLifetime = DateTime.UtcNow - authorization.AccessTokenIssueDateUtc.Value;
+ double proportionLifetimeRemaining = 1 - (elapsedLifetime.TotalSeconds / totalLifetime.TotalSeconds);
+ return proportionLifetimeRemaining;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2.Client/OAuth2/UserAgentClient.cs b/src/DotNetOpenAuth.OAuth2.Client/OAuth2/UserAgentClient.cs
new file mode 100644
index 0000000..d452525
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2.Client/OAuth2/UserAgentClient.cs
@@ -0,0 +1,123 @@
+//-----------------------------------------------------------------------
+// <copyright file="UserAgentClient.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.Messages;
+
+ /// <summary>
+ /// The OAuth client for the user-agent flow, providing services for installed apps
+ /// and in-browser Javascript widgets.
+ /// </summary>
+ public class UserAgentClient : ClientBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserAgentClient"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The token issuer.</param>
+ /// <param name="clientIdentifier">The client identifier.</param>
+ /// <param name="clientSecret">The client secret.</param>
+ public UserAgentClient(AuthorizationServerDescription authorizationServer, string clientIdentifier = null, string clientSecret = null)
+ : base(authorizationServer, clientIdentifier, clientSecret) {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserAgentClient"/> class.
+ /// </summary>
+ /// <param name="authorizationEndpoint">The authorization endpoint.</param>
+ /// <param name="tokenEndpoint">The token endpoint.</param>
+ /// <param name="clientIdentifier">The client identifier.</param>
+ /// <param name="clientSecret">The client secret.</param>
+ public UserAgentClient(Uri authorizationEndpoint, Uri tokenEndpoint, string clientIdentifier = null, string clientSecret = null)
+ : this(new AuthorizationServerDescription { AuthorizationEndpoint = authorizationEndpoint, TokenEndpoint = tokenEndpoint }, clientIdentifier, clientSecret) {
+ Requires.NotNull(authorizationEndpoint, "authorizationEndpoint");
+ Requires.NotNull(tokenEndpoint, "tokenEndpoint");
+ }
+
+ /// <summary>
+ /// Generates a URL that the user's browser can be directed to in order to authorize
+ /// this client to access protected data at some resource server.
+ /// </summary>
+ /// <param name="scope">The scope of authorized access requested.</param>
+ /// <param name="state">The client state that should be returned with the authorization response.</param>
+ /// <param name="returnTo">The URL that the authorization response should be sent to via a user-agent redirect.</param>
+ /// <returns>
+ /// A fully-qualified URL suitable to initiate the authorization flow.
+ /// </returns>
+ public Uri RequestUserAuthorization(IEnumerable<string> scope = null, string state = null, Uri returnTo = null) {
+ var authorization = new AuthorizationState(scope) {
+ Callback = returnTo,
+ };
+
+ return this.RequestUserAuthorization(authorization);
+ }
+
+ /// <summary>
+ /// Generates a URL that the user's browser can be directed to in order to authorize
+ /// this client to access protected data at some resource server.
+ /// </summary>
+ /// <param name="authorization">The authorization state that is tracking this particular request. Optional.</param>
+ /// <param name="state">The client state that should be returned with the authorization response.</param>
+ /// <returns>
+ /// A fully-qualified URL suitable to initiate the authorization flow.
+ /// </returns>
+ public Uri RequestUserAuthorization(IAuthorizationState authorization, string state = null) {
+ Requires.NotNull(authorization, "authorization");
+ Requires.ValidState(!string.IsNullOrEmpty(this.ClientIdentifier));
+
+ if (authorization.Callback == null) {
+ authorization.Callback = new Uri("http://localhost/");
+ }
+
+ var request = new EndUserAuthorizationRequest(this.AuthorizationServer) {
+ ClientIdentifier = this.ClientIdentifier,
+ Callback = authorization.Callback,
+ ClientState = state,
+ };
+ request.Scope.ResetContents(authorization.Scope);
+
+ return this.Channel.PrepareResponse(request).GetDirectUriRequest(this.Channel);
+ }
+
+ /// <summary>
+ /// Scans the incoming request for an authorization response message.
+ /// </summary>
+ /// <param name="actualRedirectUrl">The actual URL of the incoming HTTP request.</param>
+ /// <param name="authorizationState">The authorization.</param>
+ /// <returns>The granted authorization, or <c>null</c> if the incoming HTTP request did not contain an authorization server response or authorization was rejected.</returns>
+ public IAuthorizationState ProcessUserAuthorization(Uri actualRedirectUrl, IAuthorizationState authorizationState = null) {
+ Requires.NotNull(actualRedirectUrl, "actualRedirectUrl");
+
+ if (authorizationState == null) {
+ authorizationState = new AuthorizationState();
+ }
+
+ var carrier = new HttpRequestInfo("GET", actualRedirectUrl, actualRedirectUrl.PathAndQuery, new System.Net.WebHeaderCollection(), null);
+ IDirectedProtocolMessage response = this.Channel.ReadFromRequest(carrier);
+ if (response == null) {
+ return null;
+ }
+
+ EndUserAuthorizationSuccessAccessTokenResponse accessTokenSuccess;
+ EndUserAuthorizationSuccessAuthCodeResponse authCodeSuccess;
+ EndUserAuthorizationFailedResponse failure;
+ if ((accessTokenSuccess = response as EndUserAuthorizationSuccessAccessTokenResponse) != null) {
+ UpdateAuthorizationWithResponse(authorizationState, accessTokenSuccess);
+ } else if ((authCodeSuccess = response as EndUserAuthorizationSuccessAuthCodeResponse) != null) {
+ this.UpdateAuthorizationWithResponse(authorizationState, authCodeSuccess);
+ } else if ((failure = response as EndUserAuthorizationFailedResponse) != null) {
+ authorizationState.Delete();
+ return null;
+ }
+
+ return authorizationState;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2.Client/OAuth2/WebServerClient.cs b/src/DotNetOpenAuth.OAuth2.Client/OAuth2/WebServerClient.cs
new file mode 100644
index 0000000..4f793a5
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2.Client/OAuth2/WebServerClient.cs
@@ -0,0 +1,130 @@
+//-----------------------------------------------------------------------
+// <copyright file="WebServerClient.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Net;
+ using System.Text;
+ using System.Web;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.Messages;
+
+ /// <summary>
+ /// An OAuth 2.0 consumer designed for web applications.
+ /// </summary>
+ public class WebServerClient : ClientBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="WebServerClient"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ /// <param name="clientIdentifier">The client identifier.</param>
+ /// <param name="clientSecret">The client secret.</param>
+ public WebServerClient(AuthorizationServerDescription authorizationServer, string clientIdentifier = null, string clientSecret = null)
+ : base(authorizationServer, clientIdentifier, clientSecret) {
+ }
+
+ /// <summary>
+ /// Gets or sets an optional component that gives you greater control to record and influence the authorization process.
+ /// </summary>
+ /// <value>The authorization tracker.</value>
+ public IClientAuthorizationTracker AuthorizationTracker { get; set; }
+
+ /// <summary>
+ /// Prepares a request for user authorization from an authorization server.
+ /// </summary>
+ /// <param name="scope">The scope of authorized access requested.</param>
+ /// <param name="state">The state of the client that should be sent back with the authorization response.</param>
+ /// <param name="returnTo">The URL the authorization server should redirect the browser (typically on this site) to when the authorization is completed. If null, the current request's URL will be used.</param>
+ public void RequestUserAuthorization(IEnumerable<string> scope = null, string state = null, Uri returnTo = null) {
+ var authorizationState = new AuthorizationState(scope) {
+ Callback = returnTo,
+ };
+ this.PrepareRequestUserAuthorization(authorizationState, state).Send();
+ }
+
+ /// <summary>
+ /// Prepares a request for user authorization from an authorization server.
+ /// </summary>
+ /// <param name="scopes">The scope of authorized access requested.</param>
+ /// <param name="state">The state of the client that should be sent back with the authorization response.</param>
+ /// <returns>The authorization request.</returns>
+ public OutgoingWebResponse PrepareRequestUserAuthorization(IEnumerable<string> scopes = null, string state = null) {
+ var authorizationState = new AuthorizationState(scopes);
+ return this.PrepareRequestUserAuthorization(authorizationState, state);
+ }
+
+ /// <summary>
+ /// Prepares a request for user authorization from an authorization server.
+ /// </summary>
+ /// <param name="authorization">The authorization state to associate with this particular request.</param>
+ /// <param name="state">The state of the client that should be sent back with the authorization response.</param>
+ /// <returns>The authorization request.</returns>
+ public OutgoingWebResponse PrepareRequestUserAuthorization(IAuthorizationState authorization, string state = null) {
+ Requires.NotNull(authorization, "authorization");
+ Requires.ValidState(authorization.Callback != null || (HttpContext.Current != null && HttpContext.Current.Request != null), MessagingStrings.HttpContextRequired);
+ Requires.ValidState(!string.IsNullOrEmpty(this.ClientIdentifier));
+ Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null);
+
+ if (authorization.Callback == null) {
+ authorization.Callback = this.Channel.GetRequestFromContext().UrlBeforeRewriting
+ .StripMessagePartsFromQueryString(this.Channel.MessageDescriptions.Get(typeof(EndUserAuthorizationSuccessResponseBase), Protocol.Default.Version))
+ .StripMessagePartsFromQueryString(this.Channel.MessageDescriptions.Get(typeof(EndUserAuthorizationFailedResponse), Protocol.Default.Version));
+ authorization.SaveChanges();
+ }
+
+ var request = new EndUserAuthorizationRequest(this.AuthorizationServer) {
+ ClientIdentifier = this.ClientIdentifier,
+ Callback = authorization.Callback,
+ ClientState = state,
+ };
+ request.Scope.ResetContents(authorization.Scope);
+
+ return this.Channel.PrepareResponse(request);
+ }
+
+ /// <summary>
+ /// Processes the authorization response from an authorization server, if available.
+ /// </summary>
+ /// <param name="request">The incoming HTTP request that may carry an authorization response.</param>
+ /// <returns>The authorization state that contains the details of the authorization.</returns>
+ public IAuthorizationState ProcessUserAuthorization(HttpRequestInfo request = null) {
+ Requires.ValidState(!string.IsNullOrEmpty(this.ClientIdentifier));
+ Requires.ValidState(!string.IsNullOrEmpty(this.ClientSecret));
+
+ if (request == null) {
+ request = this.Channel.GetRequestFromContext();
+ }
+
+ IMessageWithClientState response;
+ if (this.Channel.TryReadFromRequest<IMessageWithClientState>(request, out response)) {
+ Uri callback = MessagingUtilities.StripMessagePartsFromQueryString(request.UrlBeforeRewriting, this.Channel.MessageDescriptions.Get(response));
+ IAuthorizationState authorizationState;
+ if (this.AuthorizationTracker != null) {
+ authorizationState = this.AuthorizationTracker.GetAuthorizationState(callback, response.ClientState);
+ ErrorUtilities.VerifyProtocol(authorizationState != null, "Unexpected OAuth authorization response received with callback and client state that does not match an expected value.");
+ } else {
+ authorizationState = new AuthorizationState { Callback = callback };
+ }
+ var success = response as EndUserAuthorizationSuccessAuthCodeResponse;
+ var failure = response as EndUserAuthorizationFailedResponse;
+ ErrorUtilities.VerifyProtocol(success != null || failure != null, MessagingStrings.UnexpectedMessageReceivedOfMany);
+ if (success != null) {
+ this.UpdateAuthorizationWithResponse(authorizationState, success);
+ } else { // failure
+ Logger.OAuth.Info("User refused to grant the requested authorization at the Authorization Server.");
+ authorizationState.Delete();
+ }
+
+ return authorizationState;
+ }
+
+ return null;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2.Client/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth.OAuth2.Client/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..54db6cf
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2.Client/Properties/AssemblyInfo.cs
@@ -0,0 +1,54 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssemblyInfo.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+// We DON'T put an AssemblyVersionAttribute in here because it is generated in the build.
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Net;
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Security.Permissions;
+using System.Web.UI;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("DotNetOpenAuth OAuth 2.0")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DotNetOpenAuth")]
+[assembly: AssemblyCopyright("Copyright © 2008")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+[assembly: NeutralResourcesLanguage("en-US")]
+[assembly: CLSCompliant(true)]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("7d73990c-47c0-4256-9f20-a893add9e289")]
+
+[assembly: ContractVerification(true)]
+
+#if StrongNameSigned
+// See comment at top of this file. We need this so that strong-naming doesn't
+// keep this assembly from being useful to shared host (medium trust) web sites.
+[assembly: AllowPartiallyTrustedCallers]
+
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
+#else
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
+#endif
diff --git a/src/DotNetOpenAuth.OAuth2.ResourceServer/DotNetOpenAuth.OAuth2.ResourceServer.csproj b/src/DotNetOpenAuth.OAuth2.ResourceServer/DotNetOpenAuth.OAuth2.ResourceServer.csproj
new file mode 100644
index 0000000..43c478b
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2.ResourceServer/DotNetOpenAuth.OAuth2.ResourceServer.csproj
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))\EnlistmentInfo.props" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))' != '' " />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" />
+ <PropertyGroup>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{A1A3150A-7B0E-4A34-8E35-045296CD3C76}</ProjectGuid>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <AssemblyName>DotNetOpenAuth.OAuth2.ResourceServer</AssemblyName>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" />
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="OAuth2\ResourceServer.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\DotNetOpenAuth.Core\DotNetOpenAuth.Core.csproj">
+ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project>
+ <Name>DotNetOpenAuth.Core</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OAuth.ServiceProvider\DotNetOpenAuth.OAuth.ServiceProvider.csproj">
+ <Project>{FED1923A-6D70-49B5-A37A-FB744FEC1C86}</Project>
+ <Name>DotNetOpenAuth.OAuth.ServiceProvider</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OAuth2\DotNetOpenAuth.OAuth2.csproj">
+ <Project>{56459A6C-6BA2-4BAC-A9C0-27E3BD961FA6}</Project>
+ <Name>DotNetOpenAuth.OAuth2</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
+</Project> \ No newline at end of file
diff --git a/src/DotNetOpenAuth.OAuth2.ResourceServer/OAuth2/ResourceServer.cs b/src/DotNetOpenAuth.OAuth2.ResourceServer/OAuth2/ResourceServer.cs
new file mode 100644
index 0000000..927a6ed
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2.ResourceServer/OAuth2/ResourceServer.cs
@@ -0,0 +1,136 @@
+//-----------------------------------------------------------------------
+// <copyright file="ResourceServer.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Net;
+ using System.Security.Principal;
+ using System.ServiceModel.Channels;
+ using System.Text;
+ using System.Text.RegularExpressions;
+ using System.Web;
+ using ChannelElements;
+ using Messages;
+ using Messaging;
+
+ /// <summary>
+ /// Provides services for validating OAuth access tokens.
+ /// </summary>
+ public class ResourceServer {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ResourceServer"/> class.
+ /// </summary>
+ /// <param name="accessTokenAnalyzer">The access token analyzer.</param>
+ public ResourceServer(IAccessTokenAnalyzer accessTokenAnalyzer) {
+ Requires.NotNull(accessTokenAnalyzer, "accessTokenAnalyzer");
+
+ this.AccessTokenAnalyzer = accessTokenAnalyzer;
+ this.Channel = new OAuth2ResourceServerChannel();
+ }
+
+ /// <summary>
+ /// Gets the access token analyzer.
+ /// </summary>
+ /// <value>The access token analyzer.</value>
+ public IAccessTokenAnalyzer AccessTokenAnalyzer { get; private set; }
+
+ /// <summary>
+ /// Gets the channel.
+ /// </summary>
+ /// <value>The channel.</value>
+ internal OAuth2ResourceServerChannel Channel { get; private set; }
+
+ /// <summary>
+ /// Discovers what access the client should have considering the access token in the current request.
+ /// </summary>
+ /// <param name="userName">The name on the account the client has access to.</param>
+ /// <param name="scope">The set of operations the client is authorized for.</param>
+ /// <returns>An error to return to the client if access is not authorized; <c>null</c> if access is granted.</returns>
+ [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Try pattern")]
+ [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#", Justification = "Try pattern")]
+ public OutgoingWebResponse VerifyAccess(out string userName, out HashSet<string> scope) {
+ return this.VerifyAccess(this.Channel.GetRequestFromContext(), out userName, out scope);
+ }
+
+ /// <summary>
+ /// Discovers what access the client should have considering the access token in the current request.
+ /// </summary>
+ /// <param name="httpRequestInfo">The HTTP request info.</param>
+ /// <param name="userName">The name on the account the client has access to.</param>
+ /// <param name="scope">The set of operations the client is authorized for.</param>
+ /// <returns>
+ /// An error to return to the client if access is not authorized; <c>null</c> if access is granted.
+ /// </returns>
+ [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#", Justification = "Try pattern")]
+ [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification = "Try pattern")]
+ public virtual OutgoingWebResponse VerifyAccess(HttpRequestInfo httpRequestInfo, out string userName, out HashSet<string> scope) {
+ Requires.NotNull(httpRequestInfo, "httpRequestInfo");
+
+ AccessProtectedResourceRequest request = null;
+ try {
+ if (this.Channel.TryReadFromRequest<AccessProtectedResourceRequest>(httpRequestInfo, out request)) {
+ if (this.AccessTokenAnalyzer.TryValidateAccessToken(request, request.AccessToken, out userName, out scope)) {
+ // No errors to return.
+ return null;
+ }
+
+ throw ErrorUtilities.ThrowProtocol("Bad access token");
+ } else {
+ var response = new UnauthorizedResponse(new ProtocolException("Missing access token"));
+
+ userName = null;
+ scope = null;
+ return this.Channel.PrepareResponse(response);
+ }
+ } catch (ProtocolException ex) {
+ var response = request != null ? new UnauthorizedResponse(request, ex) : new UnauthorizedResponse(ex);
+
+ userName = null;
+ scope = null;
+ return this.Channel.PrepareResponse(response);
+ }
+ }
+
+ /// <summary>
+ /// Discovers what access the client should have considering the access token in the current request.
+ /// </summary>
+ /// <param name="httpRequestInfo">The HTTP request info.</param>
+ /// <param name="principal">The principal that contains the user and roles that the access token is authorized for.</param>
+ /// <returns>
+ /// An error to return to the client if access is not authorized; <c>null</c> if access is granted.
+ /// </returns>
+ [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#", Justification = "Try pattern")]
+ public virtual OutgoingWebResponse VerifyAccess(HttpRequestInfo httpRequestInfo, out IPrincipal principal) {
+ string username;
+ HashSet<string> scope;
+ var result = this.VerifyAccess(httpRequestInfo, out username, out scope);
+ principal = result == null ? new OAuth.ChannelElements.OAuthPrincipal(username, scope != null ? scope.ToArray() : new string[0]) : null;
+ return result;
+ }
+
+ /// <summary>
+ /// Discovers what access the client should have considering the access token in the current request.
+ /// </summary>
+ /// <param name="request">HTTP details from an incoming WCF message.</param>
+ /// <param name="requestUri">The URI of the WCF service endpoint.</param>
+ /// <param name="principal">The principal that contains the user and roles that the access token is authorized for.</param>
+ /// <returns>
+ /// An error to return to the client if access is not authorized; <c>null</c> if access is granted.
+ /// </returns>
+ [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#", Justification = "Try pattern")]
+ [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification = "Try pattern")]
+ public virtual OutgoingWebResponse VerifyAccess(HttpRequestMessageProperty request, Uri requestUri, out IPrincipal principal) {
+ Requires.NotNull(request, "request");
+ Requires.NotNull(requestUri, "requestUri");
+
+ return this.VerifyAccess(new HttpRequestInfo(request, requestUri), out principal);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2.ResourceServer/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth.OAuth2.ResourceServer/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..54db6cf
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2.ResourceServer/Properties/AssemblyInfo.cs
@@ -0,0 +1,54 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssemblyInfo.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+// We DON'T put an AssemblyVersionAttribute in here because it is generated in the build.
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Net;
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Security.Permissions;
+using System.Web.UI;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("DotNetOpenAuth OAuth 2.0")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DotNetOpenAuth")]
+[assembly: AssemblyCopyright("Copyright © 2008")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+[assembly: NeutralResourcesLanguage("en-US")]
+[assembly: CLSCompliant(true)]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("7d73990c-47c0-4256-9f20-a893add9e289")]
+
+[assembly: ContractVerification(true)]
+
+#if StrongNameSigned
+// See comment at top of this file. We need this so that strong-naming doesn't
+// keep this assembly from being useful to shared host (medium trust) web sites.
+[assembly: AllowPartiallyTrustedCallers]
+
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
+#else
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
+#endif
diff --git a/src/DotNetOpenAuth.OAuth2/DotNetOpenAuth.OAuth2.csproj b/src/DotNetOpenAuth.OAuth2/DotNetOpenAuth.OAuth2.csproj
new file mode 100644
index 0000000..aa685a2
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/DotNetOpenAuth.OAuth2.csproj
@@ -0,0 +1,100 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))\EnlistmentInfo.props" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))' != '' " />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" />
+ <PropertyGroup>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{56459A6C-6BA2-4BAC-A9C0-27E3BD961FA6}</ProjectGuid>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <AssemblyName>DotNetOpenAuth.OAuth2</AssemblyName>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" />
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="OAuth2\AuthorizationState.cs" />
+ <Compile Include="OAuth2\ChannelElements\AccessRequestBindingElement.cs" />
+ <Compile Include="OAuth2\ChannelElements\AccessToken.cs" />
+ <Compile Include="OAuth2\ChannelElements\AccessTokenBindingElement.cs" />
+ <Compile Include="OAuth2\ChannelElements\AuthorizationDataBag.cs" />
+ <Compile Include="OAuth2\ChannelElements\AuthServerBindingElementBase.cs" />
+ <Compile Include="OAuth2\ChannelElements\GrantTypeEncoder.cs" />
+ <Compile Include="OAuth2\ChannelElements\EndUserAuthorizationResponseTypeEncoder.cs" />
+ <Compile Include="OAuth2\ChannelElements\OAuth2ChannelBase.cs" />
+ <Compile Include="OAuth2\ChannelElements\OAuth2ClientChannel.cs" />
+ <Compile Include="OAuth2\ChannelElements\ScopeEncoder.cs" />
+ <Compile Include="OAuth2\ChannelElements\IAuthorizationDescription.cs" />
+ <Compile Include="OAuth2\ChannelElements\IAuthorizationCarryingRequest.cs" />
+ <Compile Include="OAuth2\ChannelElements\OAuth2ResourceServerChannel.cs" />
+ <Compile Include="OAuth2\ChannelElements\RefreshToken.cs" />
+ <Compile Include="OAuth2\ChannelElements\AuthorizationCode.cs" />
+ <Compile Include="OAuth2\ChannelElements\AuthorizationCodeBindingElement.cs" />
+ <Compile Include="OAuth2\ChannelElements\AuthServerAllFlowsBindingElement.cs" />
+ <Compile Include="OAuth2\IAccessTokenAnalyzer.cs" />
+ <Compile Include="OAuth2\IAuthorizationServer.cs" />
+ <Compile Include="OAuth2\IAuthorizationState.cs" />
+ <Compile Include="OAuth2\IClientAuthorizationTracker.cs" />
+ <Compile Include="OAuth2\IConsumerDescription.cs" />
+ <Compile Include="OAuth2\Messages\AccessProtectedResourceRequest.cs" />
+ <Compile Include="OAuth2\Messages\AccessTokenAuthorizationCodeRequest.cs" />
+ <Compile Include="OAuth2\Messages\AccessTokenResourceOwnerPasswordCredentialsRequest.cs" />
+ <Compile Include="OAuth2\Messages\AccessTokenRequestBase.cs" />
+ <Compile Include="OAuth2\Messages\AccessTokenClientCredentialsRequest.cs" />
+ <Compile Include="OAuth2\Messages\AuthenticatedClientRequestBase.cs" />
+ <Compile Include="OAuth2\Messages\EndUserAuthorizationSuccessAccessTokenResponse.cs" />
+ <Compile Include="OAuth2\Messages\EndUserAuthorizationFailedResponse.cs" />
+ <Compile Include="OAuth2\Messages\EndUserAuthorizationSuccessAuthCodeResponse.cs" />
+ <Compile Include="OAuth2\Messages\GrantType.cs" />
+ <Compile Include="OAuth2\Messages\AccessTokenRefreshRequest.cs" />
+ <Compile Include="OAuth2\Messages\EndUserAuthorizationResponseType.cs" />
+ <Compile Include="OAuth2\Messages\IAccessTokenRequest.cs" />
+ <Compile Include="OAuth2\Messages\IMessageWithClientState.cs" />
+ <Compile Include="OAuth2\Messages\ScopedAccessTokenRequest.cs" />
+ <Compile Include="OAuth2\Messages\UnauthorizedResponse.cs" />
+ <Compile Include="OAuth2\Messages\AccessTokenFailedResponse.cs" />
+ <Compile Include="OAuth2\Messages\AccessTokenSuccessResponse.cs" />
+ <Compile Include="OAuth2\Messages\EndUserAuthorizationSuccessResponseBase.cs" />
+ <Compile Include="OAuth2\StandardAccessTokenAnalyzer.cs" />
+ <Compile Include="OAuth2\OAuthUtilities.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ <Compile Include="OAuth2\ChannelElements\OAuth2AuthorizationServerChannel.cs" />
+ <Compile Include="OAuth2\Messages\MessageBase.cs" />
+ <Compile Include="OAuth2\Messages\EndUserAuthorizationRequest.cs" />
+ <Compile Include="OAuth2\Protocol.cs" />
+ <Compile Include="OAuth2\OAuthStrings.Designer.cs">
+ <AutoGen>True</AutoGen>
+ <DesignTime>True</DesignTime>
+ <DependentUpon>OAuthStrings.resx</DependentUpon>
+ </Compile>
+ <Compile Include="OAuth2\AuthorizationServerDescription.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="OAuth2\Messages\OAuth 2 Messages.cd" />
+ <None Include="OAuth2\OAuth 2 client facades.cd" />
+ </ItemGroup>
+ <ItemGroup>
+ <EmbeddedResource Include="OAuth2\OAuthStrings.resx">
+ <Generator>ResXFileCodeGenerator</Generator>
+ <LastGenOutput>OAuthStrings.Designer.cs</LastGenOutput>
+ </EmbeddedResource>
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\DotNetOpenAuth.Core\DotNetOpenAuth.Core.csproj">
+ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project>
+ <Name>DotNetOpenAuth.Core</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OAuth\DotNetOpenAuth.OAuth.csproj">
+ <Project>{A288FCC8-6FCF-46DA-A45E-5F9281556361}</Project>
+ <Name>DotNetOpenAuth.OAuth</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
+</Project> \ No newline at end of file
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/AuthorizationServerDescription.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/AuthorizationServerDescription.cs
new file mode 100644
index 0000000..bbad27c
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/AuthorizationServerDescription.cs
@@ -0,0 +1,62 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthorizationServerDescription.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+
+ /// <summary>
+ /// A description of an OAuth Authorization Server as seen by an OAuth Client.
+ /// </summary>
+ public class AuthorizationServerDescription {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthorizationServerDescription"/> class.
+ /// </summary>
+ public AuthorizationServerDescription() {
+ this.ProtocolVersion = Protocol.Default.ProtocolVersion;
+ }
+
+ /// <summary>
+ /// Gets or sets the Authorization Server URL from which an Access Token is requested by the Client.
+ /// </summary>
+ /// <value>An HTTPS URL.</value>
+ /// <remarks>
+ /// <para>After obtaining authorization from the resource owner, clients request an access token from the authorization server's token endpoint.</para>
+ /// <para>The URI of the token endpoint can be found in the service documentation, or can be obtained by the client by making an unauthorized protected resource request (from the WWW-Authenticate response header token-uri (The 'authorization-uri' Attribute) attribute).</para>
+ /// <para>The token endpoint advertised by the resource server MAY include a query component as defined by [RFC3986] (Berners-Lee, T., Fielding, R., and L. Masinter, “Uniform Resource Identifier (URI): Generic Syntax,” January 2005.) section 3.</para>
+ /// <para>Since requests to the token endpoint result in the transmission of plain text credentials in the HTTP request and response, the authorization server MUST require the use of a transport-layer mechanism such as TLS/SSL (or a secure channel with equivalent protections) when sending requests to the token endpoints. </para>
+ /// </remarks>
+ public Uri TokenEndpoint { get; set; }
+
+ /// <summary>
+ /// Gets or sets the Authorization Server URL where the Client (re)directs the User
+ /// to make an authorization request.
+ /// </summary>
+ /// <value>An HTTPS URL.</value>
+ /// <remarks>
+ /// <para>Clients direct the resource owner to the authorization endpoint to approve their access request. Before granting access, the resource owner first authenticates with the authorization server. The way in which the authorization server authenticates the end-user (e.g. username and password login, OpenID, session cookies) and in which the authorization server obtains the end-user's authorization, including whether it uses a secure channel such as TLS/SSL, is beyond the scope of this specification. However, the authorization server MUST first verify the identity of the end-user.</para>
+ /// <para>The URI of the authorization endpoint can be found in the service documentation, or can be obtained by the client by making an unauthorized protected resource request (from the WWW-Authenticate response header auth-uri (The 'authorization-uri' Attribute) attribute).</para>
+ /// <para>The authorization endpoint advertised by the resource server MAY include a query component as defined by [RFC3986] (Berners-Lee, T., Fielding, R., and L. Masinter, “Uniform Resource Identifier (URI): Generic Syntax,” January 2005.) section 3.</para>
+ /// <para>Since requests to the authorization endpoint result in user authentication and the transmission of sensitive values, the authorization server SHOULD require the use of a transport-layer mechanism such as TLS/SSL (or a secure channel with equivalent protections) when sending requests to the authorization endpoints.</para>
+ /// </remarks>
+ public Uri AuthorizationEndpoint { get; set; }
+
+ /// <summary>
+ /// Gets or sets the OAuth version supported by the Authorization Server.
+ /// </summary>
+ public ProtocolVersion ProtocolVersion { get; set; }
+
+ /// <summary>
+ /// Gets the version of the OAuth protocol to use with this Authorization Server.
+ /// </summary>
+ /// <value>The version.</value>
+ internal Version Version {
+ get { return Protocol.Lookup(this.ProtocolVersion).Version; }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/AuthorizationState.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/AuthorizationState.cs
new file mode 100644
index 0000000..bfc33aa
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/AuthorizationState.cs
@@ -0,0 +1,93 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthorizationState.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A simple in-memory copy of an authorization state.
+ /// </summary>
+ [Serializable]
+ public class AuthorizationState : IAuthorizationState {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthorizationState"/> class.
+ /// </summary>
+ /// <param name="scopes">The scopes of access being requested or that was obtained.</param>
+ public AuthorizationState(IEnumerable<string> scopes = null) {
+ this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer);
+ if (scopes != null) {
+ this.Scope.AddRange(scopes);
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the callback URL used to obtain authorization.
+ /// </summary>
+ /// <value>The callback URL.</value>
+ public Uri Callback { get; set; }
+
+ /// <summary>
+ /// Gets or sets the long-lived token used to renew the short-lived <see cref="AccessToken"/>.
+ /// </summary>
+ /// <value>The refresh token.</value>
+ public string RefreshToken { get; set; }
+
+ /// <summary>
+ /// Gets or sets the access token.
+ /// </summary>
+ /// <value>The access token.</value>
+ public string AccessToken { get; set; }
+
+ /// <summary>
+ /// Gets or sets the access token UTC expiration date.
+ /// </summary>
+ /// <value></value>
+ public DateTime? AccessTokenExpirationUtc { get; set; }
+
+ /// <summary>
+ /// Gets or sets the access token issue date UTC.
+ /// </summary>
+ /// <value>The access token issue date UTC.</value>
+ public DateTime? AccessTokenIssueDateUtc { get; set; }
+
+ /// <summary>
+ /// Gets the scope the token is (to be) authorized for.
+ /// </summary>
+ /// <value>The scope.</value>
+ public HashSet<string> Scope { get; private set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this instance is deleted.
+ /// </summary>
+ /// <value>
+ /// <c>true</c> if this instance is deleted; otherwise, <c>false</c>.
+ /// </value>
+ public bool IsDeleted { get; set; }
+
+ /// <summary>
+ /// Deletes this authorization, including access token and refresh token where applicable.
+ /// </summary>
+ /// <remarks>
+ /// This method is invoked when an authorization attempt fails, is rejected, is revoked, or
+ /// expires and cannot be renewed.
+ /// </remarks>
+ public virtual void Delete() {
+ this.IsDeleted = true;
+ }
+
+ /// <summary>
+ /// Saves any changes made to this authorization object's properties.
+ /// </summary>
+ /// <remarks>
+ /// This method is invoked after DotNetOpenAuth changes any property.
+ /// </remarks>
+ public virtual void SaveChanges() {
+ }
+ }
+} \ No newline at end of file
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AccessRequestBindingElement.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AccessRequestBindingElement.cs
new file mode 100644
index 0000000..b86f5dd
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AccessRequestBindingElement.cs
@@ -0,0 +1,158 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessRequestBindingElement.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Globalization;
+ using System.Linq;
+ using System.Security.Cryptography;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+ using DotNetOpenAuth.OAuth2.Messages;
+
+ /// <summary>
+ /// Decodes verification codes, refresh tokens and access tokens on incoming messages.
+ /// </summary>
+ /// <remarks>
+ /// This binding element also ensures that the code/token coming in is issued to
+ /// the same client that is sending the code/token and that the authorization has
+ /// not been revoked and that an access token has not expired.
+ /// </remarks>
+ internal class AccessRequestBindingElement : AuthServerBindingElementBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessRequestBindingElement"/> class.
+ /// </summary>
+ internal AccessRequestBindingElement() {
+ }
+
+ /// <summary>
+ /// Gets the protection commonly offered (if any) by this binding element.
+ /// </summary>
+ /// <value></value>
+ /// <remarks>
+ /// This value is used to assist in sorting binding elements in the channel stack.
+ /// </remarks>
+ public override MessageProtections Protection {
+ get { return MessageProtections.None; }
+ }
+
+ /// <summary>
+ /// Prepares a message for sending based on the rules of this channel binding element.
+ /// </summary>
+ /// <param name="message">The message to prepare for sending.</param>
+ /// <returns>
+ /// The protections (if any) that this binding element applied to the message.
+ /// Null if this binding element did not even apply to this binding element.
+ /// </returns>
+ /// <remarks>
+ /// Implementations that provide message protection must honor the
+ /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable.
+ /// </remarks>
+ public override MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) {
+ var response = message as IAuthorizationCarryingRequest;
+ if (response != null) {
+ switch (response.CodeOrTokenType) {
+ case CodeOrTokenType.AuthorizationCode:
+ var codeFormatter = AuthorizationCode.CreateFormatter(this.AuthorizationServer);
+ var code = (AuthorizationCode)response.AuthorizationDescription;
+ response.CodeOrToken = codeFormatter.Serialize(code);
+ break;
+ case CodeOrTokenType.AccessToken:
+ var responseWithOriginatingRequest = (IDirectResponseProtocolMessage)message;
+ var request = (IAccessTokenRequest)responseWithOriginatingRequest.OriginatingRequest;
+
+ using (var resourceServerKey = this.AuthorizationServer.GetResourceServerEncryptionKey(request)) {
+ var tokenFormatter = AccessToken.CreateFormatter(this.AuthorizationServer.AccessTokenSigningKey, resourceServerKey);
+ var token = (AccessToken)response.AuthorizationDescription;
+ response.CodeOrToken = tokenFormatter.Serialize(token);
+ break;
+ }
+ default:
+ throw ErrorUtilities.ThrowInternal(string.Format(CultureInfo.CurrentCulture, "Unexpected outgoing code or token type: {0}", response.CodeOrTokenType));
+ }
+
+ return MessageProtections.None;
+ }
+
+ var accessTokenResponse = message as AccessTokenSuccessResponse;
+ if (accessTokenResponse != null) {
+ var directResponseMessage = (IDirectResponseProtocolMessage)accessTokenResponse;
+ var accessTokenRequest = (AccessTokenRequestBase)directResponseMessage.OriginatingRequest;
+ ErrorUtilities.VerifyProtocol(accessTokenRequest.GrantType != GrantType.ClientCredentials || accessTokenResponse.RefreshToken == null, OAuthStrings.NoGrantNoRefreshToken);
+ }
+
+ return null;
+ }
+
+ /// <summary>
+ /// Performs any transformation on an incoming message that may be necessary and/or
+ /// validates an incoming message based on the rules of this channel binding element.
+ /// </summary>
+ /// <param name="message">The incoming message to process.</param>
+ /// <returns>
+ /// The protections (if any) that this binding element applied to the message.
+ /// Null if this binding element did not even apply to this binding element.
+ /// </returns>
+ /// <exception cref="ProtocolException">
+ /// Thrown when the binding element rules indicate that this message is invalid and should
+ /// NOT be processed.
+ /// </exception>
+ /// <remarks>
+ /// Implementations that provide message protection must honor the
+ /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable.
+ /// </remarks>
+ public override MessageProtections? ProcessIncomingMessage(IProtocolMessage message) {
+ var tokenRequest = message as IAuthorizationCarryingRequest;
+ if (tokenRequest != null) {
+ try {
+ switch (tokenRequest.CodeOrTokenType) {
+ case CodeOrTokenType.AuthorizationCode:
+ var verificationCodeFormatter = AuthorizationCode.CreateFormatter(this.AuthorizationServer);
+ var verificationCode = verificationCodeFormatter.Deserialize(message, tokenRequest.CodeOrToken);
+ tokenRequest.AuthorizationDescription = verificationCode;
+ break;
+ case CodeOrTokenType.RefreshToken:
+ var refreshTokenFormatter = RefreshToken.CreateFormatter(this.AuthorizationServer.CryptoKeyStore);
+ var refreshToken = refreshTokenFormatter.Deserialize(message, tokenRequest.CodeOrToken);
+ tokenRequest.AuthorizationDescription = refreshToken;
+ break;
+ default:
+ throw ErrorUtilities.ThrowInternal("Unexpected value for CodeOrTokenType: " + tokenRequest.CodeOrTokenType);
+ }
+ } catch (ExpiredMessageException ex) {
+ throw ErrorUtilities.Wrap(ex, Protocol.authorization_expired);
+ }
+
+ var accessRequest = tokenRequest as AccessTokenRequestBase;
+ if (accessRequest != null) {
+ // Make sure the client sending us this token is the client we issued the token to.
+ ErrorUtilities.VerifyProtocol(string.Equals(accessRequest.ClientIdentifier, tokenRequest.AuthorizationDescription.ClientIdentifier, StringComparison.Ordinal), Protocol.incorrect_client_credentials);
+
+ // Check that the client secret is correct.
+ var client = this.AuthorizationServer.GetClientOrThrow(accessRequest.ClientIdentifier);
+ string secret = client.Secret;
+ ErrorUtilities.VerifyProtocol(!String.IsNullOrEmpty(secret), Protocol.unauthorized_client); // an empty secret is not allowed for client authenticated calls.
+ ErrorUtilities.VerifyProtocol(MessagingUtilities.EqualsConstantTime(secret, accessRequest.ClientSecret), Protocol.incorrect_client_credentials);
+
+ var scopedAccessRequest = accessRequest as ScopedAccessTokenRequest;
+ if (scopedAccessRequest != null) {
+ // Make sure the scope the client is requesting does not exceed the scope in the grant.
+ ErrorUtilities.VerifyProtocol(scopedAccessRequest.Scope.IsSubsetOf(tokenRequest.AuthorizationDescription.Scope), OAuthStrings.AccessScopeExceedsGrantScope, scopedAccessRequest.Scope, tokenRequest.AuthorizationDescription.Scope);
+ }
+ }
+
+ // Make sure the authorization this token represents hasn't already been revoked.
+ ErrorUtilities.VerifyProtocol(this.AuthorizationServer.IsAuthorizationValid(tokenRequest.AuthorizationDescription), Protocol.authorization_expired);
+
+ return MessageProtections.None;
+ }
+
+ return null;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AccessToken.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AccessToken.cs
new file mode 100644
index 0000000..a502962
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AccessToken.cs
@@ -0,0 +1,102 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessToken.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Security.Cryptography;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+
+ /// <summary>
+ /// A short-lived token that accompanies HTTP requests to protected data to authorize the request.
+ /// </summary>
+ internal class AccessToken : AuthorizationDataBag {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessToken"/> class.
+ /// </summary>
+ public AccessToken() {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessToken"/> class.
+ /// </summary>
+ /// <param name="authorization">The authorization to be described by the access token.</param>
+ /// <param name="lifetime">The lifetime of the access token.</param>
+ internal AccessToken(IAuthorizationDescription authorization, TimeSpan? lifetime) {
+ Requires.NotNull(authorization, "authorization");
+
+ this.ClientIdentifier = authorization.ClientIdentifier;
+ this.UtcCreationDate = authorization.UtcIssued;
+ this.User = authorization.User;
+ this.Scope.ResetContents(authorization.Scope);
+ this.Lifetime = lifetime;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessToken"/> class.
+ /// </summary>
+ /// <param name="clientIdentifier">The client identifier.</param>
+ /// <param name="scopes">The scopes.</param>
+ /// <param name="username">The username of the account that authorized this token.</param>
+ /// <param name="lifetime">The lifetime for this access token.</param>
+ internal AccessToken(string clientIdentifier, IEnumerable<string> scopes, string username, TimeSpan? lifetime) {
+ Requires.NotNullOrEmpty(clientIdentifier, "clientIdentifier");
+
+ this.ClientIdentifier = clientIdentifier;
+ this.Scope.ResetContents(scopes);
+ this.User = username;
+ this.Lifetime = lifetime;
+ this.UtcCreationDate = DateTime.UtcNow;
+ }
+
+ /// <summary>
+ /// Gets or sets the lifetime of the access token.
+ /// </summary>
+ /// <value>The lifetime.</value>
+ [MessagePart(Encoder = typeof(TimespanSecondsEncoder))]
+ internal TimeSpan? Lifetime { get; set; }
+
+ /// <summary>
+ /// Creates a formatter capable of serializing/deserializing an access token.
+ /// </summary>
+ /// <param name="signingKey">The crypto service provider with the authorization server's private key used to asymmetrically sign the access token.</param>
+ /// <param name="encryptingKey">The crypto service provider with the resource server's public key used to encrypt the access token.</param>
+ /// <returns>An access token serializer.</returns>
+ internal static IDataBagFormatter<AccessToken> CreateFormatter(RSACryptoServiceProvider signingKey, RSACryptoServiceProvider encryptingKey) {
+ Contract.Requires(signingKey != null || !signingKey.PublicOnly);
+ Contract.Requires(encryptingKey != null);
+ Contract.Ensures(Contract.Result<IDataBagFormatter<AccessToken>>() != null);
+
+ return new UriStyleMessageFormatter<AccessToken>(signingKey, encryptingKey);
+ }
+
+ /// <summary>
+ /// Checks the message state for conformity to the protocol specification
+ /// and throws an exception if the message is invalid.
+ /// </summary>
+ /// <remarks>
+ /// <para>Some messages have required fields, or combinations of fields that must relate to each other
+ /// in specialized ways. After deserializing a message, this method checks the state of the
+ /// message to see if it conforms to the protocol.</para>
+ /// <para>Note that this property should <i>not</i> check signatures or perform any state checks
+ /// outside this scope of this particular message.</para>
+ /// </remarks>
+ /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception>
+ protected override void EnsureValidMessage() {
+ base.EnsureValidMessage();
+
+ // Has this token expired?
+ if (this.Lifetime.HasValue) {
+ DateTime expirationDate = this.UtcCreationDate + this.Lifetime.Value;
+ if (expirationDate < DateTime.UtcNow) {
+ throw new ExpiredMessageException(expirationDate, this.ContainingMessage);
+ }
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AccessTokenBindingElement.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AccessTokenBindingElement.cs
new file mode 100644
index 0000000..3a709b6
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AccessTokenBindingElement.cs
@@ -0,0 +1,93 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessTokenBindingElement.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Security.Cryptography;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.Messages;
+
+ /// <summary>
+ /// Serializes access tokens inside an outgoing message.
+ /// </summary>
+ internal class AccessTokenBindingElement : AuthServerBindingElementBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenBindingElement"/> class.
+ /// </summary>
+ internal AccessTokenBindingElement() {
+ }
+
+ /// <summary>
+ /// Gets the protection commonly offered (if any) by this binding element.
+ /// </summary>
+ /// <value>Always <c>MessageProtections.None</c></value>
+ /// <remarks>
+ /// This value is used to assist in sorting binding elements in the channel stack.
+ /// </remarks>
+ public override MessageProtections Protection {
+ get { return MessageProtections.None; }
+ }
+
+ /// <summary>
+ /// Prepares a message for sending based on the rules of this channel binding element.
+ /// </summary>
+ /// <param name="message">The message to prepare for sending.</param>
+ /// <returns>
+ /// The protections (if any) that this binding element applied to the message.
+ /// Null if this binding element did not even apply to this binding element.
+ /// </returns>
+ public override MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) {
+ var directResponse = message as IDirectResponseProtocolMessage;
+ IAccessTokenRequest request = directResponse != null ? directResponse.OriginatingRequest as IAccessTokenRequest : null;
+
+ var implicitGrantResponse = message as EndUserAuthorizationSuccessAccessTokenResponse;
+ if (implicitGrantResponse != null) {
+ IAuthorizationCarryingRequest tokenCarryingResponse = implicitGrantResponse;
+ tokenCarryingResponse.AuthorizationDescription = new AccessToken(request.ClientIdentifier, implicitGrantResponse.Scope, implicitGrantResponse.AuthorizingUsername, implicitGrantResponse.Lifetime);
+
+ return MessageProtections.None;
+ }
+
+ var accessTokenResponse = message as AccessTokenSuccessResponse;
+ if (accessTokenResponse != null) {
+ var authCarryingRequest = (IAuthorizationCarryingRequest)request;
+ var accessToken = new AccessToken(authCarryingRequest.AuthorizationDescription, accessTokenResponse.Lifetime);
+ using (var resourceServerEncryptionKey = this.AuthorizationServer.GetResourceServerEncryptionKey(request)) {
+ var accessTokenFormatter = AccessToken.CreateFormatter(this.AuthorizationServer.AccessTokenSigningKey, resourceServerEncryptionKey);
+ accessTokenResponse.AccessToken = accessTokenFormatter.Serialize(accessToken);
+ }
+
+ if (accessTokenResponse.HasRefreshToken) {
+ var refreshToken = new RefreshToken(authCarryingRequest.AuthorizationDescription);
+ var refreshTokenFormatter = RefreshToken.CreateFormatter(this.AuthorizationServer.CryptoKeyStore);
+ accessTokenResponse.RefreshToken = refreshTokenFormatter.Serialize(refreshToken);
+ }
+ }
+
+ return null;
+ }
+
+ /// <summary>
+ /// Performs any transformation on an incoming message that may be necessary and/or
+ /// validates an incoming message based on the rules of this channel binding element.
+ /// </summary>
+ /// <param name="message">The incoming message to process.</param>
+ /// <returns>
+ /// The protections (if any) that this binding element applied to the message.
+ /// Null if this binding element did not even apply to this binding element.
+ /// </returns>
+ /// <exception cref="ProtocolException">
+ /// Thrown when the binding element rules indicate that this message is invalid and should
+ /// NOT be processed.
+ /// </exception>
+ public override MessageProtections? ProcessIncomingMessage(IProtocolMessage message) {
+ return null;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthServerAllFlowsBindingElement.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthServerAllFlowsBindingElement.cs
new file mode 100644
index 0000000..bc464e2
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthServerAllFlowsBindingElement.cs
@@ -0,0 +1,83 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthServerAllFlowsBindingElement.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.OAuth2.Messages;
+ using Messaging;
+
+ /// <summary>
+ /// A binding element that should be applied for authorization server channels regardless of which flows
+ /// are supported.
+ /// </summary>
+ internal class AuthServerAllFlowsBindingElement : AuthServerBindingElementBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthServerAllFlowsBindingElement"/> class.
+ /// </summary>
+ internal AuthServerAllFlowsBindingElement() {
+ }
+
+ /// <summary>
+ /// Gets the protection commonly offered (if any) by this binding element.
+ /// </summary>
+ /// <remarks>
+ /// This value is used to assist in sorting binding elements in the channel stack.
+ /// </remarks>
+ public override MessageProtections Protection {
+ get { return MessageProtections.None; }
+ }
+
+ /// <summary>
+ /// Prepares a message for sending based on the rules of this channel binding element.
+ /// </summary>
+ /// <param name="message">The message to prepare for sending.</param>
+ /// <returns>
+ /// The protections (if any) that this binding element applied to the message.
+ /// Null if this binding element did not even apply to this binding element.
+ /// </returns>
+ /// <remarks>
+ /// Implementations that provide message protection must honor the
+ /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable.
+ /// </remarks>
+ public override MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) {
+ return null;
+ }
+
+ /// <summary>
+ /// Performs any transformation on an incoming message that may be necessary and/or
+ /// validates an incoming message based on the rules of this channel binding element.
+ /// </summary>
+ /// <param name="message">The incoming message to process.</param>
+ /// <returns>
+ /// The protections (if any) that this binding element applied to the message.
+ /// Null if this binding element did not even apply to this binding element.
+ /// </returns>
+ /// <exception cref="ProtocolException">
+ /// Thrown when the binding element rules indicate that this message is invalid and should
+ /// NOT be processed.
+ /// </exception>
+ /// <remarks>
+ /// Implementations that provide message protection must honor the
+ /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable.
+ /// </remarks>
+ public override MessageProtections? ProcessIncomingMessage(IProtocolMessage message) {
+ var authorizationRequest = message as EndUserAuthorizationRequest;
+ if (authorizationRequest != null) {
+ var client = this.AuthorizationServer.GetClientOrThrow(authorizationRequest.ClientIdentifier);
+ ErrorUtilities.VerifyProtocol(authorizationRequest.Callback == null || client.IsCallbackAllowed(authorizationRequest.Callback), OAuthStrings.ClientCallbackDisallowed, authorizationRequest.Callback);
+ ErrorUtilities.VerifyProtocol(authorizationRequest.Callback != null || client.DefaultCallback != null, OAuthStrings.NoCallback);
+
+ return MessageProtections.None;
+ }
+
+ return null;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthServerBindingElementBase.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthServerBindingElementBase.cs
new file mode 100644
index 0000000..9d3e78f
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthServerBindingElementBase.cs
@@ -0,0 +1,92 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthServerBindingElementBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using Messaging;
+
+ /// <summary>
+ /// The base class for any authorization server channel binding element.
+ /// </summary>
+ internal abstract class AuthServerBindingElementBase : IChannelBindingElement {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthServerBindingElementBase"/> class.
+ /// </summary>
+ protected AuthServerBindingElementBase()
+ {
+ }
+
+ /// <summary>
+ /// Gets or sets the channel that this binding element belongs to.
+ /// </summary>
+ /// <remarks>
+ /// This property is set by the channel when it is first constructed.
+ /// </remarks>
+ public Channel Channel { get; set; }
+
+ /// <summary>
+ /// Gets the protection commonly offered (if any) by this binding element.
+ /// </summary>
+ /// <remarks>
+ /// This value is used to assist in sorting binding elements in the channel stack.
+ /// </remarks>
+ public abstract MessageProtections Protection { get; }
+
+ /// <summary>
+ /// Gets the channel that this binding element belongs to.
+ /// </summary>
+ /// <remarks>
+ /// This property is set by the channel when it is first constructed.
+ /// </remarks>
+ protected OAuth2AuthorizationServerChannel OAuthChannel {
+ get { return (OAuth2AuthorizationServerChannel)this.Channel; }
+ }
+
+ /// <summary>
+ /// Gets the authorization server hosting this channel.
+ /// </summary>
+ /// <value>The authorization server.</value>
+ protected IAuthorizationServer AuthorizationServer {
+ get { return this.OAuthChannel.AuthorizationServer; }
+ }
+
+ /// <summary>
+ /// Prepares a message for sending based on the rules of this channel binding element.
+ /// </summary>
+ /// <param name="message">The message to prepare for sending.</param>
+ /// <returns>
+ /// The protections (if any) that this binding element applied to the message.
+ /// Null if this binding element did not even apply to this binding element.
+ /// </returns>
+ /// <remarks>
+ /// Implementations that provide message protection must honor the
+ /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable.
+ /// </remarks>
+ public abstract MessageProtections? ProcessOutgoingMessage(IProtocolMessage message);
+
+ /// <summary>
+ /// Performs any transformation on an incoming message that may be necessary and/or
+ /// validates an incoming message based on the rules of this channel binding element.
+ /// </summary>
+ /// <param name="message">The incoming message to process.</param>
+ /// <returns>
+ /// The protections (if any) that this binding element applied to the message.
+ /// Null if this binding element did not even apply to this binding element.
+ /// </returns>
+ /// <exception cref="ProtocolException">
+ /// Thrown when the binding element rules indicate that this message is invalid and should
+ /// NOT be processed.
+ /// </exception>
+ /// <remarks>
+ /// Implementations that provide message protection must honor the
+ /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable.
+ /// </remarks>
+ public abstract MessageProtections? ProcessIncomingMessage(IProtocolMessage message);
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthorizationCode.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthorizationCode.cs
new file mode 100644
index 0000000..6900b89
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthorizationCode.cs
@@ -0,0 +1,100 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthorizationCode.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Security.Cryptography;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// Represents the authorization code created when a user approves authorization that
+ /// allows the client to request an access/refresh token.
+ /// </summary>
+ internal class AuthorizationCode : AuthorizationDataBag {
+ /// <summary>
+ /// The name of the bucket for symmetric keys used to sign authorization codes.
+ /// </summary>
+ internal const string AuthorizationCodeKeyBucket = "https://localhost/dnoa/oauth_authorization_code";
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthorizationCode"/> class.
+ /// </summary>
+ public AuthorizationCode() {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthorizationCode"/> class.
+ /// </summary>
+ /// <param name="clientIdentifier">The client identifier.</param>
+ /// <param name="callback">The callback the client used to obtain authorization.</param>
+ /// <param name="scopes">The authorized scopes.</param>
+ /// <param name="username">The name on the account that authorized access.</param>
+ internal AuthorizationCode(string clientIdentifier, Uri callback, IEnumerable<string> scopes, string username) {
+ Requires.NotNullOrEmpty(clientIdentifier, "clientIdentifier");
+ Requires.NotNull(callback, "callback");
+
+ this.ClientIdentifier = clientIdentifier;
+ this.CallbackHash = CalculateCallbackHash(callback);
+ this.Scope.ResetContents(scopes);
+ this.User = username;
+ this.UtcCreationDate = DateTime.UtcNow;
+ }
+
+ /// <summary>
+ /// Gets or sets the hash of the callback URL.
+ /// </summary>
+ [MessagePart("cb")]
+ private byte[] CallbackHash { get; set; }
+
+ /// <summary>
+ /// Creates a serializer/deserializer for this type.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server that will be serializing/deserializing this authorization code. Must not be null.</param>
+ /// <returns>A DataBag formatter.</returns>
+ internal static IDataBagFormatter<AuthorizationCode> CreateFormatter(IAuthorizationServer authorizationServer) {
+ Requires.NotNull(authorizationServer, "authorizationServer");
+ Contract.Ensures(Contract.Result<IDataBagFormatter<AuthorizationCode>>() != null);
+
+ return new UriStyleMessageFormatter<AuthorizationCode>(
+ authorizationServer.CryptoKeyStore,
+ AuthorizationCodeKeyBucket,
+ signed: true,
+ encrypted: true,
+ compressed: false,
+ maximumAge: AuthorizationCodeBindingElement.MaximumMessageAge,
+ decodeOnceOnly: authorizationServer.VerificationCodeNonceStore);
+ }
+
+ /// <summary>
+ /// Verifies the the given callback URL matches the callback originally given in the authorization request.
+ /// </summary>
+ /// <param name="callback">The callback.</param>
+ /// <remarks>
+ /// This method serves to verify that the callback URL given in the original authorization request
+ /// and the callback URL given in the access token request match.
+ /// </remarks>
+ /// <exception cref="ProtocolException">Thrown when the callback URLs do not match.</exception>
+ internal void VerifyCallback(Uri callback) {
+ ErrorUtilities.VerifyProtocol(MessagingUtilities.AreEquivalent(this.CallbackHash, CalculateCallbackHash(callback)), Protocol.redirect_uri_mismatch);
+ }
+
+ /// <summary>
+ /// Calculates the hash of the callback URL.
+ /// </summary>
+ /// <param name="callback">The callback whose hash should be calculated.</param>
+ /// <returns>
+ /// A base64 encoding of the hash of the URL.
+ /// </returns>
+ private static byte[] CalculateCallbackHash(Uri callback) {
+ using (var hasher = new SHA256Managed()) {
+ return hasher.ComputeHash(Encoding.UTF8.GetBytes(callback.AbsoluteUri));
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthorizationCodeBindingElement.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthorizationCodeBindingElement.cs
new file mode 100644
index 0000000..b0e6203
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthorizationCodeBindingElement.cs
@@ -0,0 +1,101 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthorizationCodeBindingElement.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using Messages;
+ using Messaging;
+ using Messaging.Bindings;
+
+ /// <summary>
+ /// A binding element for OAuth 2.0 authorization servers that create/verify
+ /// issued authorization codes as part of obtaining access/refresh tokens.
+ /// </summary>
+ internal class AuthorizationCodeBindingElement : AuthServerBindingElementBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthorizationCodeBindingElement"/> class.
+ /// </summary>
+ internal AuthorizationCodeBindingElement() {
+ }
+
+ /// <summary>
+ /// Gets the protection commonly offered (if any) by this binding element.
+ /// </summary>
+ /// <value>Always <c>MessageProtections.None</c></value>
+ /// <remarks>
+ /// This value is used to assist in sorting binding elements in the channel stack.
+ /// </remarks>
+ public override MessageProtections Protection {
+ get { return MessageProtections.None; }
+ }
+
+ /// <summary>
+ /// Gets the maximum message age from the standard expiration binding element.
+ /// </summary>
+ /// <value>This interval need not account for clock skew because it is only compared within a single authorization server or farm of servers.</value>
+ internal static TimeSpan MaximumMessageAge {
+ get { return Configuration.DotNetOpenAuthSection.Messaging.MaximumMessageLifetimeNoSkew; }
+ }
+
+ /// <summary>
+ /// Prepares a message for sending based on the rules of this channel binding element.
+ /// </summary>
+ /// <param name="message">The message to prepare for sending.</param>
+ /// <returns>
+ /// The protections (if any) that this binding element applied to the message.
+ /// Null if this binding element did not even apply to this binding element.
+ /// </returns>
+ /// <remarks>
+ /// Implementations that provide message protection must honor the
+ /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable.
+ /// </remarks>
+ public override MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) {
+ var response = message as EndUserAuthorizationSuccessAuthCodeResponse;
+ if (response != null) {
+ var directResponse = (IDirectResponseProtocolMessage)response;
+ var request = (EndUserAuthorizationRequest)directResponse.OriginatingRequest;
+ IAuthorizationCarryingRequest tokenCarryingResponse = response;
+ tokenCarryingResponse.AuthorizationDescription = new AuthorizationCode(request.ClientIdentifier, request.Callback, response.Scope, response.AuthorizingUsername);
+
+ return MessageProtections.None;
+ }
+
+ return null;
+ }
+
+ /// <summary>
+ /// Performs any transformation on an incoming message that may be necessary and/or
+ /// validates an incoming message based on the rules of this channel binding element.
+ /// </summary>
+ /// <param name="message">The incoming message to process.</param>
+ /// <returns>
+ /// The protections (if any) that this binding element applied to the message.
+ /// Null if this binding element did not even apply to this binding element.
+ /// </returns>
+ /// <exception cref="ProtocolException">
+ /// Thrown when the binding element rules indicate that this message is invalid and should
+ /// NOT be processed.
+ /// </exception>
+ /// <remarks>
+ /// Implementations that provide message protection must honor the
+ /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable.
+ /// </remarks>
+ public override MessageProtections? ProcessIncomingMessage(IProtocolMessage message) {
+ var request = message as AccessTokenAuthorizationCodeRequest;
+ if (request != null) {
+ IAuthorizationCarryingRequest tokenRequest = request;
+ ((AuthorizationCode)tokenRequest.AuthorizationDescription).VerifyCallback(request.Callback);
+
+ return MessageProtections.None;
+ }
+
+ return null;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthorizationDataBag.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthorizationDataBag.cs
new file mode 100644
index 0000000..8f1d983
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthorizationDataBag.cs
@@ -0,0 +1,51 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthorizationDataBag.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A data bag that stores authorization data.
+ /// </summary>
+ internal abstract class AuthorizationDataBag : DataBag, IAuthorizationDescription {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthorizationDataBag"/> class.
+ /// </summary>
+ protected AuthorizationDataBag() {
+ this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer);
+ }
+
+ /// <summary>
+ /// Gets or sets the identifier of the client authorized to access protected data.
+ /// </summary>
+ /// <value></value>
+ [MessagePart]
+ public string ClientIdentifier { get; set; }
+
+ /// <summary>
+ /// Gets the date this authorization was established or the token was issued.
+ /// </summary>
+ /// <value>A date/time expressed in UTC.</value>
+ public DateTime UtcIssued {
+ get { return this.UtcCreationDate; }
+ }
+
+ /// <summary>
+ /// Gets or sets the name on the account whose data on the resource server is accessible using this authorization.
+ /// </summary>
+ [MessagePart]
+ public string User { get; set; }
+
+ /// <summary>
+ /// Gets the scope of operations the client is allowed to invoke.
+ /// </summary>
+ [MessagePart(Encoder = typeof(ScopeEncoder))]
+ public HashSet<string> Scope { get; private set; }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/EndUserAuthorizationResponseTypeEncoder.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/EndUserAuthorizationResponseTypeEncoder.cs
new file mode 100644
index 0000000..139025d
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/EndUserAuthorizationResponseTypeEncoder.cs
@@ -0,0 +1,66 @@
+//-----------------------------------------------------------------------
+// <copyright file="EndUserAuthorizationResponseTypeEncoder.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Reflection;
+ using DotNetOpenAuth.OAuth2.Messages;
+
+ /// <summary>
+ /// Encodes/decodes the OAuth 2.0 response_type argument.
+ /// </summary>
+ internal class EndUserAuthorizationResponseTypeEncoder : IMessagePartEncoder {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EndUserAuthorizationResponseTypeEncoder"/> class.
+ /// </summary>
+ public EndUserAuthorizationResponseTypeEncoder() {
+ }
+
+ #region IMessagePartEncoder Members
+
+ /// <summary>
+ /// Encodes the specified value.
+ /// </summary>
+ /// <param name="value">The value. Guaranteed to never be null.</param>
+ /// <returns>
+ /// The <paramref name="value"/> in string form, ready for message transport.
+ /// </returns>
+ public string Encode(object value) {
+ var responseType = (EndUserAuthorizationResponseType)value;
+ switch (responseType)
+ {
+ case EndUserAuthorizationResponseType.AccessToken:
+ return Protocol.ResponseTypes.Token;
+ case EndUserAuthorizationResponseType.AuthorizationCode:
+ return Protocol.ResponseTypes.Code;
+ default:
+ throw ErrorUtilities.ThrowFormat(MessagingStrings.UnexpectedMessagePartValue, Protocol.response_type, value);
+ }
+ }
+
+ /// <summary>
+ /// Decodes the specified value.
+ /// </summary>
+ /// <param name="value">The string value carried by the transport. Guaranteed to never be null, although it may be empty.</param>
+ /// <returns>
+ /// The deserialized form of the given string.
+ /// </returns>
+ /// <exception cref="FormatException">Thrown when the string value given cannot be decoded into the required object type.</exception>
+ public object Decode(string value) {
+ switch (value) {
+ case Protocol.ResponseTypes.Token:
+ return EndUserAuthorizationResponseType.AccessToken;
+ case Protocol.ResponseTypes.Code:
+ return EndUserAuthorizationResponseType.AuthorizationCode;
+ default:
+ throw ErrorUtilities.ThrowFormat(MessagingStrings.UnexpectedMessagePartValue, Protocol.response_type, value);
+ }
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/GrantTypeEncoder.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/GrantTypeEncoder.cs
new file mode 100644
index 0000000..78ed975
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/GrantTypeEncoder.cs
@@ -0,0 +1,78 @@
+//-----------------------------------------------------------------------
+// <copyright file="GrantTypeEncoder.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Reflection;
+ using DotNetOpenAuth.OAuth2.Messages;
+
+ /// <summary>
+ /// Encodes/decodes the OAuth 2.0 grant_type argument.
+ /// </summary>
+ internal class GrantTypeEncoder : IMessagePartEncoder {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="GrantTypeEncoder"/> class.
+ /// </summary>
+ public GrantTypeEncoder() {
+ }
+
+ #region IMessagePartEncoder Members
+
+ /// <summary>
+ /// Encodes the specified value.
+ /// </summary>
+ /// <param name="value">The value. Guaranteed to never be null.</param>
+ /// <returns>
+ /// The <paramref name="value"/> in string form, ready for message transport.
+ /// </returns>
+ public string Encode(object value) {
+ var responseType = (GrantType)value;
+ switch (responseType)
+ {
+ case GrantType.ClientCredentials:
+ return Protocol.GrantTypes.ClientCredentials;
+ case GrantType.AuthorizationCode:
+ return Protocol.GrantTypes.AuthorizationCode;
+ case GrantType.RefreshToken:
+ return Protocol.GrantTypes.RefreshToken;
+ case GrantType.Password:
+ return Protocol.GrantTypes.Password;
+ case GrantType.Assertion:
+ return Protocol.GrantTypes.Assertion;
+ default:
+ throw ErrorUtilities.ThrowFormat(MessagingStrings.UnexpectedMessagePartValue, Protocol.grant_type, value);
+ }
+ }
+
+ /// <summary>
+ /// Decodes the specified value.
+ /// </summary>
+ /// <param name="value">The string value carried by the transport. Guaranteed to never be null, although it may be empty.</param>
+ /// <returns>
+ /// The deserialized form of the given string.
+ /// </returns>
+ /// <exception cref="FormatException">Thrown when the string value given cannot be decoded into the required object type.</exception>
+ public object Decode(string value) {
+ switch (value) {
+ case Protocol.GrantTypes.ClientCredentials:
+ return GrantType.ClientCredentials;
+ case Protocol.GrantTypes.Assertion:
+ return GrantType.Assertion;
+ case Protocol.GrantTypes.Password:
+ return GrantType.Password;
+ case Protocol.GrantTypes.RefreshToken:
+ return GrantType.RefreshToken;
+ case Protocol.GrantTypes.AuthorizationCode:
+ return GrantType.AuthorizationCode;
+ default:
+ throw ErrorUtilities.ThrowFormat(MessagingStrings.UnexpectedMessagePartValue, Protocol.grant_type, value);
+ }
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/IAuthorizationCarryingRequest.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/IAuthorizationCarryingRequest.cs
new file mode 100644
index 0000000..e450131
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/IAuthorizationCarryingRequest.cs
@@ -0,0 +1,54 @@
+//-----------------------------------------------------------------------
+// <copyright file="IAuthorizationCarryingRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System.Security.Cryptography;
+
+ using Messaging;
+
+ /// <summary>
+ /// The various types of tokens created by the authorization server.
+ /// </summary>
+ internal enum CodeOrTokenType {
+ /// <summary>
+ /// The code issued to the client after the user has approved authorization.
+ /// </summary>
+ AuthorizationCode,
+
+ /// <summary>
+ /// The long-lived token issued to the client that enables it to obtain
+ /// short-lived access tokens later.
+ /// </summary>
+ RefreshToken,
+
+ /// <summary>
+ /// A (typically) short-lived token.
+ /// </summary>
+ AccessToken,
+ }
+
+ /// <summary>
+ /// A message that carries some kind of token from the client to the authorization or resource server.
+ /// </summary>
+ internal interface IAuthorizationCarryingRequest : IDirectedProtocolMessage {
+ /// <summary>
+ /// Gets or sets the verification code or refresh/access token.
+ /// </summary>
+ /// <value>The code or token.</value>
+ string CodeOrToken { get; set; }
+
+ /// <summary>
+ /// Gets the type of the code or token.
+ /// </summary>
+ /// <value>The type of the code or token.</value>
+ CodeOrTokenType CodeOrTokenType { get; }
+
+ /// <summary>
+ /// Gets or sets the authorization that the token describes.
+ /// </summary>
+ IAuthorizationDescription AuthorizationDescription { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/IAuthorizationDescription.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/IAuthorizationDescription.cs
new file mode 100644
index 0000000..2b3a9ce
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/IAuthorizationDescription.cs
@@ -0,0 +1,90 @@
+//-----------------------------------------------------------------------
+// <copyright file="IAuthorizationDescription.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+
+ /// <summary>
+ /// Describes a delegated authorization between a resource server, a client, and a user.
+ /// </summary>
+ [ContractClass(typeof(IAuthorizationDescriptionContract))]
+ public interface IAuthorizationDescription {
+ /// <summary>
+ /// Gets the identifier of the client authorized to access protected data.
+ /// </summary>
+ string ClientIdentifier { get; }
+
+ /// <summary>
+ /// Gets the date this authorization was established or the token was issued.
+ /// </summary>
+ /// <value>A date/time expressed in UTC.</value>
+ DateTime UtcIssued { get; }
+
+ /// <summary>
+ /// Gets the name on the account whose data on the resource server is accessible using this authorization.
+ /// </summary>
+ string User { get; }
+
+ /// <summary>
+ /// Gets the scope of operations the client is allowed to invoke.
+ /// </summary>
+ HashSet<string> Scope { get; }
+ }
+
+ /// <summary>
+ /// Code contract for the <see cref="IAuthorizationDescription"/> interface.
+ /// </summary>
+ [ContractClassFor(typeof(IAuthorizationDescription))]
+ internal abstract class IAuthorizationDescriptionContract : IAuthorizationDescription {
+ /// <summary>
+ /// Prevents a default instance of the <see cref="IAuthorizationDescriptionContract"/> class from being created.
+ /// </summary>
+ private IAuthorizationDescriptionContract() {
+ }
+
+ /// <summary>
+ /// Gets the identifier of the client authorized to access protected data.
+ /// </summary>
+ string IAuthorizationDescription.ClientIdentifier {
+ get {
+ Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()));
+ throw new NotImplementedException();
+ }
+ }
+
+ /// <summary>
+ /// Gets the date this authorization was established or the token was issued.
+ /// </summary>
+ /// <value>A date/time expressed in UTC.</value>
+ DateTime IAuthorizationDescription.UtcIssued {
+ get { throw new NotImplementedException(); }
+ }
+
+ /// <summary>
+ /// Gets the name on the account whose data on the resource server is accessible using this authorization.
+ /// </summary>
+ string IAuthorizationDescription.User {
+ get {
+ Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()));
+ throw new NotImplementedException();
+ }
+ }
+
+ /// <summary>
+ /// Gets the scope of operations the client is allowed to invoke.
+ /// </summary>
+ HashSet<string> IAuthorizationDescription.Scope {
+ get {
+ Contract.Ensures(Contract.Result<HashSet<string>>() != null);
+ throw new NotImplementedException();
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2AuthorizationServerChannel.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2AuthorizationServerChannel.cs
new file mode 100644
index 0000000..0c31023
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2AuthorizationServerChannel.cs
@@ -0,0 +1,108 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuth2AuthorizationServerChannel.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Net.Mime;
+ using System.Web;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// The channel for the OAuth protocol.
+ /// </summary>
+ internal class OAuth2AuthorizationServerChannel : OAuth2ChannelBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="OAuth2AuthorizationServerChannel"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ protected internal OAuth2AuthorizationServerChannel(IAuthorizationServer authorizationServer)
+ : base(InitializeBindingElements(authorizationServer)) {
+ Requires.NotNull(authorizationServer, "authorizationServer");
+ this.AuthorizationServer = authorizationServer;
+ }
+
+ /// <summary>
+ /// Gets the authorization server.
+ /// </summary>
+ /// <value>The authorization server.</value>
+ public IAuthorizationServer AuthorizationServer { get; private set; }
+
+ /// <summary>
+ /// Gets the protocol message that may be in the given HTTP response.
+ /// </summary>
+ /// <param name="response">The response that is anticipated to contain an protocol message.</param>
+ /// <returns>
+ /// The deserialized message parts, if found. Null otherwise.
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown when the response is not valid.</exception>
+ protected override IDictionary<string, string> ReadFromResponseCore(IncomingWebResponse response) {
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Queues a message for sending in the response stream.
+ /// </summary>
+ /// <param name="response">The message to send as a response.</param>
+ /// <returns>
+ /// The pending user agent redirect based message to be sent as an HttpResponse.
+ /// </returns>
+ /// <remarks>
+ /// This method implements spec OAuth V1.0 section 5.3.
+ /// </remarks>
+ protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) {
+ var webResponse = new OutgoingWebResponse();
+ string json = this.SerializeAsJson(response);
+ webResponse.SetResponse(json, new ContentType(JsonEncoded));
+ return webResponse;
+ }
+
+ /// <summary>
+ /// Gets the protocol message that may be embedded in the given HTTP request.
+ /// </summary>
+ /// <param name="request">The request to search for an embedded message.</param>
+ /// <returns>
+ /// The deserialized message, if one is found. Null otherwise.
+ /// </returns>
+ protected override IDirectedProtocolMessage ReadFromRequestCore(HttpRequestInfo request) {
+ if (!string.IsNullOrEmpty(request.Url.Fragment)) {
+ var fields = HttpUtility.ParseQueryString(request.Url.Fragment.Substring(1)).ToDictionary();
+
+ MessageReceivingEndpoint recipient;
+ try {
+ recipient = request.GetRecipient();
+ } catch (ArgumentException ex) {
+ Logger.Messaging.WarnFormat("Unrecognized HTTP request: " + ex.ToString());
+ return null;
+ }
+
+ return (IDirectedProtocolMessage)this.Receive(fields, recipient);
+ }
+
+ return base.ReadFromRequestCore(request);
+ }
+
+ /// <summary>
+ /// Initializes the binding elements for the OAuth channel.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ /// <returns>
+ /// An array of binding elements used to initialize the channel.
+ /// </returns>
+ private static IChannelBindingElement[] InitializeBindingElements(IAuthorizationServer authorizationServer) {
+ Requires.NotNull(authorizationServer, "authorizationServer");
+ var bindingElements = new List<IChannelBindingElement>();
+
+ bindingElements.Add(new AuthServerAllFlowsBindingElement());
+ bindingElements.Add(new AuthorizationCodeBindingElement());
+ bindingElements.Add(new AccessTokenBindingElement());
+ bindingElements.Add(new AccessRequestBindingElement());
+
+ return bindingElements.ToArray();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2ChannelBase.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2ChannelBase.cs
new file mode 100644
index 0000000..a646f51
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2ChannelBase.cs
@@ -0,0 +1,69 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuth2ChannelBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.Messages;
+
+ /// <summary>
+ /// The base messaging channel used by OAuth 2.0 parties.
+ /// </summary>
+ internal abstract class OAuth2ChannelBase : StandardMessageFactoryChannel {
+ /// <summary>
+ /// The messages receivable by this channel.
+ /// </summary>
+ private static readonly Type[] MessageTypes = new Type[] {
+ typeof(AccessTokenRefreshRequest),
+ typeof(AccessTokenAuthorizationCodeRequest),
+ typeof(AccessTokenResourceOwnerPasswordCredentialsRequest),
+ typeof(AccessTokenClientCredentialsRequest),
+ typeof(AccessTokenSuccessResponse),
+ typeof(AccessTokenFailedResponse),
+ typeof(EndUserAuthorizationRequest),
+ typeof(EndUserAuthorizationSuccessAuthCodeResponse),
+ typeof(EndUserAuthorizationSuccessAccessTokenResponse),
+ typeof(EndUserAuthorizationFailedResponse),
+ typeof(UnauthorizedResponse),
+ };
+
+ /// <summary>
+ /// The protocol versions supported by this channel.
+ /// </summary>
+ private static readonly Version[] Versions = Protocol.AllVersions.Select(v => v.Version).ToArray();
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="OAuth2ChannelBase"/> class.
+ /// </summary>
+ /// <param name="channelBindingElements">The channel binding elements.</param>
+ internal OAuth2ChannelBase(params IChannelBindingElement[] channelBindingElements)
+ : base(MessageTypes, Versions, channelBindingElements) {
+ }
+
+ /// <summary>
+ /// Allows preprocessing and validation of message data before an appropriate message type is
+ /// selected or deserialized.
+ /// </summary>
+ /// <param name="fields">The received message data.</param>
+ protected override void FilterReceivedFields(IDictionary<string, string> fields) {
+ base.FilterReceivedFields(fields);
+
+ // Apply the OAuth 2.0 section 2.1 requirement:
+ // Parameters sent without a value MUST be treated as if they were omitted from the request.
+ // The authorization server SHOULD ignore unrecognized request parameters.
+ var emptyKeys = from pair in fields
+ where String.IsNullOrEmpty(pair.Value)
+ select pair.Key;
+ foreach (string emptyKey in emptyKeys.ToList()) {
+ fields.Remove(emptyKey);
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2ClientChannel.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2ClientChannel.cs
new file mode 100644
index 0000000..e4a9afd
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2ClientChannel.cs
@@ -0,0 +1,122 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuth2ClientChannel.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Collections.Specialized;
+ using System.Diagnostics.Contracts;
+ using System.Net;
+ using System.Web;
+
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// The messaging channel used by OAuth 2.0 Clients.
+ /// </summary>
+ internal class OAuth2ClientChannel : OAuth2ChannelBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="OAuth2ClientChannel"/> class.
+ /// </summary>
+ internal OAuth2ClientChannel() {
+ }
+
+ /// <summary>
+ /// Prepares an HTTP request that carries a given message.
+ /// </summary>
+ /// <param name="request">The message to send.</param>
+ /// <returns>
+ /// The <see cref="HttpWebRequest"/> prepared to send the request.
+ /// </returns>
+ /// <remarks>
+ /// This method must be overridden by a derived class, unless the <see cref="Channel.RequestCore"/> method
+ /// is overridden and does not require this method.
+ /// </remarks>
+ protected override HttpWebRequest CreateHttpRequest(IDirectedProtocolMessage request) {
+ HttpWebRequest httpRequest;
+ if ((request.HttpMethods & HttpDeliveryMethods.GetRequest) != 0) {
+ httpRequest = InitializeRequestAsGet(request);
+ } else if ((request.HttpMethods & HttpDeliveryMethods.PostRequest) != 0) {
+ httpRequest = InitializeRequestAsPost(request);
+ } else {
+ throw new NotSupportedException();
+ }
+
+ return httpRequest;
+ }
+
+ /// <summary>
+ /// Gets the protocol message that may be in the given HTTP response.
+ /// </summary>
+ /// <param name="response">The response that is anticipated to contain an protocol message.</param>
+ /// <returns>
+ /// The deserialized message parts, if found. Null otherwise.
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown when the response is not valid.</exception>
+ protected override IDictionary<string, string> ReadFromResponseCore(IncomingWebResponse response) {
+ // The spec says direct responses should be JSON objects, but Facebook uses HttpFormUrlEncoded instead, calling it text/plain
+ // Others return text/javascript. Again bad.
+ string body = response.GetResponseReader().ReadToEnd();
+ if (response.ContentType.MediaType == JsonEncoded || response.ContentType.MediaType == JsonTextEncoded) {
+ return this.DeserializeFromJson(body);
+ } else if (response.ContentType.MediaType == HttpFormUrlEncoded || response.ContentType.MediaType == PlainTextEncoded) {
+ return HttpUtility.ParseQueryString(body).ToDictionary();
+ } else {
+ throw ErrorUtilities.ThrowProtocol("Unexpected response Content-Type {0}", response.ContentType.MediaType);
+ }
+ }
+
+ /// <summary>
+ /// Gets the protocol message that may be embedded in the given HTTP request.
+ /// </summary>
+ /// <param name="request">The request to search for an embedded message.</param>
+ /// <returns>
+ /// The deserialized message, if one is found. Null otherwise.
+ /// </returns>
+ protected override IDirectedProtocolMessage ReadFromRequestCore(HttpRequestInfo request) {
+ Logger.Channel.DebugFormat("Incoming HTTP request: {0} {1}", request.HttpMethod, request.UrlBeforeRewriting.AbsoluteUri);
+
+ var fields = request.QueryStringBeforeRewriting.ToDictionary();
+
+ // Also read parameters from the fragment, if it's available.
+ // Typically the fragment is not available because the browser doesn't send it to a web server
+ // but this request may have been fabricated by an installed desktop app, in which case
+ // the fragment is available.
+ string fragment = request.UrlBeforeRewriting.Fragment;
+ if (!string.IsNullOrEmpty(fragment)) {
+ foreach (var pair in HttpUtility.ParseQueryString(fragment.Substring(1)).ToDictionary()) {
+ fields.Add(pair.Key, pair.Value);
+ }
+ }
+
+ MessageReceivingEndpoint recipient;
+ try {
+ recipient = request.GetRecipient();
+ } catch (ArgumentException ex) {
+ Logger.Messaging.WarnFormat("Unrecognized HTTP request: ", ex);
+ return null;
+ }
+
+ return (IDirectedProtocolMessage)this.Receive(fields, recipient);
+ }
+
+ /// <summary>
+ /// Queues a message for sending in the response stream where the fields
+ /// are sent in the response stream in querystring style.
+ /// </summary>
+ /// <param name="response">The message to send as a response.</param>
+ /// <returns>
+ /// The pending user agent redirect based message to be sent as an HttpResponse.
+ /// </returns>
+ /// <remarks>
+ /// This method implements spec OAuth V1.0 section 5.3.
+ /// </remarks>
+ protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) {
+ // Clients don't ever send direct responses.
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2ResourceServerChannel.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2ResourceServerChannel.cs
new file mode 100644
index 0000000..97a70c8
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2ResourceServerChannel.cs
@@ -0,0 +1,153 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuth2ResourceServerChannel.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Net;
+ using System.Net.Mime;
+ using System.Text;
+ using System.Web;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Reflection;
+ using DotNetOpenAuth.OAuth2.Messages;
+
+ /// <summary>
+ /// The channel for the OAuth protocol.
+ /// </summary>
+ internal class OAuth2ResourceServerChannel : StandardMessageFactoryChannel {
+ /// <summary>
+ /// The messages receivable by this channel.
+ /// </summary>
+ private static readonly Type[] MessageTypes = new Type[] {
+ typeof(Messages.AccessProtectedResourceRequest),
+ };
+
+ /// <summary>
+ /// The protocol versions supported by this channel.
+ /// </summary>
+ private static readonly Version[] Versions = Protocol.AllVersions.Select(v => v.Version).ToArray();
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="OAuth2ResourceServerChannel"/> class.
+ /// </summary>
+ protected internal OAuth2ResourceServerChannel()
+ : base(MessageTypes, Versions) {
+ // TODO: add signing (authenticated request) binding element.
+ }
+
+ /// <summary>
+ /// Gets the protocol message that may be embedded in the given HTTP request.
+ /// </summary>
+ /// <param name="request">The request to search for an embedded message.</param>
+ /// <returns>
+ /// The deserialized message, if one is found. Null otherwise.
+ /// </returns>
+ protected override IDirectedProtocolMessage ReadFromRequestCore(HttpRequestInfo request) {
+ var fields = new Dictionary<string, string>();
+ string accessToken;
+ if ((accessToken = SearchForBearerAccessTokenInRequest(request)) != null) {
+ fields["token_type"] = Protocol.AccessTokenTypes.Bearer;
+ fields["access_token"] = accessToken;
+ }
+
+ if (fields.Count > 0) {
+ MessageReceivingEndpoint recipient;
+ try {
+ recipient = request.GetRecipient();
+ } catch (ArgumentException ex) {
+ Logger.OAuth.WarnFormat("Unrecognized HTTP request: " + ex.ToString());
+ return null;
+ }
+
+ // Deserialize the message using all the data we've collected.
+ var message = (IDirectedProtocolMessage)this.Receive(fields, recipient);
+ return message;
+ }
+
+ return null;
+ }
+
+ /// <summary>
+ /// Gets the protocol message that may be in the given HTTP response.
+ /// </summary>
+ /// <param name="response">The response that is anticipated to contain an protocol message.</param>
+ /// <returns>
+ /// The deserialized message parts, if found. Null otherwise.
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown when the response is not valid.</exception>
+ protected override IDictionary<string, string> ReadFromResponseCore(IncomingWebResponse response) {
+ // We never expect resource servers to send out direct requests,
+ // and therefore won't have direct responses.
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Queues a message for sending in the response stream where the fields
+ /// are sent in the response stream in querystring style.
+ /// </summary>
+ /// <param name="response">The message to send as a response.</param>
+ /// <returns>
+ /// The pending user agent redirect based message to be sent as an HttpResponse.
+ /// </returns>
+ /// <remarks>
+ /// This method implements spec OAuth V1.0 section 5.3.
+ /// </remarks>
+ protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) {
+ var webResponse = new OutgoingWebResponse();
+
+ // The only direct response from a resource server is a 401 Unauthorized error.
+ var unauthorizedResponse = response as UnauthorizedResponse;
+ ErrorUtilities.VerifyInternal(unauthorizedResponse != null, "Only unauthorized responses are expected.");
+
+ // First initialize based on the specifics within the message.
+ var httpResponse = response as IHttpDirectResponse;
+ webResponse.Status = httpResponse != null ? httpResponse.HttpStatusCode : HttpStatusCode.Unauthorized;
+ foreach (string headerName in httpResponse.Headers) {
+ webResponse.Headers.Add(headerName, httpResponse.Headers[headerName]);
+ }
+
+ // Now serialize all the message parts into the WWW-Authenticate header.
+ var fields = this.MessageDescriptions.GetAccessor(response);
+ webResponse.Headers[HttpResponseHeader.WwwAuthenticate] = MessagingUtilities.AssembleAuthorizationHeader(Protocol.BearerHttpAuthorizationScheme, fields);
+ return webResponse;
+ }
+
+ /// <summary>
+ /// Searches for a bearer access token in the request.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ /// <returns>The bearer access token, if one exists. Otherwise <c>null</c>.</returns>
+ private static string SearchForBearerAccessTokenInRequest(HttpRequestInfo request) {
+ Requires.NotNull(request, "request");
+
+ // First search the authorization header.
+ string authorizationHeader = request.Headers[HttpRequestHeader.Authorization];
+ if (!string.IsNullOrEmpty(authorizationHeader) && authorizationHeader.StartsWith(Protocol.BearerHttpAuthorizationSchemeWithTrailingSpace, StringComparison.OrdinalIgnoreCase)) {
+ return authorizationHeader.Substring(Protocol.BearerHttpAuthorizationSchemeWithTrailingSpace.Length);
+ }
+
+ // Failing that, scan the entity
+ if (!string.IsNullOrEmpty(request.Headers[HttpRequestHeader.ContentType])) {
+ var contentType = new ContentType(request.Headers[HttpRequestHeader.ContentType]);
+ if (string.Equals(contentType.MediaType, HttpFormUrlEncoded, StringComparison.Ordinal)) {
+ if (request.Form[Protocol.BearerTokenEncodedUrlParameterName] != null) {
+ return request.Form[Protocol.BearerTokenEncodedUrlParameterName];
+ }
+ }
+ }
+
+ // Finally, check the least desirable location: the query string
+ if (!String.IsNullOrEmpty(request.QueryStringBeforeRewriting[Protocol.BearerTokenEncodedUrlParameterName])) {
+ return request.QueryStringBeforeRewriting[Protocol.BearerTokenEncodedUrlParameterName];
+ }
+
+ return null;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/RefreshToken.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/RefreshToken.cs
new file mode 100644
index 0000000..ee41957
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/RefreshToken.cs
@@ -0,0 +1,56 @@
+//-----------------------------------------------------------------------
+// <copyright file="RefreshToken.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Diagnostics.Contracts;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+
+ /// <summary>
+ /// The refresh token issued to a client by an authorization server that allows the client
+ /// to periodically obtain new short-lived access tokens.
+ /// </summary>
+ internal class RefreshToken : AuthorizationDataBag {
+ /// <summary>
+ /// The name of the bucket for symmetric keys used to sign refresh tokens.
+ /// </summary>
+ internal const string RefreshTokenKeyBucket = "https://localhost/dnoa/oauth_refresh_token";
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RefreshToken"/> class.
+ /// </summary>
+ public RefreshToken() {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RefreshToken"/> class.
+ /// </summary>
+ /// <param name="authorization">The authorization this refresh token should describe.</param>
+ internal RefreshToken(IAuthorizationDescription authorization) {
+ Requires.NotNull(authorization, "authorization");
+
+ this.ClientIdentifier = authorization.ClientIdentifier;
+ this.UtcCreationDate = authorization.UtcIssued;
+ this.User = authorization.User;
+ this.Scope.ResetContents(authorization.Scope);
+ }
+
+ /// <summary>
+ /// Creates a formatter capable of serializing/deserializing a refresh token.
+ /// </summary>
+ /// <param name="cryptoKeyStore">The crypto key store.</param>
+ /// <returns>
+ /// A DataBag formatter. Never null.
+ /// </returns>
+ internal static IDataBagFormatter<RefreshToken> CreateFormatter(ICryptoKeyStore cryptoKeyStore) {
+ Requires.NotNull(cryptoKeyStore, "cryptoKeyStore");
+ Contract.Ensures(Contract.Result<IDataBagFormatter<RefreshToken>>() != null);
+
+ return new UriStyleMessageFormatter<RefreshToken>(cryptoKeyStore, RefreshTokenKeyBucket, signed: true, encrypted: true);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/ScopeEncoder.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/ScopeEncoder.cs
new file mode 100644
index 0000000..7ae5fbf
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/ScopeEncoder.cs
@@ -0,0 +1,51 @@
+//-----------------------------------------------------------------------
+// <copyright file="ScopeEncoder.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Reflection;
+
+ /// <summary>
+ /// Encodes or decodes a set of scopes into the OAuth 2.0 scope message part.
+ /// </summary>
+ internal class ScopeEncoder : IMessagePartEncoder {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ScopeEncoder"/> class.
+ /// </summary>
+ public ScopeEncoder() {
+ }
+
+ /// <summary>
+ /// Encodes the specified value.
+ /// </summary>
+ /// <param name="value">The value. Guaranteed to never be null.</param>
+ /// <returns>
+ /// The <paramref name="value"/> in string form, ready for message transport.
+ /// </returns>
+ public string Encode(object value) {
+ var scopes = (IEnumerable<string>)value;
+ ErrorUtilities.VerifyProtocol(!scopes.Any(scope => scope.Contains(" ")), OAuthStrings.ScopesMayNotContainSpaces);
+ return (scopes != null && scopes.Any()) ? string.Join(" ", scopes.ToArray()) : null;
+ }
+
+ /// <summary>
+ /// Decodes the specified value.
+ /// </summary>
+ /// <param name="value">The string value carried by the transport. Guaranteed to never be null, although it may be empty.</param>
+ /// <returns>
+ /// The deserialized form of the given string.
+ /// </returns>
+ /// <exception cref="FormatException">Thrown when the string value given cannot be decoded into the required object type.</exception>
+ public object Decode(string value) {
+ return OAuthUtilities.SplitScopes(value);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/IAccessTokenAnalyzer.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/IAccessTokenAnalyzer.cs
new file mode 100644
index 0000000..0897090
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/IAccessTokenAnalyzer.cs
@@ -0,0 +1,64 @@
+//-----------------------------------------------------------------------
+// <copyright file="IAccessTokenAnalyzer.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// An interface that resource server hosts should implement if they accept access tokens
+ /// issued by non-DotNetOpenAuth authorization servers.
+ /// </summary>
+ [ContractClass((typeof(IAccessTokenAnalyzerContract)))]
+ public interface IAccessTokenAnalyzer {
+ /// <summary>
+ /// Reads an access token to find out what data it authorizes access to.
+ /// </summary>
+ /// <param name="message">The message carrying the access token.</param>
+ /// <param name="accessToken">The access token.</param>
+ /// <param name="user">The user whose data is accessible with this access token.</param>
+ /// <param name="scope">The scope of access authorized by this access token.</param>
+ /// <returns>A value indicating whether this access token is valid.</returns>
+ [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#", Justification = "Try pattern")]
+ [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification = "Try pattern")]
+ bool TryValidateAccessToken(IDirectedProtocolMessage message, string accessToken, out string user, out HashSet<string> scope);
+ }
+
+ /// <summary>
+ /// Code contract for the <see cref="IAccessTokenAnalyzer"/> interface.
+ /// </summary>
+ [ContractClassFor(typeof(IAccessTokenAnalyzer))]
+ internal abstract class IAccessTokenAnalyzerContract : IAccessTokenAnalyzer {
+ /// <summary>
+ /// Prevents a default instance of the <see cref="IAccessTokenAnalyzerContract"/> class from being created.
+ /// </summary>
+ private IAccessTokenAnalyzerContract() {
+ }
+
+ /// <summary>
+ /// Reads an access token to find out what data it authorizes access to.
+ /// </summary>
+ /// <param name="message">The message carrying the access token.</param>
+ /// <param name="accessToken">The access token.</param>
+ /// <param name="user">The user whose data is accessible with this access token.</param>
+ /// <param name="scope">The scope of access authorized by this access token.</param>
+ /// <returns>
+ /// A value indicating whether this access token is valid.
+ /// </returns>
+ bool IAccessTokenAnalyzer.TryValidateAccessToken(IDirectedProtocolMessage message, string accessToken, out string user, out HashSet<string> scope) {
+ Requires.NotNull(message, "message");
+ Requires.NotNullOrEmpty(accessToken, "accessToken");
+ Contract.Ensures(Contract.Result<bool>() == (Contract.ValueAtReturn<string>(out user) != null));
+
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/IAuthorizationServer.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/IAuthorizationServer.cs
new file mode 100644
index 0000000..6457f36
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/IAuthorizationServer.cs
@@ -0,0 +1,238 @@
+//-----------------------------------------------------------------------
+// <copyright file="IAuthorizationServer.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Security.Cryptography;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+ using DotNetOpenAuth.OAuth2.Messages;
+
+ /// <summary>
+ /// Provides host-specific authorization server services needed by this library.
+ /// </summary>
+ [ContractClass(typeof(IAuthorizationServerContract))]
+ public interface IAuthorizationServer {
+ /// <summary>
+ /// Gets the store for storeing crypto keys used to symmetrically encrypt and sign authorization codes and refresh tokens.
+ /// </summary>
+ /// <remarks>
+ /// This store should be kept strictly confidential in the authorization server(s)
+ /// and NOT shared with the resource server. Anyone with these secrets can mint
+ /// tokens to essentially grant themselves access to anything they want.
+ /// </remarks>
+ ICryptoKeyStore CryptoKeyStore { get; }
+
+ /// <summary>
+ /// Gets the authorization code nonce store to use to ensure that authorization codes can only be used once.
+ /// </summary>
+ /// <value>The authorization code nonce store.</value>
+ INonceStore VerificationCodeNonceStore { get; }
+
+ /// <summary>
+ /// Gets the crypto service provider with the asymmetric private key to use for signing access tokens.
+ /// </summary>
+ /// <returns>A crypto service provider instance that contains the private key.</returns>
+ /// <value>Must not be null, and must contain the private key.</value>
+ /// <remarks>
+ /// The public key in the private/public key pair will be used by the resource
+ /// servers to validate that the access token is minted by a trusted authorization server.
+ /// </remarks>
+ RSACryptoServiceProvider AccessTokenSigningKey { get; }
+
+ /// <summary>
+ /// Obtains the lifetime for a new access token.
+ /// </summary>
+ /// <param name="accessTokenRequestMessage">
+ /// Details regarding the resources that the access token will grant access to, and the identity of the client
+ /// that will receive that access.
+ /// Based on this information the receiving resource server can be determined and the lifetime of the access
+ /// token can be set based on the sensitivity of the resources.
+ /// </param>
+ /// <returns>
+ /// Receives the lifetime for this access token. Note that within this lifetime, authorization <i>may</i> not be revokable.
+ /// Short lifetimes are recommended (i.e. one hour), particularly when the client is not authenticated or
+ /// the resources to which access is being granted are sensitive.
+ /// </returns>
+ TimeSpan GetAccessTokenLifetime(IAccessTokenRequest accessTokenRequestMessage);
+
+ /// <summary>
+ /// Obtains the encryption key for an access token being created.
+ /// </summary>
+ /// <param name="accessTokenRequestMessage">
+ /// Details regarding the resources that the access token will grant access to, and the identity of the client
+ /// that will receive that access.
+ /// Based on this information the receiving resource server can be determined and the lifetime of the access
+ /// token can be set based on the sensitivity of the resources.
+ /// </param>
+ /// <returns>
+ /// The crypto service provider with the asymmetric public key to use for encrypting access tokens for a specific resource server.
+ /// The caller is responsible to dispose of this value.
+ /// </returns>
+ /// <remarks>
+ /// The caller is responsible to dispose of the returned value.
+ /// </remarks>
+ RSACryptoServiceProvider GetResourceServerEncryptionKey(IAccessTokenRequest accessTokenRequestMessage);
+
+ /// <summary>
+ /// Gets the client with a given identifier.
+ /// </summary>
+ /// <param name="clientIdentifier">The client identifier.</param>
+ /// <returns>The client registration. Never null.</returns>
+ /// <exception cref="ArgumentException">Thrown when no client with the given identifier is registered with this authorization server.</exception>
+ IConsumerDescription GetClient(string clientIdentifier);
+
+ /// <summary>
+ /// Determines whether a described authorization is (still) valid.
+ /// </summary>
+ /// <param name="authorization">The authorization.</param>
+ /// <returns>
+ /// <c>true</c> if the original authorization is still valid; otherwise, <c>false</c>.
+ /// </returns>
+ /// <remarks>
+ /// <para>When establishing that an authorization is still valid,
+ /// it's very important to only match on recorded authorizations that
+ /// meet these criteria:</para>
+ /// 1) The client identifier matches.
+ /// 2) The user account matches.
+ /// 3) The scope on the recorded authorization must include all scopes in the given authorization.
+ /// 4) The date the recorded authorization was issued must be <em>no later</em> that the date the given authorization was issued.
+ /// <para>One possible scenario is where the user authorized a client, later revoked authorization,
+ /// and even later reinstated authorization. This subsequent recorded authorization
+ /// would not satisfy requirement #4 in the above list. This is important because the revocation
+ /// the user went through should invalidate all previously issued tokens as a matter of
+ /// security in the event the user was revoking access in order to sever authorization on a stolen
+ /// account or piece of hardware in which the tokens were stored. </para>
+ /// </remarks>
+ bool IsAuthorizationValid(IAuthorizationDescription authorization);
+ }
+
+ /// <summary>
+ /// Code Contract for the <see cref="IAuthorizationServer"/> interface.
+ /// </summary>
+ [ContractClassFor(typeof(IAuthorizationServer))]
+ internal abstract class IAuthorizationServerContract : IAuthorizationServer {
+ /// <summary>
+ /// Prevents a default instance of the <see cref="IAuthorizationServerContract"/> class from being created.
+ /// </summary>
+ private IAuthorizationServerContract() {
+ }
+
+ /// <summary>
+ /// Gets the store for storeing crypto keys used to symmetrically encrypt and sign authorization codes and refresh tokens.
+ /// </summary>
+ ICryptoKeyStore IAuthorizationServer.CryptoKeyStore {
+ get {
+ Contract.Ensures(Contract.Result<ICryptoKeyStore>() != null);
+ throw new NotImplementedException();
+ }
+ }
+
+ /// <summary>
+ /// Gets the authorization code nonce store to use to ensure that authorization codes can only be used once.
+ /// </summary>
+ /// <value>The authorization code nonce store.</value>
+ INonceStore IAuthorizationServer.VerificationCodeNonceStore {
+ get {
+ Contract.Ensures(Contract.Result<INonceStore>() != null);
+ throw new NotImplementedException();
+ }
+ }
+
+ /// <summary>
+ /// Gets the crypto service provider with the asymmetric private key to use for signing access tokens.
+ /// </summary>
+ /// <value>
+ /// Must not be null, and must contain the private key.
+ /// </value>
+ /// <returns>A crypto service provider instance that contains the private key.</returns>
+ RSACryptoServiceProvider IAuthorizationServer.AccessTokenSigningKey {
+ get {
+ Contract.Ensures(Contract.Result<RSACryptoServiceProvider>() != null);
+ Contract.Ensures(!Contract.Result<RSACryptoServiceProvider>().PublicOnly);
+ throw new NotImplementedException();
+ }
+ }
+
+ /// <summary>
+ /// Obtains the lifetime for a new access token.
+ /// </summary>
+ /// <param name="accessTokenRequestMessage">Details regarding the resources that the access token will grant access to, and the identity of the client
+ /// that will receive that access.
+ /// Based on this information the receiving resource server can be determined and the lifetime of the access
+ /// token can be set based on the sensitivity of the resources.</param>
+ /// <returns>
+ /// Receives the lifetime for this access token. Note that within this lifetime, authorization <i>may</i> not be revokable.
+ /// Short lifetimes are recommended (i.e. one hour), particularly when the client is not authenticated or
+ /// the resources to which access is being granted are sensitive.
+ /// </returns>
+ TimeSpan IAuthorizationServer.GetAccessTokenLifetime(IAccessTokenRequest accessTokenRequestMessage) {
+ Requires.NotNull(accessTokenRequestMessage, "accessTokenRequestMessage");
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Obtains the encryption key for an access token being created.
+ /// </summary>
+ /// <param name="accessTokenRequestMessage">Details regarding the resources that the access token will grant access to, and the identity of the client
+ /// that will receive that access.
+ /// Based on this information the receiving resource server can be determined and the lifetime of the access
+ /// token can be set based on the sensitivity of the resources.</param>
+ /// <returns>
+ /// The crypto service provider with the asymmetric public key to use for encrypting access tokens for a specific resource server.
+ /// The caller is responsible to dispose of this value.
+ /// </returns>
+ RSACryptoServiceProvider IAuthorizationServer.GetResourceServerEncryptionKey(IAccessTokenRequest accessTokenRequestMessage) {
+ Requires.NotNull(accessTokenRequestMessage, "accessTokenRequestMessage");
+ Contract.Ensures(Contract.Result<RSACryptoServiceProvider>() != null);
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Gets the client with a given identifier.
+ /// </summary>
+ /// <param name="clientIdentifier">The client identifier.</param>
+ /// <returns>The client registration. Never null.</returns>
+ /// <exception cref="ArgumentException">Thrown when no client with the given identifier is registered with this authorization server.</exception>
+ IConsumerDescription IAuthorizationServer.GetClient(string clientIdentifier) {
+ Requires.NotNullOrEmpty(clientIdentifier, "clientIdentifier");
+ Contract.Ensures(Contract.Result<IConsumerDescription>() != null);
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Determines whether a described authorization is (still) valid.
+ /// </summary>
+ /// <param name="authorization">The authorization.</param>
+ /// <returns>
+ /// <c>true</c> if the original authorization is still valid; otherwise, <c>false</c>.
+ /// </returns>
+ /// <remarks>
+ /// <para>When establishing that an authorization is still valid,
+ /// it's very important to only match on recorded authorizations that
+ /// meet these criteria:</para>
+ /// 1) The client identifier matches.
+ /// 2) The user account matches.
+ /// 3) The scope on the recorded authorization must include all scopes in the given authorization.
+ /// 4) The date the recorded authorization was issued must be <em>no later</em> that the date the given authorization was issued.
+ /// <para>One possible scenario is where the user authorized a client, later revoked authorization,
+ /// and even later reinstated authorization. This subsequent recorded authorization
+ /// would not satisfy requirement #4 in the above list. This is important because the revocation
+ /// the user went through should invalidate all previously issued tokens as a matter of
+ /// security in the event the user was revoking access in order to sever authorization on a stolen
+ /// account or piece of hardware in which the tokens were stored. </para>
+ /// </remarks>
+ bool IAuthorizationServer.IsAuthorizationValid(IAuthorizationDescription authorization) {
+ Requires.NotNull(authorization, "authorization");
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/IAuthorizationState.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/IAuthorizationState.cs
new file mode 100644
index 0000000..39437ac
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/IAuthorizationState.cs
@@ -0,0 +1,67 @@
+//-----------------------------------------------------------------------
+// <copyright file="IAuthorizationState.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+
+ /// <summary>
+ /// Provides access to a persistent object that tracks the state of an authorization.
+ /// </summary>
+ public interface IAuthorizationState {
+ /// <summary>
+ /// Gets or sets the callback URL used to obtain authorization.
+ /// </summary>
+ /// <value>The callback URL.</value>
+ Uri Callback { get; set; }
+
+ /// <summary>
+ /// Gets or sets the long-lived token used to renew the short-lived <see cref="AccessToken"/>.
+ /// </summary>
+ /// <value>The refresh token.</value>
+ string RefreshToken { get; set; }
+
+ /// <summary>
+ /// Gets or sets the access token.
+ /// </summary>
+ /// <value>The access token.</value>
+ string AccessToken { get; set; }
+
+ /// <summary>
+ /// Gets or sets the access token issue date UTC.
+ /// </summary>
+ /// <value>The access token issue date UTC.</value>
+ DateTime? AccessTokenIssueDateUtc { get; set; }
+
+ /// <summary>
+ /// Gets or sets the access token UTC expiration date.
+ /// </summary>
+ DateTime? AccessTokenExpirationUtc { get; set; }
+
+ /// <summary>
+ /// Gets the scope the token is (to be) authorized for.
+ /// </summary>
+ /// <value>The scope.</value>
+ HashSet<string> Scope { get; }
+
+ /// <summary>
+ /// Deletes this authorization, including access token and refresh token where applicable.
+ /// </summary>
+ /// <remarks>
+ /// This method is invoked when an authorization attempt fails, is rejected, is revoked, or
+ /// expires and cannot be renewed.
+ /// </remarks>
+ void Delete();
+
+ /// <summary>
+ /// Saves any changes made to this authorization object's properties.
+ /// </summary>
+ /// <remarks>
+ /// This method is invoked after DotNetOpenAuth changes any property.
+ /// </remarks>
+ void SaveChanges();
+ }
+} \ No newline at end of file
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/IClientAuthorizationTracker.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/IClientAuthorizationTracker.cs
new file mode 100644
index 0000000..4529cef
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/IClientAuthorizationTracker.cs
@@ -0,0 +1,53 @@
+//-----------------------------------------------------------------------
+// <copyright file="IClientAuthorizationTracker.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Diagnostics.Contracts;
+
+ /// <summary>
+ /// A token manager implemented by some clients to assist in tracking authorization state.
+ /// </summary>
+ [ContractClass(typeof(IClientAuthorizationTrackerContract))]
+ public interface IClientAuthorizationTracker {
+ /// <summary>
+ /// Gets the state of the authorization for a given callback URL and client state.
+ /// </summary>
+ /// <param name="callbackUrl">The callback URL.</param>
+ /// <param name="clientState">State of the client stored at the beginning of an authorization request.</param>
+ /// <returns>The authorization state; may be <c>null</c> if no authorization state matches.</returns>
+ IAuthorizationState GetAuthorizationState(Uri callbackUrl, string clientState);
+ }
+
+ /// <summary>
+ /// Contract class for the <see cref="IClientAuthorizationTracker"/> interface.
+ /// </summary>
+ [ContractClassFor(typeof(IClientAuthorizationTracker))]
+ internal abstract class IClientAuthorizationTrackerContract : IClientAuthorizationTracker {
+ /// <summary>
+ /// Prevents a default instance of the <see cref="IClientAuthorizationTrackerContract"/> class from being created.
+ /// </summary>
+ private IClientAuthorizationTrackerContract() {
+ }
+
+ #region IClientTokenManager Members
+
+ /// <summary>
+ /// Gets the state of the authorization for a given callback URL and client state.
+ /// </summary>
+ /// <param name="callbackUrl">The callback URL.</param>
+ /// <param name="clientState">State of the client stored at the beginning of an authorization request.</param>
+ /// <returns>
+ /// The authorization state; may be <c>null</c> if no authorization state matches.
+ /// </returns>
+ IAuthorizationState IClientAuthorizationTracker.GetAuthorizationState(Uri callbackUrl, string clientState) {
+ Requires.NotNull(callbackUrl, "callbackUrl");
+ throw new NotImplementedException();
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/IConsumerDescription.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/IConsumerDescription.cs
new file mode 100644
index 0000000..cf07dc6
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/IConsumerDescription.cs
@@ -0,0 +1,101 @@
+//-----------------------------------------------------------------------
+// <copyright file="IConsumerDescription.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+
+ /// <summary>
+ /// A description of a client from an Authorization Server's point of view.
+ /// </summary>
+ [ContractClass(typeof(IConsumerDescriptionContract))]
+ public interface IConsumerDescription {
+ /// <summary>
+ /// Gets the client secret.
+ /// </summary>
+ string Secret { get; }
+
+ /// <summary>
+ /// Gets the callback to use when an individual authorization request
+ /// does not include an explicit callback URI.
+ /// </summary>
+ /// <value>An absolute URL; or <c>null</c> if none is registered.</value>
+ Uri DefaultCallback { get; }
+
+ /// <summary>
+ /// Determines whether a callback URI included in a client's authorization request
+ /// is among those allowed callbacks for the registered client.
+ /// </summary>
+ /// <param name="callback">The absolute URI the client has requested the authorization result be received at.</param>
+ /// <returns>
+ /// <c>true</c> if the callback URL is allowable for this client; otherwise, <c>false</c>.
+ /// </returns>
+ /// <remarks>
+ /// <para>
+ /// At the point this method is invoked, the identity of the client has <em>not</em>
+ /// been confirmed. To avoid open redirector attacks, the alleged client's identity
+ /// is used to lookup a list of allowable callback URLs to make sure that the callback URL
+ /// the actual client is requesting is one of the expected ones.
+ /// </para>
+ /// <para>
+ /// From OAuth 2.0 section 2.1:
+ /// The authorization server SHOULD require the client to pre-register
+ /// their redirection URI or at least certain components such as the
+ /// scheme, host, port and path. If a redirection URI was registered,
+ /// the authorization server MUST compare any redirection URI received at
+ /// the authorization endpoint with the registered URI.
+ /// </para>
+ /// </remarks>
+ bool IsCallbackAllowed(Uri callback);
+ }
+
+ /// <summary>
+ /// Contract class for the <see cref="IConsumerDescription"/> interface.
+ /// </summary>
+ [ContractClassFor(typeof(IConsumerDescription))]
+ internal abstract class IConsumerDescriptionContract : IConsumerDescription {
+ #region IConsumerDescription Members
+
+ /// <summary>
+ /// Gets the client secret.
+ /// </summary>
+ /// <value></value>
+ string IConsumerDescription.Secret {
+ get { throw new NotImplementedException(); }
+ }
+
+ /// <summary>
+ /// Gets the callback to use when an individual authorization request
+ /// does not include an explicit callback URI.
+ /// </summary>
+ /// <value>
+ /// An absolute URL; or <c>null</c> if none is registered.
+ /// </value>
+ Uri IConsumerDescription.DefaultCallback {
+ get {
+ Contract.Ensures(Contract.Result<Uri>() == null || Contract.Result<Uri>().IsAbsoluteUri);
+ throw new NotImplementedException();
+ }
+ }
+
+ /// <summary>
+ /// Determines whether a callback URI included in a client's authorization request
+ /// is among those allowed callbacks for the registered client.
+ /// </summary>
+ /// <param name="callback">The requested callback URI.</param>
+ /// <returns>
+ /// <c>true</c> if the callback is allowed; otherwise, <c>false</c>.
+ /// </returns>
+ bool IConsumerDescription.IsCallbackAllowed(Uri callback) {
+ Requires.NotNull(callback, "callback");
+ Requires.True(callback.IsAbsoluteUri, "callback");
+ throw new NotImplementedException();
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessProtectedResourceRequest.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessProtectedResourceRequest.cs
new file mode 100644
index 0000000..2e94156
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessProtectedResourceRequest.cs
@@ -0,0 +1,73 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessProtectedResourceRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using ChannelElements;
+ using Messaging;
+
+ /// <summary>
+ /// A message that accompanies an HTTP request to a resource server that provides authorization.
+ /// </summary>
+ /// <remarks>
+ /// In its current form, this class only accepts bearer access tokens.
+ /// When support for additional access token types is added, this class should probably be refactored
+ /// into derived types, where each derived type supports a particular access token type.
+ /// </remarks>
+ internal class AccessProtectedResourceRequest : MessageBase, IAuthorizationCarryingRequest {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessProtectedResourceRequest"/> class.
+ /// </summary>
+ /// <param name="recipient">The recipient.</param>
+ /// <param name="version">The version.</param>
+ internal AccessProtectedResourceRequest(Uri recipient, Version version)
+ : base(version, MessageTransport.Direct, recipient) {
+ }
+
+ /// <summary>
+ /// Gets the type of the code or token.
+ /// </summary>
+ /// <value>The type of the code or token.</value>
+ CodeOrTokenType IAuthorizationCarryingRequest.CodeOrTokenType {
+ get { return CodeOrTokenType.AccessToken; }
+ }
+
+ /// <summary>
+ /// Gets or sets the verification code or refresh/access token.
+ /// </summary>
+ /// <value>The code or token.</value>
+ string IAuthorizationCarryingRequest.CodeOrToken {
+ get { return this.AccessToken; }
+ set { this.AccessToken = value; }
+ }
+
+ /// <summary>
+ /// Gets or sets the authorization that the token describes.
+ /// </summary>
+ IAuthorizationDescription IAuthorizationCarryingRequest.AuthorizationDescription { get; set; }
+
+ /// <summary>
+ /// Gets the type of the access token.
+ /// </summary>
+ /// <value>
+ /// Always "bearer".
+ /// </value>
+ [MessagePart("token_type", IsRequired = true)]
+ internal string TokenType {
+ get { return Protocol.AccessTokenTypes.Bearer; }
+ }
+
+ /// <summary>
+ /// Gets or sets the access token.
+ /// </summary>
+ /// <value>The access token.</value>
+ [MessagePart("access_token", IsRequired = true)]
+ internal string AccessToken { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenAuthorizationCodeRequest.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenAuthorizationCodeRequest.cs
new file mode 100644
index 0000000..f3dad87
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenAuthorizationCodeRequest.cs
@@ -0,0 +1,94 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessTokenAuthorizationCodeRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// A request from a Client to an Authorization Server to exchange an authorization code for an access token,
+ /// and (at the authorization server's option) a refresh token.
+ /// </summary>
+ internal class AccessTokenAuthorizationCodeRequest : AccessTokenRequestBase, IAuthorizationCarryingRequest {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenAuthorizationCodeRequest"/> class.
+ /// </summary>
+ /// <param name="tokenEndpoint">The Authorization Server's access token endpoint URL.</param>
+ /// <param name="version">The version.</param>
+ internal AccessTokenAuthorizationCodeRequest(Uri tokenEndpoint, Version version)
+ : base(tokenEndpoint, version) {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenAuthorizationCodeRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ internal AccessTokenAuthorizationCodeRequest(AuthorizationServerDescription authorizationServer)
+ : this(authorizationServer.TokenEndpoint, authorizationServer.Version) {
+ Requires.NotNull(authorizationServer, "authorizationServer");
+ }
+
+ /// <summary>
+ /// Gets the type of the code or token.
+ /// </summary>
+ /// <value>The type of the code or token.</value>
+ CodeOrTokenType IAuthorizationCarryingRequest.CodeOrTokenType {
+ get { return CodeOrTokenType.AuthorizationCode; }
+ }
+
+ /// <summary>
+ /// Gets or sets the verification code or refresh/access token.
+ /// </summary>
+ /// <value>The code or token.</value>
+ string IAuthorizationCarryingRequest.CodeOrToken {
+ get { return this.AuthorizationCode; }
+ set { this.AuthorizationCode = value; }
+ }
+
+ /// <summary>
+ /// Gets or sets the authorization that the token describes.
+ /// </summary>
+ IAuthorizationDescription IAuthorizationCarryingRequest.AuthorizationDescription { get; set; }
+
+ /// <summary>
+ /// Gets the type of the grant.
+ /// </summary>
+ /// <value>The type of the grant.</value>
+ internal override GrantType GrantType {
+ get { return Messages.GrantType.AuthorizationCode; }
+ }
+
+ /// <summary>
+ /// Gets or sets the verification code previously communicated to the Client
+ /// in <see cref="EndUserAuthorizationSuccessAuthCodeResponse.AuthorizationCode"/>.
+ /// </summary>
+ /// <value>The verification code received from the authorization server.</value>
+ [MessagePart(Protocol.code, IsRequired = true)]
+ internal string AuthorizationCode { get; set; }
+
+ /// <summary>
+ /// Gets or sets the callback URL used in <see cref="EndUserAuthorizationRequest.Callback"/>
+ /// </summary>
+ /// <value>
+ /// The Callback URL used to obtain the Verification Code.
+ /// </value>
+ [MessagePart(Protocol.redirect_uri, IsRequired = true)]
+ internal Uri Callback { get; set; }
+
+ /// <summary>
+ /// Gets the scope of operations the client is allowed to invoke.
+ /// </summary>
+ protected override HashSet<string> RequestedScope {
+ get { return ((IAuthorizationCarryingRequest)this).AuthorizationDescription.Scope; }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenClientCredentialsRequest.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenClientCredentialsRequest.cs
new file mode 100644
index 0000000..01e1633
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenClientCredentialsRequest.cs
@@ -0,0 +1,41 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessTokenClientCredentialsRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// A request for an access token for a client application that has its
+ /// own (non-user affiliated) client name and password.
+ /// </summary>
+ /// <remarks>
+ /// This is somewhat analogous to 2-legged OAuth.
+ /// </remarks>
+ internal class AccessTokenClientCredentialsRequest : ScopedAccessTokenRequest {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenClientCredentialsRequest"/> class.
+ /// </summary>
+ /// <param name="tokenEndpoint">The authorization server.</param>
+ /// <param name="version">The version.</param>
+ internal AccessTokenClientCredentialsRequest(Uri tokenEndpoint, Version version)
+ : base(tokenEndpoint, version) {
+ this.HttpMethods = HttpDeliveryMethods.PostRequest;
+ }
+
+ /// <summary>
+ /// Gets the type of the grant.
+ /// </summary>
+ /// <value>The type of the grant.</value>
+ internal override GrantType GrantType {
+ get { return Messages.GrantType.ClientCredentials; }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenFailedResponse.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenFailedResponse.cs
new file mode 100644
index 0000000..82de341
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenFailedResponse.cs
@@ -0,0 +1,86 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessTokenFailedResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Net;
+
+ using Messaging;
+
+ /// <summary>
+ /// A response from the Authorization Server to the Client to indicate that a
+ /// request for an access token renewal failed, probably due to an invalid
+ /// refresh token.
+ /// </summary>
+ /// <remarks>
+ /// This message type is shared by the Web App, Rich App, and Username/Password profiles.
+ /// </remarks>
+ internal class AccessTokenFailedResponse : MessageBase, IHttpDirectResponse {
+ /// <summary>
+ /// A value indicating whether this error response is in result to a request that had invalid client credentials which were supplied in the HTTP Authorization header.
+ /// </summary>
+ private readonly bool invalidClientCredentialsInAuthorizationHeader;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenFailedResponse"/> class.
+ /// </summary>
+ /// <param name="request">The faulty request.</param>
+ internal AccessTokenFailedResponse(AccessTokenRequestBase request)
+ : base(request) {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenFailedResponse"/> class.
+ /// </summary>
+ /// <param name="request">The faulty request.</param>
+ /// <param name="invalidClientCredentialsInAuthorizationHeader">A value indicating whether this error response is in result to a request that had invalid client credentials which were supplied in the HTTP Authorization header.</param>
+ internal AccessTokenFailedResponse(AccessTokenRequestBase request, bool invalidClientCredentialsInAuthorizationHeader)
+ : base(request)
+ {
+ this.invalidClientCredentialsInAuthorizationHeader = invalidClientCredentialsInAuthorizationHeader;
+ }
+
+ #region IHttpDirectResponse Members
+
+ /// <summary>
+ /// Gets the HTTP status code that the direct response should be sent with.
+ /// </summary>
+ HttpStatusCode IHttpDirectResponse.HttpStatusCode {
+ get { return this.invalidClientCredentialsInAuthorizationHeader ? HttpStatusCode.Unauthorized : HttpStatusCode.BadRequest; }
+ }
+
+ /// <summary>
+ /// Gets the HTTP headers to add to the response.
+ /// </summary>
+ /// <value>May be an empty collection, but must not be <c>null</c>.</value>
+ WebHeaderCollection IHttpDirectResponse.Headers {
+ get { return new WebHeaderCollection(); }
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Gets or sets the error.
+ /// </summary>
+ /// <value>One of the values given in <see cref="Protocol.AccessTokenRequestErrorCodes"/>.</value>
+ [MessagePart(Protocol.error, IsRequired = true)]
+ internal string Error { get; set; }
+
+ /// <summary>
+ /// Gets or sets a human readable description of the error.
+ /// </summary>
+ /// <value>Human-readable text providing additional information, used to assist in the understanding and resolution of the error that occurred.</value>
+ [MessagePart(Protocol.error_description, IsRequired = false)]
+ internal string ErrorDescription { get; set; }
+
+ /// <summary>
+ /// Gets or sets the location of the web page that describes the error and possible resolution.
+ /// </summary>
+ /// <value>A URI identifying a human-readable web page with information about the error, used to provide the end-user with additional information about the error.</value>
+ [MessagePart(Protocol.error_uri, IsRequired = false)]
+ internal Uri ErrorUri { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenRefreshRequest.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenRefreshRequest.cs
new file mode 100644
index 0000000..22354e4
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenRefreshRequest.cs
@@ -0,0 +1,75 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessTokenRefreshRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// A request from the client to the token endpoint for a new access token
+ /// in exchange for a refresh token that the client has previously obtained.
+ /// </summary>
+ internal class AccessTokenRefreshRequest : ScopedAccessTokenRequest, IAuthorizationCarryingRequest {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenRefreshRequest"/> class.
+ /// </summary>
+ /// <param name="tokenEndpoint">The token endpoint.</param>
+ /// <param name="version">The version.</param>
+ internal AccessTokenRefreshRequest(Uri tokenEndpoint, Version version)
+ : base(tokenEndpoint, version) {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenRefreshRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ internal AccessTokenRefreshRequest(AuthorizationServerDescription authorizationServer)
+ : this(authorizationServer.TokenEndpoint, authorizationServer.Version) {
+ }
+
+ /// <summary>
+ /// Gets the type of the code or token.
+ /// </summary>
+ /// <value>The type of the code or token.</value>
+ CodeOrTokenType IAuthorizationCarryingRequest.CodeOrTokenType {
+ get { return CodeOrTokenType.RefreshToken; }
+ }
+
+ /// <summary>
+ /// Gets or sets the verification code or refresh/access token.
+ /// </summary>
+ /// <value>The code or token.</value>
+ string IAuthorizationCarryingRequest.CodeOrToken {
+ get { return this.RefreshToken; }
+ set { this.RefreshToken = value; }
+ }
+
+ /// <summary>
+ /// Gets or sets the authorization that the token describes.
+ /// </summary>
+ IAuthorizationDescription IAuthorizationCarryingRequest.AuthorizationDescription { get; set; }
+
+ /// <summary>
+ /// Gets or sets the refresh token.
+ /// </summary>
+ /// <value>The refresh token.</value>
+ /// <remarks>
+ /// REQUIRED. The refresh token associated with the access token to be refreshed.
+ /// </remarks>
+ [MessagePart(Protocol.refresh_token, IsRequired = true)]
+ internal string RefreshToken { get; set; }
+
+ /// <summary>
+ /// Gets the type of the grant.
+ /// </summary>
+ /// <value>The type of the grant.</value>
+ internal override GrantType GrantType {
+ get { return Messages.GrantType.RefreshToken; }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenRequestBase.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenRequestBase.cs
new file mode 100644
index 0000000..4bf593a
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenRequestBase.cs
@@ -0,0 +1,78 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessTokenRequestBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Configuration;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// A message sent from the client to the authorization server to exchange a previously obtained grant for an access token.
+ /// </summary>
+ public abstract class AccessTokenRequestBase : AuthenticatedClientRequestBase, IAccessTokenRequest {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenRequestBase"/> class.
+ /// </summary>
+ /// <param name="tokenEndpoint">The Authorization Server's access token endpoint URL.</param>
+ /// <param name="version">The version.</param>
+ protected AccessTokenRequestBase(Uri tokenEndpoint, Version version)
+ : base(tokenEndpoint, version) {
+ this.HttpMethods = HttpDeliveryMethods.PostRequest;
+ }
+
+ /// <summary>
+ /// Gets the scope of operations the client is allowed to invoke.
+ /// </summary>
+ HashSet<string> IAccessTokenRequest.Scope {
+ get { return this.RequestedScope; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the client requesting the access token has authenticated itself.
+ /// </summary>
+ /// <value>
+ /// Always true, because of our base class.
+ /// </value>
+ bool IAccessTokenRequest.ClientAuthenticated {
+ get { return true; }
+ }
+
+ /// <summary>
+ /// Gets the type of the grant.
+ /// </summary>
+ /// <value>The type of the grant.</value>
+ [MessagePart(Protocol.grant_type, IsRequired = true, Encoder = typeof(GrantTypeEncoder))]
+ internal abstract GrantType GrantType { get; }
+
+ /// <summary>
+ /// Gets the scope of operations the client is allowed to invoke.
+ /// </summary>
+ protected abstract HashSet<string> RequestedScope { get; }
+
+ /// <summary>
+ /// Checks the message state for conformity to the protocol specification
+ /// and throws an exception if the message is invalid.
+ /// </summary>
+ /// <remarks>
+ /// <para>Some messages have required fields, or combinations of fields that must relate to each other
+ /// in specialized ways. After deserializing a message, this method checks the state of the
+ /// message to see if it conforms to the protocol.</para>
+ /// <para>Note that this property should <i>not</i> check signatures or perform any state checks
+ /// outside this scope of this particular message.</para>
+ /// </remarks>
+ /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception>
+ protected override void EnsureValidMessage() {
+ base.EnsureValidMessage();
+ ErrorUtilities.VerifyProtocol(
+ DotNetOpenAuthSection.Messaging.RelaxSslRequirements || this.Recipient.IsTransportSecure(),
+ OAuthStrings.HttpsRequired);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenResourceOwnerPasswordCredentialsRequest.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenResourceOwnerPasswordCredentialsRequest.cs
new file mode 100644
index 0000000..82febe9
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenResourceOwnerPasswordCredentialsRequest.cs
@@ -0,0 +1,50 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessTokenResourceOwnerPasswordCredentialsRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A request from a Client to an Authorization Server to exchange the user's username and password for an access token.
+ /// </summary>
+ internal class AccessTokenResourceOwnerPasswordCredentialsRequest : ScopedAccessTokenRequest {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenResourceOwnerPasswordCredentialsRequest"/> class.
+ /// </summary>
+ /// <param name="accessTokenEndpoint">The access token endpoint.</param>
+ /// <param name="version">The protocol version.</param>
+ internal AccessTokenResourceOwnerPasswordCredentialsRequest(Uri accessTokenEndpoint, Version version)
+ : base(accessTokenEndpoint, version) {
+ }
+
+ /// <summary>
+ /// Gets the type of the grant.
+ /// </summary>
+ /// <value>The type of the grant.</value>
+ internal override GrantType GrantType {
+ get { return Messages.GrantType.Password; }
+ }
+
+ /// <summary>
+ /// Gets or sets the user's account username.
+ /// </summary>
+ /// <value>The username on the user's account.</value>
+ [MessagePart(Protocol.username, IsRequired = true)]
+ internal string UserName { get; set; }
+
+ /// <summary>
+ /// Gets or sets the user's password.
+ /// </summary>
+ /// <value>The password.</value>
+ [MessagePart(Protocol.password, IsRequired = true)]
+ internal string Password { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenSuccessResponse.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenSuccessResponse.cs
new file mode 100644
index 0000000..5682bf7
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenSuccessResponse.cs
@@ -0,0 +1,99 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessTokenSuccessResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Net;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// A response from the Authorization Server to the Client containing a delegation code
+ /// that the Client should use to obtain an access token.
+ /// </summary>
+ /// <remarks>
+ /// This message type is shared by the Web App, Rich App, and Username/Password profiles.
+ /// </remarks>
+ internal class AccessTokenSuccessResponse : MessageBase, IHttpDirectResponse {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenSuccessResponse"/> class.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ internal AccessTokenSuccessResponse(AccessTokenRequestBase request)
+ : base(request) {
+ this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer);
+ this.TokenType = Protocol.AccessTokenTypes.Bearer;
+ }
+
+ /// <summary>
+ /// Gets the HTTP status code that the direct response should be sent with.
+ /// </summary>
+ /// <value>Always HttpStatusCode.OK</value>
+ HttpStatusCode IHttpDirectResponse.HttpStatusCode {
+ get { return HttpStatusCode.OK; }
+ }
+
+ /// <summary>
+ /// Gets the HTTP headers to add to the response.
+ /// </summary>
+ /// <value>May be an empty collection, but must not be <c>null</c>.</value>
+ WebHeaderCollection IHttpDirectResponse.Headers {
+ get {
+ return new WebHeaderCollection
+ {
+ { HttpResponseHeader.CacheControl, "no-store" },
+ };
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the access token.
+ /// </summary>
+ /// <value>The access token.</value>
+ [MessagePart(Protocol.access_token, IsRequired = true)]
+ public string AccessToken { get; internal set; }
+
+ /// <summary>
+ /// Gets or sets the token type.
+ /// </summary>
+ /// <value>Usually "bearer".</value>
+ /// <remarks>
+ /// Described in OAuth 2.0 section 7.1.
+ /// </remarks>
+ [MessagePart(Protocol.token_type, IsRequired = true)]
+ public string TokenType { get; internal set; }
+
+ /// <summary>
+ /// Gets or sets the lifetime of the access token.
+ /// </summary>
+ /// <value>The lifetime.</value>
+ [MessagePart(Protocol.expires_in, IsRequired = false, Encoder = typeof(TimespanSecondsEncoder))]
+ public TimeSpan? Lifetime { get; internal set; }
+
+ /// <summary>
+ /// Gets or sets the refresh token.
+ /// </summary>
+ /// <value>The refresh token.</value>
+ /// <remarks>
+ /// OPTIONAL. The refresh token used to obtain new access tokens using the same end-user access grant as described in Section 6 (Refreshing an Access Token).
+ /// </remarks>
+ [MessagePart(Protocol.refresh_token, IsRequired = false)]
+ public string RefreshToken { get; internal set; }
+
+ /// <summary>
+ /// Gets the scope of access being requested.
+ /// </summary>
+ /// <value>The scope of the access request expressed as a list of space-delimited strings. The value of the scope parameter is defined by the authorization server. If the value contains multiple space-delimited strings, their order does not matter, and each string adds an additional access range to the requested scope.</value>
+ [MessagePart(Protocol.scope, IsRequired = false, Encoder = typeof(ScopeEncoder))]
+ public HashSet<string> Scope { get; private set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether a refresh token is or should be included in the response.
+ /// </summary>
+ internal bool HasRefreshToken { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AuthenticatedClientRequestBase.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AuthenticatedClientRequestBase.cs
new file mode 100644
index 0000000..22f7461
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AuthenticatedClientRequestBase.cs
@@ -0,0 +1,42 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthenticatedClientRequestBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A direct message from the client to the authorization server that includes the client's credentials.
+ /// </summary>
+ public abstract class AuthenticatedClientRequestBase : MessageBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthenticatedClientRequestBase"/> class.
+ /// </summary>
+ /// <param name="tokenEndpoint">The Authorization Server's access token endpoint URL.</param>
+ /// <param name="version">The version.</param>
+ protected AuthenticatedClientRequestBase(Uri tokenEndpoint, Version version)
+ : base(version, MessageTransport.Direct, tokenEndpoint) {
+ }
+
+ /// <summary>
+ /// Gets the client identifier previously obtained from the Authorization Server.
+ /// </summary>
+ /// <value>The client identifier.</value>
+ [MessagePart(Protocol.client_id, IsRequired = true)]
+ public string ClientIdentifier { get; internal set; }
+
+ /// <summary>
+ /// Gets the client secret.
+ /// </summary>
+ /// <value>The client secret.</value>
+ /// <remarks>
+ /// REQUIRED. The client secret as described in Section 2.1 (Client Credentials). OPTIONAL if no client secret was issued.
+ /// </remarks>
+ [MessagePart(Protocol.client_secret, IsRequired = false)]
+ public string ClientSecret { get; internal set; }
+ }
+} \ No newline at end of file
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationFailedResponse.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationFailedResponse.cs
new file mode 100644
index 0000000..ecf3254
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationFailedResponse.cs
@@ -0,0 +1,81 @@
+//-----------------------------------------------------------------------
+// <copyright file="EndUserAuthorizationFailedResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Runtime.Remoting.Messaging;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// The message that an Authorization Server responds to a Client with when the user denies a user authorization request.
+ /// </summary>
+ public class EndUserAuthorizationFailedResponse : MessageBase, IMessageWithClientState {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EndUserAuthorizationFailedResponse"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The URL to redirect to so the client receives the message. This may not be built into the request message if the client pre-registered the URL with the authorization server.</param>
+ /// <param name="version">The protocol version.</param>
+ internal EndUserAuthorizationFailedResponse(Uri clientCallback, Version version)
+ : base(version, MessageTransport.Indirect, clientCallback) {
+ Requires.NotNull(version, "version");
+ Requires.NotNull(clientCallback, "clientCallback");
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EndUserAuthorizationFailedResponse"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The URL to redirect to so the client receives the message. This may not be built into the request message if the client pre-registered the URL with the authorization server.</param>
+ /// <param name="request">The authorization request from the user agent on behalf of the client.</param>
+ internal EndUserAuthorizationFailedResponse(Uri clientCallback, EndUserAuthorizationRequest request)
+ : base(((IProtocolMessage)request).Version, MessageTransport.Indirect, clientCallback) {
+ Requires.NotNull(request, "request");
+ ((IMessageWithClientState)this).ClientState = request.ClientState;
+ }
+
+ /// <summary>
+ /// Gets or sets the error.
+ /// </summary>
+ /// <value>
+ /// One of the values given in <see cref="Protocol.EndUserAuthorizationRequestErrorCodes"/>.
+ /// OR a numerical HTTP status code from the 4xx or 5xx
+ /// range, with the exception of the 400 (Bad Request) and
+ /// 401 (Unauthorized) status codes. For example, if the
+ /// service is temporarily unavailable, the authorization
+ /// server MAY return an error response with "error" set to
+ /// "503".
+ /// </value>
+ [MessagePart(Protocol.error, IsRequired = true)]
+ public string Error { get; set; }
+
+ /// <summary>
+ /// Gets or sets a human readable description of the error.
+ /// </summary>
+ /// <value>Human-readable text providing additional information, used to assist in the understanding and resolution of the error that occurred.</value>
+ [MessagePart(Protocol.error_description, IsRequired = false)]
+ public string ErrorDescription { get; set; }
+
+ /// <summary>
+ /// Gets or sets the location of the web page that describes the error and possible resolution.
+ /// </summary>
+ /// <value>A URI identifying a human-readable web page with information about the error, used to provide the end-user with additional information about the error.</value>
+ [MessagePart(Protocol.error_uri, IsRequired = false)]
+ public Uri ErrorUri { get; set; }
+
+ /// <summary>
+ /// Gets or sets some state as provided by the client in the authorization request.
+ /// </summary>
+ /// <value>An opaque value defined by the client.</value>
+ /// <remarks>
+ /// REQUIRED if the Client sent the value in the <see cref="EndUserAuthorizationRequest"/>.
+ /// </remarks>
+ [MessagePart(Protocol.state, IsRequired = false)]
+ string IMessageWithClientState.ClientState { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationRequest.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationRequest.cs
new file mode 100644
index 0000000..2455406
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationRequest.cs
@@ -0,0 +1,118 @@
+//-----------------------------------------------------------------------
+// <copyright file="EndUserAuthorizationRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Diagnostics.Contracts;
+ using DotNetOpenAuth.Configuration;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// A message sent by a web application Client to the AuthorizationServer
+ /// via the user agent to obtain authorization from the user and prepare
+ /// to issue an access token to the Consumer if permission is granted.
+ /// </summary>
+ [Serializable]
+ public class EndUserAuthorizationRequest : MessageBase, IAccessTokenRequest {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EndUserAuthorizationRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationEndpoint">The Authorization Server's user authorization URL to direct the user to.</param>
+ /// <param name="version">The protocol version.</param>
+ internal EndUserAuthorizationRequest(Uri authorizationEndpoint, Version version)
+ : base(version, MessageTransport.Indirect, authorizationEndpoint) {
+ Requires.NotNull(authorizationEndpoint, "authorizationEndpoint");
+ Requires.NotNull(version, "version");
+ this.HttpMethods = HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.PostRequest;
+ this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer);
+ this.ResponseType = EndUserAuthorizationResponseType.AuthorizationCode;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EndUserAuthorizationRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ internal EndUserAuthorizationRequest(AuthorizationServerDescription authorizationServer)
+ : this(authorizationServer.AuthorizationEndpoint, authorizationServer.Version) {
+ Requires.NotNull(authorizationServer, "authorizationServer");
+ Requires.True(authorizationServer.Version != null, "authorizationServer");
+ Requires.True(authorizationServer.AuthorizationEndpoint != null, "authorizationServer");
+ }
+
+ /// <summary>
+ /// Gets or sets the grant type that the client expects of the authorization server.
+ /// </summary>
+ /// <value>Always <see cref="EndUserAuthorizationResponseType.AuthorizationCode"/>. Other response types are not supported.</value>
+ [MessagePart(Protocol.response_type, IsRequired = true, Encoder = typeof(EndUserAuthorizationResponseTypeEncoder))]
+ public EndUserAuthorizationResponseType ResponseType { get; set; }
+
+ /// <summary>
+ /// Gets or sets the identifier by which this client is known to the Authorization Server.
+ /// </summary>
+ [MessagePart(Protocol.client_id, IsRequired = true)]
+ public string ClientIdentifier { get; set; }
+
+ /// <summary>
+ /// Gets a value indicating whether the client requesting the access token has authenticated itself.
+ /// </summary>
+ /// <value>
+ /// Always false because authorization requests only include the client_id, without a secret.
+ /// </value>
+ bool IAccessTokenRequest.ClientAuthenticated {
+ get { return false; }
+ }
+
+ /// <summary>
+ /// Gets or sets the callback URL.
+ /// </summary>
+ /// <value>
+ /// An absolute URL to which the Authorization Server will redirect the User back after
+ /// the user has approved the authorization request.
+ /// </value>
+ /// <remarks>
+ /// REQUIRED unless a redirection URI has been established between the client and authorization server via other means. An absolute URI to which the authorization server will redirect the user-agent to when the end-user authorization step is completed. The authorization server MAY require the client to pre-register their redirection URI. The redirection URI MUST NOT include a query component as defined by [RFC3986] (Berners-Lee, T., Fielding, R., and L. Masinter, “Uniform Resource Identifier (URI): Generic Syntax,” January 2005.) section 3 if the state parameter is present.
+ /// </remarks>
+ [MessagePart(Protocol.redirect_uri, IsRequired = false)]
+ public Uri Callback { get; set; }
+
+ /// <summary>
+ /// Gets or sets state of the client that should be sent back with the authorization response.
+ /// </summary>
+ /// <value>
+ /// An opaque value that Clients can use to maintain state associated with this request.
+ /// </value>
+ /// <remarks>
+ /// This data is proprietary to the client and should be considered an opaque string to the
+ /// authorization server.
+ /// </remarks>
+ [MessagePart(Protocol.state, IsRequired = false)]
+ public string ClientState { get; set; }
+
+ /// <summary>
+ /// Gets the scope of access being requested.
+ /// </summary>
+ /// <value>The scope of the access request expressed as a list of space-delimited strings. The value of the scope parameter is defined by the authorization server. If the value contains multiple space-delimited strings, their order does not matter, and each string adds an additional access range to the requested scope.</value>
+ [MessagePart(Protocol.scope, IsRequired = false, Encoder = typeof(ScopeEncoder))]
+ public HashSet<string> Scope { get; private set; }
+
+ /// <summary>
+ /// Checks the message state for conformity to the protocol specification
+ /// and throws an exception if the message is invalid.
+ /// </summary>
+ /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception>
+ protected override void EnsureValidMessage() {
+ base.EnsureValidMessage();
+
+ ErrorUtilities.VerifyProtocol(
+ DotNetOpenAuthSection.Messaging.RelaxSslRequirements || this.Recipient.IsTransportSecure(),
+ OAuthStrings.HttpsRequired);
+ ErrorUtilities.VerifyProtocol(this.Callback == null || this.Callback.IsAbsoluteUri, this, OAuthStrings.AbsoluteUriRequired, Protocol.redirect_uri);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationResponseType.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationResponseType.cs
new file mode 100644
index 0000000..815fef6
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationResponseType.cs
@@ -0,0 +1,25 @@
+//-----------------------------------------------------------------------
+// <copyright file="EndUserAuthorizationResponseType.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+
+ /// <summary>
+ /// An indication of what kind of response the client is requesting from the authorization server
+ /// after the user has granted authorized access.
+ /// </summary>
+ public enum EndUserAuthorizationResponseType {
+ /// <summary>
+ /// An access token should be returned immediately.
+ /// </summary>
+ AccessToken,
+
+ /// <summary>
+ /// An authorization code should be returned, which can later be exchanged for refresh and access tokens.
+ /// </summary>
+ AuthorizationCode,
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessAccessTokenResponse.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessAccessTokenResponse.cs
new file mode 100644
index 0000000..b82b1da
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessAccessTokenResponse.cs
@@ -0,0 +1,121 @@
+//-----------------------------------------------------------------------
+// <copyright file="EndUserAuthorizationSuccessAccessTokenResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// The message sent by the Authorization Server to the Client via the user agent
+ /// to indicate that user authorization was granted, carrying only an access token,
+ /// and to return the user to the Client where they started their experience.
+ /// </summary>
+ internal class EndUserAuthorizationSuccessAccessTokenResponse : EndUserAuthorizationSuccessResponseBase, IAuthorizationCarryingRequest, IHttpIndirectResponse {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EndUserAuthorizationSuccessAccessTokenResponse"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The URL to redirect to so the client receives the message. This may not be built into the request message if the client pre-registered the URL with the authorization server.</param>
+ /// <param name="version">The protocol version.</param>
+ internal EndUserAuthorizationSuccessAccessTokenResponse(Uri clientCallback, Version version)
+ : base(clientCallback, version) {
+ Requires.NotNull(version, "version");
+ Requires.NotNull(clientCallback, "clientCallback");
+ this.TokenType = Protocol.AccessTokenTypes.Bearer;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EndUserAuthorizationSuccessAccessTokenResponse"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The URL to redirect to so the client receives the message. This may not be built into the request message if the client pre-registered the URL with the authorization server.</param>
+ /// <param name="request">The authorization request from the user agent on behalf of the client.</param>
+ internal EndUserAuthorizationSuccessAccessTokenResponse(Uri clientCallback, EndUserAuthorizationRequest request)
+ : base(clientCallback, request) {
+ Requires.NotNull(clientCallback, "clientCallback");
+ Requires.NotNull(request, "request");
+ ((IMessageWithClientState)this).ClientState = request.ClientState;
+ this.TokenType = Protocol.AccessTokenTypes.Bearer;
+ }
+
+ #region IAuthorizationCarryingRequest Members
+
+ /// <summary>
+ /// Gets or sets the verification code or refresh/access token.
+ /// </summary>
+ /// <value>The code or token.</value>
+ string IAuthorizationCarryingRequest.CodeOrToken {
+ get { return this.AccessToken; }
+ set { this.AccessToken = value; }
+ }
+
+ /// <summary>
+ /// Gets the type of the code or token.
+ /// </summary>
+ /// <value>The type of the code or token.</value>
+ CodeOrTokenType IAuthorizationCarryingRequest.CodeOrTokenType {
+ get { return CodeOrTokenType.AccessToken; }
+ }
+
+ /// <summary>
+ /// Gets or sets the authorization that the token describes.
+ /// </summary>
+ /// <value></value>
+ IAuthorizationDescription IAuthorizationCarryingRequest.AuthorizationDescription { get; set; }
+
+ #endregion
+
+ #region IHttpIndirectResponse Members
+
+ /// <summary>
+ /// Gets a value indicating whether the payload for the message should be included
+ /// in the redirect fragment instead of the query string or POST entity.
+ /// </summary>
+ bool IHttpIndirectResponse.Include301RedirectPayloadInFragment {
+ get { return true; }
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Gets or sets the token type.
+ /// </summary>
+ /// <value>Usually "bearer".</value>
+ /// <remarks>
+ /// Described in OAuth 2.0 section 7.1.
+ /// </remarks>
+ [MessagePart(Protocol.token_type, IsRequired = true)]
+ public string TokenType { get; internal set; }
+
+ /// <summary>
+ /// Gets or sets the access token.
+ /// </summary>
+ /// <value>The access token.</value>
+ [MessagePart(Protocol.access_token, IsRequired = true)]
+ public string AccessToken { get; set; }
+
+ /// <summary>
+ /// Gets or sets the scope of the <see cref="AccessToken"/> if one is given; otherwise the scope of the authorization code.
+ /// </summary>
+ /// <value>The scope.</value>
+ [MessagePart(Protocol.scope, IsRequired = false, Encoder = typeof(ScopeEncoder))]
+ public new ICollection<string> Scope {
+ get { return base.Scope; }
+ protected set { base.Scope = value; }
+ }
+
+ /// <summary>
+ /// Gets or sets the lifetime of the authorization.
+ /// </summary>
+ /// <value>The lifetime.</value>
+ [MessagePart(Protocol.expires_in, IsRequired = false, Encoder = typeof(TimespanSecondsEncoder))]
+ internal TimeSpan? Lifetime { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessAuthCodeResponse.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessAuthCodeResponse.cs
new file mode 100644
index 0000000..ac7f392
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessAuthCodeResponse.cs
@@ -0,0 +1,76 @@
+//-----------------------------------------------------------------------
+// <copyright file="EndUserAuthorizationSuccessAuthCodeResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Diagnostics.Contracts;
+
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// The message sent by the Authorization Server to the Client via the user agent
+ /// to indicate that user authorization was granted, carrying an authorization code and possibly an access token,
+ /// and to return the user to the Client where they started their experience.
+ /// </summary>
+ internal class EndUserAuthorizationSuccessAuthCodeResponse : EndUserAuthorizationSuccessResponseBase, IAuthorizationCarryingRequest {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EndUserAuthorizationSuccessAuthCodeResponse"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The URL to redirect to so the client receives the message. This may not be built into the request message if the client pre-registered the URL with the authorization server.</param>
+ /// <param name="version">The protocol version.</param>
+ internal EndUserAuthorizationSuccessAuthCodeResponse(Uri clientCallback, Version version)
+ : base(clientCallback, version) {
+ Requires.NotNull(version, "version");
+ Requires.NotNull(clientCallback, "clientCallback");
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EndUserAuthorizationSuccessAuthCodeResponse"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The URL to redirect to so the client receives the message. This may not be built into the request message if the client pre-registered the URL with the authorization server.</param>
+ /// <param name="request">The authorization request from the user agent on behalf of the client.</param>
+ internal EndUserAuthorizationSuccessAuthCodeResponse(Uri clientCallback, EndUserAuthorizationRequest request)
+ : base(clientCallback, request) {
+ Requires.NotNull(clientCallback, "clientCallback");
+ Requires.NotNull(request, "request");
+ ((IMessageWithClientState)this).ClientState = request.ClientState;
+ }
+
+ #region IAuthorizationCarryingRequest Members
+
+ /// <summary>
+ /// Gets or sets the verification code or refresh/access token.
+ /// </summary>
+ /// <value>The code or token.</value>
+ string IAuthorizationCarryingRequest.CodeOrToken {
+ get { return this.AuthorizationCode; }
+ set { this.AuthorizationCode = value; }
+ }
+
+ /// <summary>
+ /// Gets the type of the code or token.
+ /// </summary>
+ /// <value>The type of the code or token.</value>
+ CodeOrTokenType IAuthorizationCarryingRequest.CodeOrTokenType {
+ get { return CodeOrTokenType.AuthorizationCode; }
+ }
+
+ /// <summary>
+ /// Gets or sets the authorization that the token describes.
+ /// </summary>
+ IAuthorizationDescription IAuthorizationCarryingRequest.AuthorizationDescription { get; set; }
+
+ #endregion
+
+ /// <summary>
+ /// Gets or sets the authorization code.
+ /// </summary>
+ /// <value>The authorization code.</value>
+ [MessagePart(Protocol.code, IsRequired = true)]
+ internal string AuthorizationCode { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessResponseBase.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessResponseBase.cs
new file mode 100644
index 0000000..ff52743
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessResponseBase.cs
@@ -0,0 +1,69 @@
+//-----------------------------------------------------------------------
+// <copyright file="EndUserAuthorizationSuccessResponseBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Security.Cryptography;
+
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// The message sent by the Authorization Server to the Client via the user agent
+ /// to indicate that user authorization was granted, and to return the user
+ /// to the Client where they started their experience.
+ /// </summary>
+ public abstract class EndUserAuthorizationSuccessResponseBase : MessageBase, IMessageWithClientState {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EndUserAuthorizationSuccessResponseBase"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The URL to redirect to so the client receives the message. This may not be built into the request message if the client pre-registered the URL with the authorization server.</param>
+ /// <param name="version">The protocol version.</param>
+ internal EndUserAuthorizationSuccessResponseBase(Uri clientCallback, Version version)
+ : base(version, MessageTransport.Indirect, clientCallback) {
+ Requires.NotNull(version, "version");
+ Requires.NotNull(clientCallback, "clientCallback");
+ this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EndUserAuthorizationSuccessResponseBase"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The URL to redirect to so the client receives the message. This may not be built into the request message if the client pre-registered the URL with the authorization server.</param>
+ /// <param name="request">The authorization request from the user agent on behalf of the client.</param>
+ internal EndUserAuthorizationSuccessResponseBase(Uri clientCallback, EndUserAuthorizationRequest request)
+ : base(request, clientCallback) {
+ Requires.NotNull(clientCallback, "clientCallback");
+ Requires.NotNull(request, "request");
+ ((IMessageWithClientState)this).ClientState = request.ClientState;
+ this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer);
+ this.Scope.ResetContents(request.Scope);
+ }
+
+ /// <summary>
+ /// Gets or sets some state as provided by the client in the authorization request.
+ /// </summary>
+ /// <value>An opaque value defined by the client.</value>
+ /// <remarks>
+ /// REQUIRED if the Client sent the value in the <see cref="EndUserAuthorizationRequest"/>.
+ /// </remarks>
+ [MessagePart(Protocol.state, IsRequired = false)]
+ string IMessageWithClientState.ClientState { get; set; }
+
+ /// <summary>
+ /// Gets or sets the scope of the <see cref="AccessToken"/> if one is given; otherwise the scope of the authorization code.
+ /// </summary>
+ /// <value>The scope.</value>
+ public ICollection<string> Scope { get; protected set; }
+
+ /// <summary>
+ /// Gets or sets the authorizing user's account name.
+ /// </summary>
+ internal string AuthorizingUsername { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/GrantType.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/GrantType.cs
new file mode 100644
index 0000000..4580a7f
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/GrantType.cs
@@ -0,0 +1,42 @@
+//-----------------------------------------------------------------------
+// <copyright file="GrantType.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ /// <summary>
+ /// The types of authorizations that a client can use to obtain
+ /// a refresh token and/or an access token.
+ /// </summary>
+ internal enum GrantType {
+ /// <summary>
+ /// The client is providing the authorization code previously obtained from an end user authorization response.
+ /// </summary>
+ AuthorizationCode,
+
+ /// <summary>
+ /// The client is providing the end user's username and password to the authorization server.
+ /// </summary>
+ Password,
+
+ /// <summary>
+ /// The client is providing an assertion it obtained from another source.
+ /// </summary>
+ Assertion,
+
+ /// <summary>
+ /// The client is providing a refresh token.
+ /// </summary>
+ RefreshToken,
+
+ /// <summary>
+ /// No authorization to access a user's data has been given. The client is requesting
+ /// an access token authorized for its own private data. This fits the classic OAuth 1.0(a) "2-legged OAuth" scenario.
+ /// </summary>
+ /// <remarks>
+ /// When requesting an access token using the none access grant type (no access grant is included), the client is requesting access to the protected resources under its control, or those of another resource owner which has been previously arranged with the authorization server (the method of which is beyond the scope of this specification).
+ /// </remarks>
+ ClientCredentials,
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/IAccessTokenRequest.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/IAccessTokenRequest.cs
new file mode 100644
index 0000000..7246beb
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/IAccessTokenRequest.cs
@@ -0,0 +1,37 @@
+//-----------------------------------------------------------------------
+// <copyright file="IAccessTokenRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// A request from a client that should be responded to directly with an access token.
+ /// </summary>
+ public interface IAccessTokenRequest : IMessage {
+ /// <summary>
+ /// Gets a value indicating whether the client requesting the access token has authenticated itself.
+ /// </summary>
+ /// <value>
+ /// <c>false</c> for implicit grant requests; otherwise, <c>true</c>.
+ /// </value>
+ bool ClientAuthenticated { get; }
+
+ /// <summary>
+ /// Gets the identifier of the client authorized to access protected data.
+ /// </summary>
+ string ClientIdentifier { get; }
+
+ /// <summary>
+ /// Gets the scope of operations the client is allowed to invoke.
+ /// </summary>
+ HashSet<string> Scope { get; }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/IMessageWithClientState.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/IMessageWithClientState.cs
new file mode 100644
index 0000000..fa371ae
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/IMessageWithClientState.cs
@@ -0,0 +1,21 @@
+//-----------------------------------------------------------------------
+// <copyright file="IMessageWithClientState.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A message carrying client state the authorization server should preserve on behalf of the client
+ /// during an authorization.
+ /// </summary>
+ internal interface IMessageWithClientState : IProtocolMessage {
+ /// <summary>
+ /// Gets or sets the state of the client.
+ /// </summary>
+ /// <value>The state of the client.</value>
+ string ClientState { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/MessageBase.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/MessageBase.cs
new file mode 100644
index 0000000..c5e438f
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/MessageBase.cs
@@ -0,0 +1,239 @@
+//-----------------------------------------------------------------------
+// <copyright file="MessageBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Diagnostics.Contracts;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A common message base class for OAuth messages.
+ /// </summary>
+ [Serializable]
+ public class MessageBase : IDirectedProtocolMessage, IDirectResponseProtocolMessage {
+ /// <summary>
+ /// A dictionary to contain extra message data.
+ /// </summary>
+ private Dictionary<string, string> extraData = new Dictionary<string, string>();
+
+ /// <summary>
+ /// The originating request.
+ /// </summary>
+ private IDirectedProtocolMessage originatingRequest;
+
+ /// <summary>
+ /// The backing field for the <see cref="IMessage.Version"/> property.
+ /// </summary>
+ private Version version;
+
+ /// <summary>
+ /// A value indicating whether this message is a direct or indirect message.
+ /// </summary>
+ private MessageTransport messageTransport;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MessageBase"/> class
+ /// that is used for direct response messages.
+ /// </summary>
+ /// <param name="version">The version.</param>
+ protected MessageBase(Version version) {
+ Requires.NotNull(version, "version");
+ this.messageTransport = MessageTransport.Direct;
+ this.version = version;
+ this.HttpMethods = HttpDeliveryMethods.GetRequest;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MessageBase"/> class.
+ /// </summary>
+ /// <param name="request">The originating request.</param>
+ /// <param name="recipient">The recipient of the directed message. Null if not applicable.</param>
+ protected MessageBase(IDirectedProtocolMessage request, Uri recipient = null) {
+ Requires.NotNull(request, "request");
+ this.originatingRequest = request;
+ this.messageTransport = request.Transport;
+ this.version = request.Version;
+ this.Recipient = recipient;
+ this.HttpMethods = HttpDeliveryMethods.GetRequest;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MessageBase"/> class
+ /// that is used for directed messages.
+ /// </summary>
+ /// <param name="version">The version.</param>
+ /// <param name="messageTransport">The message transport.</param>
+ /// <param name="recipient">The recipient.</param>
+ protected MessageBase(Version version, MessageTransport messageTransport, Uri recipient) {
+ Requires.NotNull(version, "version");
+ Requires.NotNull(recipient, "recipient");
+
+ this.version = version;
+ this.messageTransport = messageTransport;
+ this.Recipient = recipient;
+ this.HttpMethods = HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.PostRequest;
+ }
+
+ #region IMessage Properties
+
+ /// <summary>
+ /// Gets the version of the protocol or extension this message is prepared to implement.
+ /// </summary>
+ /// <remarks>
+ /// Implementations of this interface should ensure that this property never returns null.
+ /// </remarks>
+ Version IMessage.Version {
+ get { return this.Version; }
+ }
+
+ /// <summary>
+ /// Gets the extra, non-standard Protocol parameters included in the message.
+ /// </summary>
+ /// <value></value>
+ /// <remarks>
+ /// Implementations of this interface should ensure that this property never returns null.
+ /// </remarks>
+ public IDictionary<string, string> ExtraData {
+ get { return this.extraData; }
+ }
+
+ #endregion
+
+ #region IProtocolMessage Members
+
+ /// <summary>
+ /// Gets the level of protection this message requires.
+ /// </summary>
+ /// <value><see cref="MessageProtections.None"/></value>
+ MessageProtections IProtocolMessage.RequiredProtection {
+ get { return RequiredProtection; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether this is a direct or indirect message.
+ /// </summary>
+ /// <value></value>
+ MessageTransport IProtocolMessage.Transport {
+ get { return this.Transport; }
+ }
+
+ #endregion
+
+ #region IDirectedProtocolMessage Members
+
+ /// <summary>
+ /// Gets the preferred method of transport for the message.
+ /// </summary>
+ /// <remarks>
+ /// For indirect messages this will likely be GET+POST, which both can be simulated in the user agent:
+ /// the GET with a simple 301 Redirect, and the POST with an HTML form in the response with javascript
+ /// to automate submission.
+ /// </remarks>
+ HttpDeliveryMethods IDirectedProtocolMessage.HttpMethods {
+ get { return this.HttpMethods; }
+ }
+
+ /// <summary>
+ /// Gets the URL of the intended receiver of this message.
+ /// </summary>
+ Uri IDirectedProtocolMessage.Recipient {
+ get { return this.Recipient; }
+ }
+
+ #endregion
+
+ #region IDirectResponseProtocolMessage Members
+
+ /// <summary>
+ /// Gets the originating request message that caused this response to be formed.
+ /// </summary>
+ IDirectedProtocolMessage IDirectResponseProtocolMessage.OriginatingRequest {
+ get { return this.OriginatingRequest; }
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Gets the level of protection this message requires.
+ /// </summary>
+ protected static MessageProtections RequiredProtection {
+ get { return MessageProtections.None; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether this is a direct or indirect message.
+ /// </summary>
+ protected MessageTransport Transport {
+ get { return this.messageTransport; }
+ }
+
+ /// <summary>
+ /// Gets the version of the protocol or extension this message is prepared to implement.
+ /// </summary>
+ protected Version Version {
+ get { return this.version; }
+ }
+
+ /// <summary>
+ /// Gets or sets the preferred method of transport for the message.
+ /// </summary>
+ /// <remarks>
+ /// For indirect messages this will likely be GET+POST, which both can be simulated in the user agent:
+ /// the GET with a simple 301 Redirect, and the POST with an HTML form in the response with javascript
+ /// to automate submission.
+ /// </remarks>
+ protected HttpDeliveryMethods HttpMethods { get; set; }
+
+ /// <summary>
+ /// Gets the originating request message that caused this response to be formed.
+ /// </summary>
+ protected IDirectedProtocolMessage OriginatingRequest {
+ get { return this.originatingRequest; }
+ }
+
+ /// <summary>
+ /// Gets the URL of the intended receiver of this message.
+ /// </summary>
+ protected Uri Recipient { get; private set; }
+
+ #region IMessage Methods
+
+ /// <summary>
+ /// Checks the message state for conformity to the protocol specification
+ /// and throws an exception if the message is invalid.
+ /// </summary>
+ /// <remarks>
+ /// <para>Some messages have required fields, or combinations of fields that must relate to each other
+ /// in specialized ways. After deserializing a message, this method checks the state of the
+ /// message to see if it conforms to the protocol.</para>
+ /// <para>Note that this property should <i>not</i> check signatures or perform any state checks
+ /// outside this scope of this particular message.</para>
+ /// </remarks>
+ /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception>
+ void IMessage.EnsureValidMessage() {
+ this.EnsureValidMessage();
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Checks the message state for conformity to the protocol specification
+ /// and throws an exception if the message is invalid.
+ /// </summary>
+ /// <remarks>
+ /// <para>Some messages have required fields, or combinations of fields that must relate to each other
+ /// in specialized ways. After deserializing a message, this method checks the state of the
+ /// message to see if it conforms to the protocol.</para>
+ /// <para>Note that this property should <i>not</i> check signatures or perform any state checks
+ /// outside this scope of this particular message.</para>
+ /// </remarks>
+ /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception>
+ protected virtual void EnsureValidMessage() {
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/OAuth 2 Messages.cd b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/OAuth 2 Messages.cd
new file mode 100644
index 0000000..05e3ad9
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/OAuth 2 Messages.cd
@@ -0,0 +1,164 @@
+<?xml version="1.0" encoding="utf-8"?>
+<ClassDiagram MajorVersion="1" MinorVersion="1">
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.MessageBase" Collapsed="true">
+ <Position X="0.5" Y="0.5" Width="1.5" />
+ <TypeIdentifier>
+ <HashCode>IAAMACQAQAAAgAkAAAAIAAYACgAAIAAAIACAACAAAIA=</HashCode>
+ <FileName>OAuth2\Messages\MessageBase.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.AccessTokenAuthorizationCodeRequest" Collapsed="true">
+ <Position X="8.5" Y="6.75" Width="3" />
+ <TypeIdentifier>
+ <HashCode>ACAAEAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAgAAAATAA=</HashCode>
+ <FileName>OAuth2\Messages\AccessTokenAuthorizationCodeRequest.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.AccessTokenClientCredentialsRequest" Collapsed="true">
+ <Position X="8.5" Y="8.75" Width="2.75" />
+ <TypeIdentifier>
+ <HashCode>AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA=</HashCode>
+ <FileName>OAuth2\Messages\AccessTokenClientCredentialsRequest.cs</FileName>
+ </TypeIdentifier>
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.AccessTokenFailedResponse" Collapsed="true">
+ <Position X="3.25" Y="8.5" Width="2.25" />
+ <TypeIdentifier>
+ <HashCode>AAAAAIAAAAAAAQAAAABAAAQAAAAAAAEQAAAAAAAAAAA=</HashCode>
+ <FileName>OAuth2\Messages\AccessTokenFailedResponse.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.AccessTokenRefreshRequest" Collapsed="true">
+ <Position X="8.5" Y="9.75" Width="2.25" />
+ <TypeIdentifier>
+ <HashCode>AAAAEAAAQAAAAAAAAAAAAAAQAAAAAAAAAAAgAAAABAA=</HashCode>
+ <FileName>OAuth2\Messages\AccessTokenRefreshRequest.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.AccessTokenRequestBase" Collapsed="true">
+ <Position X="5.75" Y="5.75" Width="2" />
+ <TypeIdentifier>
+ <HashCode>AAAAAAAAQABAAAAAAAAAAAAQAAAAAAAAAAAAAAAACAA=</HashCode>
+ <FileName>OAuth2\Messages\AccessTokenRequestBase.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.AccessTokenResourceOwnerPasswordCredentialsRequest" Collapsed="true">
+ <Position X="8.5" Y="10.5" Width="4" />
+ <TypeIdentifier>
+ <HashCode>AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAACAQAAAAAAAAA=</HashCode>
+ <FileName>OAuth2\Messages\AccessTokenResourceOwnerPasswordCredentialsRequest.cs</FileName>
+ </TypeIdentifier>
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.AccessTokenSuccessResponse" Collapsed="true">
+ <Position X="3.25" Y="7.5" Width="2.25" />
+ <TypeIdentifier>
+ <HashCode>AAAAAAAAQAAAACAAAAAAAAQAEAAAAAAQAEAAAAAAAgA=</HashCode>
+ <FileName>OAuth2\Messages\AccessTokenSuccessResponse.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.AuthenticatedClientRequestBase" Collapsed="true">
+ <Position X="3.25" Y="5.25" Width="2.25" />
+ <TypeIdentifier>
+ <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAA=</HashCode>
+ <FileName>OAuth2\Messages\AuthenticatedClientRequestBase.cs</FileName>
+ </TypeIdentifier>
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationFailedResponse" Collapsed="true">
+ <Position X="3.25" Y="4.5" Width="2.75" />
+ <TypeIdentifier>
+ <HashCode>AAAAAIAAAAAAAQAAAAAAAAgAAAAAAAEAAAAAAAAAAAA=</HashCode>
+ <FileName>OAuth2\Messages\EndUserAuthorizationFailedResponse.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationRequest" Collapsed="true">
+ <Position X="3.25" Y="0.5" Width="2.25" />
+ <TypeIdentifier>
+ <HashCode>AAAAAAAAQABAACAAAAAAAACAAAQAAAQAAAAAAAAAQAA=</HashCode>
+ <FileName>OAuth2\Messages\EndUserAuthorizationRequest.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationSuccessAccessTokenResponse" Collapsed="true">
+ <Position X="6.25" Y="3.75" Width="3.75" />
+ <TypeIdentifier>
+ <HashCode>AAAAEAAAAAAAAAAAAAAAAAACEAAAAAAAAAAgAAAABgA=</HashCode>
+ <FileName>OAuth2\Messages\EndUserAuthorizationSuccessAccessTokenResponse.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationSuccessAuthCodeResponse" Collapsed="true">
+ <Position X="6.25" Y="2.5" Width="3.5" />
+ <TypeIdentifier>
+ <HashCode>ACAAEAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAgAAAABAA=</HashCode>
+ <FileName>OAuth2\Messages\EndUserAuthorizationSuccessAuthCodeResponse.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationSuccessResponseBase" Collapsed="true">
+ <Position X="3.25" Y="1.5" Width="2.75" />
+ <TypeIdentifier>
+ <HashCode>AAACAAAAAAAAACAAAAAAAAgAAAAAAAAAAEAAAAAAAAA=</HashCode>
+ <FileName>OAuth2\Messages\EndUserAuthorizationSuccessResponseBase.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.AccessProtectedResourceRequest" Collapsed="true">
+ <Position X="3.25" Y="9.75" Width="2.5" />
+ <TypeIdentifier>
+ <HashCode>AAAAEAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAgAAAABgA=</HashCode>
+ <FileName>OAuth2\Messages\AccessProtectedResourceRequest.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.UnauthorizedResponse" Collapsed="true">
+ <Position X="3.25" Y="10.75" Width="2" />
+ <TypeIdentifier>
+ <HashCode>AUABAAAAAAAAACAAAAAAAAQIAAAAAAAQAAAAAAAAABA=</HashCode>
+ <FileName>OAuth2\Messages\UnauthorizedResponse.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.ScopedAccessTokenRequest" Collapsed="true">
+ <Position X="6.75" Y="7.75" Width="2.25" />
+ <TypeIdentifier>
+ <HashCode>AAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAACAA=</HashCode>
+ <FileName>OAuth2\Messages\ScopedAccessTokenRequest.cs</FileName>
+ </TypeIdentifier>
+ </Class>
+ <Interface Name="DotNetOpenAuth.OAuth2.Messages.IMessageWithClientState">
+ <Position X="11.5" Y="0.5" Width="2" />
+ <TypeIdentifier>
+ <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAA=</HashCode>
+ <FileName>OAuth2\Messages\IMessageWithClientState.cs</FileName>
+ </TypeIdentifier>
+ </Interface>
+ <Interface Name="DotNetOpenAuth.OAuth2.ChannelElements.IAuthorizationCarryingRequest">
+ <Position X="11.75" Y="2" Width="2.5" />
+ <TypeIdentifier>
+ <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAEAAAAA=</HashCode>
+ <FileName>OAuth2\ChannelElements\IAuthorizationCarryingRequest.cs</FileName>
+ </TypeIdentifier>
+ </Interface>
+ <Enum Name="DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationResponseType">
+ <Position X="8" Y="0.5" Width="3" />
+ <TypeIdentifier>
+ <HashCode>ACAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAA=</HashCode>
+ <FileName>OAuth2\Messages\EndUserAuthorizationResponseType.cs</FileName>
+ </TypeIdentifier>
+ </Enum>
+ <Enum Name="DotNetOpenAuth.OAuth2.Messages.GrantType">
+ <Position X="6.25" Y="0.5" Width="1.5" />
+ <TypeIdentifier>
+ <HashCode>ACAAAAAAQAAAAAQAAgAAAAAAAAAAAAACAAAAAAAAAAA=</HashCode>
+ <FileName>OAuth2\Messages\GrantType.cs</FileName>
+ </TypeIdentifier>
+ </Enum>
+ <Font Name="Segoe UI" Size="9" />
+</ClassDiagram> \ No newline at end of file
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/ScopedAccessTokenRequest.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/ScopedAccessTokenRequest.cs
new file mode 100644
index 0000000..5568b1c
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/ScopedAccessTokenRequest.cs
@@ -0,0 +1,41 @@
+//-----------------------------------------------------------------------
+// <copyright file="ScopedAccessTokenRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// An access token request that includes a scope parameter.
+ /// </summary>
+ internal abstract class ScopedAccessTokenRequest : AccessTokenRequestBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ScopedAccessTokenRequest"/> class.
+ /// </summary>
+ /// <param name="tokenEndpoint">The Authorization Server's access token endpoint URL.</param>
+ /// <param name="version">The version.</param>
+ internal ScopedAccessTokenRequest(Uri tokenEndpoint, Version version)
+ : base(tokenEndpoint, version) {
+ this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer);
+ }
+
+ /// <summary>
+ /// Gets the set of scopes the Client would like the access token to provide access to.
+ /// </summary>
+ /// <value>A set of scopes. Never null.</value>
+ [MessagePart(Protocol.scope, IsRequired = false, Encoder = typeof(ScopeEncoder))]
+ internal HashSet<string> Scope { get; private set; }
+
+ /// <summary>
+ /// Gets the scope of operations the client is allowed to invoke.
+ /// </summary>
+ protected override HashSet<string> RequestedScope {
+ get { return this.Scope; }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/UnauthorizedResponse.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/UnauthorizedResponse.cs
new file mode 100644
index 0000000..529fab2
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/UnauthorizedResponse.cs
@@ -0,0 +1,115 @@
+//-----------------------------------------------------------------------
+// <copyright file="UnauthorizedResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Diagnostics.Contracts;
+ using System.Net;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A direct response that is simply a 401 Unauthorized with an
+ /// WWW-Authenticate: OAuth header.
+ /// </summary>
+ internal class UnauthorizedResponse : MessageBase, IHttpDirectResponse {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UnauthorizedResponse"/> class.
+ /// </summary>
+ /// <param name="exception">The exception.</param>
+ /// <param name="version">The protocol version.</param>
+ internal UnauthorizedResponse(ProtocolException exception, Version version = null)
+ : base(version ?? Protocol.Default.Version) {
+ Requires.NotNull(exception, "exception");
+ this.ErrorMessage = exception.Message;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UnauthorizedResponse"/> class.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ internal UnauthorizedResponse(IDirectedProtocolMessage request)
+ : base(request) {
+ this.Realm = "Service";
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UnauthorizedResponse"/> class.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ /// <param name="exception">The exception.</param>
+ internal UnauthorizedResponse(IDirectedProtocolMessage request, ProtocolException exception)
+ : this(request) {
+ Requires.NotNull(exception, "exception");
+ this.ErrorMessage = exception.Message;
+ }
+
+ #region IHttpDirectResponse Members
+
+ /// <summary>
+ /// Gets the HTTP status code that the direct response should be sent with.
+ /// </summary>
+ HttpStatusCode IHttpDirectResponse.HttpStatusCode {
+ get { return HttpStatusCode.Unauthorized; }
+ }
+
+ /// <summary>
+ /// Gets the HTTP headers to add to the response.
+ /// </summary>
+ /// <value>May be an empty collection, but must not be <c>null</c>.</value>
+ WebHeaderCollection IHttpDirectResponse.Headers {
+ get {
+ return new WebHeaderCollection() {
+ { HttpResponseHeader.WwwAuthenticate, Protocol.BearerHttpAuthorizationScheme },
+ };
+ }
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Gets or sets the error message.
+ /// </summary>
+ /// <value>The error message.</value>
+ [MessagePart("error")]
+ internal string ErrorMessage { get; set; }
+
+ /// <summary>
+ /// Gets or sets the realm.
+ /// </summary>
+ /// <value>The realm.</value>
+ [MessagePart("realm")]
+ internal string Realm { get; set; }
+
+ /// <summary>
+ /// Gets or sets the scope.
+ /// </summary>
+ /// <value>The scope.</value>
+ [MessagePart("scope")]
+ internal string Scope { get; set; }
+
+ /// <summary>
+ /// Gets or sets the algorithms.
+ /// </summary>
+ /// <value>The algorithms.</value>
+ [MessagePart("algorithms")]
+ internal string Algorithms { get; set; }
+
+ /// <summary>
+ /// Gets or sets the user endpoint.
+ /// </summary>
+ /// <value>The user endpoint.</value>
+ [MessagePart("user-uri")]
+ internal Uri UserEndpoint { get; set; }
+
+ /// <summary>
+ /// Gets or sets the token endpoint.
+ /// </summary>
+ /// <value>The token endpoint.</value>
+ [MessagePart("token-uri")]
+ internal Uri TokenEndpoint { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/OAuth 2 client facades.cd b/src/DotNetOpenAuth.OAuth2/OAuth2/OAuth 2 client facades.cd
new file mode 100644
index 0000000..97bf2eb
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/OAuth 2 client facades.cd
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<ClassDiagram MajorVersion="1" MinorVersion="1">
+ <Class Name="DotNetOpenAuth.OAuth2.ClientBase">
+ <Position X="0.5" Y="0.5" Width="3.5" />
+ <TypeIdentifier>
+ <HashCode>AAACAAAwAEAAAAAAAgAAAIEAAAwAAAAAAAAAAAAAAAA=</HashCode>
+ <FileName>OAuth2\ClientBase.cs</FileName>
+ </TypeIdentifier>
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.WebServerClient">
+ <Position X="4.5" Y="0.5" Width="3.5" />
+ <TypeIdentifier>
+ <HashCode>AAAAAQAAAAAAEAAAAAAABAAAAAAAAAAAAAAAAAABAAA=</HashCode>
+ <FileName>OAuth2\WebServerClient.cs</FileName>
+ </TypeIdentifier>
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.UserAgentClient">
+ <Position X="4.5" Y="3" Width="3.5" />
+ <InheritanceLine Type="DotNetOpenAuth.OAuth2.ClientBase" FixedFromPoint="true">
+ <Path>
+ <Point X="4" Y="3.166" />
+ <Point X="4.5" Y="3.166" />
+ </Path>
+ </InheritanceLine>
+ <TypeIdentifier>
+ <HashCode>AAAAAAAAAAAAEAAAAAAABAAAAAAAAAAAAAAAAAAAAAA=</HashCode>
+ <FileName>OAuth2\UserAgentClient.cs</FileName>
+ </TypeIdentifier>
+ </Class>
+ <Font Name="Segoe UI" Size="9" />
+</ClassDiagram> \ No newline at end of file
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthStrings.Designer.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthStrings.Designer.cs
new file mode 100644
index 0000000..9ea12ab
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthStrings.Designer.cs
@@ -0,0 +1,144 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.225
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+
+
+ /// <summary>
+ /// A strongly-typed resource class, for looking up localized strings, etc.
+ /// </summary>
+ // This class was auto-generated by the StronglyTypedResourceBuilder
+ // class via a tool like ResGen or Visual Studio.
+ // To add or remove a member, edit your .ResX file then rerun ResGen
+ // with the /str option, or rebuild your VS project.
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class OAuthStrings {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal OAuthStrings() {
+ }
+
+ /// <summary>
+ /// Returns the cached ResourceManager instance used by this class.
+ /// </summary>
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager {
+ get {
+ if (object.ReferenceEquals(resourceMan, null)) {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DotNetOpenAuth.OAuth2.OAuthStrings", typeof(OAuthStrings).Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ /// <summary>
+ /// Overrides the current thread's CurrentUICulture property for all
+ /// resource lookups using this strongly typed resource class.
+ /// </summary>
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture {
+ get {
+ return resourceCulture;
+ }
+ set {
+ resourceCulture = value;
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to The value for message part &quot;{0}&quot; must be an absolute URI..
+ /// </summary>
+ internal static string AbsoluteUriRequired {
+ get {
+ return ResourceManager.GetString("AbsoluteUriRequired", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to The requested access scope (&quot;{0}&quot;) exceeds the grant scope (&quot;{1}&quot;)..
+ /// </summary>
+ internal static string AccessScopeExceedsGrantScope {
+ get {
+ return ResourceManager.GetString("AccessScopeExceedsGrantScope", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Failed to obtain access token. Authorization Server reports reason: {0}.
+ /// </summary>
+ internal static string CannotObtainAccessTokenWithReason {
+ get {
+ return ResourceManager.GetString("CannotObtainAccessTokenWithReason", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to The callback URL ({0}) is not allowed for this client..
+ /// </summary>
+ internal static string ClientCallbackDisallowed {
+ get {
+ return ResourceManager.GetString("ClientCallbackDisallowed", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to This message can only be sent over HTTPS..
+ /// </summary>
+ internal static string HttpsRequired {
+ get {
+ return ResourceManager.GetString("HttpsRequired", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Failed to obtain access token due to invalid Client Identifier or Client Secret..
+ /// </summary>
+ internal static string InvalidClientCredentials {
+ get {
+ return ResourceManager.GetString("InvalidClientCredentials", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to No callback URI was available for this request..
+ /// </summary>
+ internal static string NoCallback {
+ get {
+ return ResourceManager.GetString("NoCallback", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Refresh tokens should not be granted without the request including an access grant..
+ /// </summary>
+ internal static string NoGrantNoRefreshToken {
+ get {
+ return ResourceManager.GetString("NoGrantNoRefreshToken", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Individual scopes may not contain spaces..
+ /// </summary>
+ internal static string ScopesMayNotContainSpaces {
+ get {
+ return ResourceManager.GetString("ScopesMayNotContainSpaces", resourceCulture);
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthStrings.resx b/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthStrings.resx
new file mode 100644
index 0000000..fc2f2d2
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthStrings.resx
@@ -0,0 +1,147 @@
+<?xml version="1.0" encoding="utf-8"?>
+<root>
+ <!--
+ Microsoft ResX Schema
+
+ Version 2.0
+
+ The primary goals of this format is to allow a simple XML format
+ that is mostly human readable. The generation and parsing of the
+ various data types are done through the TypeConverter classes
+ associated with the data types.
+
+ Example:
+
+ ... ado.net/XML headers & schema ...
+ <resheader name="resmimetype">text/microsoft-resx</resheader>
+ <resheader name="version">2.0</resheader>
+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+ <value>[base64 mime encoded serialized .NET Framework object]</value>
+ </data>
+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+ <comment>This is a comment</comment>
+ </data>
+
+ There are any number of "resheader" rows that contain simple
+ name/value pairs.
+
+ Each data row contains a name, and value. The row also contains a
+ type or mimetype. Type corresponds to a .NET class that support
+ text/value conversion through the TypeConverter architecture.
+ Classes that don't support this are serialized and stored with the
+ mimetype set.
+
+ The mimetype is used for serialized objects, and tells the
+ ResXResourceReader how to depersist the object. This is currently not
+ extensible. For a given mimetype the value must be set accordingly:
+
+ Note - application/x-microsoft.net.object.binary.base64 is the format
+ that the ResXResourceWriter will generate, however the reader can
+ read any of the formats listed below.
+
+ mimetype: application/x-microsoft.net.object.binary.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.soap.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.bytearray.base64
+ value : The object must be serialized into a byte array
+ : using a System.ComponentModel.TypeConverter
+ : and then encoded with base64 encoding.
+ -->
+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
+ <xsd:element name="root" msdata:IsDataSet="true">
+ <xsd:complexType>
+ <xsd:choice maxOccurs="unbounded">
+ <xsd:element name="metadata">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" />
+ </xsd:sequence>
+ <xsd:attribute name="name" use="required" type="xsd:string" />
+ <xsd:attribute name="type" type="xsd:string" />
+ <xsd:attribute name="mimetype" type="xsd:string" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="assembly">
+ <xsd:complexType>
+ <xsd:attribute name="alias" type="xsd:string" />
+ <xsd:attribute name="name" type="xsd:string" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="data">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="resheader">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" />
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:choice>
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:schema>
+ <resheader name="resmimetype">
+ <value>text/microsoft-resx</value>
+ </resheader>
+ <resheader name="version">
+ <value>2.0</value>
+ </resheader>
+ <resheader name="reader">
+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <resheader name="writer">
+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <data name="AbsoluteUriRequired" xml:space="preserve">
+ <value>The value for message part "{0}" must be an absolute URI.</value>
+ </data>
+ <data name="AccessScopeExceedsGrantScope" xml:space="preserve">
+ <value>The requested access scope ("{0}") exceeds the grant scope ("{1}").</value>
+ </data>
+ <data name="CannotObtainAccessTokenWithReason" xml:space="preserve">
+ <value>Failed to obtain access token. Authorization Server reports reason: {0}</value>
+ </data>
+ <data name="ClientCallbackDisallowed" xml:space="preserve">
+ <value>The callback URL ({0}) is not allowed for this client.</value>
+ </data>
+ <data name="HttpsRequired" xml:space="preserve">
+ <value>This message can only be sent over HTTPS.</value>
+ </data>
+ <data name="InvalidClientCredentials" xml:space="preserve">
+ <value>Failed to obtain access token due to invalid Client Identifier or Client Secret.</value>
+ </data>
+ <data name="NoCallback" xml:space="preserve">
+ <value>No callback URI was available for this request.</value>
+ </data>
+ <data name="NoGrantNoRefreshToken" xml:space="preserve">
+ <value>Refresh tokens should not be granted without the request including an access grant.</value>
+ </data>
+ <data name="ScopesMayNotContainSpaces" xml:space="preserve">
+ <value>Individual scopes may not contain spaces.</value>
+ </data>
+</root> \ No newline at end of file
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthUtilities.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthUtilities.cs
new file mode 100644
index 0000000..1ae3701
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthUtilities.cs
@@ -0,0 +1,123 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuthUtilities.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Globalization;
+ using System.Linq;
+ using System.Net;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// Some common utility methods for OAuth 2.0.
+ /// </summary>
+ public static class OAuthUtilities {
+ /// <summary>
+ /// The <see cref="StringComparer"/> instance to use when comparing scope equivalence.
+ /// </summary>
+ public static readonly StringComparer ScopeStringComparer = StringComparer.Ordinal;
+
+ /// <summary>
+ /// The delimiter between scope elements.
+ /// </summary>
+ private static char[] scopeDelimiter = new char[] { ' ' };
+
+ /// <summary>
+ /// The characters that may appear in an access token that is included in an HTTP Authorization header.
+ /// </summary>
+ /// <remarks>
+ /// This is defined in OAuth 2.0 DRAFT 10, section 5.1.1. (http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#authz-header)
+ /// </remarks>
+ private static string accessTokenAuthorizationHeaderAllowedCharacters = MessagingUtilities.UppercaseLetters +
+ MessagingUtilities.LowercaseLetters +
+ MessagingUtilities.Digits +
+ @"!#$%&'()*+-./:<=>?@[]^_`{|}~\,;";
+
+ /// <summary>
+ /// Determines whether one given scope is a subset of another scope.
+ /// </summary>
+ /// <param name="requestedScope">The requested scope, which may be a subset of <paramref name="grantedScope"/>.</param>
+ /// <param name="grantedScope">The granted scope, the suspected superset.</param>
+ /// <returns>
+ /// <c>true</c> if all the elements that appear in <paramref name="requestedScope"/> also appear in <paramref name="grantedScope"/>;
+ /// <c>false</c> otherwise.
+ /// </returns>
+ public static bool IsScopeSubset(string requestedScope, string grantedScope) {
+ if (string.IsNullOrEmpty(requestedScope)) {
+ return true;
+ }
+
+ if (string.IsNullOrEmpty(grantedScope)) {
+ return false;
+ }
+
+ var requestedScopes = new HashSet<string>(requestedScope.Split(scopeDelimiter, StringSplitOptions.RemoveEmptyEntries));
+ var grantedScopes = new HashSet<string>(grantedScope.Split(scopeDelimiter, StringSplitOptions.RemoveEmptyEntries));
+ return requestedScopes.IsSubsetOf(grantedScopes);
+ }
+
+ /// <summary>
+ /// Identifies individual scope elements
+ /// </summary>
+ /// <param name="scope">The space-delimited list of scopes.</param>
+ /// <returns>A set of individual scopes, with any duplicates removed.</returns>
+ public static HashSet<string> SplitScopes(string scope) {
+ if (string.IsNullOrEmpty(scope)) {
+ return new HashSet<string>();
+ }
+
+ return new HashSet<string>(scope.Split(scopeDelimiter, StringSplitOptions.RemoveEmptyEntries), ScopeStringComparer);
+ }
+
+ /// <summary>
+ /// Serializes a set of scopes as a space-delimited list.
+ /// </summary>
+ /// <param name="scopes">The scopes to serialize.</param>
+ /// <returns>A space-delimited list.</returns>
+ public static string JoinScopes(HashSet<string> scopes) {
+ Requires.NotNull(scopes, "scopes");
+ return string.Join(" ", scopes.ToArray());
+ }
+
+ /// <summary>
+ /// Authorizes an HTTP request using an OAuth 2.0 access token in an HTTP Authorization header.
+ /// </summary>
+ /// <param name="request">The request to authorize.</param>
+ /// <param name="accessToken">The access token previously obtained from the Authorization Server.</param>
+ internal static void AuthorizeWithBearerToken(this HttpWebRequest request, string accessToken) {
+ Requires.NotNull(request, "request");
+ Requires.NotNullOrEmpty(accessToken, "accessToken");
+ ErrorUtilities.VerifyProtocol(accessToken.All(ch => accessTokenAuthorizationHeaderAllowedCharacters.IndexOf(ch) >= 0), "The access token contains characters that must not appear in the HTTP Authorization header.");
+
+ request.Headers[HttpRequestHeader.Authorization] = string.Format(
+ CultureInfo.InvariantCulture,
+ Protocol.BearerHttpAuthorizationHeaderFormat,
+ accessToken);
+ }
+
+ /// <summary>
+ /// Gets information about the client with a given identifier.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ /// <param name="clientIdentifier">The client identifier.</param>
+ /// <returns>The client information. Never null.</returns>
+ internal static IConsumerDescription GetClientOrThrow(this IAuthorizationServer authorizationServer, string clientIdentifier) {
+ Requires.NotNullOrEmpty(clientIdentifier, "clientIdentifier");
+ Contract.Ensures(Contract.Result<IConsumerDescription>() != null);
+
+ try {
+ return authorizationServer.GetClient(clientIdentifier);
+ } catch (KeyNotFoundException ex) {
+ throw ErrorUtilities.Wrap(ex, OAuth.OAuthStrings.ConsumerOrTokenSecretNotFound);
+ } catch (ArgumentException ex) {
+ throw ErrorUtilities.Wrap(ex, OAuth.OAuthStrings.ConsumerOrTokenSecretNotFound);
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Protocol.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Protocol.cs
new file mode 100644
index 0000000..3cb8253
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Protocol.cs
@@ -0,0 +1,355 @@
+// <auto-generated/> // disable StyleCop on this file
+//-----------------------------------------------------------------------
+// <copyright file="Protocol.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+
+ /// <summary>
+ /// An enumeration of the OAuth protocol versions supported by this library.
+ /// </summary>
+ public enum ProtocolVersion {
+ /// <summary>
+ /// The OAuth 2.0 specification.
+ /// </summary>
+ V20,
+ }
+
+ /// <summary>
+ /// Protocol constants for OAuth 2.0.
+ /// </summary>
+ internal class Protocol {
+ /// <summary>
+ /// The HTTP authorization scheme "Bearer";
+ /// </summary>
+ internal const string BearerHttpAuthorizationScheme = "Bearer";
+
+ /// <summary>
+ /// The HTTP authorization scheme "Bearer ";
+ /// </summary>
+ internal const string BearerHttpAuthorizationSchemeWithTrailingSpace = BearerHttpAuthorizationScheme + " ";
+
+ /// <summary>
+ /// The format of the HTTP Authorization header value that authorizes OAuth 2.0 requests using bearer access tokens.
+ /// </summary>
+ internal const string BearerHttpAuthorizationHeaderFormat = BearerHttpAuthorizationSchemeWithTrailingSpace + "{0}";
+
+ /// <summary>
+ /// The name of the parameter whose value is an OAuth 2.0 bearer access token, as it is defined
+ /// in a URL-encoded POST entity or URL query string.
+ /// </summary>
+ internal const string BearerTokenEncodedUrlParameterName = "access_token";
+
+ /// <summary>
+ /// The "type" string.
+ /// </summary>
+ internal const string type = "type";
+
+ /// <summary>
+ /// The "state" string.
+ /// </summary>
+ internal const string state = "state";
+
+ /// <summary>
+ /// The "redirect_uri_mismatch" string.
+ /// </summary>
+ internal const string redirect_uri_mismatch = "redirect_uri_mismatch";
+
+ /// <summary>
+ /// The "bad_verification_code" string.
+ /// </summary>
+ internal const string bad_verification_code = "bad_verification_code";
+
+ /// <summary>
+ /// The "incorrect_client_credentials" string.
+ /// </summary>
+ internal const string incorrect_client_credentials = "incorrect_client_credentials";
+
+ /// <summary>
+ /// The "unauthorized_client" string.
+ /// </summary>
+ internal const string unauthorized_client = "unauthorized_client";
+
+ /// <summary>
+ /// The "authorization_expired" string.
+ /// </summary>
+ internal const string authorization_expired = "authorization_expired";
+
+ /// <summary>
+ /// The "redirect_uri" string.
+ /// </summary>
+ internal const string redirect_uri = "redirect_uri";
+
+ /// <summary>
+ /// The "client_id" string.
+ /// </summary>
+ internal const string client_id = "client_id";
+
+ /// <summary>
+ /// The "scope" string.
+ /// </summary>
+ internal const string scope = "scope";
+
+ /// <summary>
+ /// The "immediate" string.
+ /// </summary>
+ internal const string immediate = "immediate";
+
+ /// <summary>
+ /// The "client_secret" string.
+ /// </summary>
+ internal const string client_secret = "client_secret";
+
+ /// <summary>
+ /// The "code" string.
+ /// </summary>
+ internal const string code = "code";
+
+ /// <summary>
+ /// The "user_code" string.
+ /// </summary>
+ internal const string user_code = "user_code";
+
+ /// <summary>
+ /// The "verification_uri" string.
+ /// </summary>
+ internal const string verification_uri = "verification_uri";
+
+ /// <summary>
+ /// The "interval" string.
+ /// </summary>
+ internal const string interval = "interval";
+
+ /// <summary>
+ /// The "error" string.
+ /// </summary>
+ internal const string error = "error";
+
+ /// <summary>
+ /// The "access_token" string.
+ /// </summary>
+ internal const string access_token = "access_token";
+
+ /// <summary>
+ /// The "access_token_secret" string.
+ /// </summary>
+ internal const string access_token_secret = "access_token_secret";
+
+ /// <summary>
+ /// The "token_type" string.
+ /// </summary>
+ internal const string token_type = "token_type";
+
+ /// <summary>
+ /// The "refresh_token" string.
+ /// </summary>
+ internal const string refresh_token = "refresh_token";
+
+ /// <summary>
+ /// The "expires_in" string.
+ /// </summary>
+ internal const string expires_in = "expires_in";
+
+ /// <summary>
+ /// The "expired_delegation_code" string.
+ /// </summary>
+ internal const string expired_delegation_code = "expired_delegation_code";
+
+ /// <summary>
+ /// The "username" string.
+ /// </summary>
+ internal const string username = "username";
+
+ /// <summary>
+ /// The "password" string.
+ /// </summary>
+ internal const string password = "password";
+
+ /// <summary>
+ /// The "format" string.
+ /// </summary>
+ internal const string format = "format";
+
+ /// <summary>
+ /// The "assertion" string.
+ /// </summary>
+ internal const string assertion = "assertion";
+
+ /// <summary>
+ /// The "assertion_type" string.
+ /// </summary>
+ internal const string assertion_type = "assertion_type";
+
+ /// <summary>
+ /// The "user_denied" string.
+ /// </summary>
+ internal const string user_denied = "user_denied";
+
+ /// <summary>
+ /// Gets the <see cref="Protocol"/> instance with values initialized for V1.0 of the protocol.
+ /// </summary>
+ internal static readonly Protocol V20 = new Protocol {
+ Version = new Version(2, 0),
+ ProtocolVersion = ProtocolVersion.V20,
+ };
+
+ /// <summary>
+ /// A list of all supported OAuth versions, in order starting from newest version.
+ /// </summary>
+ internal static readonly List<Protocol> AllVersions = new List<Protocol>() { V20 };
+
+ /// <summary>
+ /// The default (or most recent) supported version of the OpenID protocol.
+ /// </summary>
+ internal static readonly Protocol Default = AllVersions[0];
+
+ /// <summary>
+ /// The "error_uri" string.
+ /// </summary>
+ public const string error_uri = "error_uri";
+
+ /// <summary>
+ /// The "error_description" string.
+ /// </summary>
+ internal const string error_description = "error_description";
+
+ /// <summary>
+ /// The "response_type" string.
+ /// </summary>
+ internal const string response_type = "response_type";
+
+ /// <summary>
+ /// The "grant_type" string.
+ /// </summary>
+ internal const string grant_type = "grant_type";
+
+ /// <summary>
+ /// Gets or sets the OAuth 2.0 version represented by this instance.
+ /// </summary>
+ /// <value>The version.</value>
+ internal Version Version { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the OAuth 2.0 version represented by this instance.
+ /// </summary>
+ /// <value>The protocol version.</value>
+ internal ProtocolVersion ProtocolVersion { get; private set; }
+
+ /// <summary>
+ /// Gets the OAuth Protocol instance to use for the given version.
+ /// </summary>
+ /// <param name="version">The OAuth version to get.</param>
+ /// <returns>A matching <see cref="Protocol"/> instance.</returns>
+ public static Protocol Lookup(ProtocolVersion version) {
+ switch (version) {
+ case ProtocolVersion.V20: return Protocol.V20;
+ default: throw new ArgumentOutOfRangeException("version");
+ }
+ }
+
+ /// <summary>
+ /// Values for the "response_type" parameter.
+ /// </summary>
+ internal static class ResponseTypes
+ {
+ /// <summary>
+ /// The string "code".
+ /// </summary>
+ internal const string Code = "code";
+
+ /// <summary>
+ /// The string "token".
+ /// </summary>
+ internal const string Token = "token";
+ }
+
+ internal static class GrantTypes
+ {
+ internal const string AuthorizationCode = "authorization_code";
+
+ internal const string Password = "password";
+
+ internal const string Assertion = "assertion";
+
+ internal const string RefreshToken = "refresh_token";
+
+ internal const string ClientCredentials = "client_credentials";
+ }
+
+ /// <summary>
+ /// Error codes that an authorization server can return to a client in response to a malformed or unsupported access token request.
+ /// </summary>
+ internal static class AccessTokenRequestErrorCodes
+ {
+ /// <summary>
+ /// The request is missing a required parameter, includes an unknown parameter or parameter value, repeats a parameter, includes multiple credentials, utilizes more than one mechanism for authenticating the client, or is otherwise malformed.
+ /// </summary>
+ internal const string InvalidRequest = "invalid_request";
+
+ /// <summary>
+ /// The client is not authorized to use the access grant type provided.
+ /// </summary>
+ internal const string UnauthorizedClient = "unauthorized_client";
+
+ /// <summary>
+ /// The resource owner or authorization server denied the request.
+ /// </summary>
+ internal const string AccessDenied = "access_denied";
+
+ /// <summary>
+ /// The authorization server does not support obtaining an access token using this method.
+ /// </summary>
+ internal const string UnsupportedGrantType = "unsupported_response_type";
+
+ /// <summary>
+ /// The requested scope is invalid, unknown, malformed, or exceeds the previously granted scope.
+ /// </summary>
+ internal const string InvalidScope = "invalid_scope";
+ }
+
+ /// <summary>
+ /// Error codes that an authorization server can return to a client in response to a malformed or unsupported end user authorization request.
+ /// </summary>
+ internal static class EndUserAuthorizationRequestErrorCodes
+ {
+ /// <summary>
+ /// The request is missing a required parameter, includes an unknown parameter or parameter value, or is otherwise malformed.
+ /// </summary>
+ internal const string InvalidRequest = "invalid_request";
+
+ /// <summary>
+ /// The client is not authorized to use the requested response type.
+ /// </summary>
+ internal const string UnauthorizedClient = "unauthorized_client";
+
+ /// <summary>
+ /// The end-user or authorization server denied the request.
+ /// </summary>
+ internal const string AccessDenied = "access_denied";
+
+ /// <summary>
+ /// The requested response type is not supported by the authorization server.
+ /// </summary>
+ internal const string UnsupportedResponseType = "unsupported_response_type";
+
+ /// <summary>
+ /// The requested scope is invalid, unknown, or malformed.
+ /// </summary>
+ internal const string InvalidScope = "invalid_scope";
+ }
+
+ /// <summary>
+ /// Recognized access token types.
+ /// </summary>
+ internal static class AccessTokenTypes {
+ /// <summary>
+ /// The "bearer" token type.
+ /// </summary>
+ internal const string Bearer = "bearer";
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/StandardAccessTokenAnalyzer.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/StandardAccessTokenAnalyzer.cs
new file mode 100644
index 0000000..f2b7d1c
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/OAuth2/StandardAccessTokenAnalyzer.cs
@@ -0,0 +1,66 @@
+//-----------------------------------------------------------------------
+// <copyright file="StandardAccessTokenAnalyzer.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Security.Cryptography;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// An access token reader that understands DotNetOpenAuth authorization server issued tokens.
+ /// </summary>
+ public class StandardAccessTokenAnalyzer : IAccessTokenAnalyzer {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="StandardAccessTokenAnalyzer"/> class.
+ /// </summary>
+ /// <param name="authorizationServerPublicSigningKey">The crypto service provider with the authorization server public signing key.</param>
+ /// <param name="resourceServerPrivateEncryptionKey">The crypto service provider with the resource server private encryption key.</param>
+ public StandardAccessTokenAnalyzer(RSACryptoServiceProvider authorizationServerPublicSigningKey, RSACryptoServiceProvider resourceServerPrivateEncryptionKey) {
+ Requires.NotNull(authorizationServerPublicSigningKey, "authorizationServerPublicSigningKey");
+ Requires.NotNull(resourceServerPrivateEncryptionKey, "resourceServerPrivateEncryptionKey");
+ Requires.True(!resourceServerPrivateEncryptionKey.PublicOnly, "resourceServerPrivateEncryptionKey");
+ this.AuthorizationServerPublicSigningKey = authorizationServerPublicSigningKey;
+ this.ResourceServerPrivateEncryptionKey = resourceServerPrivateEncryptionKey;
+ }
+
+ /// <summary>
+ /// Gets the authorization server public signing key.
+ /// </summary>
+ /// <value>The authorization server public signing key.</value>
+ public RSACryptoServiceProvider AuthorizationServerPublicSigningKey { get; private set; }
+
+ /// <summary>
+ /// Gets the resource server private encryption key.
+ /// </summary>
+ /// <value>The resource server private encryption key.</value>
+ public RSACryptoServiceProvider ResourceServerPrivateEncryptionKey { get; private set; }
+
+ /// <summary>
+ /// Reads an access token to find out what data it authorizes access to.
+ /// </summary>
+ /// <param name="message">The message carrying the access token.</param>
+ /// <param name="accessToken">The access token.</param>
+ /// <param name="user">The user whose data is accessible with this access token.</param>
+ /// <param name="scope">The scope of access authorized by this access token.</param>
+ /// <returns>
+ /// A value indicating whether this access token is valid.
+ /// </returns>
+ /// <remarks>
+ /// This method also responsible to throw a <see cref="ProtocolException"/> or return
+ /// <c>false</c> when the access token is expired, invalid, or from an untrusted authorization server.
+ /// </remarks>
+ public virtual bool TryValidateAccessToken(IDirectedProtocolMessage message, string accessToken, out string user, out HashSet<string> scope) {
+ var accessTokenFormatter = AccessToken.CreateFormatter(this.AuthorizationServerPublicSigningKey, this.ResourceServerPrivateEncryptionKey);
+ var token = accessTokenFormatter.Deserialize(message, accessToken);
+ user = token.User;
+ scope = new HashSet<string>(token.Scope, OAuthUtilities.ScopeStringComparer);
+ return true;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OAuth2/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth.OAuth2/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..5c7b883
--- /dev/null
+++ b/src/DotNetOpenAuth.OAuth2/Properties/AssemblyInfo.cs
@@ -0,0 +1,60 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssemblyInfo.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+// We DON'T put an AssemblyVersionAttribute in here because it is generated in the build.
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Net;
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Security.Permissions;
+using System.Web.UI;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("DotNetOpenAuth OAuth 2.0")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DotNetOpenAuth")]
+[assembly: AssemblyCopyright("Copyright © 2008")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+[assembly: NeutralResourcesLanguage("en-US")]
+[assembly: CLSCompliant(true)]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("7d73990c-47c0-4256-9f20-a893add9e289")]
+
+[assembly: ContractVerification(true)]
+
+#if StrongNameSigned
+// See comment at top of this file. We need this so that strong-naming doesn't
+// keep this assembly from being useful to shared host (medium trust) web sites.
+[assembly: AllowPartiallyTrustedCallers]
+
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2.AuthorizationServer, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2.ResourceServer, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2.Client, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
+#else
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2.AuthorizationServer")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2.ResourceServer")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2.Client")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
+#endif
diff --git a/src/DotNetOpenAuth.OpenId.Provider.UI/DotNetOpenAuth.OpenId.Provider.UI.csproj b/src/DotNetOpenAuth.OpenId.Provider.UI/DotNetOpenAuth.OpenId.Provider.UI.csproj
new file mode 100644
index 0000000..aede485
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.Provider.UI/DotNetOpenAuth.OpenId.Provider.UI.csproj
@@ -0,0 +1,59 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))\EnlistmentInfo.props" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))' != '' " />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" />
+ <PropertyGroup>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{9D0F8866-2131-4C2A-BC0E-16FEA5B50828}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>DotNetOpenAuth</RootNamespace>
+ <AssemblyName>DotNetOpenAuth.OpenId.Provider.UI</AssemblyName>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" />
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="OpenId\Provider\AnonymousRequestEventArgs.cs" />
+ <Compile Include="OpenId\Provider\AuthenticationChallengeEventArgs.cs" />
+ <Compile Include="OpenId\Provider\IdentityEndpoint.cs" />
+ <Compile Include="OpenId\Provider\IdentityEndpointNormalizationEventArgs.cs" />
+ <Compile Include="OpenId\Provider\ProviderEndpoint.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\DotNetOpenAuth.Core\DotNetOpenAuth.Core.csproj">
+ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project>
+ <Name>DotNetOpenAuth.Core</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OpenId.Provider\DotNetOpenAuth.OpenId.Provider.csproj">
+ <Project>{F8284738-3B5D-4733-A511-38C23F4A763F}</Project>
+ <Name>DotNetOpenAuth.OpenId.Provider</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OpenId.UI\DotNetOpenAuth.OpenId.UI.csproj">
+ <Project>{75E13AAE-7D51-4421-ABFD-3F3DC91F576E}</Project>
+ <Name>DotNetOpenAuth.OpenId.UI</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OpenId\DotNetOpenAuth.OpenId.csproj">
+ <Project>{3896A32A-E876-4C23-B9B8-78E17D134CD3}</Project>
+ <Name>DotNetOpenAuth.OpenId</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\Org.Mentalis.Security.Cryptography\Org.Mentalis.Security.Cryptography.csproj">
+ <Project>{26DC877F-5987-48DD-9DDB-E62F2DE0E150}</Project>
+ <Name>Org.Mentalis.Security.Cryptography</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <ItemGroup>
+ <Reference Include="System" />
+ </ItemGroup>
+ <ItemGroup />
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
+</Project> \ No newline at end of file
diff --git a/src/DotNetOpenAuth/OpenId/Provider/AnonymousRequestEventArgs.cs b/src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/AnonymousRequestEventArgs.cs
index 9ffaa55..2cf680d 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/AnonymousRequestEventArgs.cs
+++ b/src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/AnonymousRequestEventArgs.cs
@@ -18,7 +18,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// </summary>
/// <param name="request">The incoming OpenID request.</param>
internal AnonymousRequestEventArgs(IAnonymousRequest request) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
this.Request = request;
}
diff --git a/src/DotNetOpenAuth/OpenId/Provider/AuthenticationChallengeEventArgs.cs b/src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/AuthenticationChallengeEventArgs.cs
index 1594994..1594994 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/AuthenticationChallengeEventArgs.cs
+++ b/src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/AuthenticationChallengeEventArgs.cs
diff --git a/src/DotNetOpenAuth/OpenId/Provider/IdentityEndpoint.cs b/src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/IdentityEndpoint.cs
index 2685af2..2685af2 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/IdentityEndpoint.cs
+++ b/src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/IdentityEndpoint.cs
diff --git a/src/DotNetOpenAuth/OpenId/Provider/IdentityEndpointNormalizationEventArgs.cs b/src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/IdentityEndpointNormalizationEventArgs.cs
index d190792..d190792 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/IdentityEndpointNormalizationEventArgs.cs
+++ b/src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/IdentityEndpointNormalizationEventArgs.cs
diff --git a/src/DotNetOpenAuth/OpenId/Provider/ProviderEndpoint.cs b/src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/ProviderEndpoint.cs
index e792a81..d0dee75 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/ProviderEndpoint.cs
+++ b/src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/ProviderEndpoint.cs
@@ -82,7 +82,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
}
set {
- Contract.Requires<ArgumentNullException>(value != null);
+ Requires.NotNull(value, "value");
provider = value;
}
}
@@ -98,15 +98,15 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// </remarks>
public static IAuthenticationRequest PendingAuthenticationRequest {
get {
- Contract.Requires<InvalidOperationException>(HttpContext.Current != null, MessagingStrings.HttpContextRequired);
- Contract.Requires<InvalidOperationException>(HttpContext.Current.Session != null, MessagingStrings.SessionRequired);
+ Requires.ValidState(HttpContext.Current != null, MessagingStrings.HttpContextRequired);
+ Requires.ValidState(HttpContext.Current.Session != null, MessagingStrings.SessionRequired);
Contract.Ensures(Contract.Result<IAuthenticationRequest>() == null || PendingRequest != null);
return HttpContext.Current.Session[PendingRequestKey] as IAuthenticationRequest;
}
set {
- Contract.Requires<InvalidOperationException>(HttpContext.Current != null, MessagingStrings.HttpContextRequired);
- Contract.Requires<InvalidOperationException>(HttpContext.Current.Session != null, MessagingStrings.SessionRequired);
+ Requires.ValidState(HttpContext.Current != null, MessagingStrings.HttpContextRequired);
+ Requires.ValidState(HttpContext.Current.Session != null, MessagingStrings.SessionRequired);
HttpContext.Current.Session[PendingRequestKey] = value;
}
}
@@ -122,15 +122,15 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// </remarks>
public static IAnonymousRequest PendingAnonymousRequest {
get {
- Contract.Requires<InvalidOperationException>(HttpContext.Current != null, MessagingStrings.HttpContextRequired);
- Contract.Requires<InvalidOperationException>(HttpContext.Current.Session != null, MessagingStrings.SessionRequired);
+ Requires.ValidState(HttpContext.Current != null, MessagingStrings.HttpContextRequired);
+ Requires.ValidState(HttpContext.Current.Session != null, MessagingStrings.SessionRequired);
Contract.Ensures(Contract.Result<IAnonymousRequest>() == null || PendingRequest != null);
return HttpContext.Current.Session[PendingRequestKey] as IAnonymousRequest;
}
set {
- Contract.Requires<InvalidOperationException>(HttpContext.Current != null, MessagingStrings.HttpContextRequired);
- Contract.Requires<InvalidOperationException>(HttpContext.Current.Session != null, MessagingStrings.SessionRequired);
+ Requires.ValidState(HttpContext.Current != null, MessagingStrings.HttpContextRequired);
+ Requires.ValidState(HttpContext.Current.Session != null, MessagingStrings.SessionRequired);
HttpContext.Current.Session[PendingRequestKey] = value;
}
}
@@ -146,14 +146,14 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// </remarks>
public static IHostProcessedRequest PendingRequest {
get {
- Contract.Requires<InvalidOperationException>(HttpContext.Current != null, MessagingStrings.HttpContextRequired);
- Contract.Requires<InvalidOperationException>(HttpContext.Current.Session != null, MessagingStrings.SessionRequired);
+ Requires.ValidState(HttpContext.Current != null, MessagingStrings.HttpContextRequired);
+ Requires.ValidState(HttpContext.Current.Session != null, MessagingStrings.SessionRequired);
return HttpContext.Current.Session[PendingRequestKey] as IHostProcessedRequest;
}
set {
- Contract.Requires<InvalidOperationException>(HttpContext.Current != null, MessagingStrings.HttpContextRequired);
- Contract.Requires<InvalidOperationException>(HttpContext.Current.Session != null, MessagingStrings.SessionRequired);
+ Requires.ValidState(HttpContext.Current != null, MessagingStrings.HttpContextRequired);
+ Requires.ValidState(HttpContext.Current.Session != null, MessagingStrings.SessionRequired);
HttpContext.Current.Session[PendingRequestKey] = value;
}
}
@@ -222,9 +222,8 @@ namespace DotNetOpenAuth.OpenId.Provider {
}
}
if (request.IsResponseReady) {
- Provider.SendResponse(request);
- Page.Response.End();
PendingAuthenticationRequest = null;
+ Provider.SendResponse(request);
}
}
}
@@ -262,7 +261,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// <returns>The new instance of OpenIdProvider.</returns>
private static OpenIdProvider CreateProvider() {
Contract.Ensures(Contract.Result<OpenIdProvider>() != null);
- return new OpenIdProvider(DotNetOpenAuthSection.Configuration.OpenId.Provider.ApplicationStore.CreateInstance(OpenIdProvider.HttpApplicationStore));
+ return new OpenIdProvider(OpenIdElement.Configuration.Provider.ApplicationStore.CreateInstance(OpenIdProvider.HttpApplicationStore));
}
}
}
diff --git a/src/DotNetOpenAuth/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth.OpenId.Provider.UI/Properties/AssemblyInfo.cs
index a63c71e..2fbaebd 100644
--- a/src/DotNetOpenAuth/Properties/AssemblyInfo.cs
+++ b/src/DotNetOpenAuth.OpenId.Provider.UI/Properties/AssemblyInfo.cs
@@ -17,17 +17,12 @@ using System.Security;
using System.Security.Permissions;
using System.Web.UI;
-[assembly: TagPrefix("DotNetOpenAuth", "dnoa")]
-[assembly: TagPrefix("DotNetOpenAuth.InfoCard", "ic")]
-[assembly: TagPrefix("DotNetOpenAuth.OAuth", "oauth")]
-[assembly: TagPrefix("DotNetOpenAuth.OpenId", "openid")]
[assembly: TagPrefix("DotNetOpenAuth.OpenId.Provider", "op")]
-[assembly: TagPrefix("DotNetOpenAuth.OpenId.RelyingParty", "rp")]
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
-[assembly: AssemblyTitle("DotNetOpenAuth")]
+[assembly: AssemblyTitle("DotNetOpenAuth OpenID")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
@@ -54,6 +49,8 @@ using System.Web.UI;
[assembly: AllowPartiallyTrustedCallers]
[assembly: InternalsVisibleTo("DotNetOpenAuth.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
#else
[assembly: InternalsVisibleTo("DotNetOpenAuth.Test")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
#endif
diff --git a/src/DotNetOpenAuth.OpenId.Provider/DotNetOpenAuth.OpenId.Provider.csproj b/src/DotNetOpenAuth.OpenId.Provider/DotNetOpenAuth.OpenId.Provider.csproj
new file mode 100644
index 0000000..433a8b6
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.Provider/DotNetOpenAuth.OpenId.Provider.csproj
@@ -0,0 +1,88 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))\EnlistmentInfo.props" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))' != '' " />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" />
+ <PropertyGroup>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{F8284738-3B5D-4733-A511-38C23F4A763F}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>DotNetOpenAuth</RootNamespace>
+ <AssemblyName>DotNetOpenAuth.OpenId.Provider</AssemblyName>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" />
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="OpenId\Provider\Behaviors\AXFetchAsSregTransform.cs" />
+ <Compile Include="OpenId\Provider\Behaviors\GsaIcamProfile.cs" />
+ <Compile Include="OpenId\Provider\Behaviors\PpidGeneration.cs" />
+ <Compile Include="OpenId\ChannelElements\AssociateUnencryptedProviderRequest.cs" />
+ <Compile Include="OpenId\ChannelElements\OpenIdProviderChannel.cs" />
+ <Compile Include="OpenId\ChannelElements\OpenIdProviderMessageFactory.cs" />
+ <Compile Include="OpenId\ChannelElements\ProviderSigningBindingElement.cs" />
+ <Compile Include="OpenId\Provider\Extensions\ExtensionsInteropHelper.cs" />
+ <Compile Include="OpenId\Provider\Extensions\UI\UIRequestTools.cs" />
+ <Compile Include="OpenId\Provider\HmacShaAssociationProvider.cs" />
+ <Compile Include="OpenId\Messages\AssociateDiffieHellmanProviderRequest.cs" />
+ <Compile Include="OpenId\Messages\AssociateDiffieHellmanProviderResponse.cs" Condition=" '$(ExcludeDiffieHellman)' != 'true' " />
+ <Compile Include="OpenId\Messages\IAssociateRequestProvider.cs" />
+ <Compile Include="OpenId\Messages\AssociateRequestProviderTools.cs" />
+ <Compile Include="OpenId\Messages\AssociateSuccessfulResponseProvider.cs" />
+ <Compile Include="OpenId\Messages\AssociateSuccessfulResponseProviderContract.cs" />
+ <Compile Include="OpenId\Messages\AssociateUnencryptedResponseProvider.cs" />
+ <Compile Include="OpenId\Messages\CheckAuthenticationResponseProvider.cs" />
+ <Compile Include="OpenId\Provider\OpenIdProviderUtilities.cs" />
+ <Compile Include="OpenId\Provider\AssociationDataBag.cs" />
+ <Compile Include="OpenId\Provider\IProviderAssociationStore.cs" />
+ <Compile Include="OpenId\Provider\ProviderAssociationHandleEncoder.cs" />
+ <Compile Include="OpenId\Provider\ProviderAssociationKeyStorage.cs" />
+ <Compile Include="OpenId\Provider\AssociationRelyingPartyType.cs" />
+ <Compile Include="OpenId\Provider\PrivatePersonalIdentifierProviderBase.cs" />
+ <Compile Include="OpenId\Provider\AnonymousRequest.cs" />
+ <Compile Include="OpenId\Provider\AuthenticationRequest.cs" />
+ <Compile Include="OpenId\Provider\AutoResponsiveRequest.cs" />
+ <Compile Include="OpenId\Provider\HostProcessedRequest.cs" />
+ <Compile Include="OpenId\Provider\IAnonymousRequest.cs" />
+ <Compile Include="OpenId\Provider\IDirectedIdentityIdentifierProvider.cs" />
+ <Compile Include="OpenId\Provider\IErrorReporting.cs" />
+ <Compile Include="OpenId\Provider\Request.cs" />
+ <Compile Include="OpenId\Provider\RequestContract.cs" />
+ <Compile Include="OpenId\Provider\StandardProviderApplicationStore.cs" />
+ <Compile Include="OpenId\Provider\OpenIdProvider.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\DotNetOpenAuth.Core\DotNetOpenAuth.Core.csproj">
+ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project>
+ <Name>DotNetOpenAuth.Core</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OpenId.RelyingParty\DotNetOpenAuth.OpenId.RelyingParty.csproj">
+ <Project>{F458AB60-BA1C-43D9-8CEF-EC01B50BE87B}</Project>
+ <Name>DotNetOpenAuth.OpenId.RelyingParty</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OpenId\DotNetOpenAuth.OpenId.csproj">
+ <Project>{3896A32A-E876-4C23-B9B8-78E17D134CD3}</Project>
+ <Name>DotNetOpenAuth.OpenId</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\Org.Mentalis.Security.Cryptography\Org.Mentalis.Security.Cryptography.csproj" Condition=" '$(ExcludeDiffieHellman)' != 'true' ">
+ <Project>{26DC877F-5987-48DD-9DDB-E62F2DE0E150}</Project>
+ <Name>Org.Mentalis.Security.Cryptography</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <ItemGroup>
+ <Reference Include="System" />
+ </ItemGroup>
+ <ItemGroup>
+ <Folder Include="Configuration\" />
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
+</Project> \ No newline at end of file
diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/AssociateUnencryptedProviderRequest.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/AssociateUnencryptedProviderRequest.cs
new file mode 100644
index 0000000..322c435
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/AssociateUnencryptedProviderRequest.cs
@@ -0,0 +1,41 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssociateUnencryptedProviderRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OpenId.Messages;
+
+ /// <summary>
+ /// Represents an association request received by the OpenID Provider that is sent using HTTPS and
+ /// otherwise communicates the shared secret in plain text.
+ /// </summary>
+ internal class AssociateUnencryptedProviderRequest : AssociateUnencryptedRequest, IAssociateRequestProvider {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AssociateUnencryptedProviderRequest"/> class.
+ /// </summary>
+ /// <param name="version">The OpenID version this message must comply with.</param>
+ /// <param name="providerEndpoint">The OpenID Provider endpoint.</param>
+ internal AssociateUnencryptedProviderRequest(Version version, Uri providerEndpoint)
+ : base(version, providerEndpoint) {
+ }
+
+ /// <summary>
+ /// Creates a Provider's response to an incoming association request.
+ /// </summary>
+ /// <returns>
+ /// The appropriate association response message.
+ /// </returns>
+ public IProtocolMessage CreateResponseCore() {
+ var response = new AssociateUnencryptedResponseProvider(this.Version, this);
+ response.AssociationType = this.AssociationType;
+ return response;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/OpenIdProviderChannel.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/OpenIdProviderChannel.cs
new file mode 100644
index 0000000..5812a96
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/OpenIdProviderChannel.cs
@@ -0,0 +1,76 @@
+//-----------------------------------------------------------------------
+// <copyright file="OpenIdProviderChannel.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+ using DotNetOpenAuth.OpenId.Extensions;
+ using DotNetOpenAuth.OpenId.Provider;
+
+ /// <summary>
+ /// The messaging channel for OpenID Providers.
+ /// </summary>
+ internal class OpenIdProviderChannel : OpenIdChannel {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="OpenIdProviderChannel"/> class.
+ /// </summary>
+ /// <param name="cryptoKeyStore">The OpenID Provider's association store or handle encoder.</param>
+ /// <param name="nonceStore">The nonce store to use.</param>
+ /// <param name="securitySettings">The security settings.</param>
+ internal OpenIdProviderChannel(IProviderAssociationStore cryptoKeyStore, INonceStore nonceStore, ProviderSecuritySettings securitySettings)
+ : this(cryptoKeyStore, nonceStore, new OpenIdProviderMessageFactory(), securitySettings) {
+ Requires.NotNull(cryptoKeyStore, "cryptoKeyStore");
+ Requires.NotNull(securitySettings, "securitySettings");
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="OpenIdProviderChannel"/> class.
+ /// </summary>
+ /// <param name="cryptoKeyStore">The association store to use.</param>
+ /// <param name="nonceStore">The nonce store to use.</param>
+ /// <param name="messageTypeProvider">An object that knows how to distinguish the various OpenID message types for deserialization purposes.</param>
+ /// <param name="securitySettings">The security settings.</param>
+ private OpenIdProviderChannel(IProviderAssociationStore cryptoKeyStore, INonceStore nonceStore, IMessageFactory messageTypeProvider, ProviderSecuritySettings securitySettings)
+ : base(messageTypeProvider, InitializeBindingElements(cryptoKeyStore, nonceStore, securitySettings)) {
+ Requires.NotNull(cryptoKeyStore, "cryptoKeyStore");
+ Requires.NotNull(messageTypeProvider, "messageTypeProvider");
+ Requires.NotNull(securitySettings, "securitySettings");
+ }
+
+ /// <summary>
+ /// Initializes the binding elements.
+ /// </summary>
+ /// <param name="cryptoKeyStore">The OpenID Provider's crypto key store.</param>
+ /// <param name="nonceStore">The nonce store to use.</param>
+ /// <param name="securitySettings">The security settings to apply. Must be an instance of either RelyingPartySecuritySettings or ProviderSecuritySettings.</param>
+ /// <returns>
+ /// An array of binding elements which may be used to construct the channel.
+ /// </returns>
+ private static IChannelBindingElement[] InitializeBindingElements(IProviderAssociationStore cryptoKeyStore, INonceStore nonceStore, ProviderSecuritySettings securitySettings) {
+ Requires.NotNull(cryptoKeyStore, "cryptoKeyStore");
+ Requires.NotNull(securitySettings, "securitySettings");
+ Requires.NotNull(nonceStore, "nonceStore");
+
+ SigningBindingElement signingElement;
+ signingElement = new ProviderSigningBindingElement(cryptoKeyStore, securitySettings);
+
+ var extensionFactory = OpenIdExtensionFactoryAggregator.LoadFromConfiguration();
+
+ List<IChannelBindingElement> elements = new List<IChannelBindingElement>(8);
+ elements.Add(new ExtensionsBindingElement(extensionFactory, securitySettings, true));
+ elements.Add(new StandardReplayProtectionBindingElement(nonceStore, true));
+ elements.Add(new StandardExpirationBindingElement());
+ elements.Add(signingElement);
+
+ return elements.ToArray();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/OpenIdProviderMessageFactory.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/OpenIdProviderMessageFactory.cs
new file mode 100644
index 0000000..3fab06b
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/OpenIdProviderMessageFactory.cs
@@ -0,0 +1,86 @@
+//-----------------------------------------------------------------------
+// <copyright file="OpenIdProviderMessageFactory.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OpenId.Messages;
+
+ /// <summary>
+ /// OpenID Provider message factory.
+ /// </summary>
+ internal class OpenIdProviderMessageFactory : IMessageFactory {
+ /// <summary>
+ /// Analyzes an incoming request message payload to discover what kind of
+ /// message is embedded in it and returns the type, or null if no match is found.
+ /// </summary>
+ /// <param name="recipient">The intended or actual recipient of the request message.</param>
+ /// <param name="fields">The name/value pairs that make up the message payload.</param>
+ /// <returns>
+ /// A newly instantiated <see cref="IProtocolMessage"/>-derived object that this message can
+ /// deserialize to. Null if the request isn't recognized as a valid protocol message.
+ /// </returns>
+ public IDirectedProtocolMessage GetNewRequestMessage(MessageReceivingEndpoint recipient, IDictionary<string, string> fields) {
+ RequestBase message = null;
+
+ // Discern the OpenID version of the message.
+ Protocol protocol = Protocol.V11;
+ string ns;
+ if (fields.TryGetValue(Protocol.V20.openid.ns, out ns)) {
+ ErrorUtilities.VerifyProtocol(string.Equals(ns, Protocol.OpenId2Namespace, StringComparison.Ordinal), MessagingStrings.UnexpectedMessagePartValue, Protocol.V20.openid.ns, ns);
+ protocol = Protocol.V20;
+ }
+
+ string mode;
+ if (fields.TryGetValue(protocol.openid.mode, out mode)) {
+ if (string.Equals(mode, protocol.Args.Mode.associate)) {
+ if (fields.ContainsKey(protocol.openid.dh_consumer_public)) {
+ message = new AssociateDiffieHellmanProviderRequest(protocol.Version, recipient.Location);
+ } else {
+ message = new AssociateUnencryptedProviderRequest(protocol.Version, recipient.Location);
+ }
+ } else if (string.Equals(mode, protocol.Args.Mode.checkid_setup) ||
+ string.Equals(mode, protocol.Args.Mode.checkid_immediate)) {
+ AuthenticationRequestMode authMode = string.Equals(mode, protocol.Args.Mode.checkid_immediate) ? AuthenticationRequestMode.Immediate : AuthenticationRequestMode.Setup;
+ if (fields.ContainsKey(protocol.openid.identity)) {
+ message = new CheckIdRequest(protocol.Version, recipient.Location, authMode);
+ } else {
+ ErrorUtilities.VerifyProtocol(!fields.ContainsKey(protocol.openid.claimed_id), OpenIdStrings.IdentityAndClaimedIdentifierMustBeBothPresentOrAbsent);
+ message = new SignedResponseRequest(protocol.Version, recipient.Location, authMode);
+ }
+ } else if (string.Equals(mode, protocol.Args.Mode.check_authentication)) {
+ message = new CheckAuthenticationRequest(protocol.Version, recipient.Location);
+ } else {
+ ErrorUtilities.ThrowProtocol(MessagingStrings.UnexpectedMessagePartValue, protocol.openid.mode, mode);
+ }
+ }
+
+ if (message != null) {
+ message.SetAsIncoming();
+ }
+
+ return message;
+ }
+
+ /// <summary>
+ /// Analyzes an incoming request message payload to discover what kind of
+ /// message is embedded in it and returns the type, or null if no match is found.
+ /// </summary>
+ /// <param name="request">The message that was sent as a request that resulted in the response.</param>
+ /// <param name="fields">The name/value pairs that make up the message payload.</param>
+ /// <returns>
+ /// A newly instantiated <see cref="IProtocolMessage"/>-derived object that this message can
+ /// deserialize to. Null if the request isn't recognized as a valid protocol message.
+ /// </returns>
+ public IDirectResponseProtocolMessage GetNewResponseMessage(IDirectedProtocolMessage request, IDictionary<string, string> fields) {
+ // OpenID Providers make no outbound requests, and thus receive no direct response messages.
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/ProviderSigningBindingElement.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/ProviderSigningBindingElement.cs
new file mode 100644
index 0000000..e257e63
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/ProviderSigningBindingElement.cs
@@ -0,0 +1,251 @@
+//-----------------------------------------------------------------------
+// <copyright file="ProviderSigningBindingElement.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using System.Web;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+ using DotNetOpenAuth.Messaging.Reflection;
+ using DotNetOpenAuth.OpenId.Messages;
+ using DotNetOpenAuth.OpenId.Provider;
+
+ /// <summary>
+ /// The signing binding element for OpenID Providers.
+ /// </summary>
+ internal class ProviderSigningBindingElement : SigningBindingElement {
+ /// <summary>
+ /// The association store used by Providers to look up the secrets needed for signing.
+ /// </summary>
+ private readonly IProviderAssociationStore opAssociations;
+
+ /// <summary>
+ /// The security settings at the Provider.
+ /// Only defined when this element is instantiated to service a Provider.
+ /// </summary>
+ private readonly ProviderSecuritySettings opSecuritySettings;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ProviderSigningBindingElement"/> class.
+ /// </summary>
+ /// <param name="associationStore">The association store used to look up the secrets needed for signing.</param>
+ /// <param name="securitySettings">The security settings.</param>
+ internal ProviderSigningBindingElement(IProviderAssociationStore associationStore, ProviderSecuritySettings securitySettings) {
+ Requires.NotNull(associationStore, "associationStore");
+ Requires.NotNull(securitySettings, "securitySettings");
+
+ this.opAssociations = associationStore;
+ this.opSecuritySettings = securitySettings;
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether this binding element is on a Provider channel.
+ /// </summary>
+ protected override bool IsOnProvider {
+ get { return true; }
+ }
+
+ /// <summary>
+ /// Prepares a message for sending based on the rules of this channel binding element.
+ /// </summary>
+ /// <param name="message">The message to prepare for sending.</param>
+ /// <returns>
+ /// The protections (if any) that this binding element applied to the message.
+ /// Null if this binding element did not even apply to this binding element.
+ /// </returns>
+ public override MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) {
+ var result = base.ProcessOutgoingMessage(message);
+ if (result != null) {
+ return result;
+ }
+
+ var signedMessage = message as ITamperResistantOpenIdMessage;
+ if (signedMessage != null) {
+ Logger.Bindings.DebugFormat("Signing {0} message.", message.GetType().Name);
+ Association association = this.GetAssociation(signedMessage);
+ signedMessage.AssociationHandle = association.Handle;
+ signedMessage.SignedParameterOrder = this.GetSignedParameterOrder(signedMessage);
+ signedMessage.Signature = this.GetSignature(signedMessage, association);
+ return MessageProtections.TamperProtection;
+ }
+
+ return null;
+ }
+
+ /// <summary>
+ /// Gets the association to use to sign or verify a message.
+ /// </summary>
+ /// <param name="signedMessage">The message to sign or verify.</param>
+ /// <returns>
+ /// The association to use to sign or verify the message.
+ /// </returns>
+ protected override Association GetAssociation(ITamperResistantOpenIdMessage signedMessage) {
+ // We're on a Provider to either sign (smart/dumb) or verify a dumb signature.
+ bool signing = string.IsNullOrEmpty(signedMessage.Signature);
+
+ if (signing) {
+ // If the RP has no replay protection, coerce use of a private association
+ // instead of a shared one (if security settings indicate)
+ // to protect the authenticating user from replay attacks.
+ bool forcePrivateAssociation = this.opSecuritySettings.ProtectDownlevelReplayAttacks
+ && IsRelyingPartyVulnerableToReplays(null, (IndirectSignedResponse)signedMessage);
+
+ if (forcePrivateAssociation) {
+ if (!string.IsNullOrEmpty(signedMessage.AssociationHandle)) {
+ Logger.Signatures.Info("An OpenID 1.x authentication request with a shared association handle will be responded to with a private association in order to provide OP-side replay protection.");
+ }
+
+ return this.GetDumbAssociationForSigning();
+ } else {
+ return this.GetSpecificAssociation(signedMessage) ?? this.GetDumbAssociationForSigning();
+ }
+ } else {
+ return this.GetSpecificAssociation(signedMessage);
+ }
+ }
+
+ /// <summary>
+ /// Gets a specific association referenced in a given message's association handle.
+ /// </summary>
+ /// <param name="signedMessage">The signed message whose association handle should be used to lookup the association to return.</param>
+ /// <returns>
+ /// The referenced association; or <c>null</c> if such an association cannot be found.
+ /// </returns>
+ protected override Association GetSpecificAssociation(ITamperResistantOpenIdMessage signedMessage) {
+ Association association = null;
+
+ if (!string.IsNullOrEmpty(signedMessage.AssociationHandle)) {
+ IndirectSignedResponse indirectSignedMessage = signedMessage as IndirectSignedResponse;
+
+ // Since we have an association handle, we're either signing with a smart association,
+ // or verifying a dumb one.
+ bool signing = string.IsNullOrEmpty(signedMessage.Signature);
+ bool isPrivateAssociation = !signing;
+ association = this.opAssociations.Deserialize(signedMessage, isPrivateAssociation, signedMessage.AssociationHandle);
+ if (association == null) {
+ // There was no valid association with the requested handle.
+ // Let's tell the RP to forget about that association.
+ signedMessage.InvalidateHandle = signedMessage.AssociationHandle;
+ signedMessage.AssociationHandle = null;
+ }
+ }
+
+ return association;
+ }
+
+ /// <summary>
+ /// Gets a private Provider association used for signing messages in "dumb" mode.
+ /// </summary>
+ /// <returns>An existing or newly created association.</returns>
+ protected override Association GetDumbAssociationForSigning() {
+ // If no assoc_handle was given or it was invalid, the only thing
+ // left to do is sign a message using a 'dumb' mode association.
+ Protocol protocol = Protocol.Default;
+ Association association = HmacShaAssociationProvider.Create(protocol, protocol.Args.SignatureAlgorithm.HMAC_SHA256, AssociationRelyingPartyType.Dumb, this.opAssociations, this.opSecuritySettings);
+ return association;
+ }
+
+ /// <summary>
+ /// Verifies the signature by unrecognized handle.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <param name="signedMessage">The signed message.</param>
+ /// <param name="protectionsApplied">The protections applied.</param>
+ /// <returns>
+ /// The applied protections.
+ /// </returns>
+ protected override MessageProtections VerifySignatureByUnrecognizedHandle(IProtocolMessage message, ITamperResistantOpenIdMessage signedMessage, MessageProtections protectionsApplied) {
+ // If we're on the Provider, then the RP sent us a check_auth with a signature
+ // we don't have an association for. (It may have expired, or it may be a faulty RP).
+ throw new InvalidSignatureException(message);
+ }
+
+ /// <summary>
+ /// Determines whether the relying party sending an authentication request is
+ /// vulnerable to replay attacks.
+ /// </summary>
+ /// <param name="request">The request message from the Relying Party. Useful, but may be null for conservative estimate results.</param>
+ /// <param name="response">The response message to be signed.</param>
+ /// <returns>
+ /// <c>true</c> if the relying party is vulnerable; otherwise, <c>false</c>.
+ /// </returns>
+ private static bool IsRelyingPartyVulnerableToReplays(SignedResponseRequest request, IndirectSignedResponse response) {
+ Requires.NotNull(response, "response");
+
+ // OpenID 2.0 includes replay protection as part of the protocol.
+ if (response.Version.Major >= 2) {
+ return false;
+ }
+
+ // This library's RP may be on the remote end, and may be using 1.x merely because
+ // discovery on the Claimed Identifier suggested this was a 1.x OP.
+ // Since this library's RP has a built-in request_nonce parameter for replay
+ // protection, we'll allow for that.
+ var returnToArgs = HttpUtility.ParseQueryString(response.ReturnTo.Query);
+ if (!string.IsNullOrEmpty(returnToArgs[ReturnToNonceBindingElement.NonceParameter])) {
+ return false;
+ }
+
+ // If the OP endpoint _AND_ RP return_to URL uses HTTPS then no one
+ // can steal and replay the positive assertion.
+ // We can only ascertain this if the request message was handed to us
+ // so we know what our own OP endpoint is. If we don't have a request
+ // message, then we'll default to assuming it's insecure.
+ if (request != null) {
+ if (request.Recipient.IsTransportSecure() && response.Recipient.IsTransportSecure()) {
+ return false;
+ }
+ }
+
+ // Nothing left to protect against replays. RP is vulnerable.
+ return true;
+ }
+
+ /// <summary>
+ /// Gets the value to use for the openid.signed parameter.
+ /// </summary>
+ /// <param name="signedMessage">The signable message.</param>
+ /// <returns>
+ /// A comma-delimited list of parameter names, omitting the 'openid.' prefix, that determines
+ /// the inclusion and order of message parts that will be signed.
+ /// </returns>
+ private string GetSignedParameterOrder(ITamperResistantOpenIdMessage signedMessage) {
+ Requires.ValidState(this.Channel != null);
+ Requires.NotNull(signedMessage, "signedMessage");
+
+ Protocol protocol = Protocol.Lookup(signedMessage.Version);
+
+ MessageDescription description = this.Channel.MessageDescriptions.Get(signedMessage);
+ var signedParts = from part in description.Mapping.Values
+ where (part.RequiredProtection & System.Net.Security.ProtectionLevel.Sign) != 0
+ && part.GetValue(signedMessage) != null
+ select part.Name;
+ string prefix = Protocol.V20.openid.Prefix;
+ ErrorUtilities.VerifyInternal(signedParts.All(name => name.StartsWith(prefix, StringComparison.Ordinal)), "All signed message parts must start with 'openid.'.");
+
+ if (this.opSecuritySettings.SignOutgoingExtensions) {
+ // Tack on any ExtraData parameters that start with 'openid.'.
+ List<string> extraSignedParameters = new List<string>(signedMessage.ExtraData.Count);
+ foreach (string key in signedMessage.ExtraData.Keys) {
+ if (key.StartsWith(protocol.openid.Prefix, StringComparison.Ordinal)) {
+ extraSignedParameters.Add(key);
+ } else {
+ Logger.Signatures.DebugFormat("The extra parameter '{0}' will not be signed because it does not start with 'openid.'.", key);
+ }
+ }
+ signedParts = signedParts.Concat(extraSignedParameters);
+ }
+
+ int skipLength = prefix.Length;
+ string signedFields = string.Join(",", signedParts.Select(name => name.Substring(skipLength)).ToArray());
+ return signedFields;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateDiffieHellmanProviderRequest.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateDiffieHellmanProviderRequest.cs
new file mode 100644
index 0000000..1a3cf5d
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateDiffieHellmanProviderRequest.cs
@@ -0,0 +1,43 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssociateDiffieHellmanProviderRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// An OpenID direct request from Relying Party to Provider to initiate an association that uses Diffie-Hellman encryption.
+ /// </summary>
+ internal class AssociateDiffieHellmanProviderRequest : AssociateDiffieHellmanRequest, IAssociateRequestProvider {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AssociateDiffieHellmanProviderRequest"/> class.
+ /// </summary>
+ /// <param name="version">The OpenID version this message must comply with.</param>
+ /// <param name="providerEndpoint">The OpenID Provider endpoint.</param>
+ internal AssociateDiffieHellmanProviderRequest(Version version, Uri providerEndpoint)
+ : base(version, providerEndpoint) {
+ }
+
+ /// <summary>
+ /// Creates a Provider's response to an incoming association request.
+ /// </summary>
+ /// <returns>
+ /// The appropriate association response message.
+ /// </returns>
+ public IProtocolMessage CreateResponseCore() {
+#if !ExcludeDiffieHellman
+ var response = new AssociateDiffieHellmanProviderResponse(this.Version, this);
+ response.AssociationType = this.AssociationType;
+ return response;
+#else
+ throw new NotSupportedException();
+#endif
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/Messages/AssociateDiffieHellmanResponse.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateDiffieHellmanProviderResponse.cs
index a4fdf49..3dd1e8e 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/AssociateDiffieHellmanResponse.cs
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateDiffieHellmanProviderResponse.cs
@@ -1,5 +1,5 @@
//-----------------------------------------------------------------------
-// <copyright file="AssociateDiffieHellmanResponse.cs" company="Andrew Arnott">
+// <copyright file="AssociateDiffieHellmanProviderResponse.cs" company="Andrew Arnott">
// Copyright (c) Andrew Arnott. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
@@ -19,67 +19,59 @@ namespace DotNetOpenAuth.OpenId.Messages {
/// <remarks>
/// Association response messages are described in OpenID 2.0 section 8.2. This type covers section 8.2.3.
/// </remarks>
- internal class AssociateDiffieHellmanResponse : AssociateSuccessfulResponse {
+ internal class AssociateDiffieHellmanProviderResponse : AssociateDiffieHellmanResponse, IAssociateSuccessfulResponseProvider {
/// <summary>
- /// Initializes a new instance of the <see cref="AssociateDiffieHellmanResponse"/> class.
+ /// Initializes a new instance of the <see cref="AssociateDiffieHellmanProviderResponse"/> class.
/// </summary>
/// <param name="responseVersion">The OpenID version of the response message.</param>
/// <param name="originatingRequest">The originating request.</param>
- internal AssociateDiffieHellmanResponse(Version responseVersion, AssociateDiffieHellmanRequest originatingRequest)
+ internal AssociateDiffieHellmanProviderResponse(Version responseVersion, AssociateDiffieHellmanRequest originatingRequest)
: base(responseVersion, originatingRequest) {
}
/// <summary>
- /// Gets or sets the Provider's Diffie-Hellman public key.
+ /// Gets or sets the lifetime, in seconds, of this association. The Relying Party MUST NOT use the association after this time has passed.
/// </summary>
- /// <value>btwoc(g ^ xb mod p)</value>
- [MessagePart("dh_server_public", IsRequired = true, AllowEmpty = false)]
- internal byte[] DiffieHellmanServerPublic { get; set; }
-
- /// <summary>
- /// Gets or sets the MAC key (shared secret), encrypted with the secret Diffie-Hellman value.
- /// </summary>
- /// <value>H(btwoc(g ^ (xa * xb) mod p)) XOR MAC key. H is either "SHA1" or "SHA256" depending on the session type. </value>
- [MessagePart("enc_mac_key", IsRequired = true, AllowEmpty = false)]
- internal byte[] EncodedMacKey { get; set; }
+ /// <value>
+ /// An integer, represented in base 10 ASCII.
+ /// </value>
+ long IAssociateSuccessfulResponseProvider.ExpiresIn {
+ get { return this.ExpiresIn; }
+ set { this.ExpiresIn = value; }
+ }
/// <summary>
- /// Creates the association at relying party side after the association response has been received.
+ /// Gets or sets the association handle is used as a key to refer to this association in subsequent messages.
/// </summary>
- /// <param name="request">The original association request that was already sent and responded to.</param>
- /// <returns>The newly created association.</returns>
- /// <remarks>
- /// The resulting association is <i>not</i> added to the association store and must be done by the caller.
- /// </remarks>
- protected override Association CreateAssociationAtRelyingParty(AssociateRequest request) {
- var diffieHellmanRequest = request as AssociateDiffieHellmanRequest;
- ErrorUtilities.VerifyArgument(diffieHellmanRequest != null, OpenIdStrings.DiffieHellmanAssociationRequired);
-
- HashAlgorithm hasher = DiffieHellmanUtilities.Lookup(Protocol, this.SessionType);
- byte[] associationSecret = DiffieHellmanUtilities.SHAHashXorSecret(hasher, diffieHellmanRequest.Algorithm, this.DiffieHellmanServerPublic, this.EncodedMacKey);
-
- Association association = HmacShaAssociation.Create(Protocol, this.AssociationType, this.AssociationHandle, associationSecret, TimeSpan.FromSeconds(this.ExpiresIn));
- return association;
+ /// <value>
+ /// A string 255 characters or less in length. It MUST consist only of ASCII characters in the range 33-126 inclusive (printable non-whitespace characters).
+ /// </value>
+ string IAssociateSuccessfulResponseProvider.AssociationHandle {
+ get { return this.AssociationHandle; }
+ set { this.AssociationHandle = value; }
}
/// <summary>
/// Creates the association at the provider side after the association request has been received.
/// </summary>
/// <param name="request">The association request.</param>
+ /// <param name="associationStore">The OpenID Provider's association store or handle encoder.</param>
/// <param name="securitySettings">The security settings of the Provider.</param>
- /// <returns>The newly created association.</returns>
+ /// <returns>
+ /// The newly created association.
+ /// </returns>
/// <remarks>
/// The response message is updated to include the details of the created association by this method,
/// but the resulting association is <i>not</i> added to the association store and must be done by the caller.
/// </remarks>
- protected override Association CreateAssociationAtProvider(AssociateRequest request, ProviderSecuritySettings securitySettings) {
+ public Association CreateAssociationAtProvider(AssociateRequest request, IProviderAssociationStore associationStore, ProviderSecuritySettings securitySettings) {
var diffieHellmanRequest = request as AssociateDiffieHellmanRequest;
ErrorUtilities.VerifyInternal(diffieHellmanRequest != null, "Expected a DH request type.");
this.SessionType = this.SessionType ?? request.SessionType;
// Go ahead and create the association first, complete with its secret that we're about to share.
- Association association = HmacShaAssociation.Create(this.Protocol, this.AssociationType, AssociationRelyingPartyType.Smart, securitySettings);
+ Association association = HmacShaAssociationProvider.Create(this.Protocol, this.AssociationType, AssociationRelyingPartyType.Smart, associationStore, securitySettings);
// We now need to securely communicate the secret to the relying party using Diffie-Hellman.
// We do this by performing a DH algorithm on the secret and setting a couple of properties
diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateRequestProviderTools.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateRequestProviderTools.cs
new file mode 100644
index 0000000..e09b37e
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateRequestProviderTools.cs
@@ -0,0 +1,100 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssociateRequestProviderTools.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OpenId.Provider;
+
+ /// <summary>
+ /// OpenID Provider tools for receiving association requests.
+ /// </summary>
+ internal static class AssociateRequestProviderTools {
+ /// <summary>
+ /// Creates a Provider's response to an incoming association request.
+ /// </summary>
+ /// <param name="requestMessage">The request message.</param>
+ /// <param name="associationStore">The association store.</param>
+ /// <param name="securitySettings">The security settings on the Provider.</param>
+ /// <returns>
+ /// The appropriate association response that is ready to be sent back to the Relying Party.
+ /// </returns>
+ /// <remarks>
+ /// <para>If an association is created, it will be automatically be added to the provided
+ /// association store.</para>
+ /// <para>Successful association response messages will derive from <see cref="AssociateSuccessfulResponse"/>.
+ /// Failed association response messages will derive from <see cref="AssociateUnsuccessfulResponse"/>.</para>
+ /// </remarks>
+ internal static IProtocolMessage CreateResponse(IAssociateRequestProvider requestMessage, IProviderAssociationStore associationStore, ProviderSecuritySettings securitySettings) {
+ Requires.NotNull(requestMessage, "requestMessage");
+ Requires.NotNull(associationStore, "associationStore");
+ Requires.NotNull(securitySettings, "securitySettings");
+
+ AssociateRequest request = (AssociateRequest)requestMessage;
+ IProtocolMessage response;
+ var protocol = requestMessage.GetProtocol();
+ if (securitySettings.IsAssociationInPermittedRange(protocol, request.AssociationType) &&
+ HmacShaAssociation.IsDHSessionCompatible(protocol, request.AssociationType, request.SessionType)) {
+ response = requestMessage.CreateResponseCore();
+
+ // Create and store the association if this is a successful response.
+ var successResponse = response as IAssociateSuccessfulResponseProvider;
+ if (successResponse != null) {
+ OpenIdProviderUtilities.CreateAssociation(request, successResponse, associationStore, securitySettings);
+ }
+ } else {
+ response = CreateUnsuccessfulResponse(requestMessage, securitySettings);
+ }
+
+ return response;
+ }
+
+ /// <summary>
+ /// Creates a response that notifies the Relying Party that the requested
+ /// association type is not supported by this Provider, and offers
+ /// an alternative association type, if possible.
+ /// </summary>
+ /// <param name="requestMessage">The request message.</param>
+ /// <param name="securitySettings">The security settings that apply to this Provider.</param>
+ /// <returns>
+ /// The response to send to the Relying Party.
+ /// </returns>
+ private static AssociateUnsuccessfulResponse CreateUnsuccessfulResponse(IAssociateRequestProvider requestMessage, ProviderSecuritySettings securitySettings) {
+ Requires.NotNull(requestMessage, "requestMessage");
+ Requires.NotNull(securitySettings, "securitySettings");
+
+ var unsuccessfulResponse = new AssociateUnsuccessfulResponse(requestMessage.Version, (AssociateRequest)requestMessage);
+
+ // The strategy here is to suggest that the RP try again with the lowest
+ // permissible security settings, giving the RP the best chance of being
+ // able to match with a compatible request.
+ bool unencryptedAllowed = requestMessage.Recipient.IsTransportSecure();
+ bool useDiffieHellman = !unencryptedAllowed;
+ var request = (AssociateRequest)requestMessage;
+ var protocol = requestMessage.GetProtocol();
+ string associationType, sessionType;
+ if (HmacShaAssociation.TryFindBestAssociation(protocol, false, securitySettings, useDiffieHellman, out associationType, out sessionType)) {
+ ErrorUtilities.VerifyInternal(request.AssociationType != associationType, "The RP asked for an association that should have been allowed, but the OP is trying to suggest the same one as an alternative!");
+ unsuccessfulResponse.AssociationType = associationType;
+ unsuccessfulResponse.SessionType = sessionType;
+ Logger.OpenId.InfoFormat(
+ "Association requested of type '{0}' and session '{1}', which the Provider does not support. Sending back suggested alternative of '{0}' with session '{1}'.",
+ request.AssociationType,
+ request.SessionType,
+ unsuccessfulResponse.AssociationType,
+ unsuccessfulResponse.SessionType);
+ } else {
+ Logger.OpenId.InfoFormat("Association requested of type '{0}' and session '{1}', which the Provider does not support. No alternative association type qualified for suggesting back to the Relying Party.", request.AssociationType, request.SessionType);
+ }
+
+ return unsuccessfulResponse;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateSuccessfulResponseProvider.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateSuccessfulResponseProvider.cs
new file mode 100644
index 0000000..d057b9c
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateSuccessfulResponseProvider.cs
@@ -0,0 +1,55 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssociateSuccessfulResponseProvider.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OpenId.Provider;
+
+ /// <summary>
+ /// An outgoing successful association response from the OpenID Provider.
+ /// </summary>
+ [ContractClass(typeof(IAssociateSuccessfulResponseProviderContract))]
+ internal interface IAssociateSuccessfulResponseProvider : IProtocolMessage {
+ /// <summary>
+ /// Gets or sets the expires in.
+ /// </summary>
+ /// <value>
+ /// The expires in.
+ /// </value>
+ long ExpiresIn { get; set; }
+
+ /// <summary>
+ /// Gets or sets the association handle.
+ /// </summary>
+ /// <value>
+ /// The association handle.
+ /// </value>
+ string AssociationHandle { get; set; }
+
+ /// <summary>
+ /// Called to create the Association based on a request previously given by the Relying Party.
+ /// </summary>
+ /// <param name="request">The prior request for an association.</param>
+ /// <param name="associationStore">The Provider's association store.</param>
+ /// <param name="securitySettings">The security settings of the Provider.</param>
+ /// <returns>
+ /// The created association.
+ /// </returns>
+ /// <remarks>
+ /// <para>The caller will update this message's <see cref="AssociateSuccessfulResponse.ExpiresIn"/> and <see cref="AssociateSuccessfulResponse.AssociationHandle"/>
+ /// properties based on the <see cref="Association"/> returned by this method, but any other
+ /// association type specific properties must be set by this method.</para>
+ /// <para>The response message is updated to include the details of the created association by this method,
+ /// but the resulting association is <i>not</i> added to the association store and must be done by the caller.</para>
+ /// </remarks>
+ Association CreateAssociationAtProvider(AssociateRequest request, IProviderAssociationStore associationStore, ProviderSecuritySettings securitySettings);
+ }
+}
diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateSuccessfulResponseProviderContract.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateSuccessfulResponseProviderContract.cs
new file mode 100644
index 0000000..af60d5e
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateSuccessfulResponseProviderContract.cs
@@ -0,0 +1,96 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssociateSuccessfulResponseProviderContract.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OpenId.Provider;
+
+ /// <summary>
+ /// Code contract for the <see cref="IAssociateSuccessfulResponseProvider"/> interface.
+ /// </summary>
+ [ContractClassFor(typeof(IAssociateSuccessfulResponseProvider))]
+ internal abstract class IAssociateSuccessfulResponseProviderContract : IAssociateSuccessfulResponseProvider {
+ /// <summary>
+ /// Gets or sets the expires in.
+ /// </summary>
+ /// <value>
+ /// The expires in.
+ /// </value>
+ long IAssociateSuccessfulResponseProvider.ExpiresIn {
+ get { throw new NotImplementedException(); }
+ set { throw new NotImplementedException(); }
+ }
+
+ /// <summary>
+ /// Gets or sets the association handle.
+ /// </summary>
+ /// <value>
+ /// The association handle.
+ /// </value>
+ string IAssociateSuccessfulResponseProvider.AssociationHandle {
+ get { throw new NotImplementedException(); }
+ set { throw new NotImplementedException(); }
+ }
+
+ /// <summary>
+ /// Gets the level of protection this message requires.
+ /// </summary>
+ Messaging.MessageProtections Messaging.IProtocolMessage.RequiredProtection {
+ get { throw new NotImplementedException(); }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether this is a direct or indirect message.
+ /// </summary>
+ Messaging.MessageTransport Messaging.IProtocolMessage.Transport {
+ get { throw new NotImplementedException(); }
+ }
+
+ /// <summary>
+ /// Gets the version of the protocol or extension this message is prepared to implement.
+ /// </summary>
+ Version Messaging.IMessage.Version {
+ get { throw new NotImplementedException(); }
+ }
+
+ /// <summary>
+ /// Gets the extra, non-standard Protocol parameters included in the message.
+ /// </summary>
+ IDictionary<string, string> Messaging.IMessage.ExtraData {
+ get { throw new NotImplementedException(); }
+ }
+
+ /// <summary>
+ /// Called to create the Association based on a request previously given by the Relying Party.
+ /// </summary>
+ /// <param name="request">The prior request for an association.</param>
+ /// <param name="associationStore">The Provider's association store.</param>
+ /// <param name="securitySettings">The security settings of the Provider.</param>
+ /// <returns>
+ /// The created association.
+ /// </returns>
+ Association IAssociateSuccessfulResponseProvider.CreateAssociationAtProvider(AssociateRequest request, IProviderAssociationStore associationStore, ProviderSecuritySettings securitySettings) {
+ Requires.NotNull(request, "request");
+ Requires.NotNull(associationStore, "associationStore");
+ Requires.NotNull(securitySettings, "securitySettings");
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Checks the message state for conformity to the protocol specification
+ /// and throws an exception if the message is invalid.
+ /// </summary>
+ /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception>
+ void Messaging.IMessage.EnsureValidMessage() {
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateUnencryptedResponseProvider.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateUnencryptedResponseProvider.cs
new file mode 100644
index 0000000..1466fe2
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateUnencryptedResponseProvider.cs
@@ -0,0 +1,73 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssociateUnencryptedResponseProvider.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.OpenId.Provider;
+
+ /// <summary>
+ /// An unencrypted association response as it is sent by the Provider.
+ /// </summary>
+ internal class AssociateUnencryptedResponseProvider : AssociateUnencryptedResponse, IAssociateSuccessfulResponseProvider {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AssociateUnencryptedResponseProvider"/> class.
+ /// </summary>
+ /// <param name="version">The version.</param>
+ /// <param name="request">The request.</param>
+ internal AssociateUnencryptedResponseProvider(Version version, AssociateUnencryptedRequest request)
+ : base(version, request) {
+ }
+
+ /// <summary>
+ /// Gets or sets the lifetime, in seconds, of this association. The Relying Party MUST NOT use the association after this time has passed.
+ /// </summary>
+ /// <value>
+ /// An integer, represented in base 10 ASCII.
+ /// </value>
+ long IAssociateSuccessfulResponseProvider.ExpiresIn {
+ get { return this.ExpiresIn; }
+ set { this.ExpiresIn = value; }
+ }
+
+ /// <summary>
+ /// Gets or sets the association handle is used as a key to refer to this association in subsequent messages.
+ /// </summary>
+ /// <value>
+ /// A string 255 characters or less in length. It MUST consist only of ASCII characters in the range 33-126 inclusive (printable non-whitespace characters).
+ /// </value>
+ string IAssociateSuccessfulResponseProvider.AssociationHandle {
+ get { return this.AssociationHandle; }
+ set { this.AssociationHandle = value; }
+ }
+
+ /// <summary>
+ /// Called to create the Association based on a request previously given by the Relying Party.
+ /// </summary>
+ /// <param name="request">The prior request for an association.</param>
+ /// <param name="associationStore">The Provider's association store.</param>
+ /// <param name="securitySettings">The security settings of the Provider.</param>
+ /// <returns>
+ /// The created association.
+ /// </returns>
+ /// <remarks>
+ /// <para>The caller will update this message's
+ /// <see cref="AssociateSuccessfulResponse.ExpiresIn"/> and
+ /// <see cref="AssociateSuccessfulResponse.AssociationHandle"/>
+ /// properties based on the <see cref="Association"/> returned by this method, but any other
+ /// association type specific properties must be set by this method.</para>
+ /// <para>The response message is updated to include the details of the created association by this method,
+ /// but the resulting association is <i>not</i> added to the association store and must be done by the caller.</para>
+ /// </remarks>
+ public Association CreateAssociationAtProvider(AssociateRequest request, IProviderAssociationStore associationStore, ProviderSecuritySettings securitySettings) {
+ Association association = HmacShaAssociationProvider.Create(Protocol, this.AssociationType, AssociationRelyingPartyType.Smart, associationStore, securitySettings);
+ this.MacKey = association.SecretKey;
+ return association;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/CheckAuthenticationResponseProvider.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/CheckAuthenticationResponseProvider.cs
new file mode 100644
index 0000000..1e417e6
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/CheckAuthenticationResponseProvider.cs
@@ -0,0 +1,42 @@
+//-----------------------------------------------------------------------
+// <copyright file="CheckAuthenticationResponseProvider.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.OpenId.ChannelElements;
+ using DotNetOpenAuth.OpenId.Provider;
+
+ /// <summary>
+ /// The check_auth response message, as it is seen by the OpenID Provider.
+ /// </summary>
+ internal class CheckAuthenticationResponseProvider : CheckAuthenticationResponse {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CheckAuthenticationResponseProvider"/> class.
+ /// </summary>
+ /// <param name="request">The request that this message is responding to.</param>
+ /// <param name="provider">The OpenID Provider that is preparing to send this response.</param>
+ internal CheckAuthenticationResponseProvider(CheckAuthenticationRequest request, OpenIdProvider provider)
+ : base(request.Version, request) {
+ Requires.NotNull(provider, "provider");
+
+ // The channel's binding elements have already set the request's IsValid property
+ // appropriately. We just copy it into the response message.
+ this.IsValid = request.IsValid;
+
+ // Confirm the RP should invalidate the association handle only if the association
+ // is not valid (any longer). OpenID 2.0 section 11.4.2.2.
+ IndirectSignedResponse signedResponse = new IndirectSignedResponse(request, provider.Channel);
+ string invalidateHandle = ((ITamperResistantOpenIdMessage)signedResponse).InvalidateHandle;
+ if (!string.IsNullOrEmpty(invalidateHandle) && !provider.AssociationStore.IsValid(signedResponse, false, invalidateHandle)) {
+ this.InvalidateHandle = invalidateHandle;
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/IAssociateRequestProvider.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/IAssociateRequestProvider.cs
new file mode 100644
index 0000000..539a18e
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/IAssociateRequestProvider.cs
@@ -0,0 +1,29 @@
+//-----------------------------------------------------------------------
+// <copyright file="IAssociateRequestProvider.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Messages {
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// The openid.mode=associate message as it is received at the OpenID Provider.
+ /// </summary>
+ internal interface IAssociateRequestProvider : IDirectedProtocolMessage {
+ /// <summary>
+ /// Creates a Provider's response to an incoming association request.
+ /// </summary>
+ /// <returns>
+ /// The appropriate association response message.
+ /// </returns>
+ /// <remarks>
+ /// <para>If an association can be successfully created, the
+ /// AssociateSuccessfulResponse.CreateAssociation method must not be
+ /// called by this method.</para>
+ /// <para>Successful association response messages will derive from <see cref="AssociateSuccessfulResponse"/>.
+ /// Failed association response messages will derive from <see cref="AssociateUnsuccessfulResponse"/>.</para>
+ /// </remarks>
+ IProtocolMessage CreateResponseCore();
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/Provider/AnonymousRequest.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AnonymousRequest.cs
index c5e6bba..581d39e 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/AnonymousRequest.cs
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AnonymousRequest.cs
@@ -30,8 +30,8 @@ namespace DotNetOpenAuth.OpenId.Provider {
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Diagnostics.Contracts.__ContractsRuntime.Requires<System.ArgumentException>(System.Boolean,System.String,System.String)", Justification = "Code contracts"), SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "AuthenticationRequest", Justification = "Type name"), SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "Code contracts require it.")]
internal AnonymousRequest(OpenIdProvider provider, SignedResponseRequest request)
: base(provider, request) {
- Contract.Requires<ArgumentNullException>(provider != null);
- Contract.Requires<ArgumentException>(!(request is CheckIdRequest), "Instantiate AuthenticationRequest to handle this kind of message.");
+ Requires.NotNull(provider, "provider");
+ Requires.True(!(request is CheckIdRequest), "request");
this.positiveResponse = new IndirectSignedResponse(request);
}
diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AssociationDataBag.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AssociationDataBag.cs
new file mode 100644
index 0000000..bf3d909
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AssociationDataBag.cs
@@ -0,0 +1,95 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssociationDataBag.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Provider {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.IO;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+
+ /// <summary>
+ /// A signed and encrypted serialization of an association.
+ /// </summary>
+ internal class AssociationDataBag : DataBag, IStreamSerializingDataBag {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AssociationDataBag"/> class.
+ /// </summary>
+ public AssociationDataBag() {
+ }
+
+ /// <summary>
+ /// Gets or sets the association secret.
+ /// </summary>
+ [MessagePart(IsRequired = true)]
+ internal byte[] Secret { get; set; }
+
+ /// <summary>
+ /// Gets or sets the UTC time that this association expires.
+ /// </summary>
+ [MessagePart(IsRequired = true)]
+ internal DateTime ExpiresUtc { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this instance is for "dumb" mode RPs.
+ /// </summary>
+ /// <value>
+ /// <c>true</c> if this instance is private association; otherwise, <c>false</c>.
+ /// </value>
+ [MessagePart(IsRequired = true)]
+ internal bool IsPrivateAssociation {
+ get { return this.AssociationType == AssociationRelyingPartyType.Dumb; }
+ set { this.AssociationType = value ? AssociationRelyingPartyType.Dumb : AssociationRelyingPartyType.Smart; }
+ }
+
+ /// <summary>
+ /// Gets or sets the type of the association (shared or private, a.k.a. smart or dumb).
+ /// </summary>
+ internal AssociationRelyingPartyType AssociationType { get; set; }
+
+ /// <summary>
+ /// Serializes the instance to the specified stream.
+ /// </summary>
+ /// <param name="stream">The stream.</param>
+ public void Serialize(Stream stream) {
+ var writer = new BinaryWriter(stream);
+ writer.Write(this.IsPrivateAssociation);
+ writer.WriteBuffer(this.Secret);
+ writer.Write((int)(this.ExpiresUtc - TimestampEncoder.Epoch).TotalSeconds);
+ writer.Flush();
+ }
+
+ /// <summary>
+ /// Initializes the fields on this instance from the specified stream.
+ /// </summary>
+ /// <param name="stream">The stream.</param>
+ public void Deserialize(Stream stream) {
+ var reader = new BinaryReader(stream);
+ this.IsPrivateAssociation = reader.ReadBoolean();
+ this.Secret = reader.ReadBuffer();
+ this.ExpiresUtc = TimestampEncoder.Epoch + TimeSpan.FromSeconds(reader.ReadInt32());
+ }
+
+ /// <summary>
+ /// Creates the formatter used for serialization of this type.
+ /// </summary>
+ /// <param name="cryptoKeyStore">The crypto key store used when signing or encrypting.</param>
+ /// <param name="bucket">The bucket in which symmetric keys are stored for signing/encrypting data.</param>
+ /// <param name="minimumAge">The minimum age.</param>
+ /// <returns>
+ /// A formatter for serialization.
+ /// </returns>
+ internal static IDataBagFormatter<AssociationDataBag> CreateFormatter(ICryptoKeyStore cryptoKeyStore, string bucket, TimeSpan? minimumAge = null) {
+ Requires.NotNull(cryptoKeyStore, "cryptoKeyStore");
+ Requires.NotNullOrEmpty(bucket, "bucket");
+ Contract.Ensures(Contract.Result<IDataBagFormatter<AssociationDataBag>>() != null);
+ return new BinaryDataBagFormatter<AssociationDataBag>(cryptoKeyStore, bucket, signed: true, encrypted: true, minimumAge: minimumAge);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AssociationRelyingPartyType.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AssociationRelyingPartyType.cs
new file mode 100644
index 0000000..4d121b1
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AssociationRelyingPartyType.cs
@@ -0,0 +1,26 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssociationRelyingPartyType.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Provider {
+ /// <summary>
+ /// An enumeration that can specify how a given <see cref="Association"/> is used.
+ /// </summary>
+ public enum AssociationRelyingPartyType {
+ /// <summary>
+ /// The <see cref="Association"/> manages a shared secret between
+ /// Provider and Relying Party sites that allows the RP to verify
+ /// the signature on a message from an OP.
+ /// </summary>
+ Smart,
+
+ /// <summary>
+ /// The <see cref="Association"/> manages a secret known alone by
+ /// a Provider that allows the Provider to verify its own signatures
+ /// for "dumb" (stateless) relying parties.
+ /// </summary>
+ Dumb
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/Provider/AuthenticationRequest.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AuthenticationRequest.cs
index d22f858..09b1073 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/AuthenticationRequest.cs
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AuthenticationRequest.cs
@@ -29,7 +29,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// <param name="request">The incoming authentication request message.</param>
internal AuthenticationRequest(OpenIdProvider provider, CheckIdRequest request)
: base(provider, request) {
- Contract.Requires<ArgumentNullException>(provider != null);
+ Requires.NotNull(provider, "provider");
this.positiveResponse = new PositiveAssertionResponse(request);
@@ -216,7 +216,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// </summary>
/// <param name="identifier">The value to set to the <see cref="ClaimedIdentifier"/> and <see cref="LocalIdentifier"/> properties.</param>
internal void ResetClaimedAndLocalIdentifiers(Identifier identifier) {
- Contract.Requires<ArgumentNullException>(identifier != null);
+ Requires.NotNull(identifier, "identifier");
this.positiveResponse.ClaimedIdentifier = identifier;
this.positiveResponse.LocalIdentifier = identifier;
diff --git a/src/DotNetOpenAuth/OpenId/Provider/AutoResponsiveRequest.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AutoResponsiveRequest.cs
index 41e082b..0d98e67 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/AutoResponsiveRequest.cs
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AutoResponsiveRequest.cs
@@ -32,7 +32,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// <param name="securitySettings">The security settings.</param>
internal AutoResponsiveRequest(IDirectedProtocolMessage request, IProtocolMessage response, ProviderSecuritySettings securitySettings)
: base(request, securitySettings) {
- Contract.Requires<ArgumentNullException>(response != null);
+ Requires.NotNull(response, "response");
this.response = response;
}
@@ -45,7 +45,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// <param name="securitySettings">The security settings.</param>
internal AutoResponsiveRequest(IProtocolMessage response, ProviderSecuritySettings securitySettings)
: base(IndirectResponseBase.GetVersion(response), securitySettings) {
- Contract.Requires<ArgumentNullException>(response != null);
+ Requires.NotNull(response, "response");
this.response = response;
}
diff --git a/src/DotNetOpenAuth/OpenId/Behaviors/AXFetchAsSregTransform.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Behaviors/AXFetchAsSregTransform.cs
index 01b74a1..3a72c5e 100644
--- a/src/DotNetOpenAuth/OpenId/Behaviors/AXFetchAsSregTransform.cs
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Behaviors/AXFetchAsSregTransform.cs
@@ -4,17 +4,19 @@
// </copyright>
//-----------------------------------------------------------------------
-namespace DotNetOpenAuth.OpenId.Behaviors {
+namespace DotNetOpenAuth.OpenId.Provider.Behaviors {
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OpenId.Behaviors;
using DotNetOpenAuth.OpenId.Extensions;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using DotNetOpenAuth.OpenId.Provider;
+ using DotNetOpenAuth.OpenId.Provider.Extensions;
using DotNetOpenAuth.OpenId.RelyingParty;
/// <summary>
@@ -23,67 +25,13 @@ namespace DotNetOpenAuth.OpenId.Behaviors {
/// to the originally requested extension and format.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sreg", Justification = "Abbreviation")]
- public sealed class AXFetchAsSregTransform : IRelyingPartyBehavior, IProviderBehavior {
- /// <summary>
- /// Initializes static members of the <see cref="AXFetchAsSregTransform"/> class.
- /// </summary>
- static AXFetchAsSregTransform() {
- AXFormats = AXAttributeFormats.Common;
- }
-
+ public sealed class AXFetchAsSregTransform : AXFetchAsSregTransformBase, IProviderBehavior {
/// <summary>
/// Initializes a new instance of the <see cref="AXFetchAsSregTransform"/> class.
/// </summary>
public AXFetchAsSregTransform() {
}
- /// <summary>
- /// Gets or sets the AX attribute type URI formats this transform is willing to work with.
- /// </summary>
- public static AXAttributeFormats AXFormats { get; set; }
-
- #region IRelyingPartyBehavior Members
-
- /// <summary>
- /// Applies a well known set of security requirements to a default set of security settings.
- /// </summary>
- /// <param name="securitySettings">The security settings to enhance with the requirements of this profile.</param>
- /// <remarks>
- /// Care should be taken to never decrease security when applying a profile.
- /// Profiles should only enhance security requirements to avoid being
- /// incompatible with each other.
- /// </remarks>
- void IRelyingPartyBehavior.ApplySecuritySettings(RelyingPartySecuritySettings securitySettings) {
- }
-
- /// <summary>
- /// Called when an authentication request is about to be sent.
- /// </summary>
- /// <param name="request">The request.</param>
- /// <remarks>
- /// Implementations should be prepared to be called multiple times on the same outgoing message
- /// without malfunctioning.
- /// </remarks>
- void IRelyingPartyBehavior.OnOutgoingAuthenticationRequest(RelyingParty.IAuthenticationRequest request) {
- // Don't create AX extensions for OpenID 1.x messages, since AX requires OpenID 2.0.
- if (request.Provider.Version.Major >= 2) {
- request.SpreadSregToAX(AXFormats);
- }
- }
-
- /// <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);
- }
- }
-
- #endregion
-
#region IProviderBehavior Members
/// <summary>
diff --git a/src/DotNetOpenAuth/OpenId/Behaviors/GsaIcamProfile.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Behaviors/GsaIcamProfile.cs
index 20c207f..38f2ae7 100644
--- a/src/DotNetOpenAuth/OpenId/Behaviors/GsaIcamProfile.cs
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Behaviors/GsaIcamProfile.cs
@@ -4,12 +4,14 @@
// </copyright>
//-----------------------------------------------------------------------
-namespace DotNetOpenAuth.OpenId.Behaviors {
+namespace DotNetOpenAuth.OpenId.Provider.Behaviors {
using System;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
+ using DotNetOpenAuth.Configuration;
using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OpenId.Behaviors;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
using DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
@@ -27,7 +29,7 @@ namespace DotNetOpenAuth.OpenId.Behaviors {
/// </remarks>
[Serializable]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Icam", Justification = "Acronym")]
- public sealed class GsaIcamProfile : IRelyingPartyBehavior, IProviderBehavior {
+ public sealed class GsaIcamProfile : GsaIcamProfileBase, IProviderBehavior {
/// <summary>
/// The maximum time a shared association can live.
/// </summary>
@@ -48,100 +50,6 @@ namespace DotNetOpenAuth.OpenId.Behaviors {
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ppid", Justification = "Acronym")]
public static IDirectedIdentityIdentifierProvider PpidIdentifierProvider { get; set; }
- /// <summary>
- /// Gets or sets a value indicating whether PII is allowed to be requested or received via OpenID.
- /// </summary>
- /// <value>The default value is <c>false</c>.</value>
- public static bool AllowPersonallyIdentifiableInformation { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether to ignore the SSL requirement (for testing purposes only).
- /// </summary>
- public static bool DisableSslRequirement { get; set; }
-
- #region IRelyingPartyBehavior Members
-
- /// <summary>
- /// Applies a well known set of security requirements.
- /// </summary>
- /// <param name="securitySettings">The security settings to enhance with the requirements of this profile.</param>
- /// <remarks>
- /// Care should be taken to never decrease security when applying a profile.
- /// Profiles should only enhance security requirements to avoid being
- /// incompatible with each other.
- /// </remarks>
- void IRelyingPartyBehavior.ApplySecuritySettings(RelyingPartySecuritySettings securitySettings) {
- if (securitySettings.MaximumHashBitLength < 256) {
- securitySettings.MaximumHashBitLength = 256;
- }
-
- securitySettings.RequireSsl = !DisableSslRequirement;
- securitySettings.RequireDirectedIdentity = true;
- securitySettings.RequireAssociation = true;
- securitySettings.RejectDelegatingIdentifiers = true;
- securitySettings.IgnoreUnsignedExtensions = true;
- securitySettings.MinimumRequiredOpenIdVersion = ProtocolVersion.V20;
- }
-
- /// <summary>
- /// Called when an authentication request is about to be sent.
- /// </summary>
- /// <param name="request">The request.</param>
- void IRelyingPartyBehavior.OnOutgoingAuthenticationRequest(RelyingParty.IAuthenticationRequest request) {
- RelyingParty.AuthenticationRequest requestInternal = (RelyingParty.AuthenticationRequest)request;
- ErrorUtilities.VerifyProtocol(string.Equals(request.Realm.Scheme, Uri.UriSchemeHttps, StringComparison.Ordinal) || DisableSslRequirement, BehaviorStrings.RealmMustBeHttps);
-
- var pape = requestInternal.AppliedExtensions.OfType<PolicyRequest>().SingleOrDefault();
- if (pape == null) {
- request.AddExtension(pape = new PolicyRequest());
- }
-
- if (!pape.PreferredPolicies.Contains(AuthenticationPolicies.PrivatePersonalIdentifier)) {
- pape.PreferredPolicies.Add(AuthenticationPolicies.PrivatePersonalIdentifier);
- }
-
- if (!pape.PreferredPolicies.Contains(AuthenticationPolicies.USGovernmentTrustLevel1)) {
- pape.PreferredPolicies.Add(AuthenticationPolicies.USGovernmentTrustLevel1);
- }
-
- if (!AllowPersonallyIdentifiableInformation && !pape.PreferredPolicies.Contains(AuthenticationPolicies.NoPersonallyIdentifiableInformation)) {
- pape.PreferredPolicies.Add(AuthenticationPolicies.NoPersonallyIdentifiableInformation);
- }
-
- if (pape.PreferredPolicies.Contains(AuthenticationPolicies.NoPersonallyIdentifiableInformation)) {
- ErrorUtilities.VerifyProtocol(
- (!requestInternal.AppliedExtensions.OfType<ClaimsRequest>().Any() &&
- !requestInternal.AppliedExtensions.OfType<FetchRequest>().Any()),
- BehaviorStrings.PiiIncludedWithNoPiiPolicy);
- }
-
- Reporting.RecordEventOccurrence(this, "RP");
- }
-
- /// <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);
- }
- }
-
- #endregion
-
#region IProviderBehavior Members
/// <summary>
diff --git a/src/DotNetOpenAuth/OpenId/Behaviors/PpidGeneration.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Behaviors/PpidGeneration.cs
index a465611..1a6898e 100644
--- a/src/DotNetOpenAuth/OpenId/Behaviors/PpidGeneration.cs
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Behaviors/PpidGeneration.cs
@@ -4,12 +4,13 @@
// </copyright>
//-----------------------------------------------------------------------
-namespace DotNetOpenAuth.OpenId.Behaviors {
+namespace DotNetOpenAuth.OpenId.Provider.Behaviors {
using System;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OpenId.Behaviors;
using DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy;
using DotNetOpenAuth.OpenId.Provider;
diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Extensions/ExtensionsInteropHelper.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Extensions/ExtensionsInteropHelper.cs
new file mode 100644
index 0000000..eda768b
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Extensions/ExtensionsInteropHelper.cs
@@ -0,0 +1,162 @@
+//-----------------------------------------------------------------------
+// <copyright file="ExtensionsInteropHelper.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Provider.Extensions {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OpenId.Extensions;
+ using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
+ using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
+ using DotNetOpenAuth.OpenId.Messages;
+
+ /// <summary>
+ /// A set of methods designed to assist in improving interop across different
+ /// OpenID implementations and their extensions.
+ /// </summary>
+ internal static class ExtensionsInteropHelper {
+ /// <summary>
+ /// Transforms an AX attribute type URI from the axschema.org format into a given format.
+ /// </summary>
+ /// <param name="axSchemaOrgFormatTypeUri">The ax schema org format type URI.</param>
+ /// <param name="targetFormat">The target format. Only one flag should be set.</param>
+ /// <returns>The AX attribute type URI in the target format.</returns>
+ internal static string TransformAXFormatTestHook(string axSchemaOrgFormatTypeUri, AXAttributeFormats targetFormat) {
+ return OpenIdExtensionsInteropHelper.TransformAXFormat(axSchemaOrgFormatTypeUri, targetFormat);
+ }
+
+ /// <summary>
+ /// Looks for Simple Registration and Attribute Exchange (all known formats)
+ /// request extensions and returns them as a Simple Registration extension,
+ /// and adds the new extension to the original request message if it was absent.
+ /// </summary>
+ /// <param name="request">The authentication request.</param>
+ /// <returns>
+ /// The Simple Registration request if found,
+ /// or a fabricated one based on the Attribute Exchange extension if found,
+ /// or <c>null</c> if no attribute extension request is found.</returns>
+ internal static ClaimsRequest UnifyExtensionsAsSreg(this Provider.IHostProcessedRequest request) {
+ Requires.NotNull(request, "request");
+
+ var req = (Provider.HostProcessedRequest)request;
+ var sreg = req.GetExtension<ClaimsRequest>();
+ if (sreg != null) {
+ return sreg;
+ }
+
+ var ax = req.GetExtension<FetchRequest>();
+ if (ax != null) {
+ sreg = new ClaimsRequest(DotNetOpenAuth.OpenId.Extensions.SimpleRegistration.Constants.sreg_ns);
+ sreg.Synthesized = true;
+ ((IProtocolMessageWithExtensions)req.RequestMessage).Extensions.Add(sreg);
+ sreg.BirthDate = GetDemandLevelFor(ax, WellKnownAttributes.BirthDate.WholeBirthDate);
+ sreg.Country = GetDemandLevelFor(ax, WellKnownAttributes.Contact.HomeAddress.Country);
+ sreg.Email = GetDemandLevelFor(ax, WellKnownAttributes.Contact.Email);
+ sreg.FullName = GetDemandLevelFor(ax, WellKnownAttributes.Name.FullName);
+ sreg.Gender = GetDemandLevelFor(ax, WellKnownAttributes.Person.Gender);
+ sreg.Language = GetDemandLevelFor(ax, WellKnownAttributes.Preferences.Language);
+ sreg.Nickname = GetDemandLevelFor(ax, WellKnownAttributes.Name.Alias);
+ sreg.PostalCode = GetDemandLevelFor(ax, WellKnownAttributes.Contact.HomeAddress.PostalCode);
+ sreg.TimeZone = GetDemandLevelFor(ax, WellKnownAttributes.Preferences.TimeZone);
+ }
+
+ return sreg;
+ }
+
+ /// <summary>
+ /// Converts the Simple Registration extension response to whatever format the original
+ /// attribute request extension came in.
+ /// </summary>
+ /// <param name="request">The authentication request with the response extensions already added.</param>
+ /// <remarks>
+ /// If the original attribute request came in as AX, the Simple Registration extension is converted
+ /// to an AX response and then the Simple Registration extension is removed from the response.
+ /// </remarks>
+ internal static void ConvertSregToMatchRequest(this Provider.IHostProcessedRequest request) {
+ var req = (Provider.HostProcessedRequest)request;
+ var response = req.Response as IProtocolMessageWithExtensions; // negative responses don't support extensions.
+ var sregRequest = request.GetExtension<ClaimsRequest>();
+ if (sregRequest != null && response != null) {
+ if (sregRequest.Synthesized) {
+ var axRequest = request.GetExtension<FetchRequest>();
+ ErrorUtilities.VerifyInternal(axRequest != null, "How do we have a synthesized Sreg request without an AX request?");
+
+ var sregResponse = response.Extensions.OfType<ClaimsResponse>().SingleOrDefault();
+ if (sregResponse == null) {
+ // No Sreg response to copy from.
+ return;
+ }
+
+ // Remove the sreg response since the RP didn't ask for it.
+ response.Extensions.Remove(sregResponse);
+
+ AXAttributeFormats format = OpenIdExtensionsInteropHelper.DetectAXFormat(axRequest.Attributes.Select(att => att.TypeUri));
+ if (format == AXAttributeFormats.None) {
+ // No recognized AX attributes were requested.
+ return;
+ }
+
+ var axResponse = response.Extensions.OfType<FetchResponse>().SingleOrDefault();
+ if (axResponse == null) {
+ axResponse = new FetchResponse();
+ response.Extensions.Add(axResponse);
+ }
+
+ AddAXAttributeValue(axResponse, WellKnownAttributes.BirthDate.WholeBirthDate, format, sregResponse.BirthDateRaw);
+ AddAXAttributeValue(axResponse, WellKnownAttributes.Contact.HomeAddress.Country, format, sregResponse.Country);
+ AddAXAttributeValue(axResponse, WellKnownAttributes.Contact.HomeAddress.PostalCode, format, sregResponse.PostalCode);
+ AddAXAttributeValue(axResponse, WellKnownAttributes.Contact.Email, format, sregResponse.Email);
+ AddAXAttributeValue(axResponse, WellKnownAttributes.Name.FullName, format, sregResponse.FullName);
+ AddAXAttributeValue(axResponse, WellKnownAttributes.Name.Alias, format, sregResponse.Nickname);
+ AddAXAttributeValue(axResponse, WellKnownAttributes.Preferences.TimeZone, format, sregResponse.TimeZone);
+ AddAXAttributeValue(axResponse, WellKnownAttributes.Preferences.Language, format, sregResponse.Language);
+ if (sregResponse.Gender.HasValue) {
+ AddAXAttributeValue(axResponse, WellKnownAttributes.Person.Gender, format, OpenIdExtensionsInteropHelper.GenderEncoder.Encode(sregResponse.Gender));
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// Adds the AX attribute value to the response if it is non-empty.
+ /// </summary>
+ /// <param name="ax">The AX Fetch response to add the attribute value to.</param>
+ /// <param name="typeUri">The attribute type URI in axschema.org format.</param>
+ /// <param name="format">The target format of the actual attribute to write out.</param>
+ /// <param name="value">The value of the attribute.</param>
+ private static void AddAXAttributeValue(FetchResponse ax, string typeUri, AXAttributeFormats format, string value) {
+ if (!string.IsNullOrEmpty(value)) {
+ string targetTypeUri = OpenIdExtensionsInteropHelper.TransformAXFormat(typeUri, format);
+ if (!ax.Attributes.Contains(targetTypeUri)) {
+ ax.Attributes.Add(targetTypeUri, value);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Gets the demand level for an AX attribute.
+ /// </summary>
+ /// <param name="ax">The AX fetch request to search for the attribute.</param>
+ /// <param name="typeUri">The type URI of the attribute in axschema.org format.</param>
+ /// <returns>The demand level for the attribute.</returns>
+ private static DemandLevel GetDemandLevelFor(FetchRequest ax, string typeUri) {
+ Requires.NotNull(ax, "ax");
+ Requires.NotNullOrEmpty(typeUri, "typeUri");
+
+ foreach (AXAttributeFormats format in OpenIdExtensionsInteropHelper.ForEachFormat(AXAttributeFormats.All)) {
+ string typeUriInFormat = OpenIdExtensionsInteropHelper.TransformAXFormat(typeUri, format);
+ if (ax.Attributes.Contains(typeUriInFormat)) {
+ return ax.Attributes[typeUriInFormat].IsRequired ? DemandLevel.Require : DemandLevel.Request;
+ }
+ }
+
+ return DemandLevel.NoRequest;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Extensions/UI/UIRequestTools.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Extensions/UI/UIRequestTools.cs
new file mode 100644
index 0000000..80ee2f1
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Extensions/UI/UIRequestTools.cs
@@ -0,0 +1,68 @@
+//-----------------------------------------------------------------------
+// <copyright file="UIRequestTools.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Provider.Extensions.UI {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Diagnostics.Contracts;
+ using System.Globalization;
+ using System.Linq;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OpenId.Extensions.UI;
+ using DotNetOpenAuth.OpenId.Messages;
+ using DotNetOpenAuth.OpenId.Provider;
+ using DotNetOpenAuth.Xrds;
+
+ /// <summary>
+ /// OpenID User Interface extension 1.0 request message.
+ /// </summary>
+ /// <remarks>
+ /// <para>Implements the extension described by: http://wiki.openid.net/f/openid_ui_extension_draft01.html </para>
+ /// <para>This extension only applies to checkid_setup requests, since checkid_immediate requests display
+ /// no UI to the user. </para>
+ /// <para>For rules about how the popup window should be displayed, please see the documentation of
+ /// <see cref="UIModes.Popup"/>. </para>
+ /// <para>An RP may determine whether an arbitrary OP supports this extension (and thereby determine
+ /// whether to use a standard full window redirect or a popup) via the
+ /// <see cref="IdentifierDiscoveryResult.IsExtensionSupported&lt;T&gt;()"/> method.</para>
+ /// </remarks>
+ public static class UIRequestTools {
+ /// <summary>
+ /// Gets the URL of the RP icon for the OP to display.
+ /// </summary>
+ /// <param name="realm">The realm of the RP where the authentication request originated.</param>
+ /// <param name="webRequestHandler">The web request handler to use for discovery.
+ /// Usually available via <see cref="Channel.WebRequestHandler">OpenIdProvider.Channel.WebRequestHandler</see>.</param>
+ /// <returns>
+ /// A sequence of the RP's icons it has available for the Provider to display, in decreasing preferred order.
+ /// </returns>
+ /// <value>The icon URL.</value>
+ /// <remarks>
+ /// This property is automatically set for the OP with the result of RP discovery.
+ /// RPs should set this value by including an entry such as this in their XRDS document.
+ /// <example>
+ /// &lt;Service xmlns="xri://$xrd*($v*2.0)"&gt;
+ /// &lt;Type&gt;http://specs.openid.net/extensions/ui/icon&lt;/Type&gt;
+ /// &lt;URI&gt;http://consumer.example.com/images/image.jpg&lt;/URI&gt;
+ /// &lt;/Service&gt;
+ /// </example>
+ /// </remarks>
+ public static IEnumerable<Uri> GetRelyingPartyIconUrls(Realm realm, IDirectWebRequestHandler webRequestHandler) {
+ Contract.Requires(realm != null);
+ Contract.Requires(webRequestHandler != null);
+ ErrorUtilities.VerifyArgumentNotNull(realm, "realm");
+ ErrorUtilities.VerifyArgumentNotNull(webRequestHandler, "webRequestHandler");
+
+ XrdsDocument xrds = realm.Discover(webRequestHandler, false);
+ if (xrds == null) {
+ return Enumerable.Empty<Uri>();
+ } else {
+ return xrds.FindRelyingPartyIcons();
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/HmacShaAssociationProvider.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/HmacShaAssociationProvider.cs
new file mode 100644
index 0000000..3cfc0b6
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/HmacShaAssociationProvider.cs
@@ -0,0 +1,71 @@
+//-----------------------------------------------------------------------
+// <copyright file="HmacShaAssociationProvider.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Provider {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OpenId.Provider;
+
+ /// <summary>
+ /// OpenID Provider utility methods for HMAC-SHA* associations.
+ /// </summary>
+ internal static class HmacShaAssociationProvider {
+ /// <summary>
+ /// The default lifetime of a shared association when no lifetime is given
+ /// for a specific association type.
+ /// </summary>
+ private static readonly TimeSpan DefaultMaximumLifetime = TimeSpan.FromDays(14);
+
+ /// <summary>
+ /// Creates a new association of a given type at an OpenID Provider.
+ /// </summary>
+ /// <param name="protocol">The protocol.</param>
+ /// <param name="associationType">Type of the association (i.e. HMAC-SHA1 or HMAC-SHA256)</param>
+ /// <param name="associationUse">A value indicating whether the new association will be used privately by the Provider for "dumb mode" authentication
+ /// or shared with the Relying Party for "smart mode" authentication.</param>
+ /// <param name="associationStore">The Provider's association store.</param>
+ /// <param name="securitySettings">The security settings of the Provider.</param>
+ /// <returns>
+ /// The newly created association.
+ /// </returns>
+ /// <remarks>
+ /// The new association is NOT automatically put into an association store. This must be done by the caller.
+ /// </remarks>
+ internal static HmacShaAssociation Create(Protocol protocol, string associationType, AssociationRelyingPartyType associationUse, IProviderAssociationStore associationStore, ProviderSecuritySettings securitySettings) {
+ Requires.NotNull(protocol, "protocol");
+ Requires.NotNullOrEmpty(associationType, "associationType");
+ Requires.NotNull(associationStore, "associationStore");
+ Requires.NotNull(securitySettings, "securitySettings");
+ Contract.Ensures(Contract.Result<HmacShaAssociation>() != null);
+
+ int secretLength = HmacShaAssociation.GetSecretLength(protocol, associationType);
+
+ // Generate the secret that will be used for signing
+ byte[] secret = MessagingUtilities.GetCryptoRandomData(secretLength);
+
+ TimeSpan lifetime;
+ if (associationUse == AssociationRelyingPartyType.Smart) {
+ if (!securitySettings.AssociationLifetimes.TryGetValue(associationType, out lifetime)) {
+ lifetime = DefaultMaximumLifetime;
+ }
+ } else {
+ lifetime = HmacShaAssociation.DumbSecretLifetime;
+ }
+
+ string handle = associationStore.Serialize(secret, DateTime.UtcNow + lifetime, associationUse == AssociationRelyingPartyType.Dumb);
+
+ Contract.Assert(protocol != null); // All the way up to the method call, the condition holds, yet we get a Requires failure next
+ Contract.Assert(secret != null);
+ Contract.Assert(!String.IsNullOrEmpty(associationType));
+ var result = HmacShaAssociation.Create(protocol, associationType, handle, secret, lifetime);
+ return result;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/Provider/HostProcessedRequest.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/HostProcessedRequest.cs
index ec0c58a..3647a63 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/HostProcessedRequest.cs
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/HostProcessedRequest.cs
@@ -36,7 +36,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// <param name="request">The incoming request message.</param>
protected HostProcessedRequest(OpenIdProvider provider, SignedResponseRequest request)
: base(request, provider.SecuritySettings) {
- Contract.Requires<ArgumentNullException>(provider != null);
+ Requires.NotNull(provider, "provider");
this.negativeResponse = new NegativeAssertionResponse(request, provider.Channel);
Reporting.RecordEventOccurrence(this, request.Realm);
@@ -105,17 +105,19 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// Gets a value indicating whether verification of the return URL claimed by the Relying Party
/// succeeded.
/// </summary>
- /// <param name="provider">The OpenIdProvider that is performing the RP discovery.</param>
- /// <returns>Result of realm discovery.</returns>
+ /// <param name="requestHandler">The request handler.</param>
+ /// <returns>
+ /// Result of realm discovery.
+ /// </returns>
/// <remarks>
/// Return URL verification is only attempted if this property is queried.
/// The result of the verification is cached per request so calling this
/// property getter multiple times in one request is not a performance hit.
/// See OpenID Authentication 2.0 spec section 9.2.1.
/// </remarks>
- public RelyingPartyDiscoveryResult IsReturnUrlDiscoverable(OpenIdProvider provider) {
+ public RelyingPartyDiscoveryResult IsReturnUrlDiscoverable(IDirectWebRequestHandler requestHandler) {
if (!this.realmDiscoveryResult.HasValue) {
- this.realmDiscoveryResult = this.IsReturnUrlDiscoverableCore(provider);
+ this.realmDiscoveryResult = this.IsReturnUrlDiscoverableCore(requestHandler);
}
return this.realmDiscoveryResult.Value;
@@ -125,10 +127,12 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// Gets a value indicating whether verification of the return URL claimed by the Relying Party
/// succeeded.
/// </summary>
- /// <param name="provider">The OpenIdProvider that is performing the RP discovery.</param>
- /// <returns>Result of realm discovery.</returns>
- private RelyingPartyDiscoveryResult IsReturnUrlDiscoverableCore(OpenIdProvider provider) {
- Contract.Requires<ArgumentNullException>(provider != null);
+ /// <param name="requestHandler">The request handler.</param>
+ /// <returns>
+ /// Result of realm discovery.
+ /// </returns>
+ private RelyingPartyDiscoveryResult IsReturnUrlDiscoverableCore(IDirectWebRequestHandler requestHandler) {
+ Requires.NotNull(requestHandler, "requestHandler");
ErrorUtilities.VerifyInternal(this.Realm != null, "Realm should have been read or derived by now.");
@@ -138,7 +142,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
return RelyingPartyDiscoveryResult.NoServiceDocument;
}
- var returnToEndpoints = this.Realm.DiscoverReturnToEndpoints(provider.Channel.WebRequestHandler, false);
+ var returnToEndpoints = this.Realm.DiscoverReturnToEndpoints(requestHandler, false);
if (returnToEndpoints == null) {
return RelyingPartyDiscoveryResult.NoServiceDocument;
}
diff --git a/src/DotNetOpenAuth/OpenId/Provider/IAnonymousRequest.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/IAnonymousRequest.cs
index ec2c175..ec2c175 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/IAnonymousRequest.cs
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/IAnonymousRequest.cs
diff --git a/src/DotNetOpenAuth/OpenId/Provider/IDirectedIdentityIdentifierProvider.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/IDirectedIdentityIdentifierProvider.cs
index 985bb54..9197761 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/IDirectedIdentityIdentifierProvider.cs
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/IDirectedIdentityIdentifierProvider.cs
@@ -59,9 +59,9 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// openid.claimed_id and openid.local_id parameters. Must not be null.
/// </returns>
Uri IDirectedIdentityIdentifierProvider.GetIdentifier(Identifier localIdentifier, Realm relyingPartyRealm) {
- Contract.Requires<ArgumentNullException>(localIdentifier != null);
- Contract.Requires<ArgumentNullException>(relyingPartyRealm != null);
- Contract.Requires<ArgumentException>(((IDirectedIdentityIdentifierProvider)this).IsUserLocalIdentifier(localIdentifier), OpenIdStrings.ArgumentIsPpidIdentifier);
+ Requires.NotNull(localIdentifier, "localIdentifier");
+ Requires.NotNull(relyingPartyRealm, "relyingPartyRealm");
+ Requires.True(((IDirectedIdentityIdentifierProvider)this).IsUserLocalIdentifier(localIdentifier), "localIdentifier", OpenIdStrings.ArgumentIsPpidIdentifier);
throw new NotImplementedException();
}
@@ -73,7 +73,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// <c>true</c> if the given identifier is the valid, unique identifier for some uesr (and NOT a PPID); otherwise, <c>false</c>.
/// </returns>
bool IDirectedIdentityIdentifierProvider.IsUserLocalIdentifier(Identifier identifier) {
- Contract.Requires<ArgumentNullException>(identifier != null);
+ Requires.NotNull(identifier, "identifier");
throw new NotImplementedException();
}
diff --git a/src/DotNetOpenAuth/OpenId/Provider/IErrorReporting.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/IErrorReporting.cs
index 1c73595..1c73595 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/IErrorReporting.cs
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/IErrorReporting.cs
diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/IProviderAssociationStore.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/IProviderAssociationStore.cs
new file mode 100644
index 0000000..6c749f6
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/IProviderAssociationStore.cs
@@ -0,0 +1,90 @@
+//-----------------------------------------------------------------------
+// <copyright file="IProviderAssociationStore.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Provider {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// Provides association serialization and deserialization.
+ /// </summary>
+ /// <remarks>
+ /// Implementations may choose to store the association details in memory or a database table and simply return a
+ /// short, randomly generated string that is the key to that data. Alternatively, an implementation may
+ /// sign and encrypt the association details and then encode the results as a base64 string and return that value
+ /// as the association handle, thereby avoiding any association persistence at the OpenID Provider.
+ /// When taking the latter approach however, it is of course imperative that the association be encrypted
+ /// to avoid disclosing the secret to anyone who sees the association handle, which itself isn't considered to
+ /// be confidential.
+ /// </remarks>
+ [ContractClass(typeof(IProviderAssociationStoreContract))]
+ internal interface IProviderAssociationStore {
+ /// <summary>
+ /// Stores an association and returns a handle for it.
+ /// </summary>
+ /// <param name="secret">The association secret.</param>
+ /// <param name="expiresUtc">The UTC time that the association should expire.</param>
+ /// <param name="privateAssociation">A value indicating whether this is a private association.</param>
+ /// <returns>
+ /// The association handle that represents this association.
+ /// </returns>
+ string Serialize(byte[] secret, DateTime expiresUtc, bool privateAssociation);
+
+ /// <summary>
+ /// Retrieves an association given an association handle.
+ /// </summary>
+ /// <param name="containingMessage">The OpenID message that referenced this association handle.</param>
+ /// <param name="privateAssociation">A value indicating whether a private association is expected.</param>
+ /// <param name="handle">The association handle.</param>
+ /// <returns>
+ /// An association instance, or <c>null</c> if the association has expired or the signature is incorrect (which may be because the OP's symmetric key has changed).
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown if the association is not of the expected type.</exception>
+ Association Deserialize(IProtocolMessage containingMessage, bool privateAssociation, string handle);
+ }
+
+ /// <summary>
+ /// Code contract for the <see cref="IProviderAssociationStore"/> interface.
+ /// </summary>
+ [ContractClassFor(typeof(IProviderAssociationStore))]
+ internal abstract class IProviderAssociationStoreContract : IProviderAssociationStore {
+ /// <summary>
+ /// Stores an association and returns a handle for it.
+ /// </summary>
+ /// <param name="secret">The association secret.</param>
+ /// <param name="expiresUtc">The expires UTC.</param>
+ /// <param name="privateAssociation">A value indicating whether this is a private association.</param>
+ /// <returns>
+ /// The association handle that represents this association.
+ /// </returns>
+ string IProviderAssociationStore.Serialize(byte[] secret, DateTime expiresUtc, bool privateAssociation) {
+ Requires.NotNull(secret, "secret");
+ Requires.True(expiresUtc.Kind == DateTimeKind.Utc, "expiresUtc");
+ Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>()));
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Retrieves an association given an association handle.
+ /// </summary>
+ /// <param name="containingMessage">The OpenID message that referenced this association handle.</param>
+ /// <param name="privateAssociation">A value indicating whether a private association is expected.</param>
+ /// <param name="handle">The association handle.</param>
+ /// <returns>
+ /// An association instance, or <c>null</c> if the association has expired or the signature is incorrect (which may be because the OP's symmetric key has changed).
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown if the association is not of the expected type.</exception>
+ Association IProviderAssociationStore.Deserialize(IProtocolMessage containingMessage, bool privateAssociation, string handle) {
+ Requires.NotNull(containingMessage, "containingMessage");
+ Requires.NotNullOrEmpty(handle, "handle");
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/Provider/OpenIdProvider.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/OpenIdProvider.cs
index 3b4cb56..6b78098 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/OpenIdProvider.cs
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/OpenIdProvider.cs
@@ -40,6 +40,18 @@ namespace DotNetOpenAuth.OpenId.Provider {
private readonly ObservableCollection<IProviderBehavior> behaviors = new ObservableCollection<IProviderBehavior>();
/// <summary>
+ /// A type initializer that ensures that another type initializer runs in order to guarantee that
+ /// types are serializable.
+ /// </summary>
+ private static Identifier dummyIdentifierToInvokeStaticCtor = "http://localhost/";
+
+ /// <summary>
+ /// A type initializer that ensures that another type initializer runs in order to guarantee that
+ /// types are serializable.
+ /// </summary>
+ private static Realm dummyRealmToInvokeStaticCtor = "http://localhost/";
+
+ /// <summary>
/// Backing field for the <see cref="SecuritySettings"/> property.
/// </summary>
private ProviderSecuritySettings securitySettings;
@@ -54,8 +66,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// Initializes a new instance of the <see cref="OpenIdProvider"/> class.
/// </summary>
public OpenIdProvider()
- : this(DotNetOpenAuthSection.Configuration.OpenId.Provider.ApplicationStore.CreateInstance(HttpApplicationStore)) {
- Contract.Ensures(this.AssociationStore != null);
+ : this(OpenIdElement.Configuration.Provider.ApplicationStore.CreateInstance(HttpApplicationStore)) {
Contract.Ensures(this.SecuritySettings != null);
Contract.Ensures(this.Channel != null);
}
@@ -64,10 +75,9 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// Initializes a new instance of the <see cref="OpenIdProvider"/> class.
/// </summary>
/// <param name="applicationStore">The application store to use. Cannot be null.</param>
- public OpenIdProvider(IProviderApplicationStore applicationStore)
- : this(applicationStore, applicationStore) {
- Contract.Requires<ArgumentNullException>(applicationStore != null);
- Contract.Ensures(this.AssociationStore == applicationStore);
+ public OpenIdProvider(IOpenIdApplicationStore applicationStore)
+ : this((INonceStore)applicationStore, (ICryptoKeyStore)applicationStore) {
+ Requires.NotNull(applicationStore, "applicationStore");
Contract.Ensures(this.SecuritySettings != null);
Contract.Ensures(this.Channel != null);
}
@@ -75,25 +85,25 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// <summary>
/// Initializes a new instance of the <see cref="OpenIdProvider"/> class.
/// </summary>
- /// <param name="associationStore">The association store to use. Cannot be null.</param>
/// <param name="nonceStore">The nonce store to use. Cannot be null.</param>
- private OpenIdProvider(IAssociationStore<AssociationRelyingPartyType> associationStore, INonceStore nonceStore) {
- Contract.Requires<ArgumentNullException>(associationStore != null);
- Contract.Requires<ArgumentNullException>(nonceStore != null);
- Contract.Ensures(this.AssociationStore == associationStore);
+ /// <param name="cryptoKeyStore">The crypto key store. Cannot be null.</param>
+ private OpenIdProvider(INonceStore nonceStore, ICryptoKeyStore cryptoKeyStore) {
+ Requires.NotNull(nonceStore, "nonceStore");
+ Requires.NotNull(cryptoKeyStore, "cryptoKeyStore");
Contract.Ensures(this.SecuritySettings != null);
Contract.Ensures(this.Channel != null);
- this.AssociationStore = associationStore;
- this.SecuritySettings = DotNetOpenAuthSection.Configuration.OpenId.Provider.SecuritySettings.CreateSecuritySettings();
+ this.SecuritySettings = OpenIdElement.Configuration.Provider.SecuritySettings.CreateSecuritySettings();
this.behaviors.CollectionChanged += this.OnBehaviorsChanged;
- foreach (var behavior in DotNetOpenAuthSection.Configuration.OpenId.Provider.Behaviors.CreateInstances(false)) {
+ foreach (var behavior in OpenIdElement.Configuration.Provider.Behaviors.CreateInstances(false)) {
this.behaviors.Add(behavior);
}
- this.Channel = new OpenIdChannel(this.AssociationStore, nonceStore, this.SecuritySettings);
+ this.AssociationStore = new SwitchingAssociationStore(cryptoKeyStore, this.SecuritySettings);
+ this.Channel = new OpenIdProviderChannel(this.AssociationStore, nonceStore, this.SecuritySettings);
+ this.CryptoKeyStore = cryptoKeyStore;
- Reporting.RecordFeatureAndDependencyUse(this, associationStore, nonceStore);
+ Reporting.RecordFeatureAndDependencyUse(this, nonceStore);
}
/// <summary>
@@ -101,16 +111,16 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// HttpApplication state dictionary to store associations and nonces.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
- public static IProviderApplicationStore HttpApplicationStore {
+ public static IOpenIdApplicationStore HttpApplicationStore {
get {
- Contract.Requires<InvalidOperationException>(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
- Contract.Ensures(Contract.Result<IProviderApplicationStore>() != null);
+ Requires.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
+ Contract.Ensures(Contract.Result<IOpenIdApplicationStore>() != null);
HttpContext context = HttpContext.Current;
- var store = (IProviderApplicationStore)context.Application[ApplicationStoreKey];
+ var store = (IOpenIdApplicationStore)context.Application[ApplicationStoreKey];
if (store == null) {
context.Application.Lock();
try {
- if ((store = (IProviderApplicationStore)context.Application[ApplicationStoreKey]) == null) {
+ if ((store = (IOpenIdApplicationStore)context.Application[ApplicationStoreKey]) == null) {
context.Application[ApplicationStoreKey] = store = new StandardProviderApplicationStore();
}
} finally {
@@ -138,7 +148,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
}
internal set {
- Contract.Requires<ArgumentNullException>(value != null);
+ Requires.NotNull(value, "value");
this.securitySettings = value;
}
}
@@ -168,16 +178,28 @@ namespace DotNetOpenAuth.OpenId.Provider {
}
/// <summary>
- /// Gets the list of services that can perform discovery on identifiers given to this relying party.
+ /// Gets the crypto key store.
/// </summary>
- internal IList<IIdentifierDiscoveryService> DiscoveryServices {
- get { return this.RelyingParty.DiscoveryServices; }
- }
+ public ICryptoKeyStore CryptoKeyStore { get; private set; }
/// <summary>
/// Gets the association store.
/// </summary>
- internal IAssociationStore<AssociationRelyingPartyType> AssociationStore { get; private set; }
+ internal IProviderAssociationStore AssociationStore { get; private set; }
+
+ /// <summary>
+ /// Gets the channel.
+ /// </summary>
+ internal OpenIdChannel OpenIdChannel {
+ get { return (OpenIdChannel)this.Channel; }
+ }
+
+ /// <summary>
+ /// Gets the list of services that can perform discovery on identifiers given to this relying party.
+ /// </summary>
+ internal IList<IIdentifierDiscoveryService> DiscoveryServices {
+ get { return this.RelyingParty.DiscoveryServices; }
+ }
/// <summary>
/// Gets the web request handler to use for discovery and the part of
@@ -238,7 +260,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// <exception cref="ProtocolException">Thrown if the incoming message is recognized
/// but deviates from the protocol specification irrecoverably.</exception>
public IRequest GetRequest(HttpRequestInfo httpRequestInfo) {
- Contract.Requires<ArgumentNullException>(httpRequestInfo != null);
+ Requires.NotNull(httpRequestInfo, "httpRequestInfo");
IDirectedProtocolMessage incomingMessage = null;
try {
@@ -271,14 +293,14 @@ namespace DotNetOpenAuth.OpenId.Provider {
if (result == null) {
var checkAuthMessage = incomingMessage as CheckAuthenticationRequest;
if (checkAuthMessage != null) {
- result = new AutoResponsiveRequest(incomingMessage, new CheckAuthenticationResponse(checkAuthMessage, this), this.SecuritySettings);
+ result = new AutoResponsiveRequest(incomingMessage, new CheckAuthenticationResponseProvider(checkAuthMessage, this), this.SecuritySettings);
}
}
if (result == null) {
- var associateMessage = incomingMessage as AssociateRequest;
+ var associateMessage = incomingMessage as IAssociateRequestProvider;
if (associateMessage != null) {
- result = new AutoResponsiveRequest(incomingMessage, associateMessage.CreateResponse(this.AssociationStore, this.SecuritySettings), this.SecuritySettings);
+ result = new AutoResponsiveRequest(incomingMessage, AssociateRequestProviderTools.CreateResponse(associateMessage, this.AssociationStore, this.SecuritySettings), this.SecuritySettings);
}
}
@@ -316,10 +338,11 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// </remarks>
/// <exception cref="InvalidOperationException">Thrown if <see cref="IRequest.IsResponseReady"/> is <c>false</c>.</exception>
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "Code Contract requires that we cast early.")]
+ [EditorBrowsable(EditorBrowsableState.Never)]
public void SendResponse(IRequest request) {
- Contract.Requires<InvalidOperationException>(HttpContext.Current != null, MessagingStrings.CurrentHttpContextRequired);
- Contract.Requires<ArgumentNullException>(request != null);
- Contract.Requires<ArgumentException>(request.IsResponseReady);
+ Requires.ValidState(HttpContext.Current != null, MessagingStrings.CurrentHttpContextRequired);
+ Requires.NotNull(request, "request");
+ Requires.True(request.IsResponseReady, "request");
this.ApplyBehaviorsToResponse(request);
Request requestInternal = (Request)request;
@@ -327,6 +350,27 @@ namespace DotNetOpenAuth.OpenId.Provider {
}
/// <summary>
+ /// Sends the response to a received request.
+ /// </summary>
+ /// <param name="request">The incoming OpenID request whose response is to be sent.</param>
+ /// <remarks>
+ /// <para>Requires an HttpContext.Current context. If one is not available, the caller should use
+ /// <see cref="PrepareResponse"/> instead and manually send the <see cref="OutgoingWebResponse"/>
+ /// to the client.</para>
+ /// </remarks>
+ /// <exception cref="InvalidOperationException">Thrown if <see cref="IRequest.IsResponseReady"/> is <c>false</c>.</exception>
+ [SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "Code Contract requires that we cast early.")]
+ public void Respond(IRequest request) {
+ Requires.ValidState(HttpContext.Current != null, MessagingStrings.CurrentHttpContextRequired);
+ Requires.NotNull(request, "request");
+ Requires.True(request.IsResponseReady, "request");
+
+ this.ApplyBehaviorsToResponse(request);
+ Request requestInternal = (Request)request;
+ this.Channel.Respond(requestInternal.Response);
+ }
+
+ /// <summary>
/// Gets the response to a received request.
/// </summary>
/// <param name="request">The request.</param>
@@ -334,8 +378,8 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// <exception cref="InvalidOperationException">Thrown if <see cref="IRequest.IsResponseReady"/> is <c>false</c>.</exception>
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "Code Contract requires that we cast early.")]
public OutgoingWebResponse PrepareResponse(IRequest request) {
- Contract.Requires<ArgumentNullException>(request != null);
- Contract.Requires<ArgumentException>(request.IsResponseReady);
+ Requires.NotNull(request, "request");
+ Requires.True(request.IsResponseReady, "request");
this.ApplyBehaviorsToResponse(request);
Request requestInternal = (Request)request;
@@ -358,12 +402,12 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// be the same as <paramref name="claimedIdentifier"/>.</param>
/// <param name="extensions">The extensions.</param>
public void SendUnsolicitedAssertion(Uri providerEndpoint, Realm relyingPartyRealm, Identifier claimedIdentifier, Identifier localIdentifier, params IExtensionMessage[] extensions) {
- Contract.Requires<InvalidOperationException>(HttpContext.Current != null, MessagingStrings.HttpContextRequired);
- Contract.Requires<ArgumentNullException>(providerEndpoint != null);
- Contract.Requires<ArgumentException>(providerEndpoint.IsAbsoluteUri);
- Contract.Requires<ArgumentNullException>(relyingPartyRealm != null);
- Contract.Requires<ArgumentNullException>(claimedIdentifier != null);
- Contract.Requires<ArgumentNullException>(localIdentifier != null);
+ Requires.ValidState(HttpContext.Current != null, MessagingStrings.HttpContextRequired);
+ Requires.NotNull(providerEndpoint, "providerEndpoint");
+ Requires.True(providerEndpoint.IsAbsoluteUri, "providerEndpoint");
+ Requires.NotNull(relyingPartyRealm, "relyingPartyRealm");
+ Requires.NotNull(claimedIdentifier, "claimedIdentifier");
+ Requires.NotNull(localIdentifier, "localIdentifier");
this.PrepareUnsolicitedAssertion(providerEndpoint, relyingPartyRealm, claimedIdentifier, localIdentifier, extensions).Send();
}
@@ -388,12 +432,12 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// the user agent to allow the redirect with assertion to happen.
/// </returns>
public OutgoingWebResponse PrepareUnsolicitedAssertion(Uri providerEndpoint, Realm relyingPartyRealm, Identifier claimedIdentifier, Identifier localIdentifier, params IExtensionMessage[] extensions) {
- Contract.Requires<ArgumentNullException>(providerEndpoint != null);
- Contract.Requires<ArgumentException>(providerEndpoint.IsAbsoluteUri);
- Contract.Requires<ArgumentNullException>(relyingPartyRealm != null);
- Contract.Requires<ArgumentNullException>(claimedIdentifier != null);
- Contract.Requires<ArgumentNullException>(localIdentifier != null);
- Contract.Requires<InvalidOperationException>(this.Channel.WebRequestHandler != null);
+ Requires.NotNull(providerEndpoint, "providerEndpoint");
+ Requires.True(providerEndpoint.IsAbsoluteUri, "providerEndpoint");
+ Requires.NotNull(relyingPartyRealm, "relyingPartyRealm");
+ Requires.NotNull(claimedIdentifier, "claimedIdentifier");
+ Requires.NotNull(localIdentifier, "localIdentifier");
+ Requires.ValidState(this.Channel.WebRequestHandler != null);
// Although the RP should do their due diligence to make sure that this OP
// is authorized to send an assertion for the given claimed identifier,
@@ -497,8 +541,8 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// Either the <see cref="IRequest"/> to return to the host site or null to indicate no response could be reasonably created and that the caller should rethrow the exception.
/// </returns>
private IRequest GetErrorResponse(ProtocolException ex, HttpRequestInfo httpRequestInfo, IDirectedProtocolMessage incomingMessage) {
- Contract.Requires<ArgumentNullException>(ex != null);
- Contract.Requires<ArgumentNullException>(httpRequestInfo != null);
+ Requires.NotNull(ex, "ex");
+ Requires.NotNull(httpRequestInfo, "httpRequestInfo");
Logger.OpenId.Error("An exception was generated while processing an incoming OpenID request.", ex);
IErrorMessage errorMessage;
@@ -557,5 +601,74 @@ namespace DotNetOpenAuth.OpenId.Provider {
Reporting.RecordFeatureUse(profile);
}
}
+
+ /// <summary>
+ /// Provides a single OP association store instance that can handle switching between
+ /// association handle encoding modes.
+ /// </summary>
+ private class SwitchingAssociationStore : IProviderAssociationStore {
+ /// <summary>
+ /// The security settings of the Provider.
+ /// </summary>
+ private readonly ProviderSecuritySettings securitySettings;
+
+ /// <summary>
+ /// The association store that records association secrets in the association handles themselves.
+ /// </summary>
+ private IProviderAssociationStore associationHandleEncoder;
+
+ /// <summary>
+ /// The association store that records association secrets in a secret store.
+ /// </summary>
+ private IProviderAssociationStore associationSecretStorage;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SwitchingAssociationStore"/> class.
+ /// </summary>
+ /// <param name="cryptoKeyStore">The crypto key store.</param>
+ /// <param name="securitySettings">The security settings.</param>
+ internal SwitchingAssociationStore(ICryptoKeyStore cryptoKeyStore, ProviderSecuritySettings securitySettings) {
+ Requires.NotNull(cryptoKeyStore, "cryptoKeyStore");
+ Requires.NotNull(securitySettings, "securitySettings");
+ this.securitySettings = securitySettings;
+
+ this.associationHandleEncoder = new ProviderAssociationHandleEncoder(cryptoKeyStore);
+ this.associationSecretStorage = new ProviderAssociationKeyStorage(cryptoKeyStore);
+ }
+
+ /// <summary>
+ /// Gets the association store that applies given the Provider's current security settings.
+ /// </summary>
+ internal IProviderAssociationStore AssociationStore {
+ get { return this.securitySettings.EncodeAssociationSecretsInHandles ? this.associationHandleEncoder : this.associationSecretStorage; }
+ }
+
+ /// <summary>
+ /// Stores an association and returns a handle for it.
+ /// </summary>
+ /// <param name="secret">The association secret.</param>
+ /// <param name="expiresUtc">The UTC time that the association should expire.</param>
+ /// <param name="privateAssociation">A value indicating whether this is a private association.</param>
+ /// <returns>
+ /// The association handle that represents this association.
+ /// </returns>
+ public string Serialize(byte[] secret, DateTime expiresUtc, bool privateAssociation) {
+ return this.AssociationStore.Serialize(secret, expiresUtc, privateAssociation);
+ }
+
+ /// <summary>
+ /// Retrieves an association given an association handle.
+ /// </summary>
+ /// <param name="containingMessage">The OpenID message that referenced this association handle.</param>
+ /// <param name="isPrivateAssociation">A value indicating whether a private association is expected.</param>
+ /// <param name="handle">The association handle.</param>
+ /// <returns>
+ /// An association instance, or <c>null</c> if the association has expired or the signature is incorrect (which may be because the OP's symmetric key has changed).
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown if the association is not of the expected type.</exception>
+ public Association Deserialize(IProtocolMessage containingMessage, bool isPrivateAssociation, string handle) {
+ return this.AssociationStore.Deserialize(containingMessage, isPrivateAssociation, handle);
+ }
+ }
}
}
diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/OpenIdProviderUtilities.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/OpenIdProviderUtilities.cs
new file mode 100644
index 0000000..cf525f1
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/OpenIdProviderUtilities.cs
@@ -0,0 +1,70 @@
+//-----------------------------------------------------------------------
+// <copyright file="OpenIdProviderUtilities.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Provider {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OpenId.Messages;
+ using DotNetOpenAuth.OpenId.Provider;
+
+ /// <summary>
+ /// Utility methods for OpenID Providers.
+ /// </summary>
+ internal static class OpenIdProviderUtilities {
+ /// <summary>
+ /// Called to create the Association based on a request previously given by the Relying Party.
+ /// </summary>
+ /// <param name="request">The prior request for an association.</param>
+ /// <param name="response">The response.</param>
+ /// <param name="associationStore">The Provider's association store.</param>
+ /// <param name="securitySettings">The security settings for the Provider. Should be <c>null</c> for Relying Parties.</param>
+ /// <returns>
+ /// The created association.
+ /// </returns>
+ /// <remarks>
+ /// The response message is updated to include the details of the created association by this method.
+ /// This method is called by both the Provider and the Relying Party, but actually performs
+ /// quite different operations in either scenario.
+ /// </remarks>
+ internal static Association CreateAssociation(AssociateRequest request, IAssociateSuccessfulResponseProvider response, IProviderAssociationStore associationStore, ProviderSecuritySettings securitySettings) {
+ Requires.NotNull(request, "request");
+ Requires.NotNull(response, "response");
+ Requires.NotNull(securitySettings, "securitySettings");
+
+ // We need to initialize some common properties based on the created association.
+ var association = response.CreateAssociationAtProvider(request, associationStore, securitySettings);
+ response.ExpiresIn = association.SecondsTillExpiration;
+ response.AssociationHandle = association.Handle;
+
+ return association;
+ }
+
+ /// <summary>
+ /// Determines whether the association with the specified handle is (still) valid.
+ /// </summary>
+ /// <param name="associationStore">The association store.</param>
+ /// <param name="containingMessage">The OpenID message that referenced this association handle.</param>
+ /// <param name="isPrivateAssociation">A value indicating whether a private association is expected.</param>
+ /// <param name="handle">The association handle.</param>
+ /// <returns>
+ /// <c>true</c> if the specified containing message is valid; otherwise, <c>false</c>.
+ /// </returns>
+ internal static bool IsValid(this IProviderAssociationStore associationStore, IProtocolMessage containingMessage, bool isPrivateAssociation, string handle) {
+ Requires.NotNull(associationStore, "associationStore");
+ Requires.NotNull(containingMessage, "containingMessage");
+ Requires.NotNullOrEmpty(handle, "handle");
+ try {
+ return associationStore.Deserialize(containingMessage, isPrivateAssociation, handle) != null;
+ } catch (ProtocolException) {
+ return false;
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/Provider/PrivatePersonalIdentifierProviderBase.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/PrivatePersonalIdentifierProviderBase.cs
index 46e172c..9ebae1d 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/PrivatePersonalIdentifierProviderBase.cs
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/PrivatePersonalIdentifierProviderBase.cs
@@ -35,7 +35,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// </summary>
/// <param name="baseIdentifier">The base URI on which to append the anonymous part.</param>
protected PrivatePersonalIdentifierProviderBase(Uri baseIdentifier) {
- Contract.Requires<ArgumentNullException>(baseIdentifier != null);
+ Requires.NotNull(baseIdentifier, "baseIdentifier");
this.Hasher = HashAlgorithm.Create(HashAlgorithmName);
this.Encoder = Encoding.UTF8;
@@ -102,7 +102,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
}
set {
- Contract.Requires<ArgumentOutOfRangeException>(value > 0);
+ Requires.InRange(value > 0, "value");
this.newSaltLength = value;
}
}
@@ -157,8 +157,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// <returns>
/// <c>true</c> if the given identifier is the valid, unique identifier for some uesr (and NOT a PPID); otherwise, <c>false</c>.
/// </returns>
- public virtual bool IsUserLocalIdentifier(Identifier identifier)
- {
+ public virtual bool IsUserLocalIdentifier(Identifier identifier) {
return !identifier.ToString().StartsWith(this.BaseIdentifier.AbsoluteUri, StringComparison.Ordinal);
}
@@ -181,7 +180,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// <returns>The full PPID Identifier.</returns>
[SuppressMessage("Microsoft.Usage", "CA2234:PassSystemUriObjectsInsteadOfStrings", Justification = "NOT equivalent overload. The recommended one breaks on relative URIs.")]
protected virtual Uri AppendIdentifiers(string uriHash) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(uriHash));
+ Requires.NotNullOrEmpty(uriHash, "uriHash");
if (string.IsNullOrEmpty(this.BaseIdentifier.Query)) {
// The uriHash will appear on the path itself.
diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/ProviderAssociationHandleEncoder.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/ProviderAssociationHandleEncoder.cs
new file mode 100644
index 0000000..0e7c174
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/ProviderAssociationHandleEncoder.cs
@@ -0,0 +1,84 @@
+//-----------------------------------------------------------------------
+// <copyright file="ProviderAssociationHandleEncoder.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Provider {
+ using System;
+ using System.Diagnostics.Contracts;
+ using System.Threading;
+ using DotNetOpenAuth.Configuration;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+
+ /// <summary>
+ /// Provides association storage in the association handle itself, but embedding signed and encrypted association
+ /// details in the handle.
+ /// </summary>
+ public class ProviderAssociationHandleEncoder : IProviderAssociationStore {
+ /// <summary>
+ /// The name of the bucket in which to store keys that encrypt association data into association handles.
+ /// </summary>
+ internal const string AssociationHandleEncodingSecretBucket = "https://localhost/dnoa/association_handles";
+
+ /// <summary>
+ /// The crypto key store used to persist encryption keys.
+ /// </summary>
+ private readonly ICryptoKeyStore cryptoKeyStore;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ProviderAssociationHandleEncoder"/> class.
+ /// </summary>
+ /// <param name="cryptoKeyStore">The crypto key store.</param>
+ public ProviderAssociationHandleEncoder(ICryptoKeyStore cryptoKeyStore) {
+ Requires.NotNull(cryptoKeyStore, "cryptoKeyStore");
+ this.cryptoKeyStore = cryptoKeyStore;
+ }
+
+ /// <summary>
+ /// Encodes the specified association data bag.
+ /// </summary>
+ /// <param name="secret">The symmetric secret.</param>
+ /// <param name="expiresUtc">The UTC time that the association should expire.</param>
+ /// <param name="privateAssociation">A value indicating whether this is a private association.</param>
+ /// <returns>
+ /// The association handle that represents this association.
+ /// </returns>
+ public string Serialize(byte[] secret, DateTime expiresUtc, bool privateAssociation) {
+ var associationDataBag = new AssociationDataBag {
+ Secret = secret,
+ IsPrivateAssociation = privateAssociation,
+ ExpiresUtc = expiresUtc,
+ };
+
+ var formatter = AssociationDataBag.CreateFormatter(this.cryptoKeyStore, AssociationHandleEncodingSecretBucket, expiresUtc - DateTime.UtcNow);
+ return formatter.Serialize(associationDataBag);
+ }
+
+ /// <summary>
+ /// Retrieves an association given an association handle.
+ /// </summary>
+ /// <param name="containingMessage">The OpenID message that referenced this association handle.</param>
+ /// <param name="privateAssociation">A value indicating whether a private association is expected.</param>
+ /// <param name="handle">The association handle.</param>
+ /// <returns>
+ /// An association instance, or <c>null</c> if the association has expired or the signature is incorrect (which may be because the OP's symmetric key has changed).
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown if the association is not of the expected type.</exception>
+ public Association Deserialize(IProtocolMessage containingMessage, bool privateAssociation, string handle) {
+ var formatter = AssociationDataBag.CreateFormatter(this.cryptoKeyStore, AssociationHandleEncodingSecretBucket);
+ AssociationDataBag bag;
+ try {
+ bag = formatter.Deserialize(containingMessage, handle);
+ } catch (ProtocolException ex) {
+ Logger.OpenId.Error("Rejecting an association because deserialization of the encoded handle failed.", ex);
+ return null;
+ }
+
+ ErrorUtilities.VerifyProtocol(bag.IsPrivateAssociation == privateAssociation, "Unexpected association type.");
+ Association assoc = Association.Deserialize(handle, bag.ExpiresUtc, bag.Secret);
+ return assoc.IsExpired ? null : assoc;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/ProviderAssociationKeyStorage.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/ProviderAssociationKeyStorage.cs
new file mode 100644
index 0000000..179699a
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/ProviderAssociationKeyStorage.cs
@@ -0,0 +1,79 @@
+//-----------------------------------------------------------------------
+// <copyright file="ProviderAssociationKeyStorage.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Provider {
+ using System;
+ using System.Diagnostics.Contracts;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+
+ /// <summary>
+ /// An association storage mechanism that stores the association secrets in a private store,
+ /// and returns randomly generated association handles to refer to these secrets.
+ /// </summary>
+ internal class ProviderAssociationKeyStorage : IProviderAssociationStore {
+ /// <summary>
+ /// The bucket to use when recording shared associations.
+ /// </summary>
+ internal const string SharedAssociationBucket = "https://localhost/dnoa/shared_associations";
+
+ /// <summary>
+ /// The bucket to use when recording private associations.
+ /// </summary>
+ internal const string PrivateAssociationBucket = "https://localhost/dnoa/private_associations";
+
+ /// <summary>
+ /// The backing crypto key store.
+ /// </summary>
+ private readonly ICryptoKeyStore cryptoKeyStore;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ProviderAssociationKeyStorage"/> class.
+ /// </summary>
+ /// <param name="cryptoKeyStore">The store where association secrets will be recorded.</param>
+ internal ProviderAssociationKeyStorage(ICryptoKeyStore cryptoKeyStore) {
+ Requires.NotNull(cryptoKeyStore, "cryptoKeyStore");
+ this.cryptoKeyStore = cryptoKeyStore;
+ }
+
+ /// <summary>
+ /// Stores an association and returns a handle for it.
+ /// </summary>
+ /// <param name="secret">The association secret.</param>
+ /// <param name="expiresUtc">The UTC time that the association should expire.</param>
+ /// <param name="privateAssociation">A value indicating whether this is a private association.</param>
+ /// <returns>
+ /// The association handle that represents this association.
+ /// </returns>
+ public string Serialize(byte[] secret, DateTime expiresUtc, bool privateAssociation) {
+ string handle;
+ this.cryptoKeyStore.StoreKey(
+ privateAssociation ? PrivateAssociationBucket : SharedAssociationBucket,
+ handle = OpenIdUtilities.GenerateRandomAssociationHandle(),
+ new CryptoKey(secret, expiresUtc));
+ return handle;
+ }
+
+ /// <summary>
+ /// Retrieves an association given an association handle.
+ /// </summary>
+ /// <param name="containingMessage">The OpenID message that referenced this association handle.</param>
+ /// <param name="isPrivateAssociation">A value indicating whether a private association is expected.</param>
+ /// <param name="handle">The association handle.</param>
+ /// <returns>
+ /// An association instance, or <c>null</c> if the association has expired or the signature is incorrect (which may be because the OP's symmetric key has changed).
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown if the association is not of the expected type.</exception>
+ public Association Deserialize(IProtocolMessage containingMessage, bool isPrivateAssociation, string handle) {
+ var key = this.cryptoKeyStore.GetKey(isPrivateAssociation ? PrivateAssociationBucket : SharedAssociationBucket, handle);
+ if (key != null) {
+ return Association.Deserialize(handle, key.ExpiresUtc, key.Key);
+ }
+
+ return null;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/Provider/Request.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Request.cs
index 4e54ef9..c5b6dac 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/Request.cs
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Request.cs
@@ -54,8 +54,8 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// <param name="request">The incoming request message.</param>
/// <param name="securitySettings">The security settings from the channel.</param>
protected Request(IDirectedProtocolMessage request, ProviderSecuritySettings securitySettings) {
- Contract.Requires<ArgumentNullException>(request != null);
- Contract.Requires<ArgumentNullException>(securitySettings != null);
+ Requires.NotNull(request, "request");
+ Requires.NotNull(securitySettings, "securitySettings");
this.request = request;
this.SecuritySettings = securitySettings;
@@ -69,8 +69,8 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// <param name="version">The version.</param>
/// <param name="securitySettings">The security settings.</param>
protected Request(Version version, ProviderSecuritySettings securitySettings) {
- Contract.Requires<ArgumentNullException>(version != null);
- Contract.Requires<ArgumentNullException>(securitySettings != null);
+ Requires.NotNull(version, "version");
+ Requires.NotNull(securitySettings, "securitySettings");
this.protocolVersion = version;
this.SecuritySettings = securitySettings;
@@ -99,7 +99,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// <exception cref="InvalidOperationException">Thrown if <see cref="IsResponseReady"/> is <c>false</c>.</exception>
internal IProtocolMessage Response {
get {
- Contract.Requires<InvalidOperationException>(this.IsResponseReady, OpenIdStrings.ResponseNotReady);
+ Requires.ValidState(this.IsResponseReady, OpenIdStrings.ResponseNotReady);
Contract.Ensures(Contract.Result<IProtocolMessage>() != null);
if (this.responseExtensions.Count > 0) {
diff --git a/src/DotNetOpenAuth/OpenId/Provider/RequestContract.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/RequestContract.cs
index dee140e..ae7104c 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/RequestContract.cs
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/RequestContract.cs
@@ -39,7 +39,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// </summary>
protected override IProtocolMessage ResponseMessage {
get {
- Contract.Requires<InvalidOperationException>(this.IsResponseReady);
+ Requires.ValidState(this.IsResponseReady);
Contract.Ensures(Contract.Result<IProtocolMessage>() != null);
throw new NotImplementedException();
}
diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/StandardProviderApplicationStore.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/StandardProviderApplicationStore.cs
new file mode 100644
index 0000000..b5880d3
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/StandardProviderApplicationStore.cs
@@ -0,0 +1,117 @@
+//-----------------------------------------------------------------------
+// <copyright file="StandardProviderApplicationStore.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Provider {
+ using System;
+ using System.Collections.Generic;
+ using DotNetOpenAuth.Configuration;
+ using DotNetOpenAuth.Messaging.Bindings;
+
+ /// <summary>
+ /// An in-memory store for Providers, suitable for single server, single process
+ /// ASP.NET web sites.
+ /// </summary>
+ /// <remarks>
+ /// This class provides only a basic implementation that is likely to work
+ /// out of the box on most single-server web sites. It is highly recommended
+ /// that high traffic web sites consider using a database to store the information
+ /// used by an OpenID Provider and write a custom implementation of the
+ /// <see cref="IOpenIdApplicationStore"/> interface to use instead of this
+ /// class.
+ /// </remarks>
+ public class StandardProviderApplicationStore : IOpenIdApplicationStore {
+ /// <summary>
+ /// The nonce store to use.
+ /// </summary>
+ private readonly INonceStore nonceStore;
+
+ /// <summary>
+ /// The crypto key store where symmetric keys are persisted.
+ /// </summary>
+ private readonly ICryptoKeyStore cryptoKeyStore;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="StandardProviderApplicationStore"/> class.
+ /// </summary>
+ public StandardProviderApplicationStore() {
+ this.nonceStore = new NonceMemoryStore(OpenIdElement.Configuration.MaxAuthenticationTime);
+ this.cryptoKeyStore = new MemoryCryptoKeyStore();
+ }
+
+ #region INonceStore Members
+
+ /// <summary>
+ /// Stores a given nonce and timestamp.
+ /// </summary>
+ /// <param name="context">The context, or namespace, within which the <paramref name="nonce"/> must be unique.</param>
+ /// <param name="nonce">A series of random characters.</param>
+ /// <param name="timestampUtc">The timestamp that together with the nonce string make it unique.
+ /// The timestamp may also be used by the data store to clear out old nonces.</param>
+ /// <returns>
+ /// True if the nonce+timestamp (combination) was not previously in the database.
+ /// False if the nonce was stored previously with the same timestamp.
+ /// </returns>
+ /// <remarks>
+ /// The nonce must be stored for no less than the maximum time window a message may
+ /// be processed within before being discarded as an expired message.
+ /// If the binding element is applicable to your channel, this expiration window
+ /// is retrieved or set using the
+ /// <see cref="StandardExpirationBindingElement.MaximumMessageAge"/> property.
+ /// </remarks>
+ public bool StoreNonce(string context, string nonce, DateTime timestampUtc) {
+ return this.nonceStore.StoreNonce(context, nonce, timestampUtc);
+ }
+
+ #endregion
+
+ #region ICryptoKeyStore
+
+ /// <summary>
+ /// Gets the key in a given bucket and handle.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <param name="handle">The key handle. Case sensitive.</param>
+ /// <returns>
+ /// The cryptographic key, or <c>null</c> if no matching key was found.
+ /// </returns>
+ public CryptoKey GetKey(string bucket, string handle) {
+ return this.cryptoKeyStore.GetKey(bucket, handle);
+ }
+
+ /// <summary>
+ /// Gets a sequence of existing keys within a given bucket.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <returns>
+ /// A sequence of handles and keys, ordered by descending <see cref="CryptoKey.ExpiresUtc"/>.
+ /// </returns>
+ public IEnumerable<KeyValuePair<string, CryptoKey>> GetKeys(string bucket) {
+ return this.cryptoKeyStore.GetKeys(bucket);
+ }
+
+ /// <summary>
+ /// Stores a cryptographic key.
+ /// </summary>
+ /// <param name="bucket">The name of the bucket to store the key in. Case sensitive.</param>
+ /// <param name="handle">The handle to the key, unique within the bucket. Case sensitive.</param>
+ /// <param name="key">The key to store.</param>
+ /// <exception cref="CryptoKeyCollisionException">Thrown in the event of a conflict with an existing key in the same bucket and with the same handle.</exception>
+ public void StoreKey(string bucket, string handle, CryptoKey key) {
+ this.cryptoKeyStore.StoreKey(bucket, handle, key);
+ }
+
+ /// <summary>
+ /// Removes the key.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <param name="handle">The key handle. Case sensitive.</param>
+ public void RemoveKey(string bucket, string handle) {
+ this.cryptoKeyStore.RemoveKey(bucket, handle);
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth.OpenId.Provider/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth.OpenId.Provider/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..c90d56f
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.Provider/Properties/AssemblyInfo.cs
@@ -0,0 +1,54 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssemblyInfo.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+// We DON'T put an AssemblyVersionAttribute in here because it is generated in the build.
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Net;
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Security.Permissions;
+using System.Web.UI;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("DotNetOpenAuth OpenID")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DotNetOpenAuth")]
+[assembly: AssemblyCopyright("Copyright © 2008")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+[assembly: NeutralResourcesLanguage("en-US")]
+[assembly: CLSCompliant(true)]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("7d73990c-47c0-4256-9f20-a893add9e289")]
+
+[assembly: ContractVerification(true)]
+
+#if StrongNameSigned
+// See comment at top of this file. We need this so that strong-naming doesn't
+// keep this assembly from being useful to shared host (medium trust) web sites.
+[assembly: AllowPartiallyTrustedCallers]
+
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
+#else
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
+#endif
diff --git a/src/DotNetOpenAuth/ComponentModel/IdentifierConverter.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/ComponentModel/IdentifierConverter.cs
index 61c0fd8..61c0fd8 100644
--- a/src/DotNetOpenAuth/ComponentModel/IdentifierConverter.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/ComponentModel/IdentifierConverter.cs
diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/DotNetOpenAuth.OpenId.RelyingParty.UI.csproj b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/DotNetOpenAuth.OpenId.RelyingParty.UI.csproj
new file mode 100644
index 0000000..4d376bf
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/DotNetOpenAuth.OpenId.RelyingParty.UI.csproj
@@ -0,0 +1,87 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))\EnlistmentInfo.props" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))' != '' " />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" />
+ <PropertyGroup>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{1ED8D424-F8AB-4050-ACEB-F27F4F909484}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>DotNetOpenAuth</RootNamespace>
+ <AssemblyName>DotNetOpenAuth.OpenId.RelyingParty.UI</AssemblyName>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" />
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="ComponentModel\IdentifierConverter.cs" />
+ <Compile Include="OpenId\Mvc\OpenIdAjaxOptions.cs" />
+ <Compile Include="OpenId\Mvc\OpenIdHelper.cs" />
+ <Compile Include="OpenId\RelyingParty\OpenIdAjaxRelyingParty.cs" />
+ <Compile Include="OpenId\RelyingParty\OpenIdAjaxTextBox.cs" />
+ <Compile Include="OpenId\RelyingParty\OpenIdButton.cs" />
+ <Compile Include="OpenId\RelyingParty\OpenIdEventArgs.cs" />
+ <Compile Include="OpenId\RelyingParty\OpenIdLogin.cs" />
+ <Compile Include="OpenId\RelyingParty\OpenIdMobileTextBox.cs" Condition=" '$(ClrVersion)' != '4' "/>
+ <Compile Include="OpenId\RelyingParty\OpenIdRelyingPartyAjaxControlBase.cs" />
+ <Compile Include="OpenId\RelyingParty\OpenIdRelyingPartyControlBase.cs" />
+ <Compile Include="OpenId\RelyingParty\OpenIdSelector.cs" />
+ <Compile Include="OpenId\RelyingParty\OpenIdTextBox.cs" />
+ <Compile Include="OpenId\RelyingParty\PopupBehavior.cs" />
+ <Compile Include="OpenId\RelyingParty\SelectorButton.cs" />
+ <Compile Include="OpenId\RelyingParty\SelectorButtonContract.cs" />
+ <Compile Include="OpenId\RelyingParty\SelectorOpenIdButton.cs" />
+ <Compile Include="OpenId\RelyingParty\SelectorProviderButton.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\DotNetOpenAuth.Core.UI\DotNetOpenAuth.Core.UI.csproj">
+ <Project>{173E7B8D-E751-46E2-A133-F72297C0D2F4}</Project>
+ <Name>DotNetOpenAuth.Core.UI</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.Core\DotNetOpenAuth.Core.csproj">
+ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project>
+ <Name>DotNetOpenAuth.Core</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OpenId.RelyingParty\DotNetOpenAuth.OpenId.RelyingParty.csproj">
+ <Project>{F458AB60-BA1C-43D9-8CEF-EC01B50BE87B}</Project>
+ <Name>DotNetOpenAuth.OpenId.RelyingParty</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OpenId\DotNetOpenAuth.OpenId.csproj">
+ <Project>{3896A32A-E876-4C23-B9B8-78E17D134CD3}</Project>
+ <Name>DotNetOpenAuth.OpenId</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\Org.Mentalis.Security.Cryptography\Org.Mentalis.Security.Cryptography.csproj">
+ <Project>{26DC877F-5987-48DD-9DDB-E62F2DE0E150}</Project>
+ <Name>Org.Mentalis.Security.Cryptography</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <ItemGroup>
+ <Reference Include="System" />
+ </ItemGroup>
+ <ItemGroup>
+ <EmbeddedResource Include="OpenId\RelyingParty\login_failure.png" />
+ <EmbeddedResource Include="OpenId\RelyingParty\login_success %28lock%29.png" />
+ <EmbeddedResource Include="OpenId\RelyingParty\login_success.png" />
+ <EmbeddedResource Include="OpenId\RelyingParty\OpenIdAjaxTextBox.css" />
+ <EmbeddedResource Include="OpenId\RelyingParty\OpenIdAjaxTextBox.js" />
+ <EmbeddedResource Include="OpenId\RelyingParty\OpenIdRelyingPartyAjaxControlBase.js" />
+ <EmbeddedResource Include="OpenId\RelyingParty\OpenIdRelyingPartyControlBase.js" />
+ <EmbeddedResource Include="OpenId\RelyingParty\OpenIdSelector.css" />
+ <EmbeddedResource Include="OpenId\RelyingParty\OpenIdSelector.js" />
+ <EmbeddedResource Include="OpenId\RelyingParty\openid_login.png" />
+ <EmbeddedResource Include="OpenId\RelyingParty\spinner.gif" />
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="OpenId\RelyingParty\Controls.cd" />
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
+</Project> \ No newline at end of file
diff --git a/src/DotNetOpenAuth/Mvc/OpenIdAjaxOptions.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/Mvc/OpenIdAjaxOptions.cs
index 4b88d04..4b88d04 100644
--- a/src/DotNetOpenAuth/Mvc/OpenIdAjaxOptions.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/Mvc/OpenIdAjaxOptions.cs
diff --git a/src/DotNetOpenAuth/Mvc/OpenIdHelper.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/Mvc/OpenIdHelper.cs
index adde6b6..3325084 100644
--- a/src/DotNetOpenAuth/Mvc/OpenIdHelper.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/Mvc/OpenIdHelper.cs
@@ -33,7 +33,7 @@ namespace DotNetOpenAuth.Mvc {
/// <param name="html">The <see cref="HtmlHelper"/> on the view.</param>
/// <returns>HTML that should be sent directly to the browser.</returns>
public static string OpenIdSelectorStyles(this HtmlHelper html) {
- Contract.Requires<ArgumentNullException>(html != null);
+ Requires.NotNull(html, "html");
Contract.Ensures(Contract.Result<string>() != null);
using (var result = new StringWriter(CultureInfo.CurrentCulture)) {
@@ -63,7 +63,7 @@ namespace DotNetOpenAuth.Mvc {
/// </returns>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "False positive")]
public static string OpenIdSelectorScripts(this HtmlHelper html, OpenIdSelector selectorOptions, OpenIdAjaxOptions additionalOptions) {
- Contract.Requires<ArgumentNullException>(html != null);
+ Requires.NotNull(html, "html");
Contract.Ensures(Contract.Result<string>() != null);
bool selectorOptionsOwned = false;
@@ -117,7 +117,7 @@ window.openid_trace = {1}; // causes lots of messages";
// Positive assertions can last no longer than this library is willing to consider them valid,
// and when they come with OP private associations they last no longer than the OP is willing
// to consider them valid. We assume the OP will hold them valid for at least five minutes.
- double assertionLifetimeInMilliseconds = Math.Min(TimeSpan.FromMinutes(5).TotalMilliseconds, Math.Min(DotNetOpenAuthSection.Configuration.OpenId.MaxAuthenticationTime.TotalMilliseconds, DotNetOpenAuthSection.Configuration.Messaging.MaximumMessageLifetime.TotalMilliseconds));
+ double assertionLifetimeInMilliseconds = Math.Min(TimeSpan.FromMinutes(5).TotalMilliseconds, Math.Min(OpenIdElement.Configuration.MaxAuthenticationTime.TotalMilliseconds, DotNetOpenAuthSection.Messaging.MaximumMessageLifetime.TotalMilliseconds));
blockBuilder.WriteLine(
"{0} = {1};",
OpenIdRelyingPartyAjaxControlBase.MaxPositiveAssertionLifetimeJsName,
@@ -207,9 +207,9 @@ window.openid_trace = {1}; // causes lots of messages";
/// HTML that should be sent directly to the browser.
/// </returns>
public static string OpenIdSelectorOPButton(this HtmlHelper html, Identifier providerIdentifier, string imageUrl) {
- Contract.Requires<ArgumentNullException>(html != null);
- Contract.Requires<ArgumentNullException>(providerIdentifier != null);
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(imageUrl));
+ Requires.NotNull(html, "html");
+ Requires.NotNull(providerIdentifier, "providerIdentifier");
+ Requires.NotNullOrEmpty(imageUrl, "imageUrl");
Contract.Ensures(Contract.Result<string>() != null);
return OpenIdSelectorButton(html, providerIdentifier, "OPButton", imageUrl);
@@ -225,8 +225,8 @@ window.openid_trace = {1}; // causes lots of messages";
/// HTML that should be sent directly to the browser.
/// </returns>
public static string OpenIdSelectorOpenIdButton(this HtmlHelper html, string imageUrl) {
- Contract.Requires<ArgumentNullException>(html != null);
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(imageUrl));
+ Requires.NotNull(html, "html");
+ Requires.NotNullOrEmpty(imageUrl, "imageUrl");
Contract.Ensures(Contract.Result<string>() != null);
return OpenIdSelectorButton(html, "OpenIDButton", "OpenIDButton", imageUrl);
@@ -242,8 +242,8 @@ window.openid_trace = {1}; // causes lots of messages";
/// </returns>
[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "Not a problem for this type.")]
public static string OpenIdSelector(this HtmlHelper html, params SelectorButton[] buttons) {
- Contract.Requires<ArgumentNullException>(html != null);
- Contract.Requires<ArgumentNullException>(buttons != null);
+ Requires.NotNull(html, "html");
+ Requires.NotNull(buttons, "buttons");
Contract.Ensures(Contract.Result<string>() != null);
using (var writer = new StringWriter(CultureInfo.CurrentCulture)) {
@@ -307,9 +307,9 @@ window.openid_trace = {1}; // causes lots of messages";
/// </returns>
[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "Not a problem for this type.")]
private static string OpenIdSelectorButton(this HtmlHelper html, string id, string cssClass, string imageUrl) {
- Contract.Requires<ArgumentNullException>(html != null);
- Contract.Requires<ArgumentNullException>(id != null);
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(imageUrl));
+ Requires.NotNull(html, "html");
+ Requires.NotNull(id, "id");
+ Requires.NotNullOrEmpty(imageUrl, "imageUrl");
Contract.Ensures(Contract.Result<string>() != null);
using (var writer = new StringWriter(CultureInfo.CurrentCulture)) {
@@ -357,8 +357,8 @@ window.openid_trace = {1}; // causes lots of messages";
/// <param name="writer">The writer to emit the tags to.</param>
/// <param name="scriptUrls">The locations of the scripts to import.</param>
private static void WriteScriptTagsUrls(this TextWriter writer, IEnumerable<string> scriptUrls) {
- Contract.Requires<ArgumentNullException>(writer != null);
- Contract.Requires<ArgumentNullException>(scriptUrls != null);
+ Requires.NotNull(writer, "writer");
+ Requires.NotNull(scriptUrls, "scriptUrls");
foreach (string script in scriptUrls) {
writer.WriteLine("<script type='text/javascript' src='{0}'></script>", script);
@@ -371,8 +371,8 @@ window.openid_trace = {1}; // causes lots of messages";
/// <param name="writer">The writer to emit the tags to.</param>
/// <param name="resourceName">Name of the resource.</param>
private static void WriteScriptTags(this TextWriter writer, string resourceName) {
- Contract.Requires<ArgumentNullException>(writer != null);
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(resourceName));
+ Requires.NotNull(writer, "writer");
+ Requires.NotNullOrEmpty(resourceName, "resourceName");
WriteScriptTags(writer, new[] { resourceName });
}
@@ -383,8 +383,8 @@ window.openid_trace = {1}; // causes lots of messages";
/// <param name="writer">The writer to emit the tags to.</param>
/// <param name="resourceNames">The resource names.</param>
private static void WriteScriptTags(this TextWriter writer, IEnumerable<string> resourceNames) {
- Contract.Requires<ArgumentNullException>(writer != null);
- Contract.Requires<ArgumentNullException>(resourceNames != null);
+ Requires.NotNull(writer, "writer");
+ Requires.NotNull(resourceNames, "resourceNames");
writer.WriteScriptTagsUrls(resourceNames.Select(r => Util.GetWebResourceUrl(typeof(OpenIdRelyingPartyControlBase), r)));
}
@@ -395,8 +395,8 @@ window.openid_trace = {1}; // causes lots of messages";
/// <param name="writer">The writer to emit the tags to.</param>
/// <param name="script">The script to inline on the page.</param>
private static void WriteScriptBlock(this TextWriter writer, string script) {
- Contract.Requires<ArgumentNullException>(writer != null);
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(script));
+ Requires.NotNull(writer, "writer");
+ Requires.NotNullOrEmpty(script, "script");
writer.WriteLine("<script type='text/javascript' language='javascript'><!--");
writer.WriteLine("//<![CDATA[");
@@ -410,8 +410,8 @@ window.openid_trace = {1}; // causes lots of messages";
/// <param name="writer">The writer to emit the tags to.</param>
/// <param name="resourceName">Name of the resource containing the CSS content.</param>
private static void WriteStylesheetLink(this TextWriter writer, string resourceName) {
- Contract.Requires<ArgumentNullException>(writer != null);
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(resourceName));
+ Requires.NotNull(writer, "writer");
+ Requires.NotNullOrEmpty(resourceName, "resourceName");
WriteStylesheetLinkUrl(writer, Util.GetWebResourceUrl(typeof(OpenIdRelyingPartyAjaxControlBase), resourceName));
}
@@ -422,8 +422,8 @@ window.openid_trace = {1}; // causes lots of messages";
/// <param name="writer">The writer to emit the tags to.</param>
/// <param name="stylesheet">The stylesheet to link in.</param>
private static void WriteStylesheetLinkUrl(this TextWriter writer, string stylesheet) {
- Contract.Requires<ArgumentNullException>(writer != null);
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(stylesheet));
+ Requires.NotNull(writer, "writer");
+ Requires.NotNullOrEmpty(stylesheet, "stylesheet");
writer.WriteLine("<link rel='stylesheet' type='text/css' href='{0}' />", stylesheet);
}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/Controls.cd b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/Controls.cd
index f96db36..f96db36 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/Controls.cd
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/Controls.cd
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdAjaxRelyingParty.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxRelyingParty.cs
index 5978c21..8e915cd 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdAjaxRelyingParty.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxRelyingParty.cs
@@ -37,7 +37,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// Initializes a new instance of the <see cref="OpenIdAjaxRelyingParty"/> class.
/// </summary>
/// <param name="applicationStore">The application store. If <c>null</c>, the relying party will always operate in "dumb mode".</param>
- public OpenIdAjaxRelyingParty(IRelyingPartyApplicationStore applicationStore)
+ public OpenIdAjaxRelyingParty(IOpenIdApplicationStore applicationStore)
: base(applicationStore) {
Reporting.RecordFeatureUse(this);
}
@@ -92,7 +92,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
req.SetUntrustedCallbackArgument("index", (reqIndex++).ToString(CultureInfo.InvariantCulture));
// If the ReturnToUrl was explicitly set, we'll need to reset our first parameter
- if (DotNetOpenAuthSection.Configuration.OpenId.RelyingParty.PreserveUserSuppliedIdentifier) {
+ if (OpenIdElement.Configuration.RelyingParty.PreserveUserSuppliedIdentifier) {
if (string.IsNullOrEmpty(HttpUtility.ParseQueryString(req.ReturnToUrl.Query)[AuthenticationRequest.UserSuppliedIdentifierParameterName])) {
req.SetUntrustedCallbackArgument(AuthenticationRequest.UserSuppliedIdentifierParameterName, userSuppliedIdentifier.OriginalString);
}
@@ -143,7 +143,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </code>
/// </remarks>
public OutgoingWebResponse AsAjaxDiscoveryResult(IEnumerable<IAuthenticationRequest> requests) {
- Contract.Requires<ArgumentNullException>(requests != null);
+ Requires.NotNull(requests, "requests");
var serializer = new JavaScriptSerializer();
return new OutgoingWebResponse {
@@ -160,7 +160,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// The JSON result to return to the user agent.
/// </returns>
public string AsAjaxPreloadedDiscoveryResult(IEnumerable<IAuthenticationRequest> requests) {
- Contract.Requires<ArgumentNullException>(requests != null);
+ Requires.NotNull(requests, "requests");
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(this.AsJsonPreloadedDiscoveryResult(requests));
@@ -175,7 +175,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <param name="requests">The discovery results from just <i>one</i> identifier to serialize as a JSON response.</param>
/// <returns>A JSON object, not yet serialized.</returns>
internal object AsJsonDiscoveryResult(IEnumerable<IAuthenticationRequest> requests) {
- Contract.Requires<ArgumentNullException>(requests != null);
+ Requires.NotNull(requests, "requests");
requests = requests.CacheGeneratedResults();
@@ -205,7 +205,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// A JSON object, not yet serialized to a string.
/// </returns>
private object AsJsonPreloadedDiscoveryResult(IEnumerable<IAuthenticationRequest> requests) {
- Contract.Requires<ArgumentNullException>(requests != null);
+ Requires.NotNull(requests, "requests");
// We prepare a JSON object with this interface:
// Array discoveryWrappers;
@@ -233,7 +233,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <c>false</c> to create a checkid_setup request.</param>
/// <returns>The absolute URL that carries the entire OpenID message.</returns>
private Uri GetRedirectUrl(IAuthenticationRequest request, bool immediate) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
request.Mode = immediate ? AuthenticationRequestMode.Immediate : AuthenticationRequestMode.Setup;
return request.RedirectingResponse.GetDirectUriRequest(this.Channel);
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdAjaxTextBox.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxTextBox.cs
index 8be097f..5440be8 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdAjaxTextBox.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxTextBox.cs
@@ -382,7 +382,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
}
set {
- Contract.Requires<ArgumentOutOfRangeException>(value >= 0);
+ Requires.InRange(value >= 0, "value");
this.ViewState[ColumnsViewStateKey] = value;
}
}
@@ -430,7 +430,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
}
set {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(value));
+ Requires.NotNullOrEmpty(value, "value");
this.ViewState[NameViewStateKey] = value ?? string.Empty;
}
}
@@ -446,7 +446,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
}
set {
- Contract.Requires<ArgumentOutOfRangeException>(value.TotalMilliseconds > 0);
+ Requires.InRange(value.TotalMilliseconds > 0, "value");
this.ViewState[TimeoutViewStateKey] = value;
}
}
@@ -462,7 +462,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
}
set {
- Contract.Requires<ArgumentOutOfRangeException>(value > 0);
+ Requires.InRange(value > 0, "value");
this.ViewState[ThrottleViewStateKey] = value;
}
}
@@ -478,7 +478,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
}
set {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(value));
+ Requires.NotNullOrEmpty(value, "value");
this.ViewState[LogOnTextViewStateKey] = value ?? string.Empty;
}
}
@@ -514,7 +514,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
}
set {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(value));
+ Requires.NotNullOrEmpty(value, "value");
this.ViewState[RetryTextViewStateKey] = value ?? string.Empty;
}
}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdAjaxTextBox.css b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxTextBox.css
index bed2e79..bed2e79 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdAjaxTextBox.css
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxTextBox.css
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdAjaxTextBox.js b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxTextBox.js
index 9907b4e..9907b4e 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdAjaxTextBox.js
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxTextBox.js
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdButton.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdButton.cs
index 6243917..6243917 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdButton.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdButton.cs
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdEventArgs.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdEventArgs.cs
index 5668cf4..cf38b61 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdEventArgs.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdEventArgs.cs
@@ -22,7 +22,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <param name="request">The outgoing authentication request.</param>
internal OpenIdEventArgs(IAuthenticationRequest request) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
this.Request = request;
this.ClaimedIdentifier = request.ClaimedIdentifier;
@@ -36,7 +36,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <param name="response">The incoming authentication response.</param>
internal OpenIdEventArgs(IAuthenticationResponse response) {
- Contract.Requires<ArgumentNullException>(response != null);
+ Requires.NotNull(response, "response");
this.Response = response;
this.ClaimedIdentifier = response.ClaimedIdentifier;
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdLogin.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdLogin.cs
index eccdacf..e65b3f4 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdLogin.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdLogin.cs
@@ -1,4 +1,4 @@
-//-----------------------------------------------------------------------
+//-----------------------------------------------------------------------
// <copyright file="OpenIdLogin.cs" company="Andrew Arnott">
// Copyright (c) Andrew Arnott. All rights reserved.
// </copyright>
@@ -38,7 +38,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <summary>
/// The default value for the <see cref="ButtonText"/> property.
/// </summary>
- private const string ButtonTextDefault = "Login ";
+ private const string ButtonTextDefault = "Login »";
/// <summary>
/// The default value for the <see cref="CanceledText"/> property.
@@ -622,7 +622,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
[Category("Behavior")]
[Description("The unique hash string that ends your idselector.com account.")]
public string IdSelectorIdentifier {
- get { return (string)(ViewState[IdSelectorIdentifierViewStateKey]); }
+ get { return (string)ViewState[IdSelectorIdentifierViewStateKey]; }
set { ViewState[IdSelectorIdentifierViewStateKey] = value; }
}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdMobileTextBox.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdMobileTextBox.cs
index 8684bd1..d4b6769 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdMobileTextBox.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdMobileTextBox.cs
@@ -524,7 +524,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// If set, this property must be set in each Page Load event
/// as it is not persisted across postbacks.
/// </remarks>
- public IRelyingPartyApplicationStore CustomApplicationStore { get; set; }
+ public IOpenIdApplicationStore CustomApplicationStore { get; set; }
#endregion
@@ -583,8 +583,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </remarks>
[SuppressMessage("Microsoft.Usage", "CA2234:PassSystemUriObjectsInsteadOfStrings", Justification = "Uri(Uri, string) accepts second arguments that Uri(Uri, new Uri(string)) does not that we must support.")]
public IAuthenticationRequest CreateRequest() {
- Contract.Requires<InvalidOperationException>(this.Request == null, OpenIdStrings.CreateRequestAlreadyCalled);
- Contract.Requires<InvalidOperationException>(!string.IsNullOrEmpty(this.Text), OpenIdStrings.OpenIdTextBoxEmpty);
+ Requires.ValidState(this.Request == null, OpenIdStrings.CreateRequestAlreadyCalled);
+ Requires.ValidState(!string.IsNullOrEmpty(this.Text), OpenIdStrings.OpenIdTextBoxEmpty);
try {
// Resolve the trust root, and swap out the scheme and port if necessary to match the
@@ -669,7 +669,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <param name="response">The response.</param>
protected virtual void OnLoggedIn(IAuthenticationResponse response) {
- Contract.Requires<ArgumentNullException>(response != null);
+ Requires.NotNull(response, "response");
ErrorUtilities.VerifyInternal(response.Status == AuthenticationStatus.Authenticated, "Firing OnLoggedIn event without an authenticated response.");
var loggedIn = this.LoggedIn;
@@ -688,7 +688,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <param name="response">The response.</param>
protected virtual void OnFailed(IAuthenticationResponse response) {
- Contract.Requires<ArgumentNullException>(response != null);
+ Requires.NotNull(response, "response");
ErrorUtilities.VerifyInternal(response.Status == AuthenticationStatus.Failed, "Firing Failed event for the wrong response type.");
var failed = this.Failed;
@@ -702,7 +702,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <param name="response">The response.</param>
protected virtual void OnCanceled(IAuthenticationResponse response) {
- Contract.Requires<ArgumentNullException>(response != null);
+ Requires.NotNull(response, "response");
ErrorUtilities.VerifyInternal(response.Status == AuthenticationStatus.Canceled, "Firing Canceled event for the wrong response type.");
var canceled = this.Canceled;
@@ -716,7 +716,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <param name="response">The response.</param>
protected virtual void OnSetupRequired(IAuthenticationResponse response) {
- Contract.Requires<ArgumentNullException>(response != null);
+ Requires.NotNull(response, "response");
ErrorUtilities.VerifyInternal(response.Status == AuthenticationStatus.SetupRequired, "Firing SetupRequired event for the wrong response type.");
// Why are we firing Failed when we're OnSetupRequired? Backward compatibility.
@@ -734,7 +734,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <param name="request">The authentication request to add the extensions to.</param>
private void AddProfileArgs(IAuthenticationRequest request) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
request.AddExtension(new ClaimsRequest() {
Nickname = this.RequestNickname,
@@ -759,8 +759,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
// If we're in stateful mode, first use the explicitly given one 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 OpenIdRelyingParty.
- IRelyingPartyApplicationStore store = this.Stateless ? null :
- (this.CustomApplicationStore ?? DotNetOpenAuthSection.Configuration.OpenId.RelyingParty.ApplicationStore.CreateInstance(OpenIdRelyingParty.HttpApplicationStore));
+ IOpenIdApplicationStore store = this.Stateless ? null :
+ (this.CustomApplicationStore ?? OpenIdElement.Configuration.RelyingParty.ApplicationStore.CreateInstance(OpenIdRelyingParty.HttpApplicationStore));
var rp = new OpenIdRelyingParty(store);
try {
// Only set RequireSsl to true, as we don't want to override
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingPartyAjaxControlBase.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyAjaxControlBase.cs
index f22645f..e83cf0e 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingPartyAjaxControlBase.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyAjaxControlBase.cs
@@ -241,7 +241,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </remarks>
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "By design")]
public void RegisterClientScriptExtension<T>(string propertyName) where T : IClientScriptExtensionResponse {
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(propertyName));
+ Requires.NotNullOrEmpty(propertyName, "propertyName");
this.RelyingParty.RegisterClientScriptExtension<T>(propertyName);
}
@@ -301,7 +301,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <param name="store">The store to pass to the relying party constructor.</param>
/// <returns>The instantiated relying party.</returns>
- protected override OpenIdRelyingParty CreateRelyingParty(IRelyingPartyApplicationStore store) {
+ protected override OpenIdRelyingParty CreateRelyingParty(IOpenIdApplicationStore store) {
return new OpenIdAjaxRelyingParty(store);
}
@@ -386,7 +386,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
// Positive assertions can last no longer than this library is willing to consider them valid,
// and when they come with OP private associations they last no longer than the OP is willing
// to consider them valid. We assume the OP will hold them valid for at least five minutes.
- double assertionLifetimeInMilliseconds = Math.Min(TimeSpan.FromMinutes(5).TotalMilliseconds, Math.Min(DotNetOpenAuthSection.Configuration.OpenId.MaxAuthenticationTime.TotalMilliseconds, DotNetOpenAuthSection.Configuration.Messaging.MaximumMessageLifetime.TotalMilliseconds));
+ double assertionLifetimeInMilliseconds = Math.Min(TimeSpan.FromMinutes(5).TotalMilliseconds, Math.Min(OpenIdElement.Configuration.MaxAuthenticationTime.TotalMilliseconds, DotNetOpenAuthSection.Messaging.MaximumMessageLifetime.TotalMilliseconds));
initScript.AppendLine(MaxPositiveAssertionLifetimeJsName + " = " + assertionLifetimeInMilliseconds.ToString(CultureInfo.InvariantCulture) + ";");
// We register this callback code explicitly with a specific type rather than the derived-type of the control
@@ -436,7 +436,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <param name="async">if set to <c>true</c> causes the AJAX callback to be a little more asynchronous. Note that <c>false</c> does not mean the call is absolutely synchronous.</param>
/// <returns>The string defining a javascript anonymous function that initiates a callback.</returns>
- private string GetJsCallbackConvenienceFunction(bool async) {
+ private string GetJsCallbackConvenienceFunction(bool @async) {
string argumentParameterName = "argument";
string callbackResultParameterName = "resultFunction";
string callbackErrorCallbackParameterName = "errorCallback";
@@ -446,7 +446,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
callbackResultParameterName,
argumentParameterName,
callbackErrorCallbackParameterName,
- async);
+ @async);
return string.Format(
CultureInfo.InvariantCulture,
"function({1}, {2}, {3}) {{{0}\treturn {4};{0}}};",
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingPartyAjaxControlBase.js b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyAjaxControlBase.js
index 4de5188..4de5188 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingPartyAjaxControlBase.js
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyAjaxControlBase.js
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingPartyControlBase.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyControlBase.cs
index 7cda8e0..c86ee1d 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingPartyControlBase.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyControlBase.cs
@@ -359,7 +359,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
}
set {
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(value));
+ Requires.NotNullOrEmpty(value, "value");
if (Page != null && !DesignMode) {
// Validate new value by trying to construct a Realm object based on it.
@@ -522,7 +522,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <param name="request">The request.</param>
public void LogOn(IAuthenticationRequest request) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
if (this.IsPopupAppropriate(request)) {
this.ScriptPopupWindow(request);
@@ -562,7 +562,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// used to determine the user's control of the <see cref="IAuthenticationRequest.ClaimedIdentifier"/>.
/// </returns>
protected internal virtual IEnumerable<IAuthenticationRequest> CreateRequests(Identifier identifier) {
- Contract.Requires<ArgumentNullException>(identifier != null);
+ Requires.NotNull(identifier, "identifier");
// If this control is actually a member of another OpenID RP control,
// delegate creation of requests to the parent control.
@@ -604,7 +604,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// used to determine the user's control of the <see cref="IAuthenticationRequest.ClaimedIdentifier"/>.
/// </returns>
protected IEnumerable<IAuthenticationRequest> CreateRequests() {
- Contract.Requires<InvalidOperationException>(this.Identifier != null, OpenIdStrings.NoIdentifierSet);
+ Requires.ValidState(this.Identifier != null, OpenIdStrings.NoIdentifierSet);
return this.CreateRequests(this.Identifier);
}
@@ -714,8 +714,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <param name="response">The response.</param>
protected virtual void OnLoggedIn(IAuthenticationResponse response) {
- Contract.Requires<ArgumentNullException>(response != null);
- Contract.Requires<ArgumentException>(response.Status == AuthenticationStatus.Authenticated);
+ Requires.NotNull(response, "response");
+ Requires.True(response.Status == AuthenticationStatus.Authenticated, "response");
var loggedIn = this.LoggedIn;
OpenIdEventArgs args = new OpenIdEventArgs(response);
@@ -747,7 +747,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// Returns whether the login should proceed. False if some event handler canceled the request.
/// </returns>
protected virtual bool OnLoggingIn(IAuthenticationRequest request) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
EventHandler<OpenIdEventArgs> loggingIn = this.LoggingIn;
@@ -764,8 +764,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <param name="response">The response.</param>
protected virtual void OnCanceled(IAuthenticationResponse response) {
- Contract.Requires<ArgumentNullException>(response != null);
- Contract.Requires<ArgumentException>(response.Status == AuthenticationStatus.Canceled);
+ Requires.NotNull(response, "response");
+ Requires.True(response.Status == AuthenticationStatus.Canceled, "response");
var canceled = this.Canceled;
if (canceled != null) {
@@ -778,8 +778,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <param name="response">The response.</param>
protected virtual void OnFailed(IAuthenticationResponse response) {
- Contract.Requires<ArgumentNullException>(response != null);
- Contract.Requires<ArgumentException>(response.Status == AuthenticationStatus.Failed);
+ Requires.NotNull(response, "response");
+ Requires.True(response.Status == AuthenticationStatus.Failed, "response");
var failed = this.Failed;
if (failed != null) {
@@ -792,7 +792,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <returns>The instantiated relying party.</returns>
protected OpenIdRelyingParty CreateRelyingParty() {
- IRelyingPartyApplicationStore store = this.Stateless ? null : DotNetOpenAuthSection.Configuration.OpenId.RelyingParty.ApplicationStore.CreateInstance(OpenIdRelyingParty.HttpApplicationStore);
+ IOpenIdApplicationStore store = this.Stateless ? null : OpenIdElement.Configuration.RelyingParty.ApplicationStore.CreateInstance(OpenIdRelyingParty.HttpApplicationStore);
return this.CreateRelyingParty(store);
}
@@ -801,7 +801,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <param name="store">The store to pass to the relying party constructor.</param>
/// <returns>The instantiated relying party.</returns>
- protected virtual OpenIdRelyingParty CreateRelyingParty(IRelyingPartyApplicationStore store) {
+ protected virtual OpenIdRelyingParty CreateRelyingParty(IOpenIdApplicationStore store) {
return new OpenIdRelyingParty(store);
}
@@ -811,7 +811,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <param name="relyingParty">The relying party.</param>
[SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "relyingParty", Justification = "This makes it possible for overrides to see the value before it is set on a field.")]
protected virtual void ConfigureRelyingParty(OpenIdRelyingParty relyingParty) {
- Contract.Requires<ArgumentNullException>(relyingParty != null);
+ Requires.NotNull(relyingParty, "relyingParty");
// Only set RequireSsl to true, as we don't want to override
// a .config setting of true with false.
@@ -828,7 +828,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <c>true</c> if a popup should be used; <c>false</c> otherwise.
/// </returns>
protected virtual bool IsPopupAppropriate(IAuthenticationRequest request) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
switch (this.Popup) {
case PopupBehavior.Never:
@@ -850,8 +850,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <param name="request">The outgoing authentication request.</param>
/// <param name="windowStatus">The text to try to display in the status bar on mouse hover.</param>
protected void RenderOpenIdMessageTransmissionAsAnchorAttributes(HtmlTextWriter writer, IAuthenticationRequest request, string windowStatus) {
- Contract.Requires<ArgumentNullException>(writer != null);
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(writer, "writer");
+ Requires.NotNull(request, "request");
// We render a standard HREF attribute for non-javascript browsers.
writer.AddAttribute(HtmlTextWriterAttribute.Href, request.RedirectingResponse.GetDirectUriRequest(this.RelyingParty.Channel).AbsoluteUri);
@@ -983,7 +983,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
// Apply the control's association preference to this auth request, but only if
// it is less demanding (greater ordinal value) than the existing one.
// That way, we protect against retrying an association that was already attempted.
- var authReq = ((AuthenticationRequest)req);
+ var authReq = (AuthenticationRequest)req;
if (authReq.AssociationPreference < this.AssociationPreference) {
authReq.AssociationPreference = this.AssociationPreference;
}
@@ -1004,7 +1004,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <param name="request">The authentication request to send.</param>
/// <returns>The javascript that should execute.</returns>
private string CreateGetOrPostAHrefValue(IAuthenticationRequest request) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
Uri directUri = request.RedirectingResponse.GetDirectUriRequest(this.RelyingParty.Channel);
return "window.dnoa_internal.GetOrPost(" + MessagingUtilities.GetSafeJavascriptValue(directUri.AbsoluteUri) + ");";
@@ -1015,8 +1015,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <param name="request">The request.</param>
private void ScriptPopupWindow(IAuthenticationRequest request) {
- Contract.Requires<ArgumentNullException>(request != null);
- Contract.Requires<InvalidOperationException>(this.RelyingParty != null);
+ Requires.NotNull(request, "request");
+ Requires.ValidState(this.RelyingParty != null);
StringBuilder startupScript = new StringBuilder();
@@ -1027,7 +1027,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
startupScript.AppendLine("window.dnoa_internal.popupWindow = function() {");
startupScript.AppendFormat(
@"\tvar openidPopup = {0}",
- UIUtilities.GetWindowPopupScript(this.RelyingParty, request, "openidPopup"));
+ OpenId.RelyingParty.Extensions.UI.UIUtilities.GetWindowPopupScript(this.RelyingParty, request, "openidPopup"));
startupScript.AppendLine("};");
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "loginPopup", startupScript.ToString(), true);
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingPartyControlBase.js b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyControlBase.js
index 58b283d..58b283d 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingPartyControlBase.js
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyControlBase.js
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdSelector.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdSelector.cs
index 538e181..e666e4e 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdSelector.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdSelector.cs
@@ -22,7 +22,6 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using DotNetOpenAuth.ComponentModel;
- using DotNetOpenAuth.InfoCard;
using DotNetOpenAuth.Messaging;
/// <summary>
@@ -86,16 +85,6 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
}
/// <summary>
- /// Occurs when an InfoCard has been submitted and decoded.
- /// </summary>
- public event EventHandler<ReceivedTokenEventArgs> ReceivedToken;
-
- /// <summary>
- /// Occurs when [token processing error].
- /// </summary>
- public event EventHandler<TokenProcessingErrorEventArgs> TokenProcessingError;
-
- /// <summary>
/// Gets the text box where applicable.
/// </summary>
public OpenIdAjaxTextBox TextBox {
@@ -270,16 +259,6 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
return;
}
- var selectorButton = this.Buttons.OfType<SelectorInfoCardButton>().FirstOrDefault();
- if (selectorButton != null) {
- var selector = selectorButton.InfoCardSelector;
- selector.ClaimsRequested.Add(new ClaimType { Name = ClaimTypes.PPID });
- selector.ImageSize = InfoCardImageSize.Size60x42;
- selector.ReceivedToken += this.InfoCardSelector_ReceivedToken;
- selector.TokenProcessingError += this.InfoCardSelector_TokenProcessingError;
- this.Controls.Add(selector);
- }
-
this.textBox = new OpenIdAjaxTextBox();
this.textBox.ID = "openid_identifier";
this.textBox.HookFormSubmit = false;
@@ -392,55 +371,6 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
}
/// <summary>
- /// Fires the <see cref="ReceivedToken"/> event.
- /// </summary>
- /// <param name="e">The token, if it was decrypted.</param>
- protected virtual void OnReceivedToken(ReceivedTokenEventArgs e) {
- Contract.Requires(e != null);
- ErrorUtilities.VerifyArgumentNotNull(e, "e");
-
- var receivedInfoCard = this.ReceivedToken;
- if (receivedInfoCard != null) {
- receivedInfoCard(this, e);
- }
- }
-
- /// <summary>
- /// Raises the <see cref="E:TokenProcessingError"/> event.
- /// </summary>
- /// <param name="e">The <see cref="DotNetOpenAuth.InfoCard.TokenProcessingErrorEventArgs"/> instance containing the event data.</param>
- protected virtual void OnTokenProcessingError(TokenProcessingErrorEventArgs e) {
- Contract.Requires(e != null);
- ErrorUtilities.VerifyArgumentNotNull(e, "e");
-
- var tokenProcessingError = this.TokenProcessingError;
- if (tokenProcessingError != null) {
- tokenProcessingError(this, e);
- }
- }
-
- /// <summary>
- /// Handles the ReceivedToken event of the infoCardSelector control.
- /// </summary>
- /// <param name="sender">The source of the event.</param>
- /// <param name="e">The <see cref="DotNetOpenAuth.InfoCard.ReceivedTokenEventArgs"/> instance containing the event data.</param>
- private void InfoCardSelector_ReceivedToken(object sender, ReceivedTokenEventArgs e) {
- this.Page.Response.SetCookie(new HttpCookie("openid_identifier", "infocard") {
- Path = this.Page.Request.ApplicationPath,
- });
- this.OnReceivedToken(e);
- }
-
- /// <summary>
- /// Handles the TokenProcessingError event of the infoCardSelector control.
- /// </summary>
- /// <param name="sender">The source of the event.</param>
- /// <param name="e">The <see cref="DotNetOpenAuth.InfoCard.TokenProcessingErrorEventArgs"/> instance containing the event data.</param>
- private void InfoCardSelector_TokenProcessingError(object sender, TokenProcessingErrorEventArgs e) {
- this.OnTokenProcessingError(e);
- }
-
- /// <summary>
/// Ensures the <see cref="Buttons"/> collection has a valid set of buttons.
/// </summary>
private void EnsureValidButtons() {
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdSelector.css b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdSelector.css
index e7eafc7..e7eafc7 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdSelector.css
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdSelector.css
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdSelector.js b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdSelector.js
index 297ea23..297ea23 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdSelector.js
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdSelector.js
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdTextBox.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdTextBox.cs
index 335b435..1dea39a 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdTextBox.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdTextBox.cs
@@ -683,7 +683,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <param name="request">The authentication request to add the extensions to.</param>
private void AddProfileArgs(IAuthenticationRequest request) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
var sreg = new ClaimsRequest() {
Nickname = this.RequestNickname,
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/PopupBehavior.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/PopupBehavior.cs
index e84f4f5..e84f4f5 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/PopupBehavior.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/PopupBehavior.cs
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/SelectorButton.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/SelectorButton.cs
index 0be3a5f..0be3a5f 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/SelectorButton.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/SelectorButton.cs
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/SelectorButtonContract.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/SelectorButtonContract.cs
index c70218a..709ad2d 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/SelectorButtonContract.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/SelectorButtonContract.cs
@@ -30,7 +30,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <param name="writer">The writer.</param>
protected internal override void RenderLeadingAttributes(HtmlTextWriter writer) {
- Contract.Requires<ArgumentNullException>(writer != null);
+ Requires.NotNull(writer, "writer");
}
/// <summary>
@@ -39,8 +39,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <param name="writer">The writer.</param>
/// <param name="selector">The containing selector control.</param>
protected internal override void RenderButtonContent(HtmlTextWriter writer, OpenIdSelector selector) {
- Contract.Requires<ArgumentNullException>(writer != null);
- Contract.Requires<ArgumentNullException>(selector != null);
+ Requires.NotNull(writer, "writer");
+ Requires.NotNull(selector, "selector");
}
}
}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/SelectorOpenIdButton.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/SelectorOpenIdButton.cs
index ac4dcbf..26b10e8 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/SelectorOpenIdButton.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/SelectorOpenIdButton.cs
@@ -30,7 +30,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <param name="imageUrl">The image to display on the button.</param>
public SelectorOpenIdButton(string imageUrl)
: this() {
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(imageUrl));
+ Requires.NotNullOrEmpty(imageUrl, "imageUrl");
this.Image = imageUrl;
}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/SelectorProviderButton.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/SelectorProviderButton.cs
index 2195e73..efd6c50 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/SelectorProviderButton.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/SelectorProviderButton.cs
@@ -32,8 +32,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <param name="imageUrl">The image to display on the button.</param>
public SelectorProviderButton(Identifier providerIdentifier, string imageUrl)
: this() {
- Contract.Requires<ArgumentNullException>(providerIdentifier != null);
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(imageUrl));
+ Requires.NotNull(providerIdentifier, "providerIdentifier");
+ Requires.NotNullOrEmpty(imageUrl, "imageUrl");
this.OPIdentifier = providerIdentifier;
this.Image = imageUrl;
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/login_failure.png b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/login_failure.png
index 8003700..8003700 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/login_failure.png
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/login_failure.png
Binary files differ
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/login_success (lock).png b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/login_success (lock).png
index bc0c0c8..bc0c0c8 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/login_success (lock).png
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/login_success (lock).png
Binary files differ
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/login_success.png b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/login_success.png
index 0ae1365..0ae1365 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/login_success.png
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/login_success.png
Binary files differ
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/openid_login.png b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/openid_login.png
index caebd58..caebd58 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/openid_login.png
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/openid_login.png
Binary files differ
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/spinner.gif b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/spinner.gif
index 9cb298e..9cb298e 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/spinner.gif
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/spinner.gif
Binary files differ
diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..2b8f823
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/Properties/AssemblyInfo.cs
@@ -0,0 +1,60 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssemblyInfo.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+// We DON'T put an AssemblyVersionAttribute in here because it is generated in the build.
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Net;
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Security.Permissions;
+using System.Web.UI;
+
+[assembly: TagPrefix("DotNetOpenAuth.OpenId.RelyingParty", "rp")]
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("DotNetOpenAuth OpenID")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DotNetOpenAuth")]
+[assembly: AssemblyCopyright("Copyright © 2008")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+[assembly: NeutralResourcesLanguage("en-US")]
+[assembly: CLSCompliant(true)]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("7d73990c-47c0-4256-9f20-a893add9e289")]
+
+[assembly: ContractVerification(true)]
+
+#if StrongNameSigned
+// See comment at top of this file. We need this so that strong-naming doesn't
+// keep this assembly from being useful to shared host (medium trust) web sites.
+[assembly: AllowPartiallyTrustedCallers]
+
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenIdInfoCard.UI, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
+#else
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenIdInfoCard.UI")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
+#endif
diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/DotNetOpenAuth.OpenId.RelyingParty.csproj b/src/DotNetOpenAuth.OpenId.RelyingParty/DotNetOpenAuth.OpenId.RelyingParty.csproj
new file mode 100644
index 0000000..6fa3076
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/DotNetOpenAuth.OpenId.RelyingParty.csproj
@@ -0,0 +1,88 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))\EnlistmentInfo.props" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))' != '' " />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" />
+ <PropertyGroup>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{F458AB60-BA1C-43D9-8CEF-EC01B50BE87B}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>DotNetOpenAuth</RootNamespace>
+ <AssemblyName>DotNetOpenAuth.OpenId.RelyingParty</AssemblyName>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" />
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="OpenId\RelyingParty\Behaviors\AXFetchAsSregTransform.cs" />
+ <Compile Include="OpenId\RelyingParty\Behaviors\GsaIcamProfile.cs" />
+ <Compile Include="OpenId\ChannelElements\ExtensionsBindingElementRelyingParty.cs" />
+ <Compile Include="OpenId\ChannelElements\OpenIdRelyingPartyChannel.cs" />
+ <Compile Include="OpenId\ChannelElements\OpenIdRelyingPartyMessageFactory.cs" />
+ <Compile Include="OpenId\ChannelElements\RelyingPartySecurityOptions.cs" />
+ <Compile Include="OpenId\ChannelElements\RelyingPartySigningBindingElement.cs" />
+ <Compile Include="OpenId\ChannelElements\ReturnToNonceBindingElement.cs" />
+ <Compile Include="OpenId\RelyingParty\Extensions\ExtensionsInteropHelper.cs" />
+ <Compile Include="OpenId\HostMetaDiscoveryService.cs" />
+ <Compile Include="OpenId\Interop\AuthenticationResponseShim.cs" />
+ <Compile Include="OpenId\Interop\ClaimsResponseShim.cs" />
+ <Compile Include="OpenId\Interop\OpenIdRelyingPartyShim.cs" />
+ <Compile Include="OpenId\Messages\AssociateDiffieHellmanRelyingPartyResponse.cs" Condition=" '$(ExcludeDiffieHellman)' != 'true' " />
+ <Compile Include="OpenId\Messages\AssociateRequestRelyingParty.cs" />
+ <Compile Include="OpenId\Messages\AssociateSuccessfulResponseRelyingPartyContract.cs" />
+ <Compile Include="OpenId\Messages\IAssociateSuccessfulResponseRelyingParty.cs" />
+ <Compile Include="OpenId\Messages\AssociateUnencryptedResponseRelyingParty.cs" />
+ <Compile Include="OpenId\RelyingParty\CryptoKeyStoreAsRelyingPartyAssociationStore.cs" />
+ <Compile Include="OpenId\RelyingParty\Extensions\UIUtilities.cs" />
+ <Compile Include="OpenId\RelyingParty\IRelyingPartyAssociationStore.cs" />
+ <Compile Include="OpenId\RelyingParty\Associations.cs" />
+ <Compile Include="OpenId\RelyingParty\AssociationManager.cs" />
+ <Compile Include="OpenId\RelyingParty\AssociationPreference.cs" />
+ <Compile Include="OpenId\RelyingParty\AuthenticationRequest.cs" />
+ <Compile Include="OpenId\RelyingParty\DuplicateRequestedHostsComparer.cs" />
+ <Compile Include="OpenId\RelyingParty\NegativeAuthenticationResponse.cs" />
+ <Compile Include="OpenId\RelyingParty\PositiveAnonymousResponse.cs" />
+ <Compile Include="OpenId\RelyingParty\PositiveAuthenticationResponse.cs" />
+ <Compile Include="OpenId\RelyingParty\FailedAuthenticationResponse.cs" />
+ <Compile Include="OpenId\RelyingParty\ISetupRequiredAuthenticationResponse.cs" />
+ <Compile Include="OpenId\RelyingParty\OpenIdRelyingParty.cs" />
+ <Compile Include="OpenId\RelyingParty\PositiveAuthenticationResponseSnapshot.cs" />
+ <Compile Include="OpenId\RelyingParty\SimpleXrdsProviderEndpoint.cs" />
+ <Compile Include="OpenId\RelyingParty\StandardRelyingPartyApplicationStore.cs" />
+ <Compile Include="OpenId\RelyingParty\WellKnownProviders.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="OpenId\RelyingParty\OpenIdRelyingParty.cd" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\DotNetOpenAuth.Core\DotNetOpenAuth.Core.csproj">
+ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project>
+ <Name>DotNetOpenAuth.Core</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OpenId\DotNetOpenAuth.OpenId.csproj">
+ <Project>{3896A32A-E876-4C23-B9B8-78E17D134CD3}</Project>
+ <Name>DotNetOpenAuth.OpenId</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\Org.Mentalis.Security.Cryptography\Org.Mentalis.Security.Cryptography.csproj" Condition=" '$(ExcludeDiffieHellman)' != 'true' ">
+ <Project>{26DC877F-5987-48DD-9DDB-E62F2DE0E150}</Project>
+ <Name>Org.Mentalis.Security.Cryptography</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <ItemGroup>
+ <Reference Include="System" />
+ </ItemGroup>
+ <ItemGroup>
+ <Folder Include="ComponentModel\" />
+ <Folder Include="Configuration\" />
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
+</Project> \ No newline at end of file
diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/ExtensionsBindingElementRelyingParty.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/ExtensionsBindingElementRelyingParty.cs
new file mode 100644
index 0000000..099573d
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/ExtensionsBindingElementRelyingParty.cs
@@ -0,0 +1,38 @@
+//-----------------------------------------------------------------------
+// <copyright file="ExtensionsBindingElementRelyingParty.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.OpenId.RelyingParty;
+
+ /// <summary>
+ /// The OpenID binding element responsible for reading/writing OpenID extensions
+ /// at the Relying Party.
+ /// </summary>
+ internal class ExtensionsBindingElementRelyingParty : ExtensionsBindingElement {
+ /// <summary>
+ /// The security settings that apply to this relying party, if it is a relying party.
+ /// </summary>
+ private readonly RelyingPartySecuritySettings relyingPartySecuritySettings;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ExtensionsBindingElementRelyingParty"/> class.
+ /// </summary>
+ /// <param name="extensionFactory">The extension factory.</param>
+ /// <param name="securitySettings">The security settings.</param>
+ internal ExtensionsBindingElementRelyingParty(IOpenIdExtensionFactory extensionFactory, RelyingPartySecuritySettings securitySettings)
+ : base(extensionFactory, securitySettings, !securitySettings.IgnoreUnsignedExtensions) {
+ Requires.NotNull(extensionFactory, "extensionFactory");
+ Requires.NotNull(securitySettings, "securitySettings");
+
+ this.relyingPartySecuritySettings = securitySettings;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/OpenIdRelyingPartyChannel.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/OpenIdRelyingPartyChannel.cs
new file mode 100644
index 0000000..4739d84
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/OpenIdRelyingPartyChannel.cs
@@ -0,0 +1,120 @@
+//-----------------------------------------------------------------------
+// <copyright file="OpenIdRelyingPartyChannel.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+ using DotNetOpenAuth.OpenId.Extensions;
+ using DotNetOpenAuth.OpenId.RelyingParty;
+
+ /// <summary>
+ /// The messaging channel for OpenID relying parties.
+ /// </summary>
+ internal class OpenIdRelyingPartyChannel : OpenIdChannel {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="OpenIdRelyingPartyChannel"/> class.
+ /// </summary>
+ /// <param name="cryptoKeyStore">The association store to use.</param>
+ /// <param name="nonceStore">The nonce store to use.</param>
+ /// <param name="securitySettings">The security settings to apply.</param>
+ internal OpenIdRelyingPartyChannel(ICryptoKeyStore cryptoKeyStore, INonceStore nonceStore, RelyingPartySecuritySettings securitySettings)
+ : this(cryptoKeyStore, nonceStore, new OpenIdRelyingPartyMessageFactory(), securitySettings, false) {
+ Requires.NotNull(securitySettings, "securitySettings");
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="OpenIdRelyingPartyChannel"/> class.
+ /// </summary>
+ /// <param name="cryptoKeyStore">The association store to use.</param>
+ /// <param name="nonceStore">The nonce store to use.</param>
+ /// <param name="messageTypeProvider">An object that knows how to distinguish the various OpenID message types for deserialization purposes.</param>
+ /// <param name="securitySettings">The security settings to apply.</param>
+ /// <param name="nonVerifying">A value indicating whether the channel is set up with no functional security binding elements.</param>
+ private OpenIdRelyingPartyChannel(ICryptoKeyStore cryptoKeyStore, INonceStore nonceStore, IMessageFactory messageTypeProvider, RelyingPartySecuritySettings securitySettings, bool nonVerifying) :
+ base(messageTypeProvider, InitializeBindingElements(cryptoKeyStore, nonceStore, securitySettings, nonVerifying)) {
+ Requires.NotNull(messageTypeProvider, "messageTypeProvider");
+ Requires.NotNull(securitySettings, "securitySettings");
+ Requires.True(!nonVerifying || securitySettings is RelyingPartySecuritySettings);
+ }
+
+ /// <summary>
+ /// A value indicating whether the channel is set up
+ /// with no functional security binding elements.
+ /// </summary>
+ /// <returns>A new <see cref="OpenIdChannel"/> instance that will not perform verification on incoming messages or apply any security to outgoing messages.</returns>
+ /// <remarks>
+ /// <para>A value of <c>true</c> allows the relying party to preview incoming
+ /// messages without invalidating nonces or checking signatures.</para>
+ /// <para>Setting this to <c>true</c> poses a great security risk and is only
+ /// present to support the OpenIdAjaxTextBox which needs to preview
+ /// messages, and will validate them later.</para>
+ /// </remarks>
+ internal static OpenIdChannel CreateNonVerifyingChannel() {
+ Contract.Ensures(Contract.Result<OpenIdChannel>() != null);
+
+ return new OpenIdRelyingPartyChannel(null, null, new OpenIdRelyingPartyMessageFactory(), new RelyingPartySecuritySettings(), true);
+ }
+
+ /// <summary>
+ /// Initializes the binding elements.
+ /// </summary>
+ /// <param name="cryptoKeyStore">The crypto key store.</param>
+ /// <param name="nonceStore">The nonce store to use.</param>
+ /// <param name="securitySettings">The security settings to apply. Must be an instance of either <see cref="RelyingPartySecuritySettings"/> or ProviderSecuritySettings.</param>
+ /// <param name="nonVerifying">A value indicating whether the channel is set up with no functional security binding elements.</param>
+ /// <returns>
+ /// An array of binding elements which may be used to construct the channel.
+ /// </returns>
+ private static IChannelBindingElement[] InitializeBindingElements(ICryptoKeyStore cryptoKeyStore, INonceStore nonceStore, RelyingPartySecuritySettings securitySettings, bool nonVerifying) {
+ Requires.NotNull(securitySettings, "securitySettings");
+
+ SigningBindingElement signingElement;
+ signingElement = nonVerifying ? null : new RelyingPartySigningBindingElement(new CryptoKeyStoreAsRelyingPartyAssociationStore(cryptoKeyStore ?? new MemoryCryptoKeyStore()));
+
+ var extensionFactory = OpenIdExtensionFactoryAggregator.LoadFromConfiguration();
+
+ List<IChannelBindingElement> elements = new List<IChannelBindingElement>(8);
+ elements.Add(new ExtensionsBindingElementRelyingParty(extensionFactory, securitySettings));
+ elements.Add(new RelyingPartySecurityOptions(securitySettings));
+ elements.Add(new BackwardCompatibilityBindingElement());
+ ReturnToNonceBindingElement requestNonceElement = null;
+
+ if (cryptoKeyStore != null) {
+ if (nonceStore != null) {
+ // There is no point in having a ReturnToNonceBindingElement without
+ // a ReturnToSignatureBindingElement because the nonce could be
+ // artificially changed without it.
+ requestNonceElement = new ReturnToNonceBindingElement(nonceStore, securitySettings);
+ elements.Add(requestNonceElement);
+ }
+
+ // It is important that the return_to signing element comes last
+ // so that the nonce is included in the signature.
+ elements.Add(new ReturnToSignatureBindingElement(cryptoKeyStore));
+ }
+
+ ErrorUtilities.VerifyOperation(!securitySettings.RejectUnsolicitedAssertions || requestNonceElement != null, OpenIdStrings.UnsolicitedAssertionRejectionRequiresNonceStore);
+
+ if (nonVerifying) {
+ elements.Add(new SkipSecurityBindingElement());
+ } else {
+ if (nonceStore != null) {
+ elements.Add(new StandardReplayProtectionBindingElement(nonceStore, true));
+ }
+
+ elements.Add(new StandardExpirationBindingElement());
+ elements.Add(signingElement);
+ }
+
+ return elements.ToArray();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/ChannelElements/OpenIdMessageFactory.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/OpenIdRelyingPartyMessageFactory.cs
index 1e5ea4c..9ec6c53 100644
--- a/src/DotNetOpenAuth/OpenId/ChannelElements/OpenIdMessageFactory.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/OpenIdRelyingPartyMessageFactory.cs
@@ -1,5 +1,5 @@
//-----------------------------------------------------------------------
-// <copyright file="OpenIdMessageFactory.cs" company="Andrew Arnott">
+// <copyright file="OpenIdRelyingPartyMessageFactory.cs" company="Andrew Arnott">
// Copyright (c) Andrew Arnott. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
@@ -7,19 +7,15 @@
namespace DotNetOpenAuth.OpenId.ChannelElements {
using System;
using System.Collections.Generic;
- using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId.Messages;
- using DotNetOpenAuth.OpenId.RelyingParty;
/// <summary>
- /// Distinguishes the various OpenID message types for deserialization purposes.
+ /// Message factory for OpenID Relying Parties.
/// </summary>
- internal class OpenIdMessageFactory : IMessageFactory {
- #region IMessageFactory Members
-
+ internal class OpenIdRelyingPartyMessageFactory : IMessageFactory {
/// <summary>
/// Analyzes an incoming request message payload to discover what kind of
/// message is embedded in it and returns the type, or null if no match is found.
@@ -43,22 +39,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
string mode;
if (fields.TryGetValue(protocol.openid.mode, out mode)) {
- if (string.Equals(mode, protocol.Args.Mode.associate)) {
- if (fields.ContainsKey(protocol.openid.dh_consumer_public)) {
- message = new AssociateDiffieHellmanRequest(protocol.Version, recipient.Location);
- } else {
- message = new AssociateUnencryptedRequest(protocol.Version, recipient.Location);
- }
- } else if (string.Equals(mode, protocol.Args.Mode.checkid_setup) ||
- string.Equals(mode, protocol.Args.Mode.checkid_immediate)) {
- AuthenticationRequestMode authMode = string.Equals(mode, protocol.Args.Mode.checkid_immediate) ? AuthenticationRequestMode.Immediate : AuthenticationRequestMode.Setup;
- if (fields.ContainsKey(protocol.openid.identity)) {
- message = new CheckIdRequest(protocol.Version, recipient.Location, authMode);
- } else {
- ErrorUtilities.VerifyProtocol(!fields.ContainsKey(protocol.openid.claimed_id), OpenIdStrings.IdentityAndClaimedIdentifierMustBeBothPresentOrAbsent);
- message = new SignedResponseRequest(protocol.Version, recipient.Location, authMode);
- }
- } else if (string.Equals(mode, protocol.Args.Mode.cancel) ||
+ if (string.Equals(mode, protocol.Args.Mode.cancel) ||
(string.Equals(mode, protocol.Args.Mode.setup_needed) && (protocol.Version.Major >= 2 || fields.ContainsKey(protocol.openid.user_setup_url)))) {
message = new NegativeAssertionResponse(protocol.Version, recipient.Location, mode);
} else if (string.Equals(mode, protocol.Args.Mode.id_res)) {
@@ -68,8 +49,6 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
ErrorUtilities.VerifyProtocol(!fields.ContainsKey(protocol.openid.claimed_id), OpenIdStrings.IdentityAndClaimedIdentifierMustBeBothPresentOrAbsent);
message = new IndirectSignedResponse(protocol.Version, recipient.Location);
}
- } else if (string.Equals(mode, protocol.Args.Mode.check_authentication)) {
- message = new CheckAuthenticationRequest(protocol.Version, recipient.Location);
} else if (string.Equals(mode, protocol.Args.Mode.error)) {
message = new IndirectErrorResponse(protocol.Version, recipient.Location);
} else {
@@ -116,15 +95,16 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
// This is a special recognized error case that we create a special message for.
message = new AssociateUnsuccessfulResponse(protocol.Version, associateRequest);
} else if (message == null) {
+#if !ExcludeDiffieHellman
var associateDiffieHellmanRequest = request as AssociateDiffieHellmanRequest;
- var associateUnencryptedRequest = request as AssociateUnencryptedRequest;
-
if (associateDiffieHellmanRequest != null) {
- message = new AssociateDiffieHellmanResponse(protocol.Version, associateDiffieHellmanRequest);
+ message = new AssociateDiffieHellmanRelyingPartyResponse(protocol.Version, associateDiffieHellmanRequest);
}
+#endif
+ var associateUnencryptedRequest = request as AssociateUnencryptedRequest;
if (associateUnencryptedRequest != null) {
- message = new AssociateUnencryptedResponse(protocol.Version, associateUnencryptedRequest);
+ message = new AssociateUnencryptedResponseRelyingParty(protocol.Version, associateUnencryptedRequest);
}
}
}
@@ -140,7 +120,5 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
return message;
}
-
- #endregion
}
}
diff --git a/src/DotNetOpenAuth/OpenId/ChannelElements/RelyingPartySecurityOptions.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/RelyingPartySecurityOptions.cs
index d8fc103..d8fc103 100644
--- a/src/DotNetOpenAuth/OpenId/ChannelElements/RelyingPartySecurityOptions.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/RelyingPartySecurityOptions.cs
diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/RelyingPartySigningBindingElement.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/RelyingPartySigningBindingElement.cs
new file mode 100644
index 0000000..4a3f5ee
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/RelyingPartySigningBindingElement.cs
@@ -0,0 +1,110 @@
+//-----------------------------------------------------------------------
+// <copyright file="RelyingPartySigningBindingElement.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+ using DotNetOpenAuth.OpenId.Messages;
+ using DotNetOpenAuth.OpenId.RelyingParty;
+
+ /// <summary>
+ /// The signing binding element for OpenID Relying Parties.
+ /// </summary>
+ internal class RelyingPartySigningBindingElement : SigningBindingElement {
+ /// <summary>
+ /// The association store used by Relying Parties to look up the secrets needed for signing.
+ /// </summary>
+ private readonly IRelyingPartyAssociationStore rpAssociations;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RelyingPartySigningBindingElement"/> class.
+ /// </summary>
+ /// <param name="associationStore">The association store used to look up the secrets needed for signing. May be null for dumb Relying Parties.</param>
+ internal RelyingPartySigningBindingElement(IRelyingPartyAssociationStore associationStore) {
+ this.rpAssociations = associationStore;
+ }
+
+ /// <summary>
+ /// Gets a specific association referenced in a given message's association handle.
+ /// </summary>
+ /// <param name="signedMessage">The signed message whose association handle should be used to lookup the association to return.</param>
+ /// <returns>
+ /// The referenced association; or <c>null</c> if such an association cannot be found.
+ /// </returns>
+ protected override Association GetSpecificAssociation(ITamperResistantOpenIdMessage signedMessage) {
+ Association association = null;
+
+ if (!string.IsNullOrEmpty(signedMessage.AssociationHandle)) {
+ IndirectSignedResponse indirectSignedMessage = signedMessage as IndirectSignedResponse;
+ if (this.rpAssociations != null) { // if on a smart RP
+ Uri providerEndpoint = indirectSignedMessage.ProviderEndpoint;
+ association = this.rpAssociations.GetAssociation(providerEndpoint, signedMessage.AssociationHandle);
+ }
+ }
+
+ return association;
+ }
+
+ /// <summary>
+ /// Gets the association to use to sign or verify a message.
+ /// </summary>
+ /// <param name="signedMessage">The message to sign or verify.</param>
+ /// <returns>
+ /// The association to use to sign or verify the message.
+ /// </returns>
+ protected override Association GetAssociation(ITamperResistantOpenIdMessage signedMessage) {
+ // We're on a Relying Party verifying a signature.
+ IDirectedProtocolMessage directedMessage = (IDirectedProtocolMessage)signedMessage;
+ if (this.rpAssociations != null) {
+ return this.rpAssociations.GetAssociation(directedMessage.Recipient, signedMessage.AssociationHandle);
+ } else {
+ return null;
+ }
+ }
+
+ /// <summary>
+ /// Verifies the signature by unrecognized handle.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <param name="signedMessage">The signed message.</param>
+ /// <param name="protectionsApplied">The protections applied.</param>
+ /// <returns>
+ /// The applied protections.
+ /// </returns>
+ protected override MessageProtections VerifySignatureByUnrecognizedHandle(IProtocolMessage message, ITamperResistantOpenIdMessage signedMessage, MessageProtections protectionsApplied) {
+ // We did not recognize the association the provider used to sign the message.
+ // Ask the provider to check the signature then.
+ var indirectSignedResponse = (IndirectSignedResponse)signedMessage;
+ var checkSignatureRequest = new CheckAuthenticationRequest(indirectSignedResponse, this.Channel);
+ var checkSignatureResponse = this.Channel.Request<CheckAuthenticationResponse>(checkSignatureRequest);
+ if (!checkSignatureResponse.IsValid) {
+ Logger.Bindings.Error("Provider reports signature verification failed.");
+ throw new InvalidSignatureException(message);
+ }
+
+ // If the OP confirms that a handle should be invalidated as well, do that.
+ if (!string.IsNullOrEmpty(checkSignatureResponse.InvalidateHandle)) {
+ if (this.rpAssociations != null) {
+ this.rpAssociations.RemoveAssociation(indirectSignedResponse.ProviderEndpoint, checkSignatureResponse.InvalidateHandle);
+ }
+ }
+
+ // When we're in dumb mode we can't provide our own replay protection,
+ // but for OpenID 2.0 Providers we can rely on them providing it as part
+ // of signature verification.
+ if (message.Version.Major >= 2) {
+ protectionsApplied |= MessageProtections.ReplayProtection;
+ }
+
+ return protectionsApplied;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/ChannelElements/ReturnToNonceBindingElement.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/ReturnToNonceBindingElement.cs
index 370192a..46cd103 100644
--- a/src/DotNetOpenAuth/OpenId/ChannelElements/ReturnToNonceBindingElement.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/ReturnToNonceBindingElement.cs
@@ -53,6 +53,11 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
internal const string NonceParameter = OpenIdUtilities.CustomParameterPrefix + "request_nonce";
/// <summary>
+ /// The context within which return_to nonces must be unique -- they all go into the same bucket.
+ /// </summary>
+ private const string ReturnToNonceContext = "https://localhost/dnoa/return_to_nonce";
+
+ /// <summary>
/// The length of the generated nonce's random part.
/// </summary>
private const int NonceByteLength = 128 / 8; // 128-bit nonce
@@ -78,8 +83,8 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
/// <param name="nonceStore">The nonce store to use.</param>
/// <param name="securitySettings">The security settings of the RP.</param>
internal ReturnToNonceBindingElement(INonceStore nonceStore, RelyingPartySecuritySettings securitySettings) {
- Contract.Requires<ArgumentNullException>(nonceStore != null);
- Contract.Requires<ArgumentNullException>(securitySettings != null);
+ Requires.NotNull(nonceStore, "nonceStore");
+ Requires.NotNull(securitySettings, "securitySettings");
this.nonceStore = nonceStore;
this.securitySettings = securitySettings;
@@ -186,7 +191,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
}
IReplayProtectedProtocolMessage replayResponse = response;
- if (!this.nonceStore.StoreNonce(replayResponse.NonceContext, nonce.RandomPartAsString, nonce.CreationDateUtc)) {
+ if (!this.nonceStore.StoreNonce(ReturnToNonceContext, nonce.RandomPartAsString, nonce.CreationDateUtc)) {
Logger.OpenId.ErrorFormat("Replayed nonce detected ({0} {1}). Rejecting message.", replayResponse.Nonce, replayResponse.UtcCreationDate);
throw new ReplayedMessageException(message);
}
@@ -259,9 +264,9 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
/// <param name="value">The base64-encoded value of the nonce.</param>
/// <returns>The instantiated and initialized nonce.</returns>
internal static CustomNonce Deserialize(string value) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(value));
+ Requires.NotNullOrEmpty(value, "value");
- byte[] nonce = Convert.FromBase64String(value);
+ byte[] nonce = MessagingUtilities.FromBase64WebSafeString(value);
Contract.Assume(nonce != null);
DateTime creationDateUtc = new DateTime(BitConverter.ToInt64(nonce, 0), DateTimeKind.Utc);
byte[] randomPart = new byte[NonceByteLength];
@@ -278,7 +283,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
byte[] nonce = new byte[timestamp.Length + this.randomPart.Length];
timestamp.CopyTo(nonce, 0);
this.randomPart.CopyTo(nonce, timestamp.Length);
- string base64Nonce = Convert.ToBase64String(nonce);
+ string base64Nonce = MessagingUtilities.ConvertToBase64WebSafeString(nonce);
return base64Nonce;
}
}
diff --git a/src/DotNetOpenAuth/OpenId/HostMetaDiscoveryService.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/HostMetaDiscoveryService.cs
index 215ea24..6d60030 100644
--- a/src/DotNetOpenAuth/OpenId/HostMetaDiscoveryService.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/HostMetaDiscoveryService.cs
@@ -158,7 +158,7 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="xrds">The XRDs to search.</param>
/// <returns>A sequence of services.</returns>
private static IEnumerable<ServiceElement> GetDescribedByServices(IEnumerable<XrdElement> xrds) {
- Contract.Requires<ArgumentNullException>(xrds != null);
+ Requires.NotNull(xrds, "xrds");
Contract.Ensures(Contract.Result<IEnumerable<ServiceElement>>() != null);
var describedBy = from xrd in xrds
@@ -175,9 +175,9 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="requestHandler">The request handler.</param>
/// <returns>The discovered services.</returns>
private static IEnumerable<IdentifierDiscoveryResult> GetExternalServices(IEnumerable<XrdElement> xrds, UriIdentifier identifier, IDirectWebRequestHandler requestHandler) {
- Contract.Requires<ArgumentNullException>(xrds != null);
- Contract.Requires<ArgumentNullException>(identifier != null);
- Contract.Requires<ArgumentNullException>(requestHandler != null);
+ Requires.NotNull(xrds, "xrds");
+ Requires.NotNull(identifier, "identifier");
+ Requires.NotNull(requestHandler, "requestHandler");
Contract.Ensures(Contract.Result<IEnumerable<IdentifierDiscoveryResult>>() != null);
var results = new List<IdentifierDiscoveryResult>();
@@ -214,9 +214,9 @@ namespace DotNetOpenAuth.OpenId {
/// <exception cref="ProtocolException">Thrown if the XRDS document has an invalid or a missing signature.</exception>
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "XmlDSig", Justification = "xml")]
private static void ValidateXmlDSig(XrdsDocument document, UriIdentifier identifier, IncomingWebResponse response, string signingHost) {
- Contract.Requires<ArgumentNullException>(document != null);
- Contract.Requires<ArgumentNullException>(identifier != null);
- Contract.Requires<ArgumentNullException>(response != null);
+ Requires.NotNull(document, "document");
+ Requires.NotNull(identifier, "identifier");
+ Requires.NotNull(response, "response");
var signatureNode = document.Node.SelectSingleNode("/xrds:XRDS/ds:Signature", document.XmlNamespaceResolver);
ErrorUtilities.VerifyProtocol(signatureNode != null, OpenIdStrings.MissingElement, "Signature");
@@ -299,9 +299,9 @@ namespace DotNetOpenAuth.OpenId {
/// </returns>
/// <exception cref="ProtocolException">Thrown if the XRDS document could not be obtained.</exception>
private static IncomingWebResponse GetXrdsResponse(UriIdentifier identifier, IDirectWebRequestHandler requestHandler, Uri xrdsLocation) {
- Contract.Requires<ArgumentNullException>(identifier != null);
- Contract.Requires<ArgumentNullException>(requestHandler != null);
- Contract.Requires<ArgumentNullException>(xrdsLocation != null);
+ Requires.NotNull(identifier, "identifier");
+ Requires.NotNull(requestHandler, "requestHandler");
+ Requires.NotNull(xrdsLocation, "xrdsLocation");
Contract.Ensures(Contract.Result<IncomingWebResponse>() != null);
var request = (HttpWebRequest)WebRequest.Create(xrdsLocation);
@@ -325,8 +325,8 @@ namespace DotNetOpenAuth.OpenId {
/// <returns>A HTTP response carrying an XRDS document, or <c>null</c> if one could not be obtained.</returns>
/// <exception cref="ProtocolException">Thrown if the XRDS document could not be obtained.</exception>
private IncomingWebResponse GetXrdsResponse(UriIdentifier identifier, IDirectWebRequestHandler requestHandler, out string signingHost) {
- Contract.Requires<ArgumentNullException>(identifier != null);
- Contract.Requires<ArgumentNullException>(requestHandler != null);
+ Requires.NotNull(identifier, "identifier");
+ Requires.NotNull(requestHandler, "requestHandler");
Uri xrdsLocation = this.GetXrdsLocation(identifier, requestHandler, out signingHost);
if (xrdsLocation == null) {
return null;
@@ -345,8 +345,8 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="signingHost">The host name on the certificate that should be used to verify the signature in the XRDS.</param>
/// <returns>An absolute URI, or <c>null</c> if one could not be determined.</returns>
private Uri GetXrdsLocation(UriIdentifier identifier, IDirectWebRequestHandler requestHandler, out string signingHost) {
- Contract.Requires<ArgumentNullException>(identifier != null);
- Contract.Requires<ArgumentNullException>(requestHandler != null);
+ Requires.NotNull(identifier, "identifier");
+ Requires.NotNull(requestHandler, "requestHandler");
using (var hostMetaResponse = this.GetHostMeta(identifier, requestHandler, out signingHost)) {
if (hostMetaResponse == null) {
return null;
@@ -377,8 +377,8 @@ namespace DotNetOpenAuth.OpenId {
/// The host-meta response, or <c>null</c> if no host-meta document could be obtained.
/// </returns>
private IncomingWebResponse GetHostMeta(UriIdentifier identifier, IDirectWebRequestHandler requestHandler, out string signingHost) {
- Contract.Requires<ArgumentNullException>(identifier != null);
- Contract.Requires<ArgumentNullException>(requestHandler != null);
+ Requires.NotNull(identifier, "identifier");
+ Requires.NotNull(requestHandler, "requestHandler");
foreach (var hostMetaProxy in this.GetHostMetaLocations(identifier)) {
var hostMetaLocation = hostMetaProxy.GetProxy(identifier);
var request = (HttpWebRequest)WebRequest.Create(hostMetaLocation);
@@ -413,7 +413,7 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="identifier">The identifier.</param>
/// <returns>A sequence of URIs that MAY provide the host-meta for a given identifier.</returns>
private IEnumerable<HostMetaProxy> GetHostMetaLocations(UriIdentifier identifier) {
- Contract.Requires<ArgumentNullException>(identifier != null);
+ Requires.NotNull(identifier, "identifier");
// First try the proxies, as they are considered more "secure" than the local
// host-meta for a domain since the domain may be defaced.
@@ -440,8 +440,8 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="proxyFormat">The proxy formatting string.</param>
/// <param name="signingHostFormat">The signing host formatting string.</param>
public HostMetaProxy(string proxyFormat, string signingHostFormat) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(proxyFormat));
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(signingHostFormat));
+ Requires.NotNullOrEmpty(proxyFormat, "proxyFormat");
+ Requires.NotNullOrEmpty(signingHostFormat, "signingHostFormat");
this.ProxyFormat = proxyFormat;
this.SigningHostFormat = signingHostFormat;
}
@@ -469,7 +469,7 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="identifier">The identifier being discovered.</param>
/// <returns>The an absolute URI.</returns>
public virtual Uri GetProxy(UriIdentifier identifier) {
- Contract.Requires<ArgumentNullException>(identifier != null);
+ Requires.NotNull(identifier, "identifier");
return new Uri(string.Format(CultureInfo.InvariantCulture, this.ProxyFormat, Uri.EscapeDataString(identifier.Uri.Host)));
}
@@ -479,7 +479,7 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="identifier">The identifier being discovered.</param>
/// <returns>A host name.</returns>
public virtual string GetSigningHost(UriIdentifier identifier) {
- Contract.Requires<ArgumentNullException>(identifier != null);
+ Requires.NotNull(identifier, "identifier");
return string.Format(CultureInfo.InvariantCulture, this.SigningHostFormat, identifier.Uri.Host, this.GetProxy(identifier).Host);
}
diff --git a/src/DotNetOpenAuth/OpenId/Interop/AuthenticationResponseShim.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Interop/AuthenticationResponseShim.cs
index c0354ac..c0d2b35 100644
--- a/src/DotNetOpenAuth/OpenId/Interop/AuthenticationResponseShim.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Interop/AuthenticationResponseShim.cs
@@ -30,7 +30,7 @@ namespace DotNetOpenAuth.OpenId.Interop {
/// </summary>
/// <param name="response">The response.</param>
internal AuthenticationResponseShim(IAuthenticationResponse response) {
- Contract.Requires<ArgumentNullException>(response != null);
+ Requires.NotNull(response, "response");
this.response = response;
var claimsResponse = this.response.GetExtension<ClaimsResponse>();
diff --git a/src/DotNetOpenAuth/OpenId/Interop/ClaimsResponseShim.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Interop/ClaimsResponseShim.cs
index 689777b..fa3b874 100644
--- a/src/DotNetOpenAuth/OpenId/Interop/ClaimsResponseShim.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Interop/ClaimsResponseShim.cs
@@ -31,7 +31,7 @@ namespace DotNetOpenAuth.OpenId.Interop {
/// <param name="response">The Simple Registration response to wrap.</param>
internal ClaimsResponseShim(ClaimsResponse response)
{
- Contract.Requires<ArgumentNullException>(response != null);
+ Requires.NotNull(response, "response");
this.response = response;
}
diff --git a/src/DotNetOpenAuth/OpenId/Interop/OpenIdRelyingPartyShim.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Interop/OpenIdRelyingPartyShim.cs
index fc0f32e..873aabe 100644
--- a/src/DotNetOpenAuth/OpenId/Interop/OpenIdRelyingPartyShim.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Interop/OpenIdRelyingPartyShim.cs
@@ -96,7 +96,7 @@ namespace DotNetOpenAuth.OpenId.Interop {
/// </summary>
static OpenIdRelyingPartyShim() {
relyingParty = new OpenIdRelyingParty(null);
- relyingParty.Behaviors.Add(new Behaviors.AXFetchAsSregTransform());
+ relyingParty.Behaviors.Add(new RelyingParty.Behaviors.AXFetchAsSregTransform());
}
/// <summary>
diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/AssociateDiffieHellmanRelyingPartyResponse.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/AssociateDiffieHellmanRelyingPartyResponse.cs
new file mode 100644
index 0000000..2112288
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/AssociateDiffieHellmanRelyingPartyResponse.cs
@@ -0,0 +1,50 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssociateDiffieHellmanRelyingPartyResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Messages {
+ using System;
+ using System.Diagnostics.Contracts;
+ using System.Security.Cryptography;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Reflection;
+ using Org.Mentalis.Security.Cryptography;
+
+ /// <summary>
+ /// The successful Diffie-Hellman association response message.
+ /// </summary>
+ /// <remarks>
+ /// Association response messages are described in OpenID 2.0 section 8.2. This type covers section 8.2.3.
+ /// </remarks>
+ internal class AssociateDiffieHellmanRelyingPartyResponse : AssociateDiffieHellmanResponse, IAssociateSuccessfulResponseRelyingParty {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AssociateDiffieHellmanRelyingPartyResponse"/> class.
+ /// </summary>
+ /// <param name="responseVersion">The OpenID version of the response message.</param>
+ /// <param name="originatingRequest">The originating request.</param>
+ internal AssociateDiffieHellmanRelyingPartyResponse(Version responseVersion, AssociateDiffieHellmanRequest originatingRequest)
+ : base(responseVersion, originatingRequest) {
+ }
+
+ /// <summary>
+ /// Creates the association at relying party side after the association response has been received.
+ /// </summary>
+ /// <param name="request">The original association request that was already sent and responded to.</param>
+ /// <returns>The newly created association.</returns>
+ /// <remarks>
+ /// The resulting association is <i>not</i> added to the association store and must be done by the caller.
+ /// </remarks>
+ public Association CreateAssociationAtRelyingParty(AssociateRequest request) {
+ var diffieHellmanRequest = request as AssociateDiffieHellmanRequest;
+ ErrorUtilities.VerifyArgument(diffieHellmanRequest != null, OpenIdStrings.DiffieHellmanAssociationRequired);
+
+ HashAlgorithm hasher = DiffieHellmanUtilities.Lookup(Protocol, this.SessionType);
+ byte[] associationSecret = DiffieHellmanUtilities.SHAHashXorSecret(hasher, diffieHellmanRequest.Algorithm, this.DiffieHellmanServerPublic, this.EncodedMacKey);
+
+ Association association = HmacShaAssociation.Create(Protocol, this.AssociationType, this.AssociationHandle, associationSecret, TimeSpan.FromSeconds(this.ExpiresIn));
+ return association;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/AssociateRequestRelyingParty.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/AssociateRequestRelyingParty.cs
new file mode 100644
index 0000000..0e00963
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/AssociateRequestRelyingParty.cs
@@ -0,0 +1,83 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssociateRequestRelyingParty.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.OpenId.RelyingParty;
+
+ /// <summary>
+ /// Utility methods for requesting associations from the relying party.
+ /// </summary>
+ internal static class AssociateRequestRelyingParty {
+ /// <summary>
+ /// Creates an association request message that is appropriate for a given Provider.
+ /// </summary>
+ /// <param name="securityRequirements">The set of requirements the selected association type must comply to.</param>
+ /// <param name="provider">The provider to create an association with.</param>
+ /// <returns>
+ /// The message to send to the Provider to request an association.
+ /// Null if no association could be created that meet the security requirements
+ /// and the provider OpenID version.
+ /// </returns>
+ internal static AssociateRequest Create(SecuritySettings securityRequirements, IProviderEndpoint provider) {
+ Requires.NotNull(securityRequirements, "securityRequirements");
+ Requires.NotNull(provider, "provider");
+
+ // Apply our knowledge of the endpoint's transport, OpenID version, and
+ // security requirements to decide the best association.
+ bool unencryptedAllowed = provider.Uri.IsTransportSecure();
+ bool useDiffieHellman = !unencryptedAllowed;
+ string associationType, sessionType;
+ if (!HmacShaAssociation.TryFindBestAssociation(Protocol.Lookup(provider.Version), true, securityRequirements, useDiffieHellman, out associationType, out sessionType)) {
+ // There are no associations that meet all requirements.
+ Logger.OpenId.Warn("Security requirements and protocol combination knock out all possible association types. Dumb mode forced.");
+ return null;
+ }
+
+ return Create(securityRequirements, provider, associationType, sessionType);
+ }
+
+ /// <summary>
+ /// Creates an association request message that is appropriate for a given Provider.
+ /// </summary>
+ /// <param name="securityRequirements">The set of requirements the selected association type must comply to.</param>
+ /// <param name="provider">The provider to create an association with.</param>
+ /// <param name="associationType">Type of the association.</param>
+ /// <param name="sessionType">Type of the session.</param>
+ /// <returns>
+ /// The message to send to the Provider to request an association.
+ /// Null if no association could be created that meet the security requirements
+ /// and the provider OpenID version.
+ /// </returns>
+ internal static AssociateRequest Create(SecuritySettings securityRequirements, IProviderEndpoint provider, string associationType, string sessionType) {
+ Requires.NotNull(securityRequirements, "securityRequirements");
+ Requires.NotNull(provider, "provider");
+ Requires.NotNullOrEmpty(associationType, "associationType");
+ Requires.NotNull(sessionType, "sessionType");
+
+ bool unencryptedAllowed = provider.Uri.IsTransportSecure();
+ if (unencryptedAllowed) {
+ var associateRequest = new AssociateUnencryptedRequest(provider.Version, provider.Uri);
+ associateRequest.AssociationType = associationType;
+ return associateRequest;
+ } else {
+#if !ExcludeDiffieHellman
+ var associateRequest = new AssociateDiffieHellmanRequest(provider.Version, provider.Uri);
+ associateRequest.AssociationType = associationType;
+ associateRequest.SessionType = sessionType;
+ associateRequest.InitializeRequest();
+ return associateRequest;
+#else
+ return null;
+#endif
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/AssociateSuccessfulResponseRelyingPartyContract.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/AssociateSuccessfulResponseRelyingPartyContract.cs
new file mode 100644
index 0000000..8999a2a
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/AssociateSuccessfulResponseRelyingPartyContract.cs
@@ -0,0 +1,79 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssociateSuccessfulResponseRelyingPartyContract.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OpenId;
+ using DotNetOpenAuth.OpenId.Messages;
+
+ /// <summary>
+ /// Code contract for the <see cref="IAssociateSuccessfulResponseRelyingParty"/> interface.
+ /// </summary>
+ [ContractClassFor(typeof(IAssociateSuccessfulResponseRelyingParty))]
+ internal abstract class IAssociateSuccessfulResponseRelyingPartyContract : IAssociateSuccessfulResponseRelyingParty {
+ #region IProtocolMessage Members
+
+ /// <summary>
+ /// Gets the level of protection this message requires.
+ /// </summary>
+ Messaging.MessageProtections Messaging.IProtocolMessage.RequiredProtection {
+ get { throw new NotImplementedException(); }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether this is a direct or indirect message.
+ /// </summary>
+ Messaging.MessageTransport Messaging.IProtocolMessage.Transport {
+ get { throw new NotImplementedException(); }
+ }
+
+ #endregion
+
+ #region IMessage members
+
+ /// <summary>
+ /// Gets the version of the protocol or extension this message is prepared to implement.
+ /// </summary>
+ Version Messaging.IMessage.Version {
+ get { throw new NotImplementedException(); }
+ }
+
+ /// <summary>
+ /// Gets the extra, non-standard Protocol parameters included in the message.
+ /// </summary>
+ IDictionary<string, string> Messaging.IMessage.ExtraData {
+ get { throw new NotImplementedException(); }
+ }
+
+ /// <summary>
+ /// Checks the message state for conformity to the protocol specification
+ /// and throws an exception if the message is invalid.
+ /// </summary>
+ /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception>
+ void Messaging.IMessage.EnsureValidMessage() {
+ throw new NotImplementedException();
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Called to create the Association based on a request previously given by the Relying Party.
+ /// </summary>
+ /// <param name="request">The prior request for an association.</param>
+ /// <returns>
+ /// The created association.
+ /// </returns>
+ Association IAssociateSuccessfulResponseRelyingParty.CreateAssociationAtRelyingParty(AssociateRequest request) {
+ Requires.NotNull(request, "request");
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/AssociateUnencryptedResponseRelyingParty.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/AssociateUnencryptedResponseRelyingParty.cs
new file mode 100644
index 0000000..b2a5e11
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/AssociateUnencryptedResponseRelyingParty.cs
@@ -0,0 +1,36 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssociateUnencryptedResponseRelyingParty.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+
+ /// <summary>
+ /// A response to an unencrypted assocation request, as it is received by the relying party.
+ /// </summary>
+ internal class AssociateUnencryptedResponseRelyingParty : AssociateUnencryptedResponse, IAssociateSuccessfulResponseRelyingParty {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AssociateUnencryptedResponseRelyingParty"/> class.
+ /// </summary>
+ /// <param name="version">The version.</param>
+ /// <param name="request">The request.</param>
+ internal AssociateUnencryptedResponseRelyingParty(Version version, AssociateUnencryptedRequest request)
+ : base(version, request) {
+ }
+
+ /// <summary>
+ /// Called to create the Association based on a request previously given by the Relying Party.
+ /// </summary>
+ /// <param name="request">The prior request for an association.</param>
+ /// <returns>The created association.</returns>
+ public Association CreateAssociationAtRelyingParty(AssociateRequest request) {
+ Association association = HmacShaAssociation.Create(Protocol, this.AssociationType, this.AssociationHandle, this.MacKey, TimeSpan.FromSeconds(this.ExpiresIn));
+ return association;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/IAssociateSuccessfulResponseRelyingParty.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/IAssociateSuccessfulResponseRelyingParty.cs
new file mode 100644
index 0000000..a3eef44
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/IAssociateSuccessfulResponseRelyingParty.cs
@@ -0,0 +1,27 @@
+//-----------------------------------------------------------------------
+// <copyright file="IAssociateSuccessfulResponseRelyingParty.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A successful association response as it is received by the relying party.
+ /// </summary>
+ [ContractClass(typeof(IAssociateSuccessfulResponseRelyingPartyContract))]
+ internal interface IAssociateSuccessfulResponseRelyingParty : IProtocolMessage {
+ /// <summary>
+ /// Called to create the Association based on a request previously given by the Relying Party.
+ /// </summary>
+ /// <param name="request">The prior request for an association.</param>
+ /// <returns>The created association.</returns>
+ Association CreateAssociationAtRelyingParty(AssociateRequest request);
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/AssociationManager.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/AssociationManager.cs
index 1ae2726..eb501c5 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/AssociationManager.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/AssociationManager.cs
@@ -23,7 +23,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <summary>
/// The storage to use for saving and retrieving associations. May be null.
/// </summary>
- private readonly IAssociationStore<Uri> associationStore;
+ private readonly IRelyingPartyAssociationStore associationStore;
/// <summary>
/// Backing field for the <see cref="Channel"/> property.
@@ -41,9 +41,9 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <param name="channel">The channel the relying party is using.</param>
/// <param name="associationStore">The association store. May be null for dumb mode relying parties.</param>
/// <param name="securitySettings">The security settings.</param>
- internal AssociationManager(Channel channel, IAssociationStore<Uri> associationStore, RelyingPartySecuritySettings securitySettings) {
- Contract.Requires<ArgumentNullException>(channel != null);
- Contract.Requires<ArgumentNullException>(securitySettings != null);
+ internal AssociationManager(Channel channel, IRelyingPartyAssociationStore associationStore, RelyingPartySecuritySettings securitySettings) {
+ Requires.NotNull(channel, "channel");
+ Requires.NotNull(securitySettings, "securitySettings");
this.channel = channel;
this.associationStore = associationStore;
@@ -60,7 +60,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
}
set {
- Contract.Requires<ArgumentNullException>(value != null);
+ Requires.NotNull(value, "value");
this.channel = value;
}
}
@@ -74,7 +74,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
}
set {
- Contract.Requires<ArgumentNullException>(value != null);
+ Requires.NotNull(value, "value");
this.securitySettings = value;
}
}
@@ -93,7 +93,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <summary>
/// Gets the storage to use for saving and retrieving associations. May be null.
/// </summary>
- internal IAssociationStore<Uri> AssociationStoreTestHook {
+ internal IRelyingPartyAssociationStore AssociationStoreTestHook {
get { return this.associationStore; }
}
@@ -104,7 +104,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <param name="provider">The provider to create an association with.</param>
/// <returns>The association if one exists and has useful life remaining. Otherwise <c>null</c>.</returns>
internal Association GetExistingAssociation(IProviderEndpoint provider) {
- Contract.Requires<ArgumentNullException>(provider != null);
+ Requires.NotNull(provider, "provider");
// If the RP has no application store for associations, there's no point in creating one.
if (this.associationStore == null) {
@@ -149,7 +149,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// Any new association is automatically added to the <see cref="associationStore"/>.
/// </remarks>
private Association CreateNewAssociation(IProviderEndpoint provider) {
- Contract.Requires<ArgumentNullException>(provider != null);
+ Requires.NotNull(provider, "provider");
// If there is no association store, there is no point in creating an association.
if (this.associationStore == null) {
@@ -157,7 +157,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
}
try {
- var associateRequest = AssociateRequest.Create(this.securitySettings, provider);
+ var associateRequest = AssociateRequestRelyingParty.Create(this.securitySettings, provider);
const int RenegotiateRetries = 1;
return this.CreateNewAssociation(provider, associateRequest, RenegotiateRetries);
@@ -183,7 +183,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// the given Provider given the current security settings.
/// </returns>
private Association CreateNewAssociation(IProviderEndpoint provider, AssociateRequest associateRequest, int retriesRemaining) {
- Contract.Requires<ArgumentNullException>(provider != null);
+ Requires.NotNull(provider, "provider");
if (associateRequest == null || retriesRemaining < 0) {
// this can happen if security requirements and protocol conflict
@@ -193,10 +193,10 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
try {
var associateResponse = this.channel.Request(associateRequest);
- var associateSuccessfulResponse = associateResponse as AssociateSuccessfulResponse;
+ var associateSuccessfulResponse = associateResponse as IAssociateSuccessfulResponseRelyingParty;
var associateUnsuccessfulResponse = associateResponse as AssociateUnsuccessfulResponse;
if (associateSuccessfulResponse != null) {
- Association association = associateSuccessfulResponse.CreateAssociation(associateRequest, null);
+ Association association = associateSuccessfulResponse.CreateAssociationAtRelyingParty(associateRequest);
this.associationStore.StoreAssociation(provider.Uri, association);
return association;
} else if (associateUnsuccessfulResponse != null) {
@@ -223,7 +223,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
associateUnsuccessfulResponse.AssociationType,
associateUnsuccessfulResponse.SessionType);
- associateRequest = AssociateRequest.Create(this.securitySettings, provider, associateUnsuccessfulResponse.AssociationType, associateUnsuccessfulResponse.SessionType);
+ associateRequest = AssociateRequestRelyingParty.Create(this.securitySettings, provider, associateUnsuccessfulResponse.AssociationType, associateUnsuccessfulResponse.SessionType);
return this.CreateNewAssociation(provider, associateRequest, retriesRemaining - 1);
} else {
throw new ProtocolException(MessagingStrings.UnexpectedMessageReceivedOfMany);
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/AssociationPreference.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/AssociationPreference.cs
index 9f4a21f..9f4a21f 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/AssociationPreference.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/AssociationPreference.cs
diff --git a/src/DotNetOpenAuth/OpenId/Associations.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Associations.cs
index cf49d1c..e65750f 100644
--- a/src/DotNetOpenAuth/OpenId/Associations.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Associations.cs
@@ -4,7 +4,7 @@
// </copyright>
//-----------------------------------------------------------------------
-namespace DotNetOpenAuth.OpenId {
+namespace DotNetOpenAuth.OpenId.RelyingParty {
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
@@ -60,7 +60,7 @@ namespace DotNetOpenAuth.OpenId {
/// </summary>
/// <param name="association">The association to add to the collection.</param>
public void Set(Association association) {
- Contract.Requires<ArgumentNullException>(association != null);
+ Requires.NotNull(association, "association");
Contract.Ensures(this.Get(association.Handle) == association);
lock (this.associations) {
this.associations.Remove(association.Handle); // just in case one already exists.
@@ -77,7 +77,7 @@ namespace DotNetOpenAuth.OpenId {
/// <returns>The desired association, or null if none with the given handle could be found.</returns>
[Pure]
public Association Get(string handle) {
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(handle));
+ Requires.NotNullOrEmpty(handle, "handle");
lock (this.associations) {
if (this.associations.Contains(handle)) {
@@ -94,7 +94,7 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="handle">The handle to the required association.</param>
/// <returns>Whether an <see cref="Association"/> with the given handle was in the collection for removal.</returns>
public bool Remove(string handle) {
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(handle));
+ Requires.NotNullOrEmpty(handle, "handle");
lock (this.associations) {
return this.associations.Remove(handle);
}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/AuthenticationRequest.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/AuthenticationRequest.cs
index 3a17263..c85c0c5 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/AuthenticationRequest.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/AuthenticationRequest.cs
@@ -69,10 +69,10 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <param name="returnToUrl">The base return_to URL that the Provider should return the user to to complete authentication. This should not include callback parameters as these should be added using the <see cref="AddCallbackArguments(string, string)"/> method.</param>
/// <param name="relyingParty">The relying party that created this instance.</param>
private AuthenticationRequest(IdentifierDiscoveryResult discoveryResult, Realm realm, Uri returnToUrl, OpenIdRelyingParty relyingParty) {
- Contract.Requires<ArgumentNullException>(discoveryResult != null);
- Contract.Requires<ArgumentNullException>(realm != null);
- Contract.Requires<ArgumentNullException>(returnToUrl != null);
- Contract.Requires<ArgumentNullException>(relyingParty != null);
+ Requires.NotNull(discoveryResult, "discoveryResult");
+ Requires.NotNull(realm, "realm");
+ Requires.NotNull(returnToUrl, "returnToUrl");
+ Requires.NotNull(relyingParty, "relyingParty");
this.DiscoveryResult = discoveryResult;
this.RelyingParty = relyingParty;
@@ -212,7 +212,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// small to ensure successful authentication. About 1.5KB is about all that should be stored.</para>
/// </remarks>
public void AddCallbackArguments(IDictionary<string, string> arguments) {
- ErrorUtilities.VerifyOperation(this.RelyingParty.CanSignCallbackArguments, OpenIdStrings.CallbackArgumentsRequireSecretStore, typeof(IAssociationStore<Uri>).Name, typeof(OpenIdRelyingParty).Name);
+ ErrorUtilities.VerifyOperation(this.RelyingParty.CanSignCallbackArguments, OpenIdStrings.CallbackArgumentsRequireSecretStore, typeof(IRelyingPartyAssociationStore).Name, typeof(OpenIdRelyingParty).Name);
this.returnToArgsMustBeSigned = true;
foreach (var pair in arguments) {
@@ -239,7 +239,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// small to ensure successful authentication. About 1.5KB is about all that should be stored.</para>
/// </remarks>
public void AddCallbackArguments(string key, string value) {
- ErrorUtilities.VerifyOperation(this.RelyingParty.CanSignCallbackArguments, OpenIdStrings.CallbackArgumentsRequireSecretStore, typeof(IAssociationStore<Uri>).Name, typeof(OpenIdRelyingParty).Name);
+ ErrorUtilities.VerifyOperation(this.RelyingParty.CanSignCallbackArguments, OpenIdStrings.CallbackArgumentsRequireSecretStore, typeof(IRelyingPartyAssociationStore).Name, typeof(OpenIdRelyingParty).Name);
this.returnToArgsMustBeSigned = true;
this.returnToArgs.Add(key, value);
@@ -260,7 +260,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// small to ensure successful authentication. About 1.5KB is about all that should be stored.</para>
/// </remarks>
public void SetCallbackArgument(string key, string value) {
- ErrorUtilities.VerifyOperation(this.RelyingParty.CanSignCallbackArguments, OpenIdStrings.CallbackArgumentsRequireSecretStore, typeof(IAssociationStore<Uri>).Name, typeof(OpenIdRelyingParty).Name);
+ ErrorUtilities.VerifyOperation(this.RelyingParty.CanSignCallbackArguments, OpenIdStrings.CallbackArgumentsRequireSecretStore, typeof(IRelyingPartyAssociationStore).Name, typeof(OpenIdRelyingParty).Name);
this.returnToArgsMustBeSigned = true;
this.returnToArgs[key] = value;
@@ -295,12 +295,10 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <summary>
/// Redirects the user agent to the provider for authentication.
- /// Execution of the current page terminates after this call.
/// </summary>
/// <remarks>
/// This method requires an ASP.NET HttpContext.
/// </remarks>
- /// <exception cref="ThreadAbortException">Typically thrown by ASP.NET in order to prevent additional data from the page being sent to the client and corrupting the response.</exception>
public void RedirectToProvider() {
this.RedirectingResponse.Send();
}
@@ -321,9 +319,9 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// Never null, but may be empty.
/// </returns>
internal static IEnumerable<AuthenticationRequest> Create(Identifier userSuppliedIdentifier, OpenIdRelyingParty relyingParty, Realm realm, Uri returnToUrl, bool createNewAssociationsAsNeeded) {
- Contract.Requires<ArgumentNullException>(userSuppliedIdentifier != null);
- Contract.Requires<ArgumentNullException>(relyingParty != null);
- Contract.Requires<ArgumentNullException>(realm != null);
+ Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier");
+ Requires.NotNull(relyingParty, "relyingParty");
+ Requires.NotNull(realm, "realm");
Contract.Ensures(Contract.Result<IEnumerable<AuthenticationRequest>>() != null);
// Normalize the portion of the return_to path that correlates to the realm for capitalization.
@@ -498,8 +496,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <param name="relyingParty">The relying party.</param>
/// <returns>A filtered and sorted list of endpoints; may be empty if the input was empty or the filter removed all endpoints.</returns>
private static List<IdentifierDiscoveryResult> FilterAndSortEndpoints(IEnumerable<IdentifierDiscoveryResult> endpoints, OpenIdRelyingParty relyingParty) {
- Contract.Requires<ArgumentNullException>(endpoints != null);
- Contract.Requires<ArgumentNullException>(relyingParty != null);
+ Requires.NotNull(endpoints, "endpoints");
+ Requires.NotNull(relyingParty, "relyingParty");
bool anyFilteredOut = false;
var filteredEndpoints = new List<IdentifierDiscoveryResult>();
@@ -556,7 +554,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
request.AssociationHandle = association != null ? association.Handle : null;
request.SignReturnTo = this.returnToArgsMustBeSigned;
request.AddReturnToArguments(this.returnToArgs);
- if (this.DiscoveryResult.UserSuppliedIdentifier != null && DotNetOpenAuthSection.Configuration.OpenId.RelyingParty.PreserveUserSuppliedIdentifier) {
+ if (this.DiscoveryResult.UserSuppliedIdentifier != null && OpenIdElement.Configuration.RelyingParty.PreserveUserSuppliedIdentifier) {
request.AddReturnToArguments(UserSuppliedIdentifierParameterName, this.DiscoveryResult.UserSuppliedIdentifier.OriginalString);
}
foreach (IOpenIdMessageExtension extension in this.extensions) {
diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Behaviors/AXFetchAsSregTransform.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Behaviors/AXFetchAsSregTransform.cs
new file mode 100644
index 0000000..b2794ec
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Behaviors/AXFetchAsSregTransform.cs
@@ -0,0 +1,76 @@
+//-----------------------------------------------------------------------
+// <copyright file="AXFetchAsSregTransform.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.RelyingParty.Behaviors {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OpenId.Behaviors;
+ using DotNetOpenAuth.OpenId.Extensions;
+ using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
+ using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
+ using DotNetOpenAuth.OpenId.RelyingParty;
+ using DotNetOpenAuth.OpenId.RelyingParty.Extensions;
+
+ /// <summary>
+ /// An Attribute Exchange and Simple Registration filter to make all incoming attribute
+ /// requests look like Simple Registration requests, and to convert the response
+ /// to the originally requested extension and format.
+ /// </summary>
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sreg", Justification = "Abbreviation")]
+ public sealed class AXFetchAsSregTransform : AXFetchAsSregTransformBase, IRelyingPartyBehavior {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AXFetchAsSregTransform"/> class.
+ /// </summary>
+ public AXFetchAsSregTransform() {
+ }
+
+ #region IRelyingPartyBehavior Members
+
+ /// <summary>
+ /// Applies a well known set of security requirements to a default set of security settings.
+ /// </summary>
+ /// <param name="securitySettings">The security settings to enhance with the requirements of this profile.</param>
+ /// <remarks>
+ /// Care should be taken to never decrease security when applying a profile.
+ /// Profiles should only enhance security requirements to avoid being
+ /// incompatible with each other.
+ /// </remarks>
+ void IRelyingPartyBehavior.ApplySecuritySettings(RelyingPartySecuritySettings securitySettings) {
+ }
+
+ /// <summary>
+ /// Called when an authentication request is about to be sent.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ /// <remarks>
+ /// Implementations should be prepared to be called multiple times on the same outgoing message
+ /// without malfunctioning.
+ /// </remarks>
+ void IRelyingPartyBehavior.OnOutgoingAuthenticationRequest(RelyingParty.IAuthenticationRequest request) {
+ // Don't create AX extensions for OpenID 1.x messages, since AX requires OpenID 2.0.
+ if (request.Provider.Version.Major >= 2) {
+ request.SpreadSregToAX(this.AXFormats);
+ }
+ }
+
+ /// <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);
+ }
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Behaviors/GsaIcamProfile.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Behaviors/GsaIcamProfile.cs
new file mode 100644
index 0000000..5a1ddaa
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Behaviors/GsaIcamProfile.cs
@@ -0,0 +1,124 @@
+//-----------------------------------------------------------------------
+// <copyright file="GsaIcamProfile.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.RelyingParty.Behaviors {
+ using System;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using DotNetOpenAuth.Configuration;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OpenId.Behaviors;
+ using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
+ using DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy;
+ using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
+ using DotNetOpenAuth.OpenId.RelyingParty;
+
+ /// <summary>
+ /// Implements the Identity, Credential, &amp; Access Management (ICAM) OpenID 2.0 Profile
+ /// for the General Services Administration (GSA).
+ /// </summary>
+ /// <remarks>
+ /// <para>Relying parties that include this profile are always held to the terms required by the profile,
+ /// but Providers are only affected by the special behaviors of the profile when the RP specifically
+ /// indicates that they want to use this profile. </para>
+ /// </remarks>
+ [Serializable]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Icam", Justification = "Acronym")]
+ public sealed class GsaIcamProfile : GsaIcamProfileBase, IRelyingPartyBehavior {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="GsaIcamProfile"/> class.
+ /// </summary>
+ public GsaIcamProfile() {
+ if (DisableSslRequirement) {
+ Logger.OpenId.Warn("GSA level 1 behavior has its RequireSsl requirement disabled.");
+ }
+ }
+
+ #region IRelyingPartyBehavior Members
+
+ /// <summary>
+ /// Applies a well known set of security requirements.
+ /// </summary>
+ /// <param name="securitySettings">The security settings to enhance with the requirements of this profile.</param>
+ /// <remarks>
+ /// Care should be taken to never decrease security when applying a profile.
+ /// Profiles should only enhance security requirements to avoid being
+ /// incompatible with each other.
+ /// </remarks>
+ void IRelyingPartyBehavior.ApplySecuritySettings(RelyingPartySecuritySettings securitySettings) {
+ if (securitySettings.MaximumHashBitLength < 256) {
+ securitySettings.MaximumHashBitLength = 256;
+ }
+
+ securitySettings.RequireSsl = !DisableSslRequirement;
+ securitySettings.RequireDirectedIdentity = true;
+ securitySettings.RequireAssociation = true;
+ securitySettings.RejectDelegatingIdentifiers = true;
+ securitySettings.IgnoreUnsignedExtensions = true;
+ securitySettings.MinimumRequiredOpenIdVersion = ProtocolVersion.V20;
+ }
+
+ /// <summary>
+ /// Called when an authentication request is about to be sent.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ void IRelyingPartyBehavior.OnOutgoingAuthenticationRequest(RelyingParty.IAuthenticationRequest request) {
+ RelyingParty.AuthenticationRequest requestInternal = (RelyingParty.AuthenticationRequest)request;
+ ErrorUtilities.VerifyProtocol(string.Equals(request.Realm.Scheme, Uri.UriSchemeHttps, StringComparison.Ordinal) || DisableSslRequirement, BehaviorStrings.RealmMustBeHttps);
+
+ var pape = requestInternal.AppliedExtensions.OfType<PolicyRequest>().SingleOrDefault();
+ if (pape == null) {
+ request.AddExtension(pape = new PolicyRequest());
+ }
+
+ if (!pape.PreferredPolicies.Contains(AuthenticationPolicies.PrivatePersonalIdentifier)) {
+ pape.PreferredPolicies.Add(AuthenticationPolicies.PrivatePersonalIdentifier);
+ }
+
+ if (!pape.PreferredPolicies.Contains(AuthenticationPolicies.USGovernmentTrustLevel1)) {
+ pape.PreferredPolicies.Add(AuthenticationPolicies.USGovernmentTrustLevel1);
+ }
+
+ if (!AllowPersonallyIdentifiableInformation && !pape.PreferredPolicies.Contains(AuthenticationPolicies.NoPersonallyIdentifiableInformation)) {
+ pape.PreferredPolicies.Add(AuthenticationPolicies.NoPersonallyIdentifiableInformation);
+ }
+
+ if (pape.PreferredPolicies.Contains(AuthenticationPolicies.NoPersonallyIdentifiableInformation)) {
+ ErrorUtilities.VerifyProtocol(
+ (!requestInternal.AppliedExtensions.OfType<ClaimsRequest>().Any() &&
+ !requestInternal.AppliedExtensions.OfType<FetchRequest>().Any()),
+ BehaviorStrings.PiiIncludedWithNoPiiPolicy);
+ }
+
+ Reporting.RecordEventOccurrence(this, "RP");
+ }
+
+ /// <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);
+ }
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/CryptoKeyStoreAsRelyingPartyAssociationStore.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/CryptoKeyStoreAsRelyingPartyAssociationStore.cs
new file mode 100644
index 0000000..1614145
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/CryptoKeyStoreAsRelyingPartyAssociationStore.cs
@@ -0,0 +1,87 @@
+//-----------------------------------------------------------------------
+// <copyright file="CryptoKeyStoreAsRelyingPartyAssociationStore.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.RelyingParty {
+ using System;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using DotNetOpenAuth.Messaging.Bindings;
+
+ /// <summary>
+ /// Wraps a standard <see cref="ICryptoKeyStore"/> so that it behaves as an association store.
+ /// </summary>
+ internal class CryptoKeyStoreAsRelyingPartyAssociationStore : IRelyingPartyAssociationStore {
+ /// <summary>
+ /// The underlying key store.
+ /// </summary>
+ private readonly ICryptoKeyStore keyStore;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CryptoKeyStoreAsRelyingPartyAssociationStore"/> class.
+ /// </summary>
+ /// <param name="keyStore">The key store.</param>
+ internal CryptoKeyStoreAsRelyingPartyAssociationStore(ICryptoKeyStore keyStore) {
+ Requires.NotNull(keyStore, "keyStore");
+ Contract.Ensures(this.keyStore == keyStore);
+ this.keyStore = keyStore;
+ }
+
+ /// <summary>
+ /// Saves an <see cref="Association"/> for later recall.
+ /// </summary>
+ /// <param name="providerEndpoint">The OP Endpoint with which the association is established.</param>
+ /// <param name="association">The association to store.</param>
+ public void StoreAssociation(Uri providerEndpoint, Association association) {
+ var cryptoKey = new CryptoKey(association.SerializePrivateData(), association.Expires);
+ this.keyStore.StoreKey(providerEndpoint.AbsoluteUri, association.Handle, cryptoKey);
+ }
+
+ /// <summary>
+ /// Gets the best association (the one with the longest remaining life) for a given key.
+ /// </summary>
+ /// <param name="providerEndpoint">The OP Endpoint with which the association is established.</param>
+ /// <param name="securityRequirements">The security requirements that the returned association must meet.</param>
+ /// <returns>
+ /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key.
+ /// </returns>
+ public Association GetAssociation(Uri providerEndpoint, SecuritySettings securityRequirements) {
+ var matches = from cryptoKey in this.keyStore.GetKeys(providerEndpoint.AbsoluteUri)
+ where cryptoKey.Value.ExpiresUtc > DateTime.UtcNow
+ orderby cryptoKey.Value.ExpiresUtc descending
+ let assoc = Association.Deserialize(cryptoKey.Key, cryptoKey.Value.ExpiresUtc, cryptoKey.Value.Key)
+ where assoc.HashBitLength >= securityRequirements.MinimumHashBitLength
+ where assoc.HashBitLength <= securityRequirements.MaximumHashBitLength
+ select assoc;
+ return matches.FirstOrDefault();
+ }
+
+ /// <summary>
+ /// Gets the association for a given key and handle.
+ /// </summary>
+ /// <param name="providerEndpoint">The OP Endpoint with which the association is established.</param>
+ /// <param name="handle">The handle of the specific association that must be recalled.</param>
+ /// <returns>
+ /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key and handle.
+ /// </returns>
+ public Association GetAssociation(Uri providerEndpoint, string handle) {
+ var cryptoKey = this.keyStore.GetKey(providerEndpoint.AbsoluteUri, handle);
+ return cryptoKey != null ? Association.Deserialize(handle, cryptoKey.ExpiresUtc, cryptoKey.Key) : null;
+ }
+
+ /// <summary>
+ /// Removes a specified handle that may exist in the store.
+ /// </summary>
+ /// <param name="providerEndpoint">The OP Endpoint with which the association is established.</param>
+ /// <param name="handle">The handle of the specific association that must be deleted.</param>
+ /// <returns>
+ /// True if the association existed in this store previous to this call.
+ /// </returns>
+ public bool RemoveAssociation(Uri providerEndpoint, string handle) {
+ this.keyStore.RemoveKey(providerEndpoint.AbsoluteUri, handle);
+ return true; // return value isn't used by DNOA.
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/DuplicateRequestedHostsComparer.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/DuplicateRequestedHostsComparer.cs
index 94eb5ba..94eb5ba 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/DuplicateRequestedHostsComparer.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/DuplicateRequestedHostsComparer.cs
diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Extensions/ExtensionsInteropHelper.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Extensions/ExtensionsInteropHelper.cs
new file mode 100644
index 0000000..0f7778f
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Extensions/ExtensionsInteropHelper.cs
@@ -0,0 +1,152 @@
+//-----------------------------------------------------------------------
+// <copyright file="ExtensionsInteropHelper.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.RelyingParty.Extensions {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OpenId.Extensions;
+ using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
+ using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
+ using DotNetOpenAuth.OpenId.Messages;
+
+ /// <summary>
+ /// A set of methods designed to assist in improving interop across different
+ /// OpenID implementations and their extensions.
+ /// </summary>
+ public static class ExtensionsInteropHelper {
+ /// <summary>
+ /// Adds an Attribute Exchange (AX) extension to the authentication request
+ /// that asks for the same attributes as the Simple Registration (sreg) extension
+ /// that is already applied.
+ /// </summary>
+ /// <param name="request">The authentication request.</param>
+ /// <param name="attributeFormats">The attribute formats to use in the AX request.</param>
+ /// <remarks>
+ /// <para>If discovery on the user-supplied identifier yields hints regarding which
+ /// extensions and attribute formats the Provider supports, this method MAY ignore the
+ /// <paramref name="attributeFormats"/> argument and accomodate the Provider to minimize
+ /// the size of the request.</para>
+ /// <para>If the request does not carry an sreg extension, the method logs a warning but
+ /// otherwise quietly returns doing nothing.</para>
+ /// </remarks>
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sreg", Justification = "Abbreviation")]
+ public static void SpreadSregToAX(this RelyingParty.IAuthenticationRequest request, AXAttributeFormats attributeFormats) {
+ Requires.NotNull(request, "request");
+
+ var req = (RelyingParty.AuthenticationRequest)request;
+ var sreg = req.AppliedExtensions.OfType<ClaimsRequest>().SingleOrDefault();
+ if (sreg == null) {
+ Logger.OpenId.Debug("No Simple Registration (ClaimsRequest) extension present in the request to spread to AX.");
+ return;
+ }
+
+ if (req.DiscoveryResult.IsExtensionSupported<ClaimsRequest>()) {
+ Logger.OpenId.Debug("Skipping generation of AX request because the Identifier advertises the Provider supports the Sreg extension.");
+ return;
+ }
+
+ var ax = req.AppliedExtensions.OfType<FetchRequest>().SingleOrDefault();
+ if (ax == null) {
+ ax = new FetchRequest();
+ req.AddExtension(ax);
+ }
+
+ // Try to use just one AX Type URI format if we can figure out which type the OP accepts.
+ AXAttributeFormats detectedFormat;
+ if (TryDetectOPAttributeFormat(request, out detectedFormat)) {
+ Logger.OpenId.Debug("Detected OP support for AX but not for Sreg. Removing Sreg extension request and using AX instead.");
+ attributeFormats = detectedFormat;
+ req.Extensions.Remove(sreg);
+ } else {
+ Logger.OpenId.Debug("Could not determine whether OP supported Sreg or AX. Using both extensions.");
+ }
+
+ foreach (AXAttributeFormats format in OpenIdExtensionsInteropHelper.ForEachFormat(attributeFormats)) {
+ OpenIdExtensionsInteropHelper.FetchAttribute(ax, format, WellKnownAttributes.BirthDate.WholeBirthDate, sreg.BirthDate);
+ OpenIdExtensionsInteropHelper.FetchAttribute(ax, format, WellKnownAttributes.Contact.HomeAddress.Country, sreg.Country);
+ OpenIdExtensionsInteropHelper.FetchAttribute(ax, format, WellKnownAttributes.Contact.Email, sreg.Email);
+ OpenIdExtensionsInteropHelper.FetchAttribute(ax, format, WellKnownAttributes.Name.FullName, sreg.FullName);
+ OpenIdExtensionsInteropHelper.FetchAttribute(ax, format, WellKnownAttributes.Person.Gender, sreg.Gender);
+ OpenIdExtensionsInteropHelper.FetchAttribute(ax, format, WellKnownAttributes.Preferences.Language, sreg.Language);
+ OpenIdExtensionsInteropHelper.FetchAttribute(ax, format, WellKnownAttributes.Name.Alias, sreg.Nickname);
+ OpenIdExtensionsInteropHelper.FetchAttribute(ax, format, WellKnownAttributes.Contact.HomeAddress.PostalCode, sreg.PostalCode);
+ OpenIdExtensionsInteropHelper.FetchAttribute(ax, format, WellKnownAttributes.Preferences.TimeZone, sreg.TimeZone);
+ }
+ }
+
+ /// <summary>
+ /// Looks for Simple Registration and Attribute Exchange (all known formats)
+ /// response extensions and returns them as a Simple Registration extension.
+ /// </summary>
+ /// <param name="response">The authentication response.</param>
+ /// <param name="allowUnsigned">if set to <c>true</c> unsigned extensions will be included in the search.</param>
+ /// <returns>
+ /// The Simple Registration response if found,
+ /// or a fabricated one based on the Attribute Exchange extension if found,
+ /// or just an empty <see cref="ClaimsResponse"/> if there was no data.
+ /// Never <c>null</c>.</returns>
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sreg", Justification = "Abbreviation")]
+ public static ClaimsResponse UnifyExtensionsAsSreg(this RelyingParty.IAuthenticationResponse response, bool allowUnsigned) {
+ Requires.NotNull(response, "response");
+
+ var resp = (RelyingParty.IAuthenticationResponse)response;
+ var sreg = allowUnsigned ? resp.GetUntrustedExtension<ClaimsResponse>() : resp.GetExtension<ClaimsResponse>();
+ if (sreg != null) {
+ return sreg;
+ }
+
+ AXAttributeFormats formats = AXAttributeFormats.All;
+ sreg = new ClaimsResponse();
+ var fetchResponse = allowUnsigned ? resp.GetUntrustedExtension<FetchResponse>() : resp.GetExtension<FetchResponse>();
+ if (fetchResponse != null) {
+ ((IOpenIdMessageExtension)sreg).IsSignedByRemoteParty = fetchResponse.IsSignedByProvider;
+ sreg.BirthDateRaw = fetchResponse.GetAttributeValue(WellKnownAttributes.BirthDate.WholeBirthDate, formats);
+ sreg.Country = fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.HomeAddress.Country, formats);
+ sreg.PostalCode = fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.HomeAddress.PostalCode, formats);
+ sreg.Email = fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Email, formats);
+ sreg.FullName = fetchResponse.GetAttributeValue(WellKnownAttributes.Name.FullName, formats);
+ sreg.Language = fetchResponse.GetAttributeValue(WellKnownAttributes.Preferences.Language, formats);
+ sreg.Nickname = fetchResponse.GetAttributeValue(WellKnownAttributes.Name.Alias, formats);
+ sreg.TimeZone = fetchResponse.GetAttributeValue(WellKnownAttributes.Preferences.TimeZone, formats);
+ string gender = fetchResponse.GetAttributeValue(WellKnownAttributes.Person.Gender, formats);
+ if (gender != null) {
+ sreg.Gender = (Gender)OpenIdExtensionsInteropHelper.GenderEncoder.Decode(gender);
+ }
+ }
+
+ return sreg;
+ }
+
+ /// <summary>
+ /// Gets the attribute value if available.
+ /// </summary>
+ /// <param name="fetchResponse">The AX fetch response extension to look for the attribute value.</param>
+ /// <param name="typeUri">The type URI of the attribute, using the axschema.org format of <see cref="WellKnownAttributes"/>.</param>
+ /// <param name="formats">The AX type URI formats to search.</param>
+ /// <returns>
+ /// The first value of the attribute, if available.
+ /// </returns>
+ internal static string GetAttributeValue(this FetchResponse fetchResponse, string typeUri, AXAttributeFormats formats) {
+ return OpenIdExtensionsInteropHelper.ForEachFormat(formats).Select(format => fetchResponse.GetAttributeValue(OpenIdExtensionsInteropHelper.TransformAXFormat(typeUri, format))).FirstOrDefault(s => s != null);
+ }
+
+ /// <summary>
+ /// Tries to find the exact format of AX attribute Type URI supported by the Provider.
+ /// </summary>
+ /// <param name="request">The authentication request.</param>
+ /// <param name="attributeFormat">The attribute formats the RP will try if this discovery fails.</param>
+ /// <returns>The AX format(s) to use based on the Provider's advertised AX support.</returns>
+ private static bool TryDetectOPAttributeFormat(RelyingParty.IAuthenticationRequest request, out AXAttributeFormats attributeFormat) {
+ Requires.NotNull(request, "request");
+ attributeFormat = OpenIdExtensionsInteropHelper.DetectAXFormat(request.DiscoveryResult.Capabilities);
+ return attributeFormat != AXAttributeFormats.None;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/UI/UIUtilities.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Extensions/UIUtilities.cs
index cee6882..4606bf7 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/UI/UIUtilities.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Extensions/UIUtilities.cs
@@ -4,7 +4,7 @@
// </copyright>
//-----------------------------------------------------------------------
-namespace DotNetOpenAuth.OpenId.Extensions.UI {
+namespace DotNetOpenAuth.OpenId.RelyingParty.Extensions.UI {
using System;
using System.Diagnostics.Contracts;
using System.Globalization;
@@ -14,17 +14,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.UI {
/// <summary>
/// Constants used in implementing support for the UI extension.
/// </summary>
- public static class UIUtilities {
- /// <summary>
- /// The required width of the popup window the relying party creates for the provider.
- /// </summary>
- public const int PopupWidth = 500; // UI extension calls for 450px, but Yahoo needs 500px
-
- /// <summary>
- /// The required height of the popup window the relying party creates for the provider.
- /// </summary>
- public const int PopupHeight = 500;
-
+ internal static class UIUtilities {
/// <summary>
/// Gets the <c>window.open</c> javascript snippet to use to open a popup window
/// compliant with the UI extension.
@@ -34,9 +24,9 @@ namespace DotNetOpenAuth.OpenId.Extensions.UI {
/// <param name="windowName">The name to assign to the popup window.</param>
/// <returns>A string starting with 'window.open' and forming just that one method call.</returns>
internal static string GetWindowPopupScript(OpenIdRelyingParty relyingParty, IAuthenticationRequest request, string windowName) {
- Contract.Requires<ArgumentNullException>(relyingParty != null);
- Contract.Requires<ArgumentNullException>(request != null);
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(windowName));
+ Requires.NotNull(relyingParty, "relyingParty");
+ Requires.NotNull(request, "request");
+ Requires.NotNullOrEmpty(windowName, "windowName");
Uri popupUrl = request.RedirectingResponse.GetDirectUriRequest(relyingParty.Channel);
@@ -45,8 +35,8 @@ namespace DotNetOpenAuth.OpenId.Extensions.UI {
"(window.showModalDialog ? window.showModalDialog({0}, {1}, 'status:0;resizable:1;scroll:1;center:1;dialogWidth:{2}px; dialogHeight:{3}') : window.open({0}, {1}, 'status=0,toolbar=0,location=1,resizable=1,scrollbars=1,left=' + ((screen.width - {2}) / 2) + ',top=' + ((screen.height - {3}) / 2) + ',width={2},height={3}'));",
MessagingUtilities.GetSafeJavascriptValue(popupUrl.AbsoluteUri),
MessagingUtilities.GetSafeJavascriptValue(windowName),
- PopupWidth,
- PopupHeight);
+ OpenId.Extensions.UI.UIUtilities.PopupWidth,
+ OpenId.Extensions.UI.UIUtilities.PopupHeight);
}
}
}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/FailedAuthenticationResponse.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/FailedAuthenticationResponse.cs
index 682e3ff..b9266d3 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/FailedAuthenticationResponse.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/FailedAuthenticationResponse.cs
@@ -28,7 +28,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <param name="exception">The exception that resulted in the failed authentication.</param>
internal FailedAuthenticationResponse(Exception exception) {
- Contract.Requires<ArgumentNullException>(exception != null);
+ Requires.NotNull(exception, "exception");
this.Exception = exception;
diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/IRelyingPartyAssociationStore.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/IRelyingPartyAssociationStore.cs
new file mode 100644
index 0000000..52e828c
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/IRelyingPartyAssociationStore.cs
@@ -0,0 +1,153 @@
+//-----------------------------------------------------------------------
+// <copyright file="IRelyingPartyAssociationStore.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.RelyingParty {
+ using System;
+ using System.Diagnostics.Contracts;
+
+ /// <summary>
+ /// Stores <see cref="Association"/>s for lookup by their handle, keeping
+ /// associations separated by a given OP Endpoint.
+ /// </summary>
+ /// <remarks>
+ /// Expired associations should be periodically cleared out of an association store.
+ /// This should be done frequently enough to avoid a memory leak, but sparingly enough
+ /// to not be a performance drain. Because this balance can vary by host, it is the
+ /// responsibility of the host to initiate this cleaning.
+ /// </remarks>
+ [ContractClass(typeof(IRelyingPartyAssociationStoreContract))]
+ public interface IRelyingPartyAssociationStore {
+ /// <summary>
+ /// Saves an <see cref="Association"/> for later recall.
+ /// </summary>
+ /// <param name="providerEndpoint">The OP Endpoint with which the association is established.</param>
+ /// <param name="association">The association to store.</param>
+ /// <remarks>
+ /// If the new association conflicts (in OP endpoint and association handle) with an existing association,
+ /// (which should never happen by the way) implementations may overwrite the previously saved association.
+ /// </remarks>
+ void StoreAssociation(Uri providerEndpoint, Association association);
+
+ /// <summary>
+ /// Gets the best association (the one with the longest remaining life) for a given key.
+ /// </summary>
+ /// <param name="providerEndpoint">The OP Endpoint with which the association is established.</param>
+ /// <param name="securityRequirements">The security requirements that the returned association must meet.</param>
+ /// <returns>
+ /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key.
+ /// </returns>
+ /// <remarks>
+ /// In the event that multiple associations exist for the given
+ /// <paramref name="providerEndpoint"/>, it is important for the
+ /// implementation for this method to use the <paramref name="securityRequirements"/>
+ /// to pick the best (highest grade or longest living as the host's policy may dictate)
+ /// association that fits the security requirements.
+ /// Associations that are returned that do not meet the security requirements will be
+ /// ignored and a new association created.
+ /// </remarks>
+ Association GetAssociation(Uri providerEndpoint, SecuritySettings securityRequirements);
+
+ /// <summary>
+ /// Gets the association for a given key and handle.
+ /// </summary>
+ /// <param name="providerEndpoint">The OP Endpoint with which the association is established.</param>
+ /// <param name="handle">The handle of the specific association that must be recalled.</param>
+ /// <returns>The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key and handle.</returns>
+ Association GetAssociation(Uri providerEndpoint, string handle);
+
+ /// <summary>Removes a specified handle that may exist in the store.</summary>
+ /// <param name="providerEndpoint">The OP Endpoint with which the association is established.</param>
+ /// <param name="handle">The handle of the specific association that must be deleted.</param>
+ /// <returns>
+ /// Deprecated. The return value is insignificant.
+ /// Previously: True if the association existed in this store previous to this call.
+ /// </returns>
+ /// <remarks>
+ /// No exception should be thrown if the association does not exist in the store
+ /// before this call.
+ /// </remarks>
+ bool RemoveAssociation(Uri providerEndpoint, string handle);
+ }
+
+ /// <summary>
+ /// Code Contract for the <see cref="IRelyingPartyAssociationStore"/> class.
+ /// </summary>
+ [ContractClassFor(typeof(IRelyingPartyAssociationStore))]
+ internal abstract class IRelyingPartyAssociationStoreContract : IRelyingPartyAssociationStore {
+ #region IAssociationStore Members
+
+ /// <summary>
+ /// Saves an <see cref="Association"/> for later recall.
+ /// </summary>
+ /// <param name="providerEndpoint">The Uri (for relying parties) or Smart/Dumb (for providers).</param>
+ /// <param name="association">The association to store.</param>
+ /// <remarks>
+ /// TODO: what should implementations do on association handle conflict?
+ /// </remarks>
+ void IRelyingPartyAssociationStore.StoreAssociation(Uri providerEndpoint, Association association) {
+ Requires.NotNull(providerEndpoint, "providerEndpoint");
+ Requires.NotNull(association, "association");
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Gets the best association (the one with the longest remaining life) for a given key.
+ /// </summary>
+ /// <param name="providerEndpoint">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
+ /// <param name="securityRequirements">The security requirements that the returned association must meet.</param>
+ /// <returns>
+ /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key.
+ /// </returns>
+ /// <remarks>
+ /// In the event that multiple associations exist for the given
+ /// <paramref name="providerEndpoint"/>, it is important for the
+ /// implementation for this method to use the <paramref name="securityRequirements"/>
+ /// to pick the best (highest grade or longest living as the host's policy may dictate)
+ /// association that fits the security requirements.
+ /// Associations that are returned that do not meet the security requirements will be
+ /// ignored and a new association created.
+ /// </remarks>
+ Association IRelyingPartyAssociationStore.GetAssociation(Uri providerEndpoint, SecuritySettings securityRequirements) {
+ Requires.NotNull(providerEndpoint, "providerEndpoint");
+ Requires.NotNull(securityRequirements, "securityRequirements");
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Gets the association for a given key and handle.
+ /// </summary>
+ /// <param name="providerEndpoint">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
+ /// <param name="handle">The handle of the specific association that must be recalled.</param>
+ /// <returns>
+ /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key and handle.
+ /// </returns>
+ Association IRelyingPartyAssociationStore.GetAssociation(Uri providerEndpoint, string handle) {
+ Requires.NotNull(providerEndpoint, "providerEndpoint");
+ Contract.Requires(!String.IsNullOrEmpty(handle));
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Removes a specified handle that may exist in the store.
+ /// </summary>
+ /// <param name="providerEndpoint">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
+ /// <param name="handle">The handle of the specific association that must be deleted.</param>
+ /// <returns>
+ /// True if the association existed in this store previous to this call.
+ /// </returns>
+ /// <remarks>
+ /// No exception should be thrown if the association does not exist in the store
+ /// before this call.
+ /// </remarks>
+ bool IRelyingPartyAssociationStore.RemoveAssociation(Uri providerEndpoint, string handle) {
+ Requires.NotNull(providerEndpoint, "providerEndpoint");
+ Contract.Requires(!String.IsNullOrEmpty(handle));
+ throw new NotImplementedException();
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/ISetupRequiredAuthenticationResponse.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/ISetupRequiredAuthenticationResponse.cs
index cfbccef..2942c9d 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/ISetupRequiredAuthenticationResponse.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/ISetupRequiredAuthenticationResponse.cs
@@ -41,7 +41,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
Identifier ISetupRequiredAuthenticationResponse.UserSuppliedIdentifier {
get {
- Contract.Requires<InvalidOperationException>(((IAuthenticationResponse)this).Status == AuthenticationStatus.SetupRequired, OpenIdStrings.OperationOnlyValidForSetupRequiredState);
+ Requires.ValidState(((IAuthenticationResponse)this).Status == AuthenticationStatus.SetupRequired, OpenIdStrings.OperationOnlyValidForSetupRequiredState);
throw new System.NotImplementedException();
}
}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/NegativeAuthenticationResponse.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/NegativeAuthenticationResponse.cs
index 9e3824d..4b21fea 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/NegativeAuthenticationResponse.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/NegativeAuthenticationResponse.cs
@@ -29,7 +29,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <param name="response">The negative assertion response received by the Relying Party.</param>
internal NegativeAuthenticationResponse(NegativeAssertionResponse response) {
- Contract.Requires<ArgumentNullException>(response != null);
+ Requires.NotNull(response, "response");
this.response = response;
Reporting.RecordEventOccurrence(this, string.Empty);
@@ -132,6 +132,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <value></value>
public Identifier UserSuppliedIdentifier {
get {
+ ErrorUtilities.VerifyOperation(((IAuthenticationResponse)this).Status == AuthenticationStatus.SetupRequired, OpenIdStrings.OperationOnlyValidForSetupRequiredState);
string userSuppliedIdentifier;
this.response.ExtraData.TryGetValue(AuthenticationRequest.UserSuppliedIdentifierParameterName, out userSuppliedIdentifier);
return userSuppliedIdentifier;
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingParty.cd b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/OpenIdRelyingParty.cd
index 0519ecb..0519ecb 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingParty.cd
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/OpenIdRelyingParty.cd
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingParty.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/OpenIdRelyingParty.cs
index 57c1f05..509e319 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingParty.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/OpenIdRelyingParty.cs
@@ -59,6 +59,18 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
private readonly IList<IIdentifierDiscoveryService> discoveryServices = new List<IIdentifierDiscoveryService>(2);
/// <summary>
+ /// A type initializer that ensures that another type initializer runs in order to guarantee that
+ /// types are serializable.
+ /// </summary>
+ private static Identifier dummyIdentifierToInvokeStaticCtor = "http://localhost/";
+
+ /// <summary>
+ /// A type initializer that ensures that another type initializer runs in order to guarantee that
+ /// types are serializable.
+ /// </summary>
+ private static Realm dummyRealmToInvokeStaticCtor = "http://localhost/";
+
+ /// <summary>
/// Backing field for the <see cref="NonVerifyingRelyingParty"/> property.
/// </summary>
private OpenIdRelyingParty nonVerifyingRelyingParty;
@@ -93,37 +105,37 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// Initializes a new instance of the <see cref="OpenIdRelyingParty"/> class.
/// </summary>
public OpenIdRelyingParty()
- : this(DotNetOpenAuthSection.Configuration.OpenId.RelyingParty.ApplicationStore.CreateInstance(HttpApplicationStore)) {
+ : this(OpenIdElement.Configuration.RelyingParty.ApplicationStore.CreateInstance(HttpApplicationStore)) {
}
/// <summary>
/// Initializes a new instance of the <see cref="OpenIdRelyingParty"/> class.
/// </summary>
/// <param name="applicationStore">The application store. If <c>null</c>, the relying party will always operate in "dumb mode".</param>
- public OpenIdRelyingParty(IRelyingPartyApplicationStore applicationStore)
+ public OpenIdRelyingParty(IOpenIdApplicationStore applicationStore)
: this(applicationStore, applicationStore) {
}
/// <summary>
/// Initializes a new instance of the <see cref="OpenIdRelyingParty"/> class.
/// </summary>
- /// <param name="associationStore">The association store. If null, the relying party will always operate in "dumb mode".</param>
+ /// <param name="cryptoKeyStore">The association store. If null, the relying party will always operate in "dumb mode".</param>
/// <param name="nonceStore">The nonce store to use. If null, the relying party will always operate in "dumb mode".</param>
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Unavoidable")]
- private OpenIdRelyingParty(IAssociationStore<Uri> associationStore, INonceStore nonceStore) {
+ private OpenIdRelyingParty(ICryptoKeyStore cryptoKeyStore, INonceStore nonceStore) {
// If we are a smart-mode RP (supporting associations), then we MUST also be
// capable of storing nonces to prevent replay attacks.
// If we're a dumb-mode RP, then 2.0 OPs are responsible for preventing replays.
- Contract.Requires<ArgumentException>(associationStore == null || nonceStore != null, OpenIdStrings.AssociationStoreRequiresNonceStore);
+ Requires.True(cryptoKeyStore == null || nonceStore != null, null, OpenIdStrings.AssociationStoreRequiresNonceStore);
- this.securitySettings = DotNetOpenAuthSection.Configuration.OpenId.RelyingParty.SecuritySettings.CreateSecuritySettings();
+ this.securitySettings = OpenIdElement.Configuration.RelyingParty.SecuritySettings.CreateSecuritySettings();
- foreach (var discoveryService in DotNetOpenAuthSection.Configuration.OpenId.RelyingParty.DiscoveryServices.CreateInstances(true)) {
+ foreach (var discoveryService in OpenIdElement.Configuration.RelyingParty.DiscoveryServices.CreateInstances(true)) {
this.discoveryServices.Add(discoveryService);
}
this.behaviors.CollectionChanged += this.OnBehaviorsChanged;
- foreach (var behavior in DotNetOpenAuthSection.Configuration.OpenId.RelyingParty.Behaviors.CreateInstances(false)) {
+ foreach (var behavior in OpenIdElement.Configuration.RelyingParty.Behaviors.CreateInstances(false)) {
this.behaviors.Add(behavior);
}
@@ -137,10 +149,14 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
this.SecuritySettings.MinimumRequiredOpenIdVersion = ProtocolVersion.V20;
}
- this.channel = new OpenIdChannel(associationStore, nonceStore, this.SecuritySettings);
- this.AssociationManager = new AssociationManager(this.Channel, associationStore, this.SecuritySettings);
+ if (cryptoKeyStore == null) {
+ cryptoKeyStore = new MemoryCryptoKeyStore();
+ }
+
+ this.channel = new OpenIdRelyingPartyChannel(cryptoKeyStore, nonceStore, this.SecuritySettings);
+ this.AssociationManager = new AssociationManager(this.Channel, new CryptoKeyStoreAsRelyingPartyAssociationStore(cryptoKeyStore), this.SecuritySettings);
- Reporting.RecordFeatureAndDependencyUse(this, associationStore, nonceStore);
+ Reporting.RecordFeatureAndDependencyUse(this, cryptoKeyStore, nonceStore);
}
/// <summary>
@@ -160,17 +176,17 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// HttpApplication state dictionary to store associations and nonces.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
- public static IRelyingPartyApplicationStore HttpApplicationStore {
+ public static IOpenIdApplicationStore HttpApplicationStore {
get {
- Contract.Ensures(Contract.Result<IRelyingPartyApplicationStore>() != null);
+ Contract.Ensures(Contract.Result<IOpenIdApplicationStore>() != null);
HttpContext context = HttpContext.Current;
- ErrorUtilities.VerifyOperation(context != null, Strings.StoreRequiredWhenNoHttpContextAvailable, typeof(IRelyingPartyApplicationStore).Name);
- var store = (IRelyingPartyApplicationStore)context.Application[ApplicationStoreKey];
+ ErrorUtilities.VerifyOperation(context != null, Strings.StoreRequiredWhenNoHttpContextAvailable, typeof(IOpenIdApplicationStore).Name);
+ var store = (IOpenIdApplicationStore)context.Application[ApplicationStoreKey];
if (store == null) {
context.Application.Lock();
try {
- if ((store = (IRelyingPartyApplicationStore)context.Application[ApplicationStoreKey]) == null) {
+ if ((store = (IOpenIdApplicationStore)context.Application[ApplicationStoreKey]) == null) {
context.Application[ApplicationStoreKey] = store = new StandardRelyingPartyApplicationStore();
}
} finally {
@@ -191,7 +207,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
}
set {
- Contract.Requires<ArgumentNullException>(value != null);
+ Requires.NotNull(value, "value");
this.channel = value;
this.AssociationManager.Channel = value;
}
@@ -207,7 +223,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
}
internal set {
- Contract.Requires<ArgumentNullException>(value != null);
+ Requires.NotNull(value, "value");
this.securitySettings = value;
this.AssociationManager.SecuritySettings = value;
}
@@ -240,7 +256,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
}
set {
- Contract.Requires<ArgumentNullException>(value != null);
+ Requires.NotNull(value, "value");
this.endpointOrder = value;
}
}
@@ -331,9 +347,9 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </returns>
/// <exception cref="ProtocolException">Thrown if no OpenID endpoint could be found.</exception>
public IAuthenticationRequest CreateRequest(Identifier userSuppliedIdentifier, Realm realm, Uri returnToUrl) {
- Contract.Requires<ArgumentNullException>(userSuppliedIdentifier != null);
- Contract.Requires<ArgumentNullException>(realm != null);
- Contract.Requires<ArgumentNullException>(returnToUrl != null);
+ Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier");
+ Requires.NotNull(realm, "realm");
+ Requires.NotNull(returnToUrl, "returnToUrl");
Contract.Ensures(Contract.Result<IAuthenticationRequest>() != null);
try {
return this.CreateRequests(userSuppliedIdentifier, realm, returnToUrl).First();
@@ -364,8 +380,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <exception cref="ProtocolException">Thrown if no OpenID endpoint could be found.</exception>
/// <exception cref="InvalidOperationException">Thrown if <see cref="HttpContext.Current">HttpContext.Current</see> == <c>null</c>.</exception>
public IAuthenticationRequest CreateRequest(Identifier userSuppliedIdentifier, Realm realm) {
- Contract.Requires<ArgumentNullException>(userSuppliedIdentifier != null);
- Contract.Requires<ArgumentNullException>(realm != null);
+ Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier");
+ Requires.NotNull(realm, "realm");
Contract.Ensures(Contract.Result<IAuthenticationRequest>() != null);
try {
var result = this.CreateRequests(userSuppliedIdentifier, realm).First();
@@ -393,7 +409,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <exception cref="ProtocolException">Thrown if no OpenID endpoint could be found.</exception>
/// <exception cref="InvalidOperationException">Thrown if <see cref="HttpContext.Current">HttpContext.Current</see> == <c>null</c>.</exception>
public IAuthenticationRequest CreateRequest(Identifier userSuppliedIdentifier) {
- Contract.Requires<ArgumentNullException>(userSuppliedIdentifier != null);
+ Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier");
Contract.Ensures(Contract.Result<IAuthenticationRequest>() != null);
try {
return this.CreateRequests(userSuppliedIdentifier).First();
@@ -430,9 +446,9 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// An empty enumerable is returned instead.</para>
/// </remarks>
public virtual IEnumerable<IAuthenticationRequest> CreateRequests(Identifier userSuppliedIdentifier, Realm realm, Uri returnToUrl) {
- Contract.Requires<ArgumentNullException>(userSuppliedIdentifier != null);
- Contract.Requires<ArgumentNullException>(realm != null);
- Contract.Requires<ArgumentNullException>(returnToUrl != null);
+ Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier");
+ Requires.NotNull(realm, "realm");
+ Requires.NotNull(returnToUrl, "returnToUrl");
Contract.Ensures(Contract.Result<IEnumerable<IAuthenticationRequest>>() != null);
return AuthenticationRequest.Create(userSuppliedIdentifier, this, realm, returnToUrl, true).Cast<IAuthenticationRequest>().CacheGeneratedResults();
@@ -464,9 +480,9 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </remarks>
/// <exception cref="InvalidOperationException">Thrown if <see cref="HttpContext.Current">HttpContext.Current</see> == <c>null</c>.</exception>
public IEnumerable<IAuthenticationRequest> CreateRequests(Identifier userSuppliedIdentifier, Realm realm) {
- Contract.Requires<InvalidOperationException>(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
- Contract.Requires<ArgumentNullException>(userSuppliedIdentifier != null);
- Contract.Requires<ArgumentNullException>(realm != null);
+ Requires.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
+ Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier");
+ Requires.NotNull(realm, "realm");
Contract.Ensures(Contract.Result<IEnumerable<IAuthenticationRequest>>() != null);
// This next code contract is a BAD idea, because it causes each authentication request to be generated
@@ -512,8 +528,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </remarks>
/// <exception cref="InvalidOperationException">Thrown if <see cref="HttpContext.Current">HttpContext.Current</see> == <c>null</c>.</exception>
public IEnumerable<IAuthenticationRequest> CreateRequests(Identifier userSuppliedIdentifier) {
- Contract.Requires<ArgumentNullException>(userSuppliedIdentifier != null);
- Contract.Requires<InvalidOperationException>(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
+ Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier");
+ Requires.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
Contract.Ensures(Contract.Result<IEnumerable<IAuthenticationRequest>>() != null);
return this.CreateRequests(userSuppliedIdentifier, Realm.AutoDetect);
@@ -527,7 +543,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <para>Requires an <see cref="HttpContext.Current">HttpContext.Current</see> context.</para>
/// </remarks>
public IAuthenticationResponse GetResponse() {
- Contract.Requires<InvalidOperationException>(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
+ Requires.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
return this.GetResponse(this.Channel.GetRequestFromContext());
}
@@ -537,7 +553,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <param name="httpRequestInfo">The HTTP request that may be carrying an authentication response from the Provider.</param>
/// <returns>The processed authentication response if there is any; <c>null</c> otherwise.</returns>
public IAuthenticationResponse GetResponse(HttpRequestInfo httpRequestInfo) {
- Contract.Requires<ArgumentNullException>(httpRequestInfo != null);
+ Requires.NotNull(httpRequestInfo, "httpRequestInfo");
try {
var message = this.Channel.ReadFromRequest(httpRequestInfo);
PositiveAssertionResponse positiveAssertion;
@@ -580,7 +596,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <para>Requires an <see cref="HttpContext.Current">HttpContext.Current</see> context.</para>
/// </remarks>
public OutgoingWebResponse ProcessResponseFromPopup() {
- Contract.Requires<InvalidOperationException>(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
+ Requires.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null);
return this.ProcessResponseFromPopup(this.Channel.GetRequestFromContext());
@@ -592,7 +608,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <param name="request">The incoming HTTP request that is expected to carry an OpenID authentication response.</param>
/// <returns>The HTTP response to send to this HTTP request.</returns>
public OutgoingWebResponse ProcessResponseFromPopup(HttpRequestInfo request) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null);
return this.ProcessResponseFromPopup(request, null);
@@ -610,7 +626,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </remarks>
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "By design")]
public void RegisterClientScriptExtension<T>(string propertyName) where T : IClientScriptExtensionResponse {
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(propertyName));
+ Requires.NotNullOrEmpty(propertyName, "propertyName");
ErrorUtilities.VerifyArgumentNamed(!this.clientScriptExtensions.ContainsValue(propertyName), "propertyName", OpenIdStrings.ClientScriptExtensionPropertyNameCollision, propertyName);
foreach (var ext in this.clientScriptExtensions.Keys) {
ErrorUtilities.VerifyArgument(ext != typeof(T), OpenIdStrings.ClientScriptExtensionTypeCollision, typeof(T).FullName);
@@ -661,7 +677,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
internal static OpenIdRelyingParty CreateNonVerifying() {
OpenIdRelyingParty rp = new OpenIdRelyingParty();
try {
- rp.Channel = OpenIdChannel.CreateNonVerifyingChannel();
+ rp.Channel = OpenIdRelyingPartyChannel.CreateNonVerifyingChannel();
return rp;
} catch {
rp.Dispose();
@@ -679,7 +695,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </returns>
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "OpenID", Justification = "real word"), SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "iframe", Justification = "Code contracts")]
internal OutgoingWebResponse ProcessResponseFromPopup(HttpRequestInfo request, Action<AuthenticationStatus> callback) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null);
string extensionsJson = null;
@@ -736,7 +752,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <param name="identifier">The identifier to discover services for.</param>
/// <returns>A non-null sequence of services discovered for the identifier.</returns>
internal IEnumerable<IdentifierDiscoveryResult> Discover(Identifier identifier) {
- Contract.Requires<ArgumentNullException>(identifier != null);
+ Requires.NotNull(identifier, "identifier");
Contract.Ensures(Contract.Result<IEnumerable<IdentifierDiscoveryResult>>() != null);
IEnumerable<IdentifierDiscoveryResult> results = Enumerable.Empty<IdentifierDiscoveryResult>();
@@ -824,7 +840,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// parameters. (i.e. "callback('arg1', 2)"). No escaping is done by this method.</param>
/// <returns>The entire HTTP response to send to the popup window or iframe to perform the invocation.</returns>
private static OutgoingWebResponse InvokeParentPageScript(string methodCall) {
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(methodCall));
+ Requires.NotNullOrEmpty(methodCall, "methodCall");
Logger.OpenId.DebugFormat("Sending Javascript callback: {0}", methodCall);
StringBuilder builder = new StringBuilder();
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/PositiveAnonymousResponse.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/PositiveAnonymousResponse.cs
index 5cfa191..de82bed 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/PositiveAnonymousResponse.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/PositiveAnonymousResponse.cs
@@ -33,7 +33,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <param name="response">The response message.</param>
protected internal PositiveAnonymousResponse(IndirectSignedResponse response) {
- Contract.Requires<ArgumentNullException>(response != null);
+ Requires.NotNull(response, "response");
this.response = response;
if (response.ProviderEndpoint != null && response.Version != null) {
@@ -174,7 +174,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
if (this.response.ReturnToParametersSignatureValidated) {
return this.GetUntrustedCallbackArgument(key);
} else {
- Logger.OpenId.WarnFormat(OpenIdStrings.CallbackArgumentsRequireSecretStore, typeof(IAssociationStore<Uri>).Name, typeof(OpenIdRelyingParty).Name);
+ Logger.OpenId.WarnFormat(OpenIdStrings.CallbackArgumentsRequireSecretStore, typeof(IRelyingPartyAssociationStore).Name, typeof(OpenIdRelyingParty).Name);
return null;
}
}
@@ -214,7 +214,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
if (this.response.ReturnToParametersSignatureValidated) {
return this.GetUntrustedCallbackArguments();
} else {
- Logger.OpenId.WarnFormat(OpenIdStrings.CallbackArgumentsRequireSecretStore, typeof(IAssociationStore<Uri>).Name, typeof(OpenIdRelyingParty).Name);
+ Logger.OpenId.WarnFormat(OpenIdStrings.CallbackArgumentsRequireSecretStore, typeof(IRelyingPartyAssociationStore).Name, typeof(OpenIdRelyingParty).Name);
return EmptyDictionary<string, string>.Instance;
}
}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/PositiveAuthenticationResponse.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/PositiveAuthenticationResponse.cs
index 3e2298c..1123912 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/PositiveAuthenticationResponse.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/PositiveAuthenticationResponse.cs
@@ -26,7 +26,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <param name="relyingParty">The relying party.</param>
internal PositiveAuthenticationResponse(PositiveAssertionResponse response, OpenIdRelyingParty relyingParty)
: base(response) {
- Contract.Requires<ArgumentNullException>(relyingParty != null);
+ Requires.NotNull(relyingParty, "relyingParty");
this.Endpoint = IdentifierDiscoveryResult.CreateForClaimedIdentifier(
this.Response.ClaimedIdentifier,
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/PositiveAuthenticationResponseSnapshot.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/PositiveAuthenticationResponseSnapshot.cs
index 80b424a..141b4f7 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/PositiveAuthenticationResponseSnapshot.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/PositiveAuthenticationResponseSnapshot.cs
@@ -33,7 +33,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <param name="copyFrom">The authentication response to copy from.</param>
internal PositiveAuthenticationResponseSnapshot(IAuthenticationResponse copyFrom) {
- Contract.Requires<ArgumentNullException>(copyFrom != null);
+ Requires.NotNull(copyFrom, "copyFrom");
this.ClaimedIdentifier = copyFrom.ClaimedIdentifier;
this.FriendlyIdentifierForDisplay = copyFrom.FriendlyIdentifierForDisplay;
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/SimpleXrdsProviderEndpoint.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/SimpleXrdsProviderEndpoint.cs
index 678f69a..678f69a 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/SimpleXrdsProviderEndpoint.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/SimpleXrdsProviderEndpoint.cs
diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/StandardRelyingPartyApplicationStore.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/StandardRelyingPartyApplicationStore.cs
new file mode 100644
index 0000000..a14b55d
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/StandardRelyingPartyApplicationStore.cs
@@ -0,0 +1,110 @@
+//-----------------------------------------------------------------------
+// <copyright file="StandardRelyingPartyApplicationStore.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.RelyingParty {
+ using System;
+ using System.Collections.Generic;
+ using DotNetOpenAuth.Configuration;
+ using DotNetOpenAuth.Messaging.Bindings;
+ using DotNetOpenAuth.OpenId.ChannelElements;
+
+ /// <summary>
+ /// An in-memory store for Relying Parties, suitable for single server, single process
+ /// ASP.NET web sites.
+ /// </summary>
+ public class StandardRelyingPartyApplicationStore : IOpenIdApplicationStore {
+ /// <summary>
+ /// The nonce store to use.
+ /// </summary>
+ private readonly INonceStore nonceStore;
+
+ /// <summary>
+ /// The association store to use.
+ /// </summary>
+ private readonly ICryptoKeyStore keyStore;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="StandardRelyingPartyApplicationStore"/> class.
+ /// </summary>
+ public StandardRelyingPartyApplicationStore() {
+ this.nonceStore = new NonceMemoryStore(OpenIdElement.Configuration.MaxAuthenticationTime);
+ this.keyStore = new MemoryCryptoKeyStore();
+ }
+
+ #region ICryptoKeyStore Members
+
+ /// <summary>
+ /// Gets the key in a given bucket and handle.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <param name="handle">The key handle. Case sensitive.</param>
+ /// <returns>
+ /// The cryptographic key, or <c>null</c> if no matching key was found.
+ /// </returns>
+ public CryptoKey GetKey(string bucket, string handle) {
+ return this.keyStore.GetKey(bucket, handle);
+ }
+
+ /// <summary>
+ /// Gets a sequence of existing keys within a given bucket.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <returns>
+ /// A sequence of handles and keys, ordered by descending <see cref="CryptoKey.ExpiresUtc"/>.
+ /// </returns>
+ public IEnumerable<KeyValuePair<string, CryptoKey>> GetKeys(string bucket) {
+ return this.keyStore.GetKeys(bucket);
+ }
+
+ /// <summary>
+ /// Stores a cryptographic key.
+ /// </summary>
+ /// <param name="bucket">The name of the bucket to store the key in. Case sensitive.</param>
+ /// <param name="handle">The handle to the key, unique within the bucket. Case sensitive.</param>
+ /// <param name="key">The key to store.</param>
+ /// <exception cref="CryptoKeyCollisionException">Thrown in the event of a conflict with an existing key in the same bucket and with the same handle.</exception>
+ public void StoreKey(string bucket, string handle, CryptoKey key) {
+ this.keyStore.StoreKey(bucket, handle, key);
+ }
+
+ /// <summary>
+ /// Removes the key.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <param name="handle">The key handle. Case sensitive.</param>
+ public void RemoveKey(string bucket, string handle) {
+ this.keyStore.RemoveKey(bucket, handle);
+ }
+
+ #endregion
+
+ #region INonceStore Members
+
+ /// <summary>
+ /// Stores a given nonce and timestamp.
+ /// </summary>
+ /// <param name="context">The context, or namespace, within which the <paramref name="nonce"/> must be unique.</param>
+ /// <param name="nonce">A series of random characters.</param>
+ /// <param name="timestampUtc">The timestamp that together with the nonce string make it unique.
+ /// The timestamp may also be used by the data store to clear out old nonces.</param>
+ /// <returns>
+ /// True if the nonce+timestamp (combination) was not previously in the database.
+ /// False if the nonce was stored previously with the same timestamp.
+ /// </returns>
+ /// <remarks>
+ /// The nonce must be stored for no less than the maximum time window a message may
+ /// be processed within before being discarded as an expired message.
+ /// If the binding element is applicable to your channel, this expiration window
+ /// is retrieved or set using the
+ /// <see cref="StandardExpirationBindingElement.MaximumMessageAge"/> property.
+ /// </remarks>
+ public bool StoreNonce(string context, string nonce, DateTime timestampUtc) {
+ return this.nonceStore.StoreNonce(context, nonce, timestampUtc);
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/WellKnownProviders.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/WellKnownProviders.cs
index ad1a11a..ad1a11a 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/WellKnownProviders.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/WellKnownProviders.cs
diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..e425143
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty/Properties/AssemblyInfo.cs
@@ -0,0 +1,58 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssemblyInfo.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+// We DON'T put an AssemblyVersionAttribute in here because it is generated in the build.
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Net;
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Security.Permissions;
+using System.Web.UI;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("DotNetOpenAuth OpenID")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DotNetOpenAuth")]
+[assembly: AssemblyCopyright("Copyright © 2008")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+[assembly: NeutralResourcesLanguage("en-US")]
+[assembly: CLSCompliant(true)]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("7d73990c-47c0-4256-9f20-a893add9e289")]
+
+[assembly: ContractVerification(true)]
+
+#if StrongNameSigned
+// See comment at top of this file. We need this so that strong-naming doesn't
+// keep this assembly from being useful to shared host (medium trust) web sites.
+[assembly: AllowPartiallyTrustedCallers]
+
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.RelyingParty.UI, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
+#else
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.RelyingParty.UI")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
+#endif
diff --git a/src/DotNetOpenAuth.OpenId.UI/DotNetOpenAuth.OpenId.UI.csproj b/src/DotNetOpenAuth.OpenId.UI/DotNetOpenAuth.OpenId.UI.csproj
new file mode 100644
index 0000000..f2a1cf5
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.UI/DotNetOpenAuth.OpenId.UI.csproj
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))\EnlistmentInfo.props" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))' != '' " />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" />
+ <PropertyGroup>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{75E13AAE-7D51-4421-ABFD-3F3DC91F576E}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>DotNetOpenAuth</RootNamespace>
+ <AssemblyName>DotNetOpenAuth.OpenId.UI</AssemblyName>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" />
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ <Compile Include="XrdsPublisher.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\DotNetOpenAuth.Core\DotNetOpenAuth.Core.csproj">
+ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project>
+ <Name>DotNetOpenAuth.Core</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OpenId\DotNetOpenAuth.OpenId.csproj">
+ <Project>{3896A32A-E876-4C23-B9B8-78E17D134CD3}</Project>
+ <Name>DotNetOpenAuth.OpenId</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\Org.Mentalis.Security.Cryptography\Org.Mentalis.Security.Cryptography.csproj">
+ <Project>{26DC877F-5987-48DD-9DDB-E62F2DE0E150}</Project>
+ <Name>Org.Mentalis.Security.Cryptography</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
+</Project> \ No newline at end of file
diff --git a/src/DotNetOpenAuth.OpenId.UI/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth.OpenId.UI/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..d1eef8c
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId.UI/Properties/AssemblyInfo.cs
@@ -0,0 +1,66 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssemblyInfo.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+// We DON'T put an AssemblyVersionAttribute in here because it is generated in the build.
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Net;
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Security.Permissions;
+using System.Web.UI;
+
+[assembly: TagPrefix("DotNetOpenAuth.OpenId", "openid")]
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("DotNetOpenAuth OpenID")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DotNetOpenAuth")]
+[assembly: AssemblyCopyright("Copyright © 2008")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+[assembly: NeutralResourcesLanguage("en-US")]
+[assembly: CLSCompliant(true)]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("7d73990c-47c0-4256-9f20-a893add9e289")]
+
+[assembly: ContractVerification(true)]
+
+#if StrongNameSigned
+// See comment at top of this file. We need this so that strong-naming doesn't
+// keep this assembly from being useful to shared host (medium trust) web sites.
+[assembly: AllowPartiallyTrustedCallers]
+
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.RelyingParty, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.RelyingParty.UI, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider.UI, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
+#else
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.RelyingParty")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.RelyingParty.UI")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider.UI")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
+#endif
diff --git a/src/DotNetOpenAuth/XrdsPublisher.cs b/src/DotNetOpenAuth.OpenId.UI/XrdsPublisher.cs
index 03c32c1..03c32c1 100644
--- a/src/DotNetOpenAuth/XrdsPublisher.cs
+++ b/src/DotNetOpenAuth.OpenId.UI/XrdsPublisher.cs
diff --git a/src/DotNetOpenAuth/Configuration/AssociationTypeCollection.cs b/src/DotNetOpenAuth.OpenId/Configuration/AssociationTypeCollection.cs
index 881fcdb..881fcdb 100644
--- a/src/DotNetOpenAuth/Configuration/AssociationTypeCollection.cs
+++ b/src/DotNetOpenAuth.OpenId/Configuration/AssociationTypeCollection.cs
diff --git a/src/DotNetOpenAuth/Configuration/AssociationTypeElement.cs b/src/DotNetOpenAuth.OpenId/Configuration/AssociationTypeElement.cs
index 0eaea0e..0eaea0e 100644
--- a/src/DotNetOpenAuth/Configuration/AssociationTypeElement.cs
+++ b/src/DotNetOpenAuth.OpenId/Configuration/AssociationTypeElement.cs
diff --git a/src/DotNetOpenAuth/Configuration/OpenIdElement.cs b/src/DotNetOpenAuth.OpenId/Configuration/OpenIdElement.cs
index 69994e6..e7b856e 100644
--- a/src/DotNetOpenAuth/Configuration/OpenIdElement.cs
+++ b/src/DotNetOpenAuth.OpenId/Configuration/OpenIdElement.cs
@@ -6,6 +6,7 @@
namespace DotNetOpenAuth.Configuration {
using System;
+ using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics.Contracts;
using DotNetOpenAuth.OpenId.ChannelElements;
@@ -15,7 +16,12 @@ namespace DotNetOpenAuth.Configuration {
/// Represents the &lt;openid&gt; element in the host's .config file.
/// </summary>
[ContractVerification(true)]
- internal class OpenIdElement : ConfigurationElement {
+ internal class OpenIdElement : ConfigurationSection {
+ /// <summary>
+ /// The name of the section under which this library's settings must be found.
+ /// </summary>
+ private const string SectionName = DotNetOpenAuthSection.SectionName + "/openid";
+
/// <summary>
/// The name of the &lt;relyingParty&gt; sub-element.
/// </summary>
@@ -53,6 +59,16 @@ namespace DotNetOpenAuth.Configuration {
}
/// <summary>
+ /// Gets the configuration section from the .config file.
+ /// </summary>
+ public static OpenIdElement Configuration {
+ get {
+ Contract.Ensures(Contract.Result<OpenIdElement>() != null);
+ return (OpenIdElement)ConfigurationManager.GetSection(SectionName) ?? new OpenIdElement();
+ }
+ }
+
+ /// <summary>
/// Gets or sets the maximum time a user can take to complete authentication.
/// </summary>
/// <remarks>
@@ -71,7 +87,7 @@ namespace DotNetOpenAuth.Configuration {
}
set {
- Contract.Requires<ArgumentOutOfRangeException>(value > TimeSpan.Zero);
+ Requires.InRange(value > TimeSpan.Zero, "value");
this[MaxAuthenticationTimePropertyName] = value;
}
}
diff --git a/src/DotNetOpenAuth/Configuration/OpenIdProviderElement.cs b/src/DotNetOpenAuth.OpenId/Configuration/OpenIdProviderElement.cs
index b51ccfb..6f5a043 100644
--- a/src/DotNetOpenAuth/Configuration/OpenIdProviderElement.cs
+++ b/src/DotNetOpenAuth.OpenId/Configuration/OpenIdProviderElement.cs
@@ -7,6 +7,7 @@
namespace DotNetOpenAuth.Configuration {
using System.Configuration;
using System.Diagnostics.Contracts;
+ using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.Provider;
/// <summary>
@@ -15,6 +16,11 @@ namespace DotNetOpenAuth.Configuration {
[ContractVerification(true)]
internal class OpenIdProviderElement : ConfigurationElement {
/// <summary>
+ /// The name of the &lt;provider&gt; sub-element.
+ /// </summary>
+ private const string ProviderElementName = "provider";
+
+ /// <summary>
/// The name of the security sub-element.
/// </summary>
private const string SecuritySettingsConfigName = "security";
@@ -58,8 +64,8 @@ namespace DotNetOpenAuth.Configuration {
/// Gets or sets the type to use for storing application state.
/// </summary>
[ConfigurationProperty(StoreConfigName)]
- public TypeConfigurationElement<IProviderApplicationStore> ApplicationStore {
- get { return (TypeConfigurationElement<IProviderApplicationStore>)this[StoreConfigName] ?? new TypeConfigurationElement<IProviderApplicationStore>(); }
+ public TypeConfigurationElement<IOpenIdApplicationStore> ApplicationStore {
+ get { return (TypeConfigurationElement<IOpenIdApplicationStore>)this[StoreConfigName] ?? new TypeConfigurationElement<IOpenIdApplicationStore>(); }
set { this[StoreConfigName] = value; }
}
}
diff --git a/src/DotNetOpenAuth/Configuration/OpenIdProviderSecuritySettingsElement.cs b/src/DotNetOpenAuth.OpenId/Configuration/OpenIdProviderSecuritySettingsElement.cs
index 3545fc5..0d8e8b4 100644
--- a/src/DotNetOpenAuth/Configuration/OpenIdProviderSecuritySettingsElement.cs
+++ b/src/DotNetOpenAuth.OpenId/Configuration/OpenIdProviderSecuritySettingsElement.cs
@@ -36,6 +36,11 @@ namespace DotNetOpenAuth.Configuration {
private const string AssociationsConfigName = "associations";
/// <summary>
+ /// The name of the @encodeAssociationSecretsInHandles attribute.
+ /// </summary>
+ private const string EncodeAssociationSecretsInHandlesConfigName = "encodeAssociationSecretsInHandles";
+
+ /// <summary>
/// Gets the name of the @requireSsl attribute.
/// </summary>
private const string RequireSslConfigName = "requireSsl";
@@ -116,6 +121,17 @@ namespace DotNetOpenAuth.Configuration {
}
/// <summary>
+ /// Gets or sets a value indicating whether the Provider should ease the burden of storing associations
+ /// by encoding their secrets (in signed, encrypted form) into the association handles themselves, storing only
+ /// a few rotating, private symmetric keys in the Provider's store instead.
+ /// </summary>
+ [ConfigurationProperty(EncodeAssociationSecretsInHandlesConfigName, DefaultValue = ProviderSecuritySettings.EncodeAssociationSecretsInHandlesDefault)]
+ public bool EncodeAssociationSecretsInHandles {
+ get { return (bool)this[EncodeAssociationSecretsInHandlesConfigName]; }
+ set { this[EncodeAssociationSecretsInHandlesConfigName] = value; }
+ }
+
+ /// <summary>
/// Initializes a programmatically manipulatable bag of these security settings with the settings from the config file.
/// </summary>
/// <returns>The newly created security settings object.</returns>
@@ -126,6 +142,7 @@ namespace DotNetOpenAuth.Configuration {
settings.MaximumHashBitLength = this.MaximumHashBitLength;
settings.ProtectDownlevelReplayAttacks = this.ProtectDownlevelReplayAttacks;
settings.UnsolicitedAssertionVerification = this.UnsolicitedAssertionVerification;
+ settings.EncodeAssociationSecretsInHandles = this.EncodeAssociationSecretsInHandles;
foreach (AssociationTypeElement element in this.AssociationLifetimes) {
Contract.Assume(element != null);
settings.AssociationLifetimes.Add(element.AssociationType, element.MaximumLifetime);
diff --git a/src/DotNetOpenAuth/Configuration/OpenIdRelyingPartyElement.cs b/src/DotNetOpenAuth.OpenId/Configuration/OpenIdRelyingPartyElement.cs
index 915776c..c80141a 100644
--- a/src/DotNetOpenAuth/Configuration/OpenIdRelyingPartyElement.cs
+++ b/src/DotNetOpenAuth.OpenId/Configuration/OpenIdRelyingPartyElement.cs
@@ -22,6 +22,11 @@ namespace DotNetOpenAuth.Configuration {
private const string StoreConfigName = "store";
/// <summary>
+ /// The name of the &lt;relyingParty&gt; sub-element.
+ /// </summary>
+ private const string RelyingPartyElementName = "relyingParty";
+
+ /// <summary>
/// The name of the attribute that specifies whether dnoa.userSuppliedIdentifier is tacked onto the openid.return_to URL.
/// </summary>
private const string PreserveUserSuppliedIdentifierConfigName = "preserveUserSuppliedIdentifier";
@@ -87,8 +92,8 @@ namespace DotNetOpenAuth.Configuration {
/// Gets or sets the type to use for storing application state.
/// </summary>
[ConfigurationProperty(StoreConfigName)]
- public TypeConfigurationElement<IRelyingPartyApplicationStore> ApplicationStore {
- get { return (TypeConfigurationElement<IRelyingPartyApplicationStore>)this[StoreConfigName] ?? new TypeConfigurationElement<IRelyingPartyApplicationStore>(); }
+ public TypeConfigurationElement<IOpenIdApplicationStore> ApplicationStore {
+ get { return (TypeConfigurationElement<IOpenIdApplicationStore>)this[StoreConfigName] ?? new TypeConfigurationElement<IOpenIdApplicationStore>(); }
set { this[StoreConfigName] = value; }
}
diff --git a/src/DotNetOpenAuth/Configuration/OpenIdRelyingPartySecuritySettingsElement.cs b/src/DotNetOpenAuth.OpenId/Configuration/OpenIdRelyingPartySecuritySettingsElement.cs
index 4347e2c..225b1e7 100644
--- a/src/DotNetOpenAuth/Configuration/OpenIdRelyingPartySecuritySettingsElement.cs
+++ b/src/DotNetOpenAuth.OpenId/Configuration/OpenIdRelyingPartySecuritySettingsElement.cs
@@ -61,11 +61,6 @@ namespace DotNetOpenAuth.Configuration {
private const string IgnoreUnsignedExtensionsConfigName = "ignoreUnsignedExtensions";
/// <summary>
- /// Gets the name of the @privateSecretMaximumAge attribute.
- /// </summary>
- private const string PrivateSecretMaximumAgeConfigName = "privateSecretMaximumAge";
-
- /// <summary>
/// Gets the name of the @allowDualPurposeIdentifiers attribute.
/// </summary>
private const string AllowDualPurposeIdentifiersConfigName = "allowDualPurposeIdentifiers";
@@ -152,17 +147,6 @@ namespace DotNetOpenAuth.Configuration {
}
/// <summary>
- /// Gets or sets the maximum allowable age of the secret a Relying Party
- /// uses to its return_to URLs and nonces with 1.0 Providers.
- /// </summary>
- /// <value>The default value is 7 days.</value>
- [ConfigurationProperty(PrivateSecretMaximumAgeConfigName, DefaultValue = "07:00:00")]
- public TimeSpan PrivateSecretMaximumAge {
- get { return (TimeSpan)this[PrivateSecretMaximumAgeConfigName]; }
- set { this[PrivateSecretMaximumAgeConfigName] = value; }
- }
-
- /// <summary>
/// Gets or sets a value indicating whether all unsolicited assertions should be ignored.
/// </summary>
/// <value>The default value is <c>false</c>.</value>
@@ -263,7 +247,7 @@ namespace DotNetOpenAuth.Configuration {
settings.MinimumRequiredOpenIdVersion = this.MinimumRequiredOpenIdVersion;
settings.MinimumHashBitLength = this.MinimumHashBitLength;
settings.MaximumHashBitLength = this.MaximumHashBitLength;
- settings.PrivateSecretMaximumAge = this.PrivateSecretMaximumAge;
+ settings.PrivateSecretMaximumAge = DotNetOpenAuthSection.Messaging.PrivateSecretMaximumAge;
settings.RejectUnsolicitedAssertions = this.RejectUnsolicitedAssertions;
settings.RejectDelegatingIdentifiers = this.RejectDelegatingIdentifiers;
settings.IgnoreUnsignedExtensions = this.IgnoreUnsignedExtensions;
diff --git a/src/DotNetOpenAuth/Configuration/XriResolverElement.cs b/src/DotNetOpenAuth.OpenId/Configuration/XriResolverElement.cs
index fdb5b29..fdb5b29 100644
--- a/src/DotNetOpenAuth/Configuration/XriResolverElement.cs
+++ b/src/DotNetOpenAuth.OpenId/Configuration/XriResolverElement.cs
diff --git a/src/DotNetOpenAuth.OpenId/DotNetOpenAuth.OpenId.csproj b/src/DotNetOpenAuth.OpenId/DotNetOpenAuth.OpenId.csproj
new file mode 100644
index 0000000..b45247b
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId/DotNetOpenAuth.OpenId.csproj
@@ -0,0 +1,188 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))\EnlistmentInfo.props" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))' != '' " />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" />
+ <PropertyGroup>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{3896A32A-E876-4C23-B9B8-78E17D134CD3}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>DotNetOpenAuth</RootNamespace>
+ <AssemblyName>DotNetOpenAuth.OpenId</AssemblyName>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" />
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="Configuration\AssociationTypeCollection.cs" />
+ <Compile Include="Configuration\AssociationTypeElement.cs" />
+ <Compile Include="Configuration\OpenIdElement.cs" />
+ <Compile Include="Configuration\OpenIdProviderElement.cs" />
+ <Compile Include="Configuration\OpenIdProviderSecuritySettingsElement.cs" />
+ <Compile Include="Configuration\OpenIdRelyingPartyElement.cs" />
+ <Compile Include="Configuration\OpenIdRelyingPartySecuritySettingsElement.cs" />
+ <Compile Include="Configuration\XriResolverElement.cs" />
+ <Compile Include="OpenIdXrdsHelper.cs" />
+ <Compile Include="OpenId\Association.cs" />
+ <Compile Include="OpenId\AuthenticationRequestMode.cs" />
+ <Compile Include="OpenId\Behaviors\AXFetchAsSregTransformBase.cs" />
+ <Compile Include="OpenId\Behaviors\BehaviorStrings.Designer.cs">
+ <AutoGen>True</AutoGen>
+ <DesignTime>True</DesignTime>
+ <DependentUpon>BehaviorStrings.resx</DependentUpon>
+ </Compile>
+ <Compile Include="OpenId\Behaviors\GsaIcamProfileBase.cs" />
+ <Compile Include="OpenId\ChannelElements\BackwardCompatibilityBindingElement.cs" />
+ <Compile Include="OpenId\ChannelElements\SigningBindingElementContract.cs" />
+ <Compile Include="OpenId\ChannelElements\ExtensionsBindingElement.cs" />
+ <Compile Include="OpenId\ChannelElements\IOpenIdExtensionFactory.cs" />
+ <Compile Include="OpenId\ChannelElements\ITamperResistantOpenIdMessage.cs" />
+ <Compile Include="OpenId\ChannelElements\OriginalStringUriEncoder.cs" />
+ <Compile Include="OpenId\ChannelElements\SigningBindingElement.cs" />
+ <Compile Include="OpenId\ChannelElements\KeyValueFormEncoding.cs" />
+ <Compile Include="OpenId\ChannelElements\OpenIdChannel.cs" />
+ <Compile Include="OpenId\ChannelElements\ReturnToSignatureBindingElement.cs" />
+ <Compile Include="OpenId\ChannelElements\SkipSecurityBindingElement.cs" />
+ <Compile Include="OpenId\AssociationContract.cs" />
+ <Compile Include="OpenId\Extensions\AliasManager.cs" />
+ <Compile Include="OpenId\Extensions\AttributeExchange\AttributeRequest.cs" />
+ <Compile Include="OpenId\Extensions\AttributeExchange\AttributeValues.cs" />
+ <Compile Include="OpenId\Extensions\AttributeExchange\AXAttributeFormats.cs" />
+ <Compile Include="OpenId\Extensions\AttributeExchange\AXUtilities.cs" />
+ <Compile Include="OpenId\Extensions\AttributeExchange\Constants.cs" />
+ <Compile Include="OpenId\Extensions\AttributeExchange\FetchRequest.cs" />
+ <Compile Include="OpenId\Extensions\AttributeExchange\FetchResponse.cs" />
+ <Compile Include="OpenId\Extensions\AttributeExchange\StoreRequest.cs" />
+ <Compile Include="OpenId\Extensions\AttributeExchange\StoreResponse.cs" />
+ <Compile Include="OpenId\Extensions\AttributeExchange\WellKnownAttributes.cs" />
+ <Compile Include="OpenId\Extensions\ExtensionBase.cs" />
+ <Compile Include="OpenId\Extensions\ExtensionArgumentsManager.cs" />
+ <Compile Include="OpenId\Extensions\IClientScriptExtensionResponse.cs" />
+ <Compile Include="OpenId\Extensions\OAuth\AuthorizationRequest.cs" />
+ <Compile Include="OpenId\Extensions\OAuth\AuthorizationApprovedResponse.cs" />
+ <Compile Include="OpenId\Extensions\OAuth\Constants.cs" />
+ <Compile Include="OpenId\Extensions\OAuth\AuthorizationDeclinedResponse.cs" />
+ <Compile Include="OpenId\Extensions\OpenIdExtensionFactoryAggregator.cs" />
+ <Compile Include="OpenId\Extensions\StandardOpenIdExtensionFactory.cs" />
+ <Compile Include="OpenId\Extensions\ProviderAuthenticationPolicy\AuthenticationPolicies.cs" />
+ <Compile Include="OpenId\Extensions\ProviderAuthenticationPolicy\Constants.cs" />
+ <Compile Include="OpenId\Extensions\ProviderAuthenticationPolicy\DateTimeEncoder.cs" />
+ <Compile Include="OpenId\Extensions\ProviderAuthenticationPolicy\NistAssuranceLevel.cs" />
+ <Compile Include="OpenId\Extensions\ProviderAuthenticationPolicy\PapeUtilities.cs" />
+ <Compile Include="OpenId\Extensions\ProviderAuthenticationPolicy\PolicyRequest.cs" />
+ <Compile Include="OpenId\Extensions\ProviderAuthenticationPolicy\PolicyResponse.cs" />
+ <Compile Include="OpenId\Extensions\SimpleRegistration\ClaimsRequest.cs" />
+ <Compile Include="OpenId\Extensions\SimpleRegistration\ClaimsResponse.cs" />
+ <Compile Include="OpenId\Extensions\SimpleRegistration\Constants.cs" />
+ <Compile Include="OpenId\Extensions\SimpleRegistration\DemandLevel.cs" />
+ <Compile Include="OpenId\Extensions\SimpleRegistration\Gender.cs" />
+ <Compile Include="OpenId\Extensions\UI\UIConstants.cs" />
+ <Compile Include="OpenId\Extensions\UI\UIModes.cs" />
+ <Compile Include="OpenId\Extensions\UI\UIRequest.cs" />
+ <Compile Include="OpenId\Extensions\UI\UIUtilities.cs" />
+ <Compile Include="OpenId\Identifier.cs" />
+ <Compile Include="OpenId\IdentifierContract.cs" />
+ <Compile Include="OpenId\Extensions\OpenIdExtensionsInteropHelper.cs" />
+ <Compile Include="OpenId\IdentifierDiscoveryResult.cs" />
+ <Compile Include="OpenId\IIdentifierDiscoveryService.cs" />
+ <Compile Include="OpenId\IProviderEndpoint.cs" />
+ <Compile Include="OpenId\Provider\IAuthenticationRequest.cs" />
+ <Compile Include="OpenId\Provider\IHostProcessedRequest.cs" />
+ <Compile Include="OpenId\Provider\IProviderBehavior.cs" />
+ <Compile Include="OpenId\Provider\IRequest.cs" />
+ <Compile Include="OpenId\Provider\ProviderSecuritySettings.cs" />
+ <Compile Include="OpenId\Provider\RelyingPartyDiscoveryResult.cs" />
+ <Compile Include="OpenId\RelyingParty\AuthenticationStatus.cs" />
+ <Compile Include="OpenId\RelyingParty\IAuthenticationRequest.cs" />
+ <Compile Include="OpenId\RelyingParty\IAuthenticationRequestContract.cs" />
+ <Compile Include="OpenId\RelyingParty\IAuthenticationResponse.cs" />
+ <Compile Include="OpenId\RelyingParty\IRelyingPartyBehavior.cs" />
+ <Compile Include="OpenId\Messages\CheckAuthenticationRequest.cs" />
+ <Compile Include="OpenId\Messages\CheckAuthenticationResponse.cs" />
+ <Compile Include="OpenId\Messages\CheckIdRequest.cs" />
+ <Compile Include="OpenId\Messages\AssociateSuccessfulResponseContract.cs" />
+ <Compile Include="OpenId\Messages\IErrorMessage.cs" />
+ <Compile Include="OpenId\Messages\IndirectResponseBase.cs" />
+ <Compile Include="OpenId\Messages\IndirectSignedResponse.cs" />
+ <Compile Include="OpenId\Messages\IOpenIdMessageExtension.cs" />
+ <Compile Include="OpenId\Messages\NegativeAssertionResponse.cs" />
+ <Compile Include="OpenId\Messages\PositiveAssertionResponse.cs" />
+ <Compile Include="OpenId\Messages\SignedResponseRequest.cs" />
+ <Compile Include="OpenId\NoDiscoveryIdentifier.cs" />
+ <Compile Include="OpenId\OpenIdUtilities.cs" />
+ <Compile Include="OpenId\OpenIdXrdsHelper.cs" />
+ <Compile Include="OpenId\ProviderEndpointDescription.cs" />
+ <Compile Include="OpenId\Realm.cs" />
+ <Compile Include="OpenId\RelyingPartyDescription.cs" />
+ <Compile Include="OpenId\DiffieHellmanUtilities.cs" Condition=" '$(ExcludeDiffieHellman)' != 'true' " />
+ <Compile Include="OpenId\HmacShaAssociation.cs" />
+ <Compile Include="OpenId\Messages\AssociateUnencryptedRequest.cs" />
+ <Compile Include="OpenId\Messages\AssociateDiffieHellmanRequest.cs" />
+ <Compile Include="OpenId\Messages\AssociateDiffieHellmanResponse.cs" Condition=" '$(ExcludeDiffieHellman)' != 'true' " />
+ <Compile Include="OpenId\Messages\AssociateRequest.cs" />
+ <Compile Include="OpenId\Messages\AssociateSuccessfulResponse.cs" />
+ <Compile Include="OpenId\Messages\AssociateUnencryptedResponse.cs" />
+ <Compile Include="OpenId\Messages\AssociateUnsuccessfulResponse.cs" />
+ <Compile Include="OpenId\Messages\IndirectErrorResponse.cs" />
+ <Compile Include="OpenId\Messages\DirectErrorResponse.cs" />
+ <Compile Include="OpenId\Messages\RequestBase.cs" />
+ <Compile Include="OpenId\Messages\DirectResponseBase.cs" />
+ <Compile Include="OpenId\OpenIdStrings.Designer.cs">
+ <DependentUpon>OpenIdStrings.resx</DependentUpon>
+ <DesignTime>True</DesignTime>
+ <AutoGen>True</AutoGen>
+ </Compile>
+ <Compile Include="OpenId\Protocol.cs" />
+ <Compile Include="OpenId\IOpenIdApplicationStore.cs" />
+ <Compile Include="OpenId\RelyingParty\RelyingPartySecuritySettings.cs" />
+ <Compile Include="OpenId\UriDiscoveryService.cs" />
+ <Compile Include="OpenId\XriDiscoveryProxyService.cs" />
+ <Compile Include="OpenId\SecuritySettings.cs" />
+ <Compile Include="OpenId\UriIdentifier.cs" />
+ <Compile Include="OpenId\XriIdentifier.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ <Compile Include="Xrds\XrdsStrings.Designer.cs">
+ <AutoGen>True</AutoGen>
+ <DesignTime>True</DesignTime>
+ <DependentUpon>XrdsStrings.resx</DependentUpon>
+ </Compile>
+ <Compile Include="Yadis\ContentTypes.cs" />
+ <Compile Include="Yadis\DiscoveryResult.cs" />
+ <Compile Include="Yadis\HtmlParser.cs" />
+ <Compile Include="Xrds\ServiceElement.cs" />
+ <Compile Include="Xrds\TypeElement.cs" />
+ <Compile Include="Xrds\UriElement.cs" />
+ <Compile Include="Xrds\XrdElement.cs" />
+ <Compile Include="Xrds\XrdsDocument.cs" />
+ <Compile Include="Xrds\XrdsNode.cs" />
+ <Compile Include="Yadis\Yadis.cs" />
+ <EmbeddedResource Include="OpenId\Behaviors\BehaviorStrings.resx" />
+ <EmbeddedResource Include="OpenId\Behaviors\BehaviorStrings.sr.resx" />
+ <EmbeddedResource Include="OpenId\OpenIdStrings.resx" />
+ <EmbeddedResource Include="OpenId\OpenIdStrings.sr.resx" />
+ <EmbeddedResource Include="Xrds\XrdsStrings.resx">
+ <Generator>ResXFileCodeGenerator</Generator>
+ <LastGenOutput>XrdsStrings.Designer.cs</LastGenOutput>
+ </EmbeddedResource>
+ <EmbeddedResource Include="Xrds\XrdsStrings.sr.resx" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\DotNetOpenAuth.Core\DotNetOpenAuth.Core.csproj">
+ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project>
+ <Name>DotNetOpenAuth.Core</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\Org.Mentalis.Security.Cryptography\Org.Mentalis.Security.Cryptography.csproj" Condition=" '$(ExcludeDiffieHellman)' != 'true' ">
+ <Project>{26DC877F-5987-48DD-9DDB-E62F2DE0E150}</Project>
+ <Name>Org.Mentalis.Security.Cryptography</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
+</Project> \ No newline at end of file
diff --git a/src/DotNetOpenAuth/OpenId/Association.cs b/src/DotNetOpenAuth.OpenId/OpenId/Association.cs
index 3c7e89f..ff30a36 100644
--- a/src/DotNetOpenAuth/OpenId/Association.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Association.cs
@@ -35,11 +35,11 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="totalLifeLength">How long the association will be useful.</param>
/// <param name="issued">The UTC time of when this association was originally issued by the Provider.</param>
protected Association(string handle, byte[] secret, TimeSpan totalLifeLength, DateTime issued) {
- Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(handle));
- Contract.Requires<ArgumentNullException>(secret != null);
- Contract.Requires<ArgumentOutOfRangeException>(totalLifeLength > TimeSpan.Zero);
- Contract.Requires<ArgumentException>(issued.Kind == DateTimeKind.Utc);
- Contract.Requires<ArgumentOutOfRangeException>(issued <= DateTime.UtcNow);
+ Requires.NotNullOrEmpty(handle, "handle");
+ Requires.NotNull(secret, "secret");
+ Requires.InRange(totalLifeLength > TimeSpan.Zero, "totalLifeLength");
+ Requires.True(issued.Kind == DateTimeKind.Utc, "issued");
+ Requires.InRange(issued <= DateTime.UtcNow, "issued");
Contract.Ensures(this.TotalLifeLength == totalLifeLength);
this.Handle = handle;
@@ -51,7 +51,7 @@ namespace DotNetOpenAuth.OpenId {
/// <summary>
/// Gets a unique handle by which this <see cref="Association"/> may be stored or retrieved.
/// </summary>
- public string Handle { get; private set; }
+ public string Handle { get; internal set; }
/// <summary>
/// Gets the UTC time when this <see cref="Association"/> will expire.
@@ -85,9 +85,20 @@ namespace DotNetOpenAuth.OpenId {
/// <summary>
/// Gets or sets the UTC time that this <see cref="Association"/> was first created.
/// </summary>
+ [MessagePart]
internal DateTime Issued { get; set; }
/// <summary>
+ /// Gets the duration a secret key used for signing dumb client requests will be good for.
+ /// </summary>
+ protected internal static TimeSpan DumbSecretLifetime {
+ get {
+ Contract.Ensures(Contract.Result<TimeSpan>() > TimeSpan.Zero);
+ return OpenIdElement.Configuration.MaxAuthenticationTime;
+ }
+ }
+
+ /// <summary>
/// Gets the number of seconds until this <see cref="Association"/> expires.
/// Never negative (counter runs to zero).
/// </summary>
@@ -102,21 +113,13 @@ namespace DotNetOpenAuth.OpenId {
/// Gets the shared secret key between the consumer and provider.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "It is a buffer.")]
+ [MessagePart("key")]
protected internal byte[] SecretKey { get; private set; }
/// <summary>
- /// Gets the duration a secret key used for signing dumb client requests will be good for.
- /// </summary>
- protected static TimeSpan DumbSecretLifetime {
- get {
- Contract.Ensures(Contract.Result<TimeSpan>() > TimeSpan.Zero);
- return DotNetOpenAuthSection.Configuration.OpenId.MaxAuthenticationTime;
- }
- }
-
- /// <summary>
/// Gets the lifetime the OpenID provider permits this <see cref="Association"/>.
/// </summary>
+ [MessagePart("ttl")]
protected TimeSpan TotalLifeLength { get; private set; }
/// <summary>
@@ -128,7 +131,7 @@ namespace DotNetOpenAuth.OpenId {
private static TimeSpan MinimumUsefulAssociationLifetime {
get {
Contract.Ensures(Contract.Result<TimeSpan>() > TimeSpan.Zero);
- return DotNetOpenAuthSection.Configuration.OpenId.MaxAuthenticationTime;
+ return OpenIdElement.Configuration.MaxAuthenticationTime;
}
}
@@ -156,11 +159,11 @@ namespace DotNetOpenAuth.OpenId {
/// <returns>
/// The newly dehydrated <see cref="Association"/>, which can be returned
/// from a custom association store's
- /// <see cref="IAssociationStore&lt;TKey&gt;.GetAssociation(TKey, SecuritySettings)"/> method.
+ /// IRelyingPartyAssociationStore.GetAssociation method.
/// </returns>
public static Association Deserialize(string handle, DateTime expiresUtc, byte[] privateData) {
- Contract.Requires<ArgumentNullException>(!String.IsNullOrEmpty(handle));
- Contract.Requires<ArgumentNullException>(privateData != null);
+ Requires.NotNullOrEmpty(handle, "handle");
+ Requires.NotNull(privateData, "privateData");
Contract.Ensures(Contract.Result<Association>() != null);
expiresUtc = expiresUtc.ToUniversalTimeSafe();
@@ -219,7 +222,7 @@ namespace DotNetOpenAuth.OpenId {
if (a.Handle != this.Handle ||
a.Issued != this.Issued ||
- a.TotalLifeLength != this.TotalLifeLength) {
+ !MessagingUtilities.Equals(a.TotalLifeLength, this.TotalLifeLength, TimeSpan.FromSeconds(1))) {
return false;
}
@@ -275,7 +278,7 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="data">The data to sign. This data will not be changed (the signature is the return value).</param>
/// <returns>The calculated signature of the data.</returns>
protected internal byte[] Sign(byte[] data) {
- Contract.Requires<ArgumentNullException>(data != null);
+ Requires.NotNull(data, "data");
using (HashAlgorithm hasher = this.CreateHasher()) {
return hasher.ComputeHash(data);
}
diff --git a/src/DotNetOpenAuth/OpenId/AssociationContract.cs b/src/DotNetOpenAuth.OpenId/OpenId/AssociationContract.cs
index 57f4fd9..e36028e 100644
--- a/src/DotNetOpenAuth/OpenId/AssociationContract.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/AssociationContract.cs
@@ -46,7 +46,7 @@ namespace DotNetOpenAuth.OpenId {
/// </returns>
[Pure]
internal override string GetAssociationType(Protocol protocol) {
- Contract.Requires<ArgumentNullException>(protocol != null);
+ Requires.NotNull(protocol, "protocol");
throw new NotImplementedException();
}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/AuthenticationRequestMode.cs b/src/DotNetOpenAuth.OpenId/OpenId/AuthenticationRequestMode.cs
index 70b7f3a..dfe7b06 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/AuthenticationRequestMode.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/AuthenticationRequestMode.cs
@@ -4,7 +4,7 @@
// </copyright>
//-----------------------------------------------------------------------
-namespace DotNetOpenAuth.OpenId.RelyingParty {
+namespace DotNetOpenAuth.OpenId {
/// <summary>
/// Indicates the mode the Provider should use while authenticating the end user.
/// </summary>
diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Behaviors/AXFetchAsSregTransformBase.cs b/src/DotNetOpenAuth.OpenId/OpenId/Behaviors/AXFetchAsSregTransformBase.cs
new file mode 100644
index 0000000..41e6b8e
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Behaviors/AXFetchAsSregTransformBase.cs
@@ -0,0 +1,37 @@
+//-----------------------------------------------------------------------
+// <copyright file="AXFetchAsSregTransformBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Behaviors {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OpenId.Extensions;
+ using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
+ using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
+
+ /// <summary>
+ /// An Attribute Exchange and Simple Registration filter to make all incoming attribute
+ /// requests look like Simple Registration requests, and to convert the response
+ /// to the originally requested extension and format.
+ /// </summary>
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sreg", Justification = "Abbreviation")]
+ public abstract class AXFetchAsSregTransformBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AXFetchAsSregTransformBase"/> class.
+ /// </summary>
+ protected AXFetchAsSregTransformBase() {
+ this.AXFormats = AXAttributeFormats.Common;
+ }
+
+ /// <summary>
+ /// Gets or sets the AX attribute type URI formats this transform is willing to work with.
+ /// </summary>
+ public AXAttributeFormats AXFormats { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/Behaviors/BehaviorStrings.Designer.cs b/src/DotNetOpenAuth.OpenId/OpenId/Behaviors/BehaviorStrings.Designer.cs
index 8c952ab..8c952ab 100644
--- a/src/DotNetOpenAuth/OpenId/Behaviors/BehaviorStrings.Designer.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Behaviors/BehaviorStrings.Designer.cs
diff --git a/src/DotNetOpenAuth/OpenId/Behaviors/BehaviorStrings.resx b/src/DotNetOpenAuth.OpenId/OpenId/Behaviors/BehaviorStrings.resx
index a8bf2d6..a8bf2d6 100644
--- a/src/DotNetOpenAuth/OpenId/Behaviors/BehaviorStrings.resx
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Behaviors/BehaviorStrings.resx
diff --git a/src/DotNetOpenAuth/OpenId/Behaviors/BehaviorStrings.sr.resx b/src/DotNetOpenAuth.OpenId/OpenId/Behaviors/BehaviorStrings.sr.resx
index 2b1b911..2b1b911 100644
--- a/src/DotNetOpenAuth/OpenId/Behaviors/BehaviorStrings.sr.resx
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Behaviors/BehaviorStrings.sr.resx
diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Behaviors/GsaIcamProfileBase.cs b/src/DotNetOpenAuth.OpenId/OpenId/Behaviors/GsaIcamProfileBase.cs
new file mode 100644
index 0000000..25a4e59
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Behaviors/GsaIcamProfileBase.cs
@@ -0,0 +1,58 @@
+//-----------------------------------------------------------------------
+// <copyright file="GsaIcamProfileBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Behaviors {
+ using System;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using DotNetOpenAuth.Configuration;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
+ using DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy;
+ using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
+
+ /// <summary>
+ /// Implements the Identity, Credential, &amp; Access Management (ICAM) OpenID 2.0 Profile
+ /// for the General Services Administration (GSA).
+ /// </summary>
+ /// <remarks>
+ /// <para>Relying parties that include this profile are always held to the terms required by the profile,
+ /// but Providers are only affected by the special behaviors of the profile when the RP specifically
+ /// indicates that they want to use this profile. </para>
+ /// </remarks>
+ [Serializable]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Icam", Justification = "Acronym")]
+ public abstract class GsaIcamProfileBase {
+ /// <summary>
+ /// Backing field for the <see cref="DisableSslRequirement"/> static property.
+ /// </summary>
+ private static bool disableSslRequirement = DotNetOpenAuthSection.Messaging.RelaxSslRequirements;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="GsaIcamProfileBase"/> class.
+ /// </summary>
+ public GsaIcamProfileBase() {
+ if (DisableSslRequirement) {
+ Logger.OpenId.Warn("GSA level 1 behavior has its RequireSsl requirement disabled.");
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether PII is allowed to be requested or received via OpenID.
+ /// </summary>
+ /// <value>The default value is <c>false</c>.</value>
+ public static bool AllowPersonallyIdentifiableInformation { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether to ignore the SSL requirement (for testing purposes only).
+ /// </summary>
+ public static bool DisableSslRequirement { // not an auto-property because it has a default value, and FxCop doesn't want us using static constructors.
+ get { return disableSslRequirement; }
+ set { disableSslRequirement = value; }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/ChannelElements/BackwardCompatibilityBindingElement.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/BackwardCompatibilityBindingElement.cs
index b730b1f..b730b1f 100644
--- a/src/DotNetOpenAuth/OpenId/ChannelElements/BackwardCompatibilityBindingElement.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/BackwardCompatibilityBindingElement.cs
diff --git a/src/DotNetOpenAuth/OpenId/ChannelElements/ExtensionsBindingElement.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/ExtensionsBindingElement.cs
index c516e8f..705f737 100644
--- a/src/DotNetOpenAuth/OpenId/ChannelElements/ExtensionsBindingElement.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/ExtensionsBindingElement.cs
@@ -15,8 +15,6 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
using DotNetOpenAuth.Messaging.Reflection;
using DotNetOpenAuth.OpenId.Extensions;
using DotNetOpenAuth.OpenId.Messages;
- using DotNetOpenAuth.OpenId.Provider;
- using DotNetOpenAuth.OpenId.RelyingParty;
/// <summary>
/// The binding element that serializes/deserializes OpenID extensions to/from
@@ -24,21 +22,22 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
/// </summary>
internal class ExtensionsBindingElement : IChannelBindingElement {
/// <summary>
- /// The security settings that apply to this relying party, if it is a relying party.
+ /// False if unsigned extensions should be dropped. Must always be true on Providers, since RPs never sign extensions.
/// </summary>
- private readonly RelyingPartySecuritySettings relyingPartySecuritySettings;
+ private readonly bool receiveUnsignedExtensions;
/// <summary>
/// Initializes a new instance of the <see cref="ExtensionsBindingElement"/> class.
/// </summary>
/// <param name="extensionFactory">The extension factory.</param>
/// <param name="securitySettings">The security settings.</param>
- internal ExtensionsBindingElement(IOpenIdExtensionFactory extensionFactory, SecuritySettings securitySettings) {
- Contract.Requires<ArgumentNullException>(extensionFactory != null);
- Contract.Requires<ArgumentNullException>(securitySettings != null);
+ /// <param name="receiveUnsignedExtensions">Security setting for relying parties. Should be true for Providers.</param>
+ internal ExtensionsBindingElement(IOpenIdExtensionFactory extensionFactory, SecuritySettings securitySettings, bool receiveUnsignedExtensions) {
+ Requires.NotNull(extensionFactory, "extensionFactory");
+ Requires.NotNull(securitySettings, "securitySettings");
this.ExtensionFactory = extensionFactory;
- this.relyingPartySecuritySettings = securitySettings as RelyingPartySecuritySettings;
+ this.receiveUnsignedExtensions = receiveUnsignedExtensions;
}
#region IChannelBindingElement Members
@@ -156,7 +155,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
// Now search again, considering ALL extensions whether they are signed or not,
// skipping the signed ones and adding the new ones as unsigned extensions.
- if (this.relyingPartySecuritySettings == null || !this.relyingPartySecuritySettings.IgnoreUnsignedExtensions) {
+ if (this.receiveUnsignedExtensions) {
Func<string, bool> isNotSigned = typeUri => !extendableMessage.Extensions.Cast<IOpenIdMessageExtension>().Any(ext => ext.TypeUri == typeUri);
foreach (IOpenIdMessageExtension unsignedExtension in this.GetExtensions(extendableMessage, false, isNotSigned)) {
Reporting.RecordFeatureUse(unsignedExtension);
@@ -239,7 +238,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
/// A dictionary of message parts, including only signed parts when appropriate.
/// </returns>
private IDictionary<string, string> GetExtensionsDictionary(IProtocolMessage message, bool ignoreUnsigned) {
- Contract.Requires<InvalidOperationException>(this.Channel != null);
+ Requires.ValidState(this.Channel != null);
IndirectSignedResponse signedResponse = message as IndirectSignedResponse;
if (signedResponse != null && ignoreUnsigned) {
diff --git a/src/DotNetOpenAuth/OpenId/ChannelElements/IOpenIdExtensionFactory.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/IOpenIdExtensionFactory.cs
index 762fc9a..0c8d95e 100644
--- a/src/DotNetOpenAuth/OpenId/ChannelElements/IOpenIdExtensionFactory.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/IOpenIdExtensionFactory.cs
@@ -8,16 +8,14 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
using System.Collections.Generic;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId.Messages;
- using DotNetOpenAuth.OpenId.Provider;
- using DotNetOpenAuth.OpenId.RelyingParty;
/// <summary>
/// OpenID extension factory class for creating extensions based on received Type URIs.
/// </summary>
/// <remarks>
/// OpenID extension factories must be registered with the library. This can be
- /// done by adding a factory to <see cref="OpenIdRelyingParty.ExtensionFactories"/>
- /// or <see cref="OpenIdProvider.ExtensionFactories"/>, or by adding a snippet
+ /// done by adding a factory to OpenIdRelyingParty.ExtensionFactories
+ /// or OpenIdProvider.ExtensionFactories, or by adding a snippet
/// such as the following to your web.config file:
/// <example>
/// &lt;dotNetOpenAuth&gt;
diff --git a/src/DotNetOpenAuth/OpenId/ChannelElements/ITamperResistantOpenIdMessage.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/ITamperResistantOpenIdMessage.cs
index 533e818..533e818 100644
--- a/src/DotNetOpenAuth/OpenId/ChannelElements/ITamperResistantOpenIdMessage.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/ITamperResistantOpenIdMessage.cs
diff --git a/src/DotNetOpenAuth/OpenId/ChannelElements/KeyValueFormEncoding.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/KeyValueFormEncoding.cs
index 46c2139..1993cb4 100644
--- a/src/DotNetOpenAuth/OpenId/ChannelElements/KeyValueFormEncoding.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/KeyValueFormEncoding.cs
@@ -101,7 +101,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
/// </remarks>
[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "Not a problem for this type.")]
public static byte[] GetBytes(IEnumerable<KeyValuePair<string, string>> keysAndValues) {
- Contract.Requires<ArgumentNullException>(keysAndValues != null);
+ Requires.NotNull(keysAndValues, "keysAndValues");
using (MemoryStream ms = new MemoryStream()) {
using (StreamWriter sw = new StreamWriter(ms, textEncoding)) {
diff --git a/src/DotNetOpenAuth/OpenId/ChannelElements/OpenIdChannel.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/OpenIdChannel.cs
index bc613ed..a2a5c88 100644
--- a/src/DotNetOpenAuth/OpenId/ChannelElements/OpenIdChannel.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/OpenIdChannel.cs
@@ -18,8 +18,6 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
using DotNetOpenAuth.Messaging.Bindings;
using DotNetOpenAuth.OpenId.Extensions;
using DotNetOpenAuth.OpenId.Messages;
- using DotNetOpenAuth.OpenId.Provider;
- using DotNetOpenAuth.OpenId.RelyingParty;
/// <summary>
/// A channel that knows how to send and receive OpenID messages.
@@ -43,68 +41,14 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
private KeyValueFormEncoding keyValueForm = new KeyValueFormEncoding();
/// <summary>
- /// Initializes a new instance of the <see cref="OpenIdChannel"/> class
- /// for use by a Relying Party.
- /// </summary>
- /// <param name="associationStore">The association store to use.</param>
- /// <param name="nonceStore">The nonce store to use.</param>
- /// <param name="securitySettings">The security settings to apply.</param>
- internal OpenIdChannel(IAssociationStore<Uri> associationStore, INonceStore nonceStore, RelyingPartySecuritySettings securitySettings)
- : this(associationStore, nonceStore, new OpenIdMessageFactory(), securitySettings, false) {
- Contract.Requires<ArgumentNullException>(securitySettings != null);
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="OpenIdChannel"/> class
- /// for use by a Provider.
- /// </summary>
- /// <param name="associationStore">The association store to use.</param>
- /// <param name="nonceStore">The nonce store to use.</param>
- /// <param name="securitySettings">The security settings.</param>
- internal OpenIdChannel(IAssociationStore<AssociationRelyingPartyType> associationStore, INonceStore nonceStore, ProviderSecuritySettings securitySettings)
- : this(associationStore, nonceStore, new OpenIdMessageFactory(), securitySettings) {
- Contract.Requires<ArgumentNullException>(securitySettings != null);
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="OpenIdChannel"/> class
- /// for use by a Relying Party.
- /// </summary>
- /// <param name="associationStore">The association store to use.</param>
- /// <param name="nonceStore">The nonce store to use.</param>
- /// <param name="messageTypeProvider">An object that knows how to distinguish the various OpenID message types for deserialization purposes.</param>
- /// <param name="securitySettings">The security settings to apply.</param>
- /// <param name="nonVerifying">A value indicating whether the channel is set up with no functional security binding elements.</param>
- private OpenIdChannel(IAssociationStore<Uri> associationStore, INonceStore nonceStore, IMessageFactory messageTypeProvider, RelyingPartySecuritySettings securitySettings, bool nonVerifying) :
- this(messageTypeProvider, InitializeBindingElements(associationStore, nonceStore, securitySettings, nonVerifying)) {
- Contract.Requires<ArgumentNullException>(messageTypeProvider != null);
- Contract.Requires<ArgumentNullException>(securitySettings != null);
- Contract.Requires<ArgumentException>(!nonVerifying || securitySettings is RelyingPartySecuritySettings);
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="OpenIdChannel"/> class
- /// for use by a Provider.
- /// </summary>
- /// <param name="associationStore">The association store to use.</param>
- /// <param name="nonceStore">The nonce store to use.</param>
- /// <param name="messageTypeProvider">An object that knows how to distinguish the various OpenID message types for deserialization purposes.</param>
- /// <param name="securitySettings">The security settings.</param>
- private OpenIdChannel(IAssociationStore<AssociationRelyingPartyType> associationStore, INonceStore nonceStore, IMessageFactory messageTypeProvider, ProviderSecuritySettings securitySettings) :
- this(messageTypeProvider, InitializeBindingElements(associationStore, nonceStore, securitySettings, false)) {
- Contract.Requires<ArgumentNullException>(messageTypeProvider != null);
- Contract.Requires<ArgumentNullException>(securitySettings != null);
- }
-
- /// <summary>
/// Initializes a new instance of the <see cref="OpenIdChannel"/> class.
/// </summary>
/// <param name="messageTypeProvider">A class prepared to analyze incoming messages and indicate what concrete
/// message types can deserialize from it.</param>
/// <param name="bindingElements">The binding elements to use in sending and receiving messages.</param>
- private OpenIdChannel(IMessageFactory messageTypeProvider, IChannelBindingElement[] bindingElements)
+ protected OpenIdChannel(IMessageFactory messageTypeProvider, IChannelBindingElement[] bindingElements)
: base(messageTypeProvider, bindingElements) {
- Contract.Requires<ArgumentNullException>(messageTypeProvider != null);
+ Requires.NotNull(messageTypeProvider, "messageTypeProvider");
// Customize the binding element order, since we play some tricks for higher
// security and backward compatibility with older OpenID versions.
@@ -133,24 +77,6 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
}
/// <summary>
- /// A value indicating whether the channel is set up
- /// with no functional security binding elements.
- /// </summary>
- /// <returns>A new <see cref="OpenIdChannel"/> instance that will not perform verification on incoming messages or apply any security to outgoing messages.</returns>
- /// <remarks>
- /// <para>A value of <c>true</c> allows the relying party to preview incoming
- /// messages without invalidating nonces or checking signatures.</para>
- /// <para>Setting this to <c>true</c> poses a great security risk and is only
- /// present to support the <see cref="OpenIdAjaxTextBox"/> which needs to preview
- /// messages, and will validate them later.</para>
- /// </remarks>
- internal static OpenIdChannel CreateNonVerifyingChannel() {
- Contract.Ensures(Contract.Result<OpenIdChannel>() != null);
-
- return new OpenIdChannel(null, null, new OpenIdMessageFactory(), new RelyingPartySecuritySettings(), true);
- }
-
- /// <summary>
/// Verifies the integrity and applicability of an incoming message.
/// </summary>
/// <param name="message">The message just received.</param>
@@ -298,81 +224,5 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
return response;
}
-
- /// <summary>
- /// Initializes the binding elements.
- /// </summary>
- /// <typeparam name="T">The distinguishing factor used by the association store.</typeparam>
- /// <param name="associationStore">The association store.</param>
- /// <param name="nonceStore">The nonce store to use.</param>
- /// <param name="securitySettings">The security settings to apply. Must be an instance of either <see cref="RelyingPartySecuritySettings"/> or <see cref="ProviderSecuritySettings"/>.</param>
- /// <param name="nonVerifying">A value indicating whether the channel is set up with no functional security binding elements.</param>
- /// <returns>
- /// An array of binding elements which may be used to construct the channel.
- /// </returns>
- [SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "Needed for code contracts.")]
- private static IChannelBindingElement[] InitializeBindingElements<T>(IAssociationStore<T> associationStore, INonceStore nonceStore, SecuritySettings securitySettings, bool nonVerifying) {
- Contract.Requires<ArgumentNullException>(securitySettings != null);
- Contract.Requires<ArgumentException>(!nonVerifying || securitySettings is RelyingPartySecuritySettings);
-
- var rpSecuritySettings = securitySettings as RelyingPartySecuritySettings;
- var opSecuritySettings = securitySettings as ProviderSecuritySettings;
- ErrorUtilities.VerifyInternal(rpSecuritySettings != null || opSecuritySettings != null, "Expected an RP or OP security settings instance.");
- ErrorUtilities.VerifyInternal(!nonVerifying || rpSecuritySettings != null, "Non-verifying channels can only be constructed for relying parties.");
- bool isRelyingPartyRole = rpSecuritySettings != null;
-
- var rpAssociationStore = associationStore as IAssociationStore<Uri>;
- var opAssociationStore = associationStore as IAssociationStore<AssociationRelyingPartyType>;
- ErrorUtilities.VerifyInternal(isRelyingPartyRole || opAssociationStore != null, "Providers MUST have an association store.");
-
- SigningBindingElement signingElement;
- if (isRelyingPartyRole) {
- signingElement = nonVerifying ? null : new SigningBindingElement(rpAssociationStore);
- } else {
- signingElement = new SigningBindingElement(opAssociationStore, opSecuritySettings);
- }
-
- var extensionFactory = OpenIdExtensionFactoryAggregator.LoadFromConfiguration();
-
- List<IChannelBindingElement> elements = new List<IChannelBindingElement>(8);
- elements.Add(new ExtensionsBindingElement(extensionFactory, securitySettings));
- if (isRelyingPartyRole) {
- elements.Add(new RelyingPartySecurityOptions(rpSecuritySettings));
- elements.Add(new BackwardCompatibilityBindingElement());
- ReturnToNonceBindingElement requestNonceElement = null;
-
- if (associationStore != null) {
- if (nonceStore != null) {
- // There is no point in having a ReturnToNonceBindingElement without
- // a ReturnToSignatureBindingElement because the nonce could be
- // artificially changed without it.
- requestNonceElement = new ReturnToNonceBindingElement(nonceStore, rpSecuritySettings);
- elements.Add(requestNonceElement);
- }
-
- // It is important that the return_to signing element comes last
- // so that the nonce is included in the signature.
- elements.Add(new ReturnToSignatureBindingElement(rpAssociationStore, rpSecuritySettings));
- }
-
- ErrorUtilities.VerifyOperation(!rpSecuritySettings.RejectUnsolicitedAssertions || requestNonceElement != null, OpenIdStrings.UnsolicitedAssertionRejectionRequiresNonceStore);
- } else {
- // Providers must always have a nonce store.
- ErrorUtilities.VerifyArgumentNotNull(nonceStore, "nonceStore");
- }
-
- if (nonVerifying) {
- elements.Add(new SkipSecurityBindingElement());
- } else {
- if (nonceStore != null) {
- elements.Add(new StandardReplayProtectionBindingElement(nonceStore, true));
- }
-
- elements.Add(new StandardExpirationBindingElement());
- elements.Add(signingElement);
- }
-
- return elements.ToArray();
- }
}
}
diff --git a/src/DotNetOpenAuth/OpenId/ChannelElements/OriginalStringUriEncoder.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/OriginalStringUriEncoder.cs
index 75b01e1..75b01e1 100644
--- a/src/DotNetOpenAuth/OpenId/ChannelElements/OriginalStringUriEncoder.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/OriginalStringUriEncoder.cs
diff --git a/src/DotNetOpenAuth/OpenId/ChannelElements/ReturnToSignatureBindingElement.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/ReturnToSignatureBindingElement.cs
index 438c496..25a29bb 100644
--- a/src/DotNetOpenAuth/OpenId/ChannelElements/ReturnToSignatureBindingElement.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/ReturnToSignatureBindingElement.cs
@@ -11,9 +11,10 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
using System.Diagnostics.Contracts;
using System.Security.Cryptography;
using System.Web;
+ using DotNetOpenAuth.Configuration;
using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
using DotNetOpenAuth.OpenId.Messages;
- using DotNetOpenAuth.OpenId.RelyingParty;
/// <summary>
/// This binding element signs a Relying Party's openid.return_to parameter
@@ -43,19 +44,23 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
private const string ReturnToSignatureHandleParameterName = OpenIdUtilities.CustomParameterPrefix + "return_to_sig_handle";
/// <summary>
- /// The hashing algorithm used to generate the private signature on the return_to parameter.
+ /// The URI to use for private associations at this RP.
/// </summary>
- private PrivateSecretManager secretManager;
+ private static readonly Uri SecretUri = new Uri("https://localhost/dnoa/secret");
+
+ /// <summary>
+ /// The key store used to generate the private signature on the return_to parameter.
+ /// </summary>
+ private ICryptoKeyStore cryptoKeyStore;
/// <summary>
/// Initializes a new instance of the <see cref="ReturnToSignatureBindingElement"/> class.
/// </summary>
- /// <param name="secretStore">The secret store from which to retrieve the secret used for signing.</param>
- /// <param name="securitySettings">The security settings.</param>
- internal ReturnToSignatureBindingElement(IAssociationStore<Uri> secretStore, RelyingPartySecuritySettings securitySettings) {
- Contract.Requires<ArgumentNullException>(secretStore != null);
+ /// <param name="cryptoKeyStore">The crypto key store.</param>
+ internal ReturnToSignatureBindingElement(ICryptoKeyStore cryptoKeyStore) {
+ Requires.NotNull(cryptoKeyStore, "cryptoKeyStore");
- this.secretManager = new PrivateSecretManager(securitySettings, secretStore);
+ this.cryptoKeyStore = cryptoKeyStore;
}
#region IChannelBindingElement Members
@@ -96,8 +101,10 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
public MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) {
SignedResponseRequest request = message as SignedResponseRequest;
if (request != null && request.ReturnTo != null && request.SignReturnTo) {
- request.AddReturnToArguments(ReturnToSignatureHandleParameterName, this.secretManager.CurrentHandle);
- request.AddReturnToArguments(ReturnToSignatureParameterName, this.GetReturnToSignature(request.ReturnTo));
+ var cryptoKeyPair = this.cryptoKeyStore.GetCurrentKey(SecretUri.AbsoluteUri, OpenIdElement.Configuration.MaxAuthenticationTime);
+ request.AddReturnToArguments(ReturnToSignatureHandleParameterName, cryptoKeyPair.Key);
+ string signature = Convert.ToBase64String(this.GetReturnToSignature(request.ReturnTo, cryptoKeyPair.Value));
+ request.AddReturnToArguments(ReturnToSignatureParameterName, signature);
// We return none because we are not signing the entire message (only a part).
return MessageProtections.None;
@@ -134,10 +141,11 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
// Only check the return_to signature if one is present.
if (returnToParameters[ReturnToSignatureHandleParameterName] != null) {
// Set the safety flag showing whether the return_to url had a valid signature.
- string expected = this.GetReturnToSignature(response.ReturnTo);
+ byte[] expectedBytes = this.GetReturnToSignature(response.ReturnTo);
string actual = returnToParameters[ReturnToSignatureParameterName];
actual = OpenIdUtilities.FixDoublyUriDecodedBase64String(actual);
- response.ReturnToParametersSignatureValidated = actual == expected;
+ byte[] actualBytes = Convert.FromBase64String(actual);
+ response.ReturnToParametersSignatureValidated = MessagingUtilities.AreEquivalentConstantTime(actualBytes, expectedBytes);
if (!response.ReturnToParametersSignatureValidated) {
Logger.Bindings.WarnFormat("The return_to signature failed verification.");
}
@@ -155,14 +163,17 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
/// Gets the return to signature.
/// </summary>
/// <param name="returnTo">The return to.</param>
- /// <returns>The generated signature.</returns>
+ /// <param name="cryptoKey">The crypto key.</param>
+ /// <returns>
+ /// The generated signature.
+ /// </returns>
/// <remarks>
/// Only the parameters in the return_to URI are signed, rather than the base URI
/// itself, in order that OPs that might change the return_to's implicit port :80 part
/// or other minor changes do not invalidate the signature.
/// </remarks>
- private string GetReturnToSignature(Uri returnTo) {
- Contract.Requires<ArgumentNullException>(returnTo != null);
+ private byte[] GetReturnToSignature(Uri returnTo, CryptoKey cryptoKey = null) {
+ Requires.NotNull(returnTo, "returnTo");
// Assemble the dictionary to sign, taking care to remove the signature itself
// in order to accurately reproduce the original signature (which of course didn't include
@@ -182,12 +193,18 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
byte[] bytesToSign = KeyValueFormEncoding.GetBytes(sortedReturnToParameters);
byte[] signature;
try {
- signature = this.secretManager.Sign(bytesToSign, returnToParameters[ReturnToSignatureHandleParameterName]);
+ if (cryptoKey == null) {
+ cryptoKey = this.cryptoKeyStore.GetKey(SecretUri.AbsoluteUri, returnToParameters[ReturnToSignatureHandleParameterName]);
+ }
+
+ using (var signer = new HMACSHA256(cryptoKey.Key)) {
+ signature = signer.ComputeHash(bytesToSign);
+ }
} catch (ProtocolException ex) {
throw ErrorUtilities.Wrap(ex, OpenIdStrings.MaximumAuthenticationTimeExpired);
}
- string signatureBase64 = Convert.ToBase64String(signature);
- return signatureBase64;
+
+ return signature;
}
}
}
diff --git a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SigningBindingElement.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SigningBindingElement.cs
new file mode 100644
index 0000000..d14ca8a
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SigningBindingElement.cs
@@ -0,0 +1,199 @@
+//-----------------------------------------------------------------------
+// <copyright file="SigningBindingElement.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics;
+ using System.Diagnostics.Contracts;
+ using System.Globalization;
+ using System.Linq;
+ using System.Net.Security;
+ using System.Web;
+ using DotNetOpenAuth.Loggers;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+ using DotNetOpenAuth.Messaging.Reflection;
+ using DotNetOpenAuth.OpenId.Messages;
+
+ /// <summary>
+ /// Signs and verifies authentication assertions.
+ /// </summary>
+ [ContractClass(typeof(SigningBindingElementContract))]
+ internal abstract class SigningBindingElement : IChannelBindingElement {
+ #region IChannelBindingElement Properties
+
+ /// <summary>
+ /// Gets the protection offered (if any) by this binding element.
+ /// </summary>
+ /// <value><see cref="MessageProtections.TamperProtection"/></value>
+ public MessageProtections Protection {
+ get { return MessageProtections.TamperProtection; }
+ }
+
+ /// <summary>
+ /// Gets or sets the channel that this binding element belongs to.
+ /// </summary>
+ public Channel Channel { get; set; }
+
+ #endregion
+
+ /// <summary>
+ /// Gets a value indicating whether this binding element is on a Provider channel.
+ /// </summary>
+ protected virtual bool IsOnProvider {
+ get { return false; }
+ }
+
+ #region IChannelBindingElement Methods
+
+ /// <summary>
+ /// Prepares a message for sending based on the rules of this channel binding element.
+ /// </summary>
+ /// <param name="message">The message to prepare for sending.</param>
+ /// <returns>
+ /// The protections (if any) that this binding element applied to the message.
+ /// Null if this binding element did not even apply to this binding element.
+ /// </returns>
+ public virtual MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) {
+ return null;
+ }
+
+ /// <summary>
+ /// Performs any transformation on an incoming message that may be necessary and/or
+ /// validates an incoming message based on the rules of this channel binding element.
+ /// </summary>
+ /// <param name="message">The incoming message to process.</param>
+ /// <returns>
+ /// The protections (if any) that this binding element applied to the message.
+ /// Null if this binding element did not even apply to this binding element.
+ /// </returns>
+ /// <exception cref="ProtocolException">
+ /// Thrown when the binding element rules indicate that this message is invalid and should
+ /// NOT be processed.
+ /// </exception>
+ public MessageProtections? ProcessIncomingMessage(IProtocolMessage message) {
+ var signedMessage = message as ITamperResistantOpenIdMessage;
+ if (signedMessage != null) {
+ Logger.Bindings.DebugFormat("Verifying incoming {0} message signature of: {1}", message.GetType().Name, signedMessage.Signature);
+ MessageProtections protectionsApplied = MessageProtections.TamperProtection;
+
+ this.EnsureParametersRequiringSignatureAreSigned(signedMessage);
+
+ Association association = this.GetSpecificAssociation(signedMessage);
+ if (association != null) {
+ string signature = this.GetSignature(signedMessage, association);
+ if (!MessagingUtilities.EqualsConstantTime(signedMessage.Signature, signature)) {
+ Logger.Bindings.Error("Signature verification failed.");
+ throw new InvalidSignatureException(message);
+ }
+ } else {
+ ErrorUtilities.VerifyInternal(this.Channel != null, "Cannot verify private association signature because we don't have a channel.");
+
+ protectionsApplied = this.VerifySignatureByUnrecognizedHandle(message, signedMessage, protectionsApplied);
+ }
+
+ return protectionsApplied;
+ }
+
+ return null;
+ }
+
+ /// <summary>
+ /// Verifies the signature by unrecognized handle.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <param name="signedMessage">The signed message.</param>
+ /// <param name="protectionsApplied">The protections applied.</param>
+ /// <returns>The applied protections.</returns>
+ protected abstract MessageProtections VerifySignatureByUnrecognizedHandle(IProtocolMessage message, ITamperResistantOpenIdMessage signedMessage, MessageProtections protectionsApplied);
+
+ #endregion
+
+ /// <summary>
+ /// Calculates the signature for a given message.
+ /// </summary>
+ /// <param name="signedMessage">The message to sign or verify.</param>
+ /// <param name="association">The association to use to sign the message.</param>
+ /// <returns>The calculated signature of the method.</returns>
+ protected string GetSignature(ITamperResistantOpenIdMessage signedMessage, Association association) {
+ Requires.NotNull(signedMessage, "signedMessage");
+ Requires.True(!String.IsNullOrEmpty(signedMessage.SignedParameterOrder), "signedMessage");
+ Requires.NotNull(association, "association");
+
+ // Prepare the parts to sign, taking care to replace an openid.mode value
+ // of check_authentication with its original id_res so the signature matches.
+ MessageDictionary dictionary = this.Channel.MessageDescriptions.GetAccessor(signedMessage);
+ var parametersToSign = from name in signedMessage.SignedParameterOrder.Split(',')
+ let prefixedName = Protocol.V20.openid.Prefix + name
+ select new KeyValuePair<string, string>(name, dictionary.GetValueOrThrow(prefixedName, signedMessage));
+
+ byte[] dataToSign = KeyValueFormEncoding.GetBytes(parametersToSign);
+ string signature = Convert.ToBase64String(association.Sign(dataToSign));
+
+ if (Logger.Signatures.IsDebugEnabled) {
+ Logger.Signatures.DebugFormat(
+ "Signing these message parts: {0}{1}{0}Base64 representation of signed data: {2}{0}Signature: {3}",
+ Environment.NewLine,
+ parametersToSign.ToStringDeferred(),
+ Convert.ToBase64String(dataToSign),
+ signature);
+ }
+
+ return signature;
+ }
+
+ /// <summary>
+ /// Gets the association to use to sign or verify a message.
+ /// </summary>
+ /// <param name="signedMessage">The message to sign or verify.</param>
+ /// <returns>The association to use to sign or verify the message.</returns>
+ protected abstract Association GetAssociation(ITamperResistantOpenIdMessage signedMessage);
+
+ /// <summary>
+ /// Gets a specific association referenced in a given message's association handle.
+ /// </summary>
+ /// <param name="signedMessage">The signed message whose association handle should be used to lookup the association to return.</param>
+ /// <returns>The referenced association; or <c>null</c> if such an association cannot be found.</returns>
+ /// <remarks>
+ /// If the association handle set in the message does not match any valid association,
+ /// the association handle property is cleared, and the
+ /// <see cref="ITamperResistantOpenIdMessage.InvalidateHandle"/> property is set to the
+ /// handle that could not be found.
+ /// </remarks>
+ protected abstract Association GetSpecificAssociation(ITamperResistantOpenIdMessage signedMessage);
+
+ /// <summary>
+ /// Gets a private Provider association used for signing messages in "dumb" mode.
+ /// </summary>
+ /// <returns>An existing or newly created association.</returns>
+ protected virtual Association GetDumbAssociationForSigning() {
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Ensures that all message parameters that must be signed are in fact included
+ /// in the signature.
+ /// </summary>
+ /// <param name="signedMessage">The signed message.</param>
+ private void EnsureParametersRequiringSignatureAreSigned(ITamperResistantOpenIdMessage signedMessage) {
+ // Verify that the signed parameter order includes the mandated fields.
+ // We do this in such a way that derived classes that add mandated fields automatically
+ // get included in the list of checked parameters.
+ Protocol protocol = Protocol.Lookup(signedMessage.Version);
+ var partsRequiringProtection = from part in this.Channel.MessageDescriptions.Get(signedMessage).Mapping.Values
+ where part.RequiredProtection != ProtectionLevel.None
+ where part.IsRequired || part.IsNondefaultValueSet(signedMessage)
+ select part.Name;
+ ErrorUtilities.VerifyInternal(partsRequiringProtection.All(name => name.StartsWith(protocol.openid.Prefix, StringComparison.Ordinal)), "Signing only works when the parameters start with the 'openid.' prefix.");
+ string[] signedParts = signedMessage.SignedParameterOrder.Split(',');
+ var unsignedParts = from partName in partsRequiringProtection
+ where !signedParts.Contains(partName.Substring(protocol.openid.Prefix.Length))
+ select partName;
+ ErrorUtilities.VerifyProtocol(!unsignedParts.Any(), OpenIdStrings.SignatureDoesNotIncludeMandatoryParts, string.Join(", ", unsignedParts.ToArray()));
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SigningBindingElementContract.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SigningBindingElementContract.cs
new file mode 100644
index 0000000..bf8b18d
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SigningBindingElementContract.cs
@@ -0,0 +1,64 @@
+//-----------------------------------------------------------------------
+// <copyright file="SigningBindingElementContract.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics;
+ using System.Diagnostics.Contracts;
+ using System.Globalization;
+ using System.Linq;
+ using System.Net.Security;
+ using System.Web;
+ using DotNetOpenAuth.Loggers;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+ using DotNetOpenAuth.Messaging.Reflection;
+ using DotNetOpenAuth.OpenId.Messages;
+
+ /// <summary>
+ /// Code contract for the <see cref="SigningBindingElement"/> class.
+ /// </summary>
+ [ContractClassFor(typeof(SigningBindingElement))]
+ internal abstract class SigningBindingElementContract : SigningBindingElement {
+ /// <summary>
+ /// Verifies the signature by unrecognized handle.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <param name="signedMessage">The signed message.</param>
+ /// <param name="protectionsApplied">The protections applied.</param>
+ /// <returns>
+ /// The applied protections.
+ /// </returns>
+ protected override MessageProtections VerifySignatureByUnrecognizedHandle(IProtocolMessage message, ITamperResistantOpenIdMessage signedMessage, MessageProtections protectionsApplied) {
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Gets the association to use to sign or verify a message.
+ /// </summary>
+ /// <param name="signedMessage">The message to sign or verify.</param>
+ /// <returns>
+ /// The association to use to sign or verify the message.
+ /// </returns>
+ protected override Association GetAssociation(ITamperResistantOpenIdMessage signedMessage) {
+ Requires.NotNull(signedMessage, "signedMessage");
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Gets a specific association referenced in a given message's association handle.
+ /// </summary>
+ /// <param name="signedMessage">The signed message whose association handle should be used to lookup the association to return.</param>
+ /// <returns>
+ /// The referenced association; or <c>null</c> if such an association cannot be found.
+ /// </returns>
+ protected override Association GetSpecificAssociation(ITamperResistantOpenIdMessage signedMessage) {
+ Requires.NotNull(signedMessage, "signedMessage");
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/ChannelElements/SkipSecurityBindingElement.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SkipSecurityBindingElement.cs
index ad65a83..ad65a83 100644
--- a/src/DotNetOpenAuth/OpenId/ChannelElements/SkipSecurityBindingElement.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SkipSecurityBindingElement.cs
diff --git a/src/DotNetOpenAuth/OpenId/DiffieHellmanUtilities.cs b/src/DotNetOpenAuth.OpenId/OpenId/DiffieHellmanUtilities.cs
index 7a92ed8..e7e1bf8 100644
--- a/src/DotNetOpenAuth/OpenId/DiffieHellmanUtilities.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/DiffieHellmanUtilities.cs
@@ -37,8 +37,8 @@ namespace DotNetOpenAuth.OpenId {
/// <returns>The hashing algorithm to use.</returns>
/// <exception cref="ProtocolException">Thrown if no match could be found for the given <paramref name="sessionType"/>.</exception>
public static HashAlgorithm Lookup(Protocol protocol, string sessionType) {
- Contract.Requires<ArgumentNullException>(protocol != null);
- Contract.Requires<ArgumentNullException>(sessionType != null);
+ Requires.NotNull(protocol, "protocol");
+ Requires.NotNull(sessionType, "sessionType");
// We COULD use just First instead of FirstOrDefault, but we want to throw ProtocolException instead of InvalidOperationException.
DHSha match = diffieHellmanSessionTypes.FirstOrDefault(dhsha => String.Equals(dhsha.GetName(protocol), sessionType, StringComparison.Ordinal));
@@ -53,7 +53,7 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="hashSizeInBits">The hash size (in bits) that the DH session must have.</param>
/// <returns>The value to be used for the openid.session_type parameter, or null if no match was found.</returns>
internal static string GetNameForSize(Protocol protocol, int hashSizeInBits) {
- Contract.Requires<ArgumentNullException>(protocol != null);
+ Requires.NotNull(protocol, "protocol");
DHSha match = diffieHellmanSessionTypes.FirstOrDefault(dhsha => dhsha.Algorithm.HashSize == hashSizeInBits);
return match != null ? match.GetName(protocol) : null;
}
@@ -73,10 +73,10 @@ namespace DotNetOpenAuth.OpenId {
/// The secret itself if the encrypted version of the secret was given in <paramref name="remotePublicKey"/>.
/// </returns>
internal static byte[] SHAHashXorSecret(HashAlgorithm hasher, DiffieHellman dh, byte[] remotePublicKey, byte[] plainOrEncryptedSecret) {
- Contract.Requires<ArgumentNullException>(hasher != null);
- Contract.Requires<ArgumentNullException>(dh != null);
- Contract.Requires<ArgumentNullException>(remotePublicKey != null);
- Contract.Requires<ArgumentNullException>(plainOrEncryptedSecret != null);
+ Requires.NotNull(hasher, "hasher");
+ Requires.NotNull(dh, "dh");
+ Requires.NotNull(remotePublicKey, "remotePublicKey");
+ Requires.NotNull(plainOrEncryptedSecret, "plainOrEncryptedSecret");
byte[] sharedBlock = dh.DecryptKeyExchange(remotePublicKey);
byte[] sharedBlockHash = hasher.ComputeHash(EnsurePositive(sharedBlock));
@@ -102,7 +102,7 @@ namespace DotNetOpenAuth.OpenId {
/// This is to be consistent with OpenID spec section 4.2.
/// </remarks>
internal static byte[] EnsurePositive(byte[] inputBytes) {
- Contract.Requires<ArgumentNullException>(inputBytes != null);
+ Requires.NotNull(inputBytes, "inputBytes");
if (inputBytes.Length == 0) {
throw new ArgumentException(MessagingStrings.UnexpectedEmptyArray, "inputBytes");
}
@@ -128,8 +128,8 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="algorithm">The hashing algorithm used in this particular Diffie-Hellman session type.</param>
/// <param name="getName">A function that will return the value of the openid.session_type parameter for a given version of OpenID.</param>
public DHSha(HashAlgorithm algorithm, Func<Protocol, string> getName) {
- Contract.Requires<ArgumentNullException>(algorithm != null);
- Contract.Requires<ArgumentNullException>(getName != null);
+ Requires.NotNull(algorithm, "algorithm");
+ Requires.NotNull(getName, "getName");
this.GetName = getName;
this.Algorithm = algorithm;
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/AliasManager.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AliasManager.cs
index 0a84266..f6878ec 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/AliasManager.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AliasManager.cs
@@ -45,7 +45,7 @@ namespace DotNetOpenAuth.OpenId.Extensions {
/// <param name="typeUri">The type URI.</param>
/// <returns>The alias assigned to this type URI. Never null.</returns>
public string GetAlias(string typeUri) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(typeUri));
+ Requires.NotNullOrEmpty(typeUri, "typeUri");
string alias;
return this.typeUriToAliasMap.TryGetValue(typeUri, out alias) ? alias : this.AssignNewAlias(typeUri);
}
@@ -56,8 +56,8 @@ namespace DotNetOpenAuth.OpenId.Extensions {
/// <param name="alias">The alias.</param>
/// <param name="typeUri">The type URI.</param>
public void SetAlias(string alias, string typeUri) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(alias));
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(typeUri));
+ Requires.NotNullOrEmpty(alias, "alias");
+ Requires.NotNullOrEmpty(typeUri, "typeUri");
this.aliasToTypeUriMap.Add(alias, typeUri);
this.typeUriToAliasMap.Add(typeUri, alias);
}
@@ -68,7 +68,7 @@ namespace DotNetOpenAuth.OpenId.Extensions {
/// <param name="typeUris">The type URIs to create aliases for.</param>
/// <param name="preferredTypeUriToAliases">An optional dictionary of URI/alias pairs that suggest preferred aliases to use if available for certain type URIs.</param>
public void AssignAliases(IEnumerable<string> typeUris, IDictionary<string, string> preferredTypeUriToAliases) {
- Contract.Requires<ArgumentNullException>(typeUris != null);
+ Requires.NotNull(typeUris, "typeUris");
// First go through the actually used type URIs and see which ones have matching preferred aliases.
if (preferredTypeUriToAliases != null) {
@@ -103,7 +103,7 @@ namespace DotNetOpenAuth.OpenId.Extensions {
/// </summary>
/// <param name="preferredTypeUriToAliases">A dictionary of type URI keys and alias values.</param>
public void SetPreferredAliasesWhereNotSet(IDictionary<string, string> preferredTypeUriToAliases) {
- Contract.Requires<ArgumentNullException>(preferredTypeUriToAliases != null);
+ Requires.NotNull(preferredTypeUriToAliases, "preferredTypeUriToAliases");
foreach (var pair in preferredTypeUriToAliases) {
if (this.typeUriToAliasMap.ContainsKey(pair.Key)) {
@@ -128,7 +128,7 @@ namespace DotNetOpenAuth.OpenId.Extensions {
/// <returns>The Type URI.</returns>
/// <exception cref="ArgumentOutOfRangeException">Thrown if the given alias does not have a matching TypeURI.</exception>
public string ResolveAlias(string alias) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(alias));
+ Requires.NotNullOrEmpty(alias, "alias");
string typeUri = this.TryResolveAlias(alias);
if (typeUri == null) {
throw new ArgumentOutOfRangeException("alias");
@@ -142,7 +142,7 @@ namespace DotNetOpenAuth.OpenId.Extensions {
/// <param name="alias">The alias.</param>
/// <returns>The Type URI for the given alias, or null if none for that alias exist.</returns>
public string TryResolveAlias(string alias) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(alias));
+ Requires.NotNullOrEmpty(alias, "alias");
string typeUri = null;
this.aliasToTypeUriMap.TryGetValue(alias, out typeUri);
return typeUri;
@@ -154,7 +154,7 @@ namespace DotNetOpenAuth.OpenId.Extensions {
/// <param name="alias">The alias in question.</param>
/// <returns>True if the alias has already been assigned. False otherwise.</returns>
public bool IsAliasUsed(string alias) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(alias));
+ Requires.NotNullOrEmpty(alias, "alias");
return this.aliasToTypeUriMap.ContainsKey(alias);
}
@@ -166,7 +166,7 @@ namespace DotNetOpenAuth.OpenId.Extensions {
/// <c>true</c> if the given type URI already has an alias assigned; <c>false</c> otherwise.
/// </returns>
public bool IsAliasAssignedTo(string typeUri) {
- Contract.Requires<ArgumentNullException>(typeUri != null);
+ Requires.NotNull(typeUri, "typeUri");
return this.typeUriToAliasMap.ContainsKey(typeUri);
}
@@ -176,7 +176,7 @@ namespace DotNetOpenAuth.OpenId.Extensions {
/// <param name="typeUri">The type URI to assign a new alias to.</param>
/// <returns>The newly generated alias.</returns>
private string AssignNewAlias(string typeUri) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(typeUri));
+ Requires.NotNullOrEmpty(typeUri, "typeUri");
ErrorUtilities.VerifyInternal(!this.typeUriToAliasMap.ContainsKey(typeUri), "Oops! This type URI already has an alias!");
string alias = string.Format(CultureInfo.InvariantCulture, AliasFormat, this.typeUriToAliasMap.Count + 1);
this.typeUriToAliasMap.Add(typeUri, alias);
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/AXAttributeFormats.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/AXAttributeFormats.cs
index decd296..decd296 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/AXAttributeFormats.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/AXAttributeFormats.cs
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/AXUtilities.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/AXUtilities.cs
index 2b947f7..96cc437 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/AXUtilities.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/AXUtilities.cs
@@ -21,7 +21,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.AttributeExchange {
/// <param name="collection">The attribute request collection.</param>
/// <param name="typeUri">The type URI of the required attribute.</param>
public static void AddRequired(this ICollection<AttributeRequest> collection, string typeUri) {
- Contract.Requires<ArgumentNullException>(collection != null);
+ Requires.NotNull(collection, "collection");
collection.Add(new AttributeRequest(typeUri, true));
}
@@ -31,7 +31,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.AttributeExchange {
/// <param name="collection">The attribute request collection.</param>
/// <param name="typeUri">The type URI of the requested attribute.</param>
public static void AddOptional(this ICollection<AttributeRequest> collection, string typeUri) {
- Contract.Requires<ArgumentNullException>(collection != null);
+ Requires.NotNull(collection, "collection");
collection.Add(new AttributeRequest(typeUri, false));
}
@@ -43,7 +43,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.AttributeExchange {
/// <param name="typeUri">The type URI of the attribute.</param>
/// <param name="values">The attribute values.</param>
public static void Add(this ICollection<AttributeValues> collection, string typeUri, params string[] values) {
- Contract.Requires<ArgumentNullException>(collection != null);
+ Requires.NotNull(collection, "collection");
collection.Add(new AttributeValues(typeUri, values));
}
@@ -53,8 +53,8 @@ namespace DotNetOpenAuth.OpenId.Extensions.AttributeExchange {
/// <param name="fields">The dictionary to fill with serialized attributes.</param>
/// <param name="attributes">The attributes.</param>
internal static void SerializeAttributes(IDictionary<string, string> fields, IEnumerable<AttributeValues> attributes) {
- Contract.Requires<ArgumentNullException>(fields != null);
- Contract.Requires<ArgumentNullException>(attributes != null);
+ Requires.NotNull(fields, "fields");
+ Requires.NotNull(attributes, "attributes");
AliasManager aliasManager = new AliasManager();
foreach (var att in attributes) {
@@ -123,7 +123,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.AttributeExchange {
/// <param name="fields">The data included in the extension message.</param>
/// <returns>The alias manager that provides lookup between aliases and type URIs.</returns>
private static AliasManager ParseAliases(IDictionary<string, string> fields) {
- Contract.Requires<ArgumentNullException>(fields != null);
+ Requires.NotNull(fields, "fields");
AliasManager aliasManager = new AliasManager();
const string TypePrefix = "type.";
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/AttributeRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/AttributeRequest.cs
index 2dc9c69..cbcbff6 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/AttributeRequest.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/AttributeRequest.cs
@@ -36,7 +36,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.AttributeExchange {
/// </summary>
/// <param name="typeUri">The unique TypeURI for that describes the attribute being sought.</param>
public AttributeRequest(string typeUri) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(typeUri));
+ Requires.NotNullOrEmpty(typeUri, "typeUri");
this.TypeUri = typeUri;
}
@@ -84,7 +84,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.AttributeExchange {
}
set {
- Contract.Requires<ArgumentOutOfRangeException>(value > 0);
+ Requires.InRange(value > 0, "value");
this.count = value;
}
}
@@ -99,8 +99,8 @@ namespace DotNetOpenAuth.OpenId.Extensions.AttributeExchange {
/// the <see cref="FetchResponse"/> object.
/// </returns>
public AttributeValues Respond(params string[] values) {
- Contract.Requires<ArgumentNullException>(values != null);
- Contract.Requires<ArgumentException>(values.Length <= this.Count);
+ Requires.NotNull(values, "values");
+ Requires.True(values.Length <= this.Count, "values");
return new AttributeValues(this.TypeUri, values);
}
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/AttributeValues.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/AttributeValues.cs
index b2fc1fe..37ebe38 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/AttributeValues.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/AttributeValues.cs
@@ -25,7 +25,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.AttributeExchange {
/// <param name="typeUri">The TypeURI that uniquely identifies the attribute.</param>
/// <param name="values">The values for the attribute.</param>
public AttributeValues(string typeUri, params string[] values) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(typeUri));
+ Requires.NotNullOrEmpty(typeUri, "typeUri");
this.TypeUri = typeUri;
this.Values = (IList<string>)values ?? EmptyList<string>.Instance;
@@ -47,7 +47,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.AttributeExchange {
/// </summary>
/// <param name="typeUri">The TypeURI of the attribute whose values are being provided.</param>
internal AttributeValues(string typeUri) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(typeUri));
+ Requires.NotNullOrEmpty(typeUri, "typeUri");
this.TypeUri = typeUri;
this.Values = new List<string>(1);
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/Constants.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/Constants.cs
index 167d0d2..167d0d2 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/Constants.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/Constants.cs
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/FetchRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/FetchRequest.cs
index 124a18c..124a18c 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/FetchRequest.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/FetchRequest.cs
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/FetchResponse.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/FetchResponse.cs
index 14b1caa..14b1caa 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/FetchResponse.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/FetchResponse.cs
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/StoreRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/StoreRequest.cs
index 641b17a..641b17a 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/StoreRequest.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/StoreRequest.cs
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/StoreResponse.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/StoreResponse.cs
index ba7f091..ba7f091 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/StoreResponse.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/StoreResponse.cs
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/WellKnownAttributes.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/WellKnownAttributes.cs
index 5aa89c6..5aa89c6 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/AttributeExchange/WellKnownAttributes.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/WellKnownAttributes.cs
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/ExtensionArgumentsManager.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ExtensionArgumentsManager.cs
index 0a78df1..328d81f 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/ExtensionArgumentsManager.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ExtensionArgumentsManager.cs
@@ -64,7 +64,7 @@ namespace DotNetOpenAuth.OpenId.Extensions {
/// <param name="query">The parameters in the OpenID message.</param>
/// <returns>The newly created instance of <see cref="ExtensionArgumentsManager"/>.</returns>
public static ExtensionArgumentsManager CreateIncomingExtensions(IDictionary<string, string> query) {
- Contract.Requires<ArgumentNullException>(query != null);
+ Requires.NotNull(query, "query");
var mgr = new ExtensionArgumentsManager();
mgr.protocol = Protocol.Detect(query);
mgr.isReadMode = true;
@@ -134,9 +134,9 @@ namespace DotNetOpenAuth.OpenId.Extensions {
/// <param name="extensionTypeUri">The extension type URI.</param>
/// <param name="arguments">The arguments for this extension to add to the message.</param>
public void AddExtensionArguments(string extensionTypeUri, IDictionary<string, string> arguments) {
- Contract.Requires<InvalidOperationException>(!this.ReadMode);
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(extensionTypeUri));
- Contract.Requires<ArgumentNullException>(arguments != null);
+ Requires.ValidState(!this.ReadMode);
+ Requires.NotNullOrEmpty(extensionTypeUri, "extensionTypeUri");
+ Requires.NotNull(arguments, "arguments");
if (arguments.Count == 0) {
return;
}
@@ -162,7 +162,7 @@ namespace DotNetOpenAuth.OpenId.Extensions {
/// </param>
/// <returns>A dictionary of key=value pairs to add to the message to carry the extension.</returns>
internal IDictionary<string, string> GetArgumentsToSend(bool includeOpenIdPrefix) {
- Contract.Requires<InvalidOperationException>(!this.ReadMode);
+ Requires.ValidState(!this.ReadMode);
Dictionary<string, string> args = new Dictionary<string, string>();
foreach (var typeUriAndExtension in this.extensions) {
string typeUri = typeUriAndExtension.Key;
@@ -195,8 +195,8 @@ namespace DotNetOpenAuth.OpenId.Extensions {
/// The fields included in the given extension, or null if the extension is not present.
/// </returns>
internal IDictionary<string, string> GetExtensionArguments(string extensionTypeUri) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(extensionTypeUri));
- Contract.Requires<InvalidOperationException>(this.ReadMode);
+ Requires.NotNullOrEmpty(extensionTypeUri, "extensionTypeUri");
+ Requires.ValidState(this.ReadMode);
IDictionary<string, string> extensionArgs;
this.extensions.TryGetValue(extensionTypeUri, out extensionArgs);
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/ExtensionBase.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ExtensionBase.cs
index 108ac52..108ac52 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/ExtensionBase.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ExtensionBase.cs
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/IClientScriptExtensionResponse.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/IClientScriptExtensionResponse.cs
index c84f507..b44f797 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/IClientScriptExtensionResponse.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/IClientScriptExtensionResponse.cs
@@ -8,7 +8,6 @@ namespace DotNetOpenAuth.OpenId.Extensions {
using System.Collections.Generic;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId.Messages;
- using DotNetOpenAuth.OpenId.RelyingParty;
/// <summary>
/// An interface that OpenID extensions can implement to allow authentication response
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/OAuth/AuthorizationApprovedResponse.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/OAuth/AuthorizationApprovedResponse.cs
index 5e7bc49..5e7bc49 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/OAuth/AuthorizationApprovedResponse.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/OAuth/AuthorizationApprovedResponse.cs
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/OAuth/AuthorizationDeclinedResponse.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/OAuth/AuthorizationDeclinedResponse.cs
index 7c3a5ad..7c3a5ad 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/OAuth/AuthorizationDeclinedResponse.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/OAuth/AuthorizationDeclinedResponse.cs
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/OAuth/AuthorizationRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/OAuth/AuthorizationRequest.cs
index 99f0880..99f0880 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/OAuth/AuthorizationRequest.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/OAuth/AuthorizationRequest.cs
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/OAuth/Constants.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/OAuth/Constants.cs
index 32efee9..32efee9 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/OAuth/Constants.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/OAuth/Constants.cs
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/OpenIdExtensionFactoryAggregator.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/OpenIdExtensionFactoryAggregator.cs
index 05e6687..95dd2c9 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/OpenIdExtensionFactoryAggregator.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/OpenIdExtensionFactoryAggregator.cs
@@ -71,7 +71,7 @@ namespace DotNetOpenAuth.OpenId.Extensions {
/// <returns>A new instance of <see cref="OpenIdExtensionFactoryAggregator"/>.</returns>
internal static OpenIdExtensionFactoryAggregator LoadFromConfiguration() {
Contract.Ensures(Contract.Result<OpenIdExtensionFactoryAggregator>() != null);
- var factoriesElement = DotNetOpenAuth.Configuration.DotNetOpenAuthSection.Configuration.OpenId.ExtensionFactories;
+ var factoriesElement = DotNetOpenAuth.Configuration.OpenIdElement.Configuration.ExtensionFactories;
var aggregator = new OpenIdExtensionFactoryAggregator();
aggregator.Factories.Add(new StandardOpenIdExtensionFactory());
aggregator.factories.AddRange(factoriesElement.CreateInstances(false));
diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Extensions/OpenIdExtensionsInteropHelper.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/OpenIdExtensionsInteropHelper.cs
new file mode 100644
index 0000000..fb6202e
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/OpenIdExtensionsInteropHelper.cs
@@ -0,0 +1,124 @@
+//-----------------------------------------------------------------------
+// <copyright file="OpenIdExtensionsInteropHelper.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Extensions {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
+ using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
+ using DotNetOpenAuth.OpenId.Messages;
+
+ /// <summary>
+ /// A set of methods designed to assist in improving interop across different
+ /// OpenID implementations and their extensions.
+ /// </summary>
+ internal static class OpenIdExtensionsInteropHelper {
+ /// <summary>
+ /// The gender decoder to translate AX genders to Sreg.
+ /// </summary>
+ private static GenderEncoder genderEncoder = new GenderEncoder();
+
+ /// <summary>
+ /// Gets the gender decoder to translate AX genders to Sreg.
+ /// </summary>
+ internal static GenderEncoder GenderEncoder {
+ get { return genderEncoder; }
+ }
+
+ /// <summary>
+ /// Splits the AX attribute format flags into individual values for processing.
+ /// </summary>
+ /// <param name="formats">The formats to split up into individual flags.</param>
+ /// <returns>A sequence of individual flags.</returns>
+ internal static IEnumerable<AXAttributeFormats> ForEachFormat(AXAttributeFormats formats) {
+ if ((formats & AXAttributeFormats.AXSchemaOrg) != 0) {
+ yield return AXAttributeFormats.AXSchemaOrg;
+ }
+
+ if ((formats & AXAttributeFormats.OpenIdNetSchema) != 0) {
+ yield return AXAttributeFormats.OpenIdNetSchema;
+ }
+
+ if ((formats & AXAttributeFormats.SchemaOpenIdNet) != 0) {
+ yield return AXAttributeFormats.SchemaOpenIdNet;
+ }
+ }
+
+ /// <summary>
+ /// Transforms an AX attribute type URI from the axschema.org format into a given format.
+ /// </summary>
+ /// <param name="axSchemaOrgFormatTypeUri">The ax schema org format type URI.</param>
+ /// <param name="targetFormat">The target format. Only one flag should be set.</param>
+ /// <returns>The AX attribute type URI in the target format.</returns>
+ internal static string TransformAXFormat(string axSchemaOrgFormatTypeUri, AXAttributeFormats targetFormat) {
+ Requires.NotNullOrEmpty(axSchemaOrgFormatTypeUri, "axSchemaOrgFormatTypeUri");
+
+ switch (targetFormat) {
+ case AXAttributeFormats.AXSchemaOrg:
+ return axSchemaOrgFormatTypeUri;
+ case AXAttributeFormats.SchemaOpenIdNet:
+ return axSchemaOrgFormatTypeUri.Replace("axschema.org", "schema.openid.net");
+ case AXAttributeFormats.OpenIdNetSchema:
+ return axSchemaOrgFormatTypeUri.Replace("axschema.org", "openid.net/schema");
+ default:
+ throw new ArgumentOutOfRangeException("targetFormat");
+ }
+ }
+
+ /// <summary>
+ /// Detects the AX attribute type URI format from a given sample.
+ /// </summary>
+ /// <param name="typeURIs">The type URIs to scan for recognized formats.</param>
+ /// <returns>The first AX type URI format recognized in the list.</returns>
+ internal static AXAttributeFormats DetectAXFormat(IEnumerable<string> typeURIs) {
+ Requires.NotNull(typeURIs, "typeURIs");
+
+ if (typeURIs.Any(uri => uri.StartsWith("http://axschema.org/", StringComparison.Ordinal))) {
+ return AXAttributeFormats.AXSchemaOrg;
+ }
+
+ if (typeURIs.Any(uri => uri.StartsWith("http://schema.openid.net/", StringComparison.Ordinal))) {
+ return AXAttributeFormats.SchemaOpenIdNet;
+ }
+
+ if (typeURIs.Any(uri => uri.StartsWith("http://openid.net/schema/", StringComparison.Ordinal))) {
+ return AXAttributeFormats.OpenIdNetSchema;
+ }
+
+ return AXAttributeFormats.None;
+ }
+
+ /// <summary>
+ /// Adds an attribute fetch request if it is not already present in the AX request.
+ /// </summary>
+ /// <param name="ax">The AX request to add the attribute request to.</param>
+ /// <param name="format">The format of the attribute's Type URI to use.</param>
+ /// <param name="axSchemaOrgFormatAttribute">The attribute in axschema.org format.</param>
+ /// <param name="demandLevel">The demand level.</param>
+ internal static void FetchAttribute(FetchRequest ax, AXAttributeFormats format, string axSchemaOrgFormatAttribute, DemandLevel demandLevel) {
+ Requires.NotNull(ax, "ax");
+ Requires.NotNullOrEmpty(axSchemaOrgFormatAttribute, "axSchemaOrgFormatAttribute");
+
+ string typeUri = TransformAXFormat(axSchemaOrgFormatAttribute, format);
+ if (!ax.Attributes.Contains(typeUri)) {
+ switch (demandLevel) {
+ case DemandLevel.Request:
+ ax.Attributes.AddOptional(typeUri);
+ break;
+ case DemandLevel.Require:
+ ax.Attributes.AddRequired(typeUri);
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/AuthenticationPolicies.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/AuthenticationPolicies.cs
index 99c7a2e..99c7a2e 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/AuthenticationPolicies.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/AuthenticationPolicies.cs
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/Constants.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/Constants.cs
index 93e76d5..93e76d5 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/Constants.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/Constants.cs
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/DateTimeEncoder.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/DateTimeEncoder.cs
index 9dc0574..9dc0574 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/DateTimeEncoder.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/DateTimeEncoder.cs
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/NistAssuranceLevel.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/NistAssuranceLevel.cs
index 3031aad..3031aad 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/NistAssuranceLevel.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/NistAssuranceLevel.cs
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/PapeUtilities.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/PapeUtilities.cs
index eeaea31..d8ffb63 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/PapeUtilities.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/PapeUtilities.cs
@@ -46,7 +46,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy {
/// <returns>The concatenated string of elements.</returns>
/// <exception cref="FormatException">Thrown if any element in the sequence includes a space.</exception>
internal static string ConcatenateListOfElements(IEnumerable<string> values) {
- Contract.Requires<ArgumentNullException>(values != null);
+ Requires.NotNull(values, "values");
StringBuilder valuesList = new StringBuilder();
foreach (string value in values.Distinct()) {
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyRequest.cs
index 84589dc..84589dc 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyRequest.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyRequest.cs
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyResponse.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyResponse.cs
index 246ec07..1fddc22 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyResponse.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyResponse.cs
@@ -83,7 +83,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy {
}
set {
- Contract.Requires<ArgumentException>(!value.HasValue || value.Value.Kind != DateTimeKind.Unspecified, OpenIdStrings.UnspecifiedDateTimeKindNotAllowed);
+ Requires.True(!value.HasValue || value.Value.Kind != DateTimeKind.Unspecified, "value", OpenIdStrings.UnspecifiedDateTimeKindNotAllowed);
// Make sure that whatever is set here, it becomes UTC time.
if (value.HasValue) {
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/SimpleRegistration/ClaimsRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/SimpleRegistration/ClaimsRequest.cs
index cec8042..18f63d4 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/SimpleRegistration/ClaimsRequest.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/SimpleRegistration/ClaimsRequest.cs
@@ -51,7 +51,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.SimpleRegistration {
/// <param name="typeUri">The type URI this extension was recognized by in the OpenID message.</param>
internal ClaimsRequest(string typeUri)
: this() {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(typeUri));
+ Requires.NotNullOrEmpty(typeUri, "typeUri");
this.typeUriDeserializedFrom = typeUri;
}
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/SimpleRegistration/ClaimsResponse.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/SimpleRegistration/ClaimsResponse.cs
index d4df028..b50833b 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/SimpleRegistration/ClaimsResponse.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/SimpleRegistration/ClaimsResponse.cs
@@ -70,7 +70,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.SimpleRegistration {
/// </param>
internal ClaimsResponse(string typeUriToUse)
: base(new Version(1, 0), typeUriToUse, Constants.AdditionalTypeUris) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(typeUriToUse));
+ Requires.NotNullOrEmpty(typeUriToUse, "typeUriToUse");
}
/// <summary>
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/SimpleRegistration/Constants.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/SimpleRegistration/Constants.cs
index 9e00137..9e00137 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/SimpleRegistration/Constants.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/SimpleRegistration/Constants.cs
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/SimpleRegistration/DemandLevel.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/SimpleRegistration/DemandLevel.cs
index 7129270..7129270 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/SimpleRegistration/DemandLevel.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/SimpleRegistration/DemandLevel.cs
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/SimpleRegistration/Gender.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/SimpleRegistration/Gender.cs
index 3cc47c6..979c481 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/SimpleRegistration/Gender.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/SimpleRegistration/Gender.cs
@@ -38,7 +38,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.SimpleRegistration {
/// The <paramref name="value"/> in string form, ready for message transport.
/// </returns>
public string Encode(object value) {
- Gender? gender = (Gender?)value;
+ var gender = (Gender?)value;
if (gender.HasValue) {
switch (gender.Value) {
case Gender.Male: return Constants.Genders.Male;
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/StandardOpenIdExtensionFactory.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/StandardOpenIdExtensionFactory.cs
index 1dcda27..1dcda27 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/StandardOpenIdExtensionFactory.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/StandardOpenIdExtensionFactory.cs
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/UI/UIConstants.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/UI/UIConstants.cs
index 1cc920a..1cc920a 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/UI/UIConstants.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/UI/UIConstants.cs
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/UI/UIModes.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/UI/UIModes.cs
index 8e3e20f..8e3e20f 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/UI/UIModes.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/UI/UIModes.cs
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/UI/UIRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/UI/UIRequest.cs
index df36b5e..9d506ca 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/UI/UIRequest.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/UI/UIRequest.cs
@@ -13,8 +13,6 @@ namespace DotNetOpenAuth.OpenId.Extensions.UI {
using System.Linq;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId.Messages;
- using DotNetOpenAuth.OpenId.Provider;
- using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.Xrds;
/// <summary>
@@ -156,68 +154,6 @@ namespace DotNetOpenAuth.OpenId.Extensions.UI {
#endregion
- /// <summary>
- /// Gets the URL of the RP icon for the OP to display.
- /// </summary>
- /// <param name="realm">The realm of the RP where the authentication request originated.</param>
- /// <param name="webRequestHandler">The web request handler to use for discovery.
- /// Usually available via <see cref="Channel.WebRequestHandler">OpenIdProvider.Channel.WebRequestHandler</see>.</param>
- /// <returns>
- /// A sequence of the RP's icons it has available for the Provider to display, in decreasing preferred order.
- /// </returns>
- /// <value>The icon URL.</value>
- /// <remarks>
- /// This property is automatically set for the OP with the result of RP discovery.
- /// RPs should set this value by including an entry such as this in their XRDS document.
- /// <example>
- /// &lt;Service xmlns="xri://$xrd*($v*2.0)"&gt;
- /// &lt;Type&gt;http://specs.openid.net/extensions/ui/icon&lt;/Type&gt;
- /// &lt;URI&gt;http://consumer.example.com/images/image.jpg&lt;/URI&gt;
- /// &lt;/Service&gt;
- /// </example>
- /// </remarks>
- public static IEnumerable<Uri> GetRelyingPartyIconUrls(Realm realm, IDirectWebRequestHandler webRequestHandler) {
- Contract.Requires(realm != null);
- Contract.Requires(webRequestHandler != null);
- ErrorUtilities.VerifyArgumentNotNull(realm, "realm");
- ErrorUtilities.VerifyArgumentNotNull(webRequestHandler, "webRequestHandler");
-
- XrdsDocument xrds = realm.Discover(webRequestHandler, false);
- if (xrds == null) {
- return Enumerable.Empty<Uri>();
- } else {
- return xrds.FindRelyingPartyIcons();
- }
- }
-
- /// <summary>
- /// Gets the URL of the RP icon for the OP to display.
- /// </summary>
- /// <param name="realm">The realm of the RP where the authentication request originated.</param>
- /// <param name="provider">The Provider instance used to obtain the authentication request.</param>
- /// <returns>
- /// A sequence of the RP's icons it has available for the Provider to display, in decreasing preferred order.
- /// </returns>
- /// <value>The icon URL.</value>
- /// <remarks>
- /// This property is automatically set for the OP with the result of RP discovery.
- /// RPs should set this value by including an entry such as this in their XRDS document.
- /// <example>
- /// &lt;Service xmlns="xri://$xrd*($v*2.0)"&gt;
- /// &lt;Type&gt;http://specs.openid.net/extensions/ui/icon&lt;/Type&gt;
- /// &lt;URI&gt;http://consumer.example.com/images/image.jpg&lt;/URI&gt;
- /// &lt;/Service&gt;
- /// </example>
- /// </remarks>
- public static IEnumerable<Uri> GetRelyingPartyIconUrls(Realm realm, OpenIdProvider provider) {
- Contract.Requires(realm != null);
- Contract.Requires(provider != null);
- ErrorUtilities.VerifyArgumentNotNull(realm, "realm");
- ErrorUtilities.VerifyArgumentNotNull(provider, "provider");
-
- return GetRelyingPartyIconUrls(realm, provider.Channel.WebRequestHandler);
- }
-
#region IMessage methods
/// <summary>
diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Extensions/UI/UIUtilities.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/UI/UIUtilities.cs
new file mode 100644
index 0000000..478666b
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/UI/UIUtilities.cs
@@ -0,0 +1,28 @@
+//-----------------------------------------------------------------------
+// <copyright file="UIUtilities.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Extensions.UI {
+ using System;
+ using System.Diagnostics.Contracts;
+ using System.Globalization;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OpenId.RelyingParty;
+
+ /// <summary>
+ /// Constants used in implementing support for the UI extension.
+ /// </summary>
+ public static class UIUtilities {
+ /// <summary>
+ /// The required width of the popup window the relying party creates for the provider.
+ /// </summary>
+ public const int PopupWidth = 500; // UI extension calls for 450px, but Yahoo needs 500px
+
+ /// <summary>
+ /// The required height of the popup window the relying party creates for the provider.
+ /// </summary>
+ public const int PopupHeight = 500;
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/HmacShaAssociation.cs b/src/DotNetOpenAuth.OpenId/OpenId/HmacShaAssociation.cs
index 95d72d2..278cb2c 100644
--- a/src/DotNetOpenAuth/OpenId/HmacShaAssociation.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/HmacShaAssociation.cs
@@ -15,7 +15,6 @@ namespace DotNetOpenAuth.OpenId {
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.Messages;
- using DotNetOpenAuth.OpenId.Provider;
/// <summary>
/// An association that uses the HMAC-SHA family of algorithms for message signing.
@@ -23,12 +22,6 @@ namespace DotNetOpenAuth.OpenId {
[ContractVerification(true)]
internal class HmacShaAssociation : Association {
/// <summary>
- /// The default lifetime of a shared association when no lifetime is given
- /// for a specific association type.
- /// </summary>
- private static readonly TimeSpan DefaultMaximumLifetime = TimeSpan.FromDays(14);
-
- /// <summary>
/// A list of HMAC-SHA algorithms in order of decreasing bit lengths.
/// </summary>
private static HmacSha[] hmacShaAssociationTypes = new List<HmacSha> {
@@ -68,10 +61,10 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="totalLifeLength">The time duration the association will be good for.</param>
private HmacShaAssociation(HmacSha typeIdentity, string handle, byte[] secret, TimeSpan totalLifeLength)
: base(handle, secret, totalLifeLength, DateTime.UtcNow) {
- Contract.Requires<ArgumentNullException>(typeIdentity != null);
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(handle));
- Contract.Requires<ArgumentNullException>(secret != null);
- Contract.Requires<ArgumentOutOfRangeException>(totalLifeLength > TimeSpan.Zero);
+ Requires.NotNull(typeIdentity, "typeIdentity");
+ Requires.NotNullOrEmpty(handle, "handle");
+ Requires.NotNull(secret, "secret");
+ Requires.InRange(totalLifeLength > TimeSpan.Zero, "totalLifeLength");
Contract.Ensures(this.TotalLifeLength == totalLifeLength);
ErrorUtilities.VerifyProtocol(secret.Length == typeIdentity.SecretLength, OpenIdStrings.AssociationSecretAndTypeLengthMismatch, secret.Length, typeIdentity.GetAssociationType(Protocol.Default));
@@ -98,11 +91,10 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="totalLifeLength">How long the association will be good for.</param>
/// <returns>The newly created association.</returns>
public static HmacShaAssociation Create(Protocol protocol, string associationType, string handle, byte[] secret, TimeSpan totalLifeLength) {
- Contract.Requires<ArgumentNullException>(protocol != null);
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(associationType));
- Contract.Requires<ArgumentNullException>(secret != null);
+ Requires.NotNull(protocol, "protocol");
+ Requires.NotNullOrEmpty(associationType, "associationType");
+ Requires.NotNull(secret, "secret");
Contract.Ensures(Contract.Result<HmacShaAssociation>() != null);
-
HmacSha match = hmacShaAssociationTypes.FirstOrDefault(sha => String.Equals(sha.GetAssociationType(protocol), associationType, StringComparison.Ordinal));
ErrorUtilities.VerifyProtocol(match != null, OpenIdStrings.NoAssociationTypeFoundByName, associationType);
return new HmacShaAssociation(match, handle, secret, totalLifeLength);
@@ -116,8 +108,8 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="totalLifeLength">Total lifetime.</param>
/// <returns>The newly created association.</returns>
public static HmacShaAssociation Create(string handle, byte[] secret, TimeSpan totalLifeLength) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(handle));
- Contract.Requires<ArgumentNullException>(secret != null);
+ Requires.NotNullOrEmpty(handle, "handle");
+ Requires.NotNull(secret, "secret");
Contract.Ensures(Contract.Result<HmacShaAssociation>() != null);
HmacSha shaType = hmacShaAssociationTypes.FirstOrDefault(sha => sha.SecretLength == secret.Length);
@@ -139,54 +131,6 @@ namespace DotNetOpenAuth.OpenId {
}
/// <summary>
- /// Creates a new association of a given type.
- /// </summary>
- /// <param name="protocol">The protocol.</param>
- /// <param name="associationType">Type of the association (i.e. HMAC-SHA1 or HMAC-SHA256)</param>
- /// <param name="associationUse">A value indicating whether the new association will be used privately by the Provider for "dumb mode" authentication
- /// or shared with the Relying Party for "smart mode" authentication.</param>
- /// <param name="securitySettings">The security settings of the Provider.</param>
- /// <returns>The newly created association.</returns>
- /// <remarks>
- /// The new association is NOT automatically put into an association store. This must be done by the caller.
- /// </remarks>
- internal static HmacShaAssociation Create(Protocol protocol, string associationType, AssociationRelyingPartyType associationUse, ProviderSecuritySettings securitySettings) {
- Contract.Requires<ArgumentNullException>(protocol != null);
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(associationType));
- Contract.Requires<ArgumentNullException>(securitySettings != null);
- Contract.Ensures(Contract.Result<HmacShaAssociation>() != null);
-
- int secretLength = GetSecretLength(protocol, associationType);
-
- // Generate the handle. It must be unique, and preferably unpredictable,
- // so we use a time element and a random data element to generate it.
- string uniq = MessagingUtilities.GetCryptoRandomDataAsBase64(4);
- string handle = string.Format(
- CultureInfo.InvariantCulture,
- "{{{0}}}{{{1}}}{{{2}}}",
- DateTime.UtcNow.Ticks,
- uniq,
- secretLength);
-
- // Generate the secret that will be used for signing
- byte[] secret = MessagingUtilities.GetCryptoRandomData(secretLength);
-
- TimeSpan lifetime;
- if (associationUse == AssociationRelyingPartyType.Smart) {
- if (!securitySettings.AssociationLifetimes.TryGetValue(associationType, out lifetime)) {
- lifetime = DefaultMaximumLifetime;
- }
- } else {
- lifetime = DumbSecretLifetime;
- }
-
- Contract.Assert(protocol != null); // All the way up to the method call, the condition holds, yet we get a Requires failure next
- Contract.Assert(secret != null);
- Contract.Assert(!String.IsNullOrEmpty(associationType));
- return Create(protocol, associationType, handle, secret, lifetime);
- }
-
- /// <summary>
/// Looks for the first association type in a preferred-order list that is
/// likely to be supported given a specific OpenID version and the security settings,
/// and perhaps a matching Diffie-Hellman session type.
@@ -201,8 +145,8 @@ namespace DotNetOpenAuth.OpenId {
/// True if a qualifying association could be found; false otherwise.
/// </returns>
internal static bool TryFindBestAssociation(Protocol protocol, bool highSecurityIsBetter, SecuritySettings securityRequirements, bool requireMatchingDHSessionType, out string associationType, out string sessionType) {
- Contract.Requires<ArgumentNullException>(protocol != null);
- Contract.Requires<ArgumentNullException>(securityRequirements != null);
+ Requires.NotNull(protocol, "protocol");
+ Requires.NotNull(securityRequirements, "securityRequirements");
associationType = null;
sessionType = null;
@@ -217,7 +161,11 @@ namespace DotNetOpenAuth.OpenId {
hashSizeInBits < securityRequirements.MinimumHashBitLength) {
continue;
}
+#if !ExcludeDiffieHellman
sessionType = DiffieHellmanUtilities.GetNameForSize(protocol, hashSizeInBits);
+#else
+ sessionType = requireMatchingDHSessionType ? null : protocol.Args.SessionType.NoEncryption;
+#endif
if (requireMatchingDHSessionType && sessionType == null) {
continue;
}
@@ -242,19 +190,23 @@ namespace DotNetOpenAuth.OpenId {
/// <c>true</c> if the named association and session types are compatible; otherwise, <c>false</c>.
/// </returns>
internal static bool IsDHSessionCompatible(Protocol protocol, string associationType, string sessionType) {
- Contract.Requires<ArgumentNullException>(protocol != null);
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(associationType));
- Contract.Requires<ArgumentNullException>(sessionType != null);
+ Requires.NotNull(protocol, "protocol");
+ Requires.NotNullOrEmpty(associationType, "associationType");
+ Requires.NotNull(sessionType, "sessionType");
// All association types can work when no DH session is used at all.
if (string.Equals(sessionType, protocol.Args.SessionType.NoEncryption, StringComparison.Ordinal)) {
return true;
}
+#if !ExcludeDiffieHellman
// When there _is_ a DH session, it must match in hash length with the association type.
int associationSecretLengthInBytes = GetSecretLength(protocol, associationType);
int sessionHashLengthInBytes = DiffieHellmanUtilities.Lookup(protocol, sessionType).HashSize / 8;
return associationSecretLengthInBytes == sessionHashLengthInBytes;
+#else
+ return false;
+#endif
}
/// <summary>
diff --git a/src/DotNetOpenAuth/OpenId/IIdentifierDiscoveryService.cs b/src/DotNetOpenAuth.OpenId/OpenId/IIdentifierDiscoveryService.cs
index fcea327..f5cefe2 100644
--- a/src/DotNetOpenAuth/OpenId/IIdentifierDiscoveryService.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/IIdentifierDiscoveryService.cs
@@ -56,8 +56,8 @@ namespace DotNetOpenAuth.OpenId {
/// A sequence of service endpoints yielded by discovery. Must not be null, but may be empty.
/// </returns>
IEnumerable<IdentifierDiscoveryResult> IIdentifierDiscoveryService.Discover(Identifier identifier, IDirectWebRequestHandler requestHandler, out bool abortDiscoveryChain) {
- Contract.Requires<ArgumentNullException>(identifier != null);
- Contract.Requires<ArgumentNullException>(requestHandler != null);
+ Requires.NotNull(identifier, "identifier");
+ Requires.NotNull(requestHandler, "requestHandler");
Contract.Ensures(Contract.Result<IEnumerable<IdentifierDiscoveryResult>>() != null);
throw new NotImplementedException();
}
diff --git a/src/DotNetOpenAuth.OpenId/OpenId/IOpenIdApplicationStore.cs b/src/DotNetOpenAuth.OpenId/OpenId/IOpenIdApplicationStore.cs
new file mode 100644
index 0000000..6c04a81
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId/OpenId/IOpenIdApplicationStore.cs
@@ -0,0 +1,16 @@
+//-----------------------------------------------------------------------
+// <copyright file="IOpenIdApplicationStore.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId {
+ using DotNetOpenAuth.Messaging.Bindings;
+
+ /// <summary>
+ /// A hybrid of the store interfaces that an OpenID Provider must implement, and
+ /// an OpenID Relying Party may implement to operate in stateful (smart) mode.
+ /// </summary>
+ public interface IOpenIdApplicationStore : ICryptoKeyStore, INonceStore {
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/IProviderEndpoint.cs b/src/DotNetOpenAuth.OpenId/OpenId/IProviderEndpoint.cs
index 5d8918d..e2a8929 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/IProviderEndpoint.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/IProviderEndpoint.cs
@@ -134,8 +134,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// the extension in the request and see if a response comes back for that extension.
/// </remarks>
bool IProviderEndpoint.IsExtensionSupported(Type extensionType) {
- Contract.Requires<ArgumentNullException>(extensionType != null);
- Contract.Requires<ArgumentException>(typeof(IOpenIdMessageExtension).IsAssignableFrom(extensionType));
+ Requires.NotNullSubtype<IOpenIdMessageExtension>(extensionType, "extensionType");
throw new NotImplementedException();
}
diff --git a/src/DotNetOpenAuth/OpenId/Identifier.cs b/src/DotNetOpenAuth.OpenId/OpenId/Identifier.cs
index 305976a..aeb0e6b 100644
--- a/src/DotNetOpenAuth/OpenId/Identifier.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Identifier.cs
@@ -11,7 +11,7 @@ namespace DotNetOpenAuth.OpenId {
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.OpenId.RelyingParty;
+ using DotNetOpenAuth.Messaging.Reflection;
/// <summary>
/// An Identifier is either a "http" or "https" URI, or an XRI.
@@ -22,6 +22,18 @@ namespace DotNetOpenAuth.OpenId {
[ContractClass(typeof(IdentifierContract))]
public abstract class Identifier {
/// <summary>
+ /// Initializes static members of the <see cref="Identifier"/> class.
+ /// </summary>
+ static Identifier() {
+ Func<string, Identifier> safeIdentifier = str => {
+ Contract.Assume(str != null);
+ ErrorUtilities.VerifyFormat(str.Length > 0, MessagingStrings.NonEmptyStringExpected);
+ return Identifier.Parse(str, true);
+ };
+ MessagePart.Map<Identifier>(id => id.SerializedString, id => id.OriginalString, safeIdentifier);
+ }
+
+ /// <summary>
/// Initializes a new instance of the <see cref="Identifier"/> class.
/// </summary>
/// <param name="originalString">The original string before any normalization.</param>
@@ -91,7 +103,7 @@ namespace DotNetOpenAuth.OpenId {
[SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Our named alternate is Parse.")]
[DebuggerStepThrough]
public static implicit operator Identifier(string identifier) {
- Contract.Requires<ArgumentException>(identifier == null || identifier.Length > 0);
+ Requires.True(identifier == null || identifier.Length > 0, "identifier");
Contract.Ensures((identifier == null) == (Contract.Result<Identifier>() == null));
if (identifier == null) {
@@ -139,7 +151,7 @@ namespace DotNetOpenAuth.OpenId {
/// <returns>An <see cref="Identifier"/> instance for the given value.</returns>
[SuppressMessage("Microsoft.Usage", "CA2234:PassSystemUriObjectsInsteadOfStrings", Justification = "Some of these identifiers are not properly formatted to be Uris at this stage.")]
public static Identifier Parse(string identifier) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(identifier));
+ Requires.NotNullOrEmpty(identifier, "identifier");
Contract.Ensures(Contract.Result<Identifier>() != null);
return Parse(identifier, false);
@@ -156,7 +168,7 @@ namespace DotNetOpenAuth.OpenId {
/// </returns>
[SuppressMessage("Microsoft.Usage", "CA2234:PassSystemUriObjectsInsteadOfStrings", Justification = "Some of these identifiers are not properly formatted to be Uris at this stage.")]
public static Identifier Parse(string identifier, bool serializeExactValue) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(identifier));
+ Requires.NotNullOrEmpty(identifier, "identifier");
Contract.Ensures(Contract.Result<Identifier>() != null);
Identifier id;
@@ -202,7 +214,7 @@ namespace DotNetOpenAuth.OpenId {
/// </returns>
[SuppressMessage("Microsoft.Usage", "CA2234:PassSystemUriObjectsInsteadOfStrings", Justification = "Some of these identifiers are not properly formatted to be Uris at this stage.")]
public static bool IsValid(string identifier) {
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(identifier));
+ Requires.NotNullOrEmpty(identifier, "identifier");
return XriIdentifier.IsValidXri(identifier) || UriIdentifier.IsValidUri(identifier);
}
@@ -263,7 +275,7 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="identifier">The identifier.</param>
/// <returns>Either <see cref="XriIdentifier"/> or <see cref="UriIdentifier"/>.</returns>
internal static Identifier Reparse(Identifier identifier) {
- Contract.Requires<ArgumentNullException>(identifier != null);
+ Requires.NotNull(identifier, "identifier");
Contract.Ensures(Contract.Result<Identifier>() != null);
return Parse(identifier, identifier.IsDeserializedInstance);
diff --git a/src/DotNetOpenAuth/OpenId/IdentifierContract.cs b/src/DotNetOpenAuth.OpenId/OpenId/IdentifierContract.cs
index 4af18e1..7355491 100644
--- a/src/DotNetOpenAuth/OpenId/IdentifierContract.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/IdentifierContract.cs
@@ -9,7 +9,6 @@ namespace DotNetOpenAuth.OpenId {
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.OpenId.RelyingParty;
/// <summary>
/// Code Contract for the <see cref="Identifier"/> class.
diff --git a/src/DotNetOpenAuth/OpenId/IdentifierDiscoveryResult.cs b/src/DotNetOpenAuth.OpenId/OpenId/IdentifierDiscoveryResult.cs
index c851f24..07abf1e 100644
--- a/src/DotNetOpenAuth/OpenId/IdentifierDiscoveryResult.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/IdentifierDiscoveryResult.cs
@@ -49,8 +49,8 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="servicePriority">The service priority.</param>
/// <param name="uriPriority">The URI priority.</param>
private IdentifierDiscoveryResult(ProviderEndpointDescription providerEndpoint, Identifier claimedIdentifier, Identifier userSuppliedIdentifier, Identifier providerLocalIdentifier, int? servicePriority, int? uriPriority) {
- Contract.Requires<ArgumentNullException>(providerEndpoint != null);
- Contract.Requires<ArgumentNullException>(claimedIdentifier != null);
+ Requires.NotNull(providerEndpoint, "providerEndpoint");
+ Requires.NotNull(claimedIdentifier, "claimedIdentifier");
this.ProviderEndpoint = providerEndpoint.Uri;
this.Capabilities = new ReadOnlyCollection<string>(providerEndpoint.Capabilities);
this.Version = providerEndpoint.Version;
@@ -366,7 +366,7 @@ namespace DotNetOpenAuth.OpenId {
/// <c>true</c> if the extension is supported by this endpoint; otherwise, <c>false</c>.
/// </returns>
public bool IsExtensionSupported(IOpenIdMessageExtension extension) {
- Contract.Requires<ArgumentNullException>(extension != null);
+ Requires.NotNull(extension, "extension");
// Consider the primary case.
if (this.IsTypeUriPresent(extension.TypeUri)) {
@@ -392,7 +392,7 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="uriPriority">The URI priority.</param>
/// <returns>The created <see cref="IdentifierDiscoveryResult"/> instance</returns>
internal static IdentifierDiscoveryResult CreateForProviderIdentifier(Identifier providerIdentifier, ProviderEndpointDescription providerEndpoint, int? servicePriority, int? uriPriority) {
- Contract.Requires<ArgumentNullException>(providerEndpoint != null);
+ Requires.NotNull(providerEndpoint, "providerEndpoint");
Protocol protocol = Protocol.Lookup(providerEndpoint.Version);
@@ -440,7 +440,7 @@ namespace DotNetOpenAuth.OpenId {
/// <c>true</c> if the type URI is present on the specified provider endpoint; otherwise, <c>false</c>.
/// </returns>
internal bool IsTypeUriPresent(string typeUri) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(typeUri));
+ Requires.NotNullOrEmpty(typeUri, "typeUri");
return this.Capabilities.Contains(typeUri);
}
diff --git a/src/DotNetOpenAuth/OpenId/Messages/AssociateDiffieHellmanRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateDiffieHellmanRequest.cs
index 01e23e4..b4f809f 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/AssociateDiffieHellmanRequest.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateDiffieHellmanRequest.cs
@@ -12,7 +12,9 @@ namespace DotNetOpenAuth.OpenId.Messages {
using System.Text;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.Messaging.Reflection;
+#if !ExcludeDiffieHellman
using Org.Mentalis.Security.Cryptography;
+#endif
/// <summary>
/// An OpenID direct request from Relying Party to Provider to initiate an association that uses Diffie-Hellman encryption.
@@ -76,6 +78,7 @@ namespace DotNetOpenAuth.OpenId.Messages {
[MessagePart("openid.dh_consumer_public", IsRequired = true, AllowEmpty = false)]
internal byte[] DiffieHellmanConsumerPublic { get; set; }
+#if !ExcludeDiffieHellman
/// <summary>
/// Gets the Diffie-Hellman algorithm.
/// </summary>
@@ -83,11 +86,13 @@ namespace DotNetOpenAuth.OpenId.Messages {
/// This property is initialized with a call to <see cref="InitializeRequest"/>.
/// </remarks>
internal DiffieHellman Algorithm { get; private set; }
+#endif
/// <summary>
/// Called by the Relying Party to initialize the Diffie-Hellman algorithm and consumer public key properties.
/// </summary>
internal void InitializeRequest() {
+#if !ExcludeDiffieHellman
if (this.DiffieHellmanModulus == null || this.DiffieHellmanGen == null) {
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, OpenIdStrings.DiffieHellmanRequiredPropertiesNotSet, string.Join(", ", new string[] { "DiffieHellmanModulus", "DiffieHellmanGen" })));
}
@@ -95,25 +100,9 @@ namespace DotNetOpenAuth.OpenId.Messages {
this.Algorithm = new DiffieHellmanManaged(this.DiffieHellmanModulus ?? DefaultMod, this.DiffieHellmanGen ?? DefaultGen, DefaultX);
byte[] consumerPublicKeyExchange = this.Algorithm.CreateKeyExchange();
this.DiffieHellmanConsumerPublic = DiffieHellmanUtilities.EnsurePositive(consumerPublicKeyExchange);
- }
-
- /// <summary>
- /// Creates a Provider's response to an incoming association request.
- /// </summary>
- /// <returns>
- /// The appropriate association response message.
- /// </returns>
- /// <remarks>
- /// <para>If an association can be successfully created, the
- /// <see cref="AssociateSuccessfulResponse.CreateAssociation"/> method must not be
- /// called by this method.</para>
- /// <para>Successful association response messages will derive from <see cref="AssociateSuccessfulResponse"/>.
- /// Failed association response messages will derive from <see cref="AssociateUnsuccessfulResponse"/>.</para>
- /// </remarks>
- protected override IProtocolMessage CreateResponseCore() {
- var response = new AssociateDiffieHellmanResponse(this.Version, this);
- response.AssociationType = this.AssociationType;
- return response;
+#else
+ throw new NotSupportedException();
+#endif
}
}
}
diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateDiffieHellmanResponse.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateDiffieHellmanResponse.cs
new file mode 100644
index 0000000..d1836ec
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateDiffieHellmanResponse.cs
@@ -0,0 +1,45 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssociateDiffieHellmanResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Messages {
+ using System;
+ using System.Diagnostics.Contracts;
+ using System.Security.Cryptography;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Reflection;
+ using Org.Mentalis.Security.Cryptography;
+
+ /// <summary>
+ /// The successful Diffie-Hellman association response message.
+ /// </summary>
+ /// <remarks>
+ /// Association response messages are described in OpenID 2.0 section 8.2. This type covers section 8.2.3.
+ /// </remarks>
+ internal abstract class AssociateDiffieHellmanResponse : AssociateSuccessfulResponse {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AssociateDiffieHellmanResponse"/> class.
+ /// </summary>
+ /// <param name="responseVersion">The OpenID version of the response message.</param>
+ /// <param name="originatingRequest">The originating request.</param>
+ internal AssociateDiffieHellmanResponse(Version responseVersion, AssociateDiffieHellmanRequest originatingRequest)
+ : base(responseVersion, originatingRequest) {
+ }
+
+ /// <summary>
+ /// Gets or sets the Provider's Diffie-Hellman public key.
+ /// </summary>
+ /// <value>btwoc(g ^ xb mod p)</value>
+ [MessagePart("dh_server_public", IsRequired = true, AllowEmpty = false)]
+ internal byte[] DiffieHellmanServerPublic { get; set; }
+
+ /// <summary>
+ /// Gets or sets the MAC key (shared secret), encrypted with the secret Diffie-Hellman value.
+ /// </summary>
+ /// <value>H(btwoc(g ^ (xa * xb) mod p)) XOR MAC key. H is either "SHA1" or "SHA256" depending on the session type. </value>
+ [MessagePart("enc_mac_key", IsRequired = true, AllowEmpty = false)]
+ internal byte[] EncodedMacKey { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateRequest.cs
new file mode 100644
index 0000000..db0c39e
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateRequest.cs
@@ -0,0 +1,67 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssociateRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// An OpenID direct request from Relying Party to Provider to initiate an association.
+ /// </summary>
+ [DebuggerDisplay("OpenID {Version} {Mode} {AssociationType} {SessionType}")]
+ internal abstract class AssociateRequest : RequestBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AssociateRequest"/> class.
+ /// </summary>
+ /// <param name="version">The OpenID version this message must comply with.</param>
+ /// <param name="providerEndpoint">The OpenID Provider endpoint.</param>
+ protected AssociateRequest(Version version, Uri providerEndpoint)
+ : base(version, providerEndpoint, GetProtocolConstant(version, p => p.Args.Mode.associate), MessageTransport.Direct) {
+ }
+
+ /// <summary>
+ /// Gets or sets the preferred association type. The association type defines the algorithm to be used to sign subsequent messages.
+ /// </summary>
+ /// <value>Value: A valid association type from Section 8.3.</value>
+ [MessagePart("openid.assoc_type", IsRequired = true, AllowEmpty = false)]
+ internal string AssociationType { get; set; }
+
+ /// <summary>
+ /// Gets or sets the preferred association session type. This defines the method used to encrypt the association's MAC key in transit.
+ /// </summary>
+ /// <value>Value: A valid association session type from Section 8.4 (Association Session Types). </value>
+ /// <remarks>Note: Unless using transport layer encryption, "no-encryption" MUST NOT be used. </remarks>
+ [MessagePart("openid.session_type", IsRequired = false, AllowEmpty = true)]
+ [MessagePart("openid.session_type", IsRequired = true, AllowEmpty = false, MinVersion = "2.0")]
+ internal string SessionType { get; set; }
+
+ /// <summary>
+ /// Checks the message state for conformity to the protocol specification
+ /// and throws an exception if the message is invalid.
+ /// </summary>
+ /// <remarks>
+ /// <para>Some messages have required fields, or combinations of fields that must relate to each other
+ /// in specialized ways. After deserializing a message, this method checks the state of the
+ /// message to see if it conforms to the protocol.</para>
+ /// <para>Note that this property should <i>not</i> check signatures or perform any state checks
+ /// outside this scope of this particular message.</para>
+ /// </remarks>
+ /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception>
+ public override void EnsureValidMessage() {
+ base.EnsureValidMessage();
+
+ ErrorUtilities.VerifyProtocol(
+ !string.Equals(this.SessionType, Protocol.Args.SessionType.NoEncryption, StringComparison.Ordinal) || this.Recipient.IsTransportSecure(),
+ OpenIdStrings.NoEncryptionSessionRequiresHttps,
+ this);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/Messages/AssociateSuccessfulResponse.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateSuccessfulResponse.cs
index 137cd60..c3d8938 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/AssociateSuccessfulResponse.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateSuccessfulResponse.cs
@@ -12,7 +12,6 @@ namespace DotNetOpenAuth.OpenId.Messages {
using System.Linq;
using System.Text;
using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.OpenId.Provider;
/// <summary>
/// The base class that all successful association response messages derive from.
@@ -24,11 +23,6 @@ namespace DotNetOpenAuth.OpenId.Messages {
[ContractClass(typeof(AssociateSuccessfulResponseContract))]
internal abstract class AssociateSuccessfulResponse : DirectResponseBase {
/// <summary>
- /// A flag indicating whether an association has already been created.
- /// </summary>
- private bool associationCreated;
-
- /// <summary>
/// Initializes a new instance of the <see cref="AssociateSuccessfulResponse"/> class.
/// </summary>
/// <param name="responseVersion">The OpenID version of the response message.</param>
@@ -94,61 +88,5 @@ namespace DotNetOpenAuth.OpenId.Messages {
this.SessionType);
}
}
-
- /// <summary>
- /// Called to create the Association based on a request previously given by the Relying Party.
- /// </summary>
- /// <param name="request">The prior request for an association.</param>
- /// <param name="securitySettings">The security settings for the Provider. Should be <c>null</c> for Relying Parties.</param>
- /// <returns>The created association.</returns>
- /// <remarks>
- /// <para>The response message is updated to include the details of the created association by this method,
- /// but the resulting association is <i>not</i> added to the association store and must be done by the caller.</para>
- /// <para>This method is called by both the Provider and the Relying Party, but actually performs
- /// quite different operations in either scenario.</para>
- /// </remarks>
- internal Association CreateAssociation(AssociateRequest request, ProviderSecuritySettings securitySettings) {
- Contract.Requires<ArgumentNullException>(request != null);
- ErrorUtilities.VerifyInternal(!this.associationCreated, "The association has already been created.");
-
- Association association;
-
- // If this message is outgoing, then we need to initialize some common
- // properties based on the created association.
- if (this.Incoming) {
- association = this.CreateAssociationAtRelyingParty(request);
- } else {
- ErrorUtilities.VerifyArgumentNotNull(securitySettings, "securitySettings");
- association = this.CreateAssociationAtProvider(request, securitySettings);
- this.ExpiresIn = association.SecondsTillExpiration;
- this.AssociationHandle = association.Handle;
- }
-
- this.associationCreated = true;
-
- return association;
- }
-
- /// <summary>
- /// Called to create the Association based on a request previously given by the Relying Party.
- /// </summary>
- /// <param name="request">The prior request for an association.</param>
- /// <param name="securitySettings">The security settings of the Provider.</param>
- /// <returns>The created association.</returns>
- /// <remarks>
- /// <para>The caller will update this message's <see cref="ExpiresIn"/> and <see cref="AssociationHandle"/>
- /// properties based on the <see cref="Association"/> returned by this method, but any other
- /// association type specific properties must be set by this method.</para>
- /// <para>The response message is updated to include the details of the created association by this method,
- /// but the resulting association is <i>not</i> added to the association store and must be done by the caller.</para>
- /// </remarks>
- protected abstract Association CreateAssociationAtProvider(AssociateRequest request, ProviderSecuritySettings securitySettings);
-
- /// <summary>
- /// Called to create the Association based on a request previously given by the Relying Party.
- /// </summary>
- /// <param name="request">The prior request for an association.</param>
- /// <returns>The created association.</returns>
- protected abstract Association CreateAssociationAtRelyingParty(AssociateRequest request);
}
}
diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateSuccessfulResponseContract.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateSuccessfulResponseContract.cs
new file mode 100644
index 0000000..39a79a4
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateSuccessfulResponseContract.cs
@@ -0,0 +1,17 @@
+// <auto-generated />
+
+namespace DotNetOpenAuth.OpenId.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ [ContractClassFor(typeof(AssociateSuccessfulResponse))]
+ internal abstract class AssociateSuccessfulResponseContract : AssociateSuccessfulResponse {
+ protected AssociateSuccessfulResponseContract() : base(null, null) {
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/Messages/AssociateUnencryptedRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateUnencryptedRequest.cs
index ef302a5..eda8cf3 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/AssociateUnencryptedRequest.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateUnencryptedRequest.cs
@@ -46,24 +46,5 @@ namespace DotNetOpenAuth.OpenId.Messages {
Protocol.Args.SessionType.NoEncryption,
SessionType);
}
-
- /// <summary>
- /// Creates a Provider's response to an incoming association request.
- /// </summary>
- /// <returns>
- /// The appropriate association response message.
- /// </returns>
- /// <remarks>
- /// <para>If an association can be successfully created, the
- /// <see cref="AssociateSuccessfulResponse.CreateAssociation"/> method must not be
- /// called by this method.</para>
- /// <para>Successful association response messages will derive from <see cref="AssociateSuccessfulResponse"/>.
- /// Failed association response messages will derive from <see cref="AssociateUnsuccessfulResponse"/>.</para>
- /// </remarks>
- protected override IProtocolMessage CreateResponseCore() {
- var response = new AssociateUnencryptedResponse(this.Version, this);
- response.AssociationType = this.AssociationType;
- return response;
- }
}
}
diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateUnencryptedResponse.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateUnencryptedResponse.cs
new file mode 100644
index 0000000..b7a0139
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateUnencryptedResponse.cs
@@ -0,0 +1,35 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssociateUnencryptedResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Messages {
+ using System;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Reflection;
+
+ /// <summary>
+ /// The successful unencrypted association response message.
+ /// </summary>
+ /// <remarks>
+ /// Association response messages are described in OpenID 2.0 section 8.2. This type covers section 8.2.2.
+ /// </remarks>
+ internal class AssociateUnencryptedResponse : AssociateSuccessfulResponse {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AssociateUnencryptedResponse"/> class.
+ /// </summary>
+ /// <param name="responseVersion">The OpenID version of the response message.</param>
+ /// <param name="originatingRequest">The originating request.</param>
+ internal AssociateUnencryptedResponse(Version responseVersion, AssociateUnencryptedRequest originatingRequest)
+ : base(responseVersion, originatingRequest) {
+ SessionType = Protocol.Args.SessionType.NoEncryption;
+ }
+
+ /// <summary>
+ /// Gets or sets the MAC key (shared secret) for this association, Base 64 (Josefsson, S., “The Base16, Base32, and Base64 Data Encodings,” .) [RFC3548] encoded.
+ /// </summary>
+ [MessagePart("mac_key", IsRequired = true, AllowEmpty = false)]
+ internal byte[] MacKey { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/Messages/AssociateUnsuccessfulResponse.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateUnsuccessfulResponse.cs
index 71ecc05..71ecc05 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/AssociateUnsuccessfulResponse.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/AssociateUnsuccessfulResponse.cs
diff --git a/src/DotNetOpenAuth/OpenId/Messages/CheckAuthenticationRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/CheckAuthenticationRequest.cs
index db69d3d..273c444 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/CheckAuthenticationRequest.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/CheckAuthenticationRequest.cs
@@ -41,7 +41,7 @@ namespace DotNetOpenAuth.OpenId.Messages {
/// <param name="channel">The channel. This is used only within the constructor and is not stored in a field.</param>
internal CheckAuthenticationRequest(IndirectSignedResponse message, Channel channel)
: base(message.Version, message.ProviderEndpoint, GetProtocolConstant(message.Version, p => p.Args.Mode.check_authentication), MessageTransport.Direct) {
- Contract.Requires<ArgumentNullException>(channel != null);
+ Requires.NotNull(channel, "channel");
// Copy all message parts from the id_res message into this one,
// except for the openid.mode parameter.
diff --git a/src/DotNetOpenAuth/OpenId/Messages/CheckAuthenticationResponse.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/CheckAuthenticationResponse.cs
index f1bb5ac..f52ccf8 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/CheckAuthenticationResponse.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/CheckAuthenticationResponse.cs
@@ -12,7 +12,6 @@ namespace DotNetOpenAuth.OpenId.Messages {
using System.Text;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId.ChannelElements;
- using DotNetOpenAuth.OpenId.Provider;
/// <summary>
/// The message sent from the Provider to the Relying Party to confirm/deny
@@ -30,29 +29,6 @@ namespace DotNetOpenAuth.OpenId.Messages {
}
/// <summary>
- /// Initializes a new instance of the <see cref="CheckAuthenticationResponse"/> class
- /// for use by the Provider.
- /// </summary>
- /// <param name="request">The request that this message is responding to.</param>
- /// <param name="provider">The OpenID Provider that is preparing to send this response.</param>
- internal CheckAuthenticationResponse(CheckAuthenticationRequest request, OpenIdProvider provider)
- : base(request.Version, request) {
- Contract.Requires<ArgumentNullException>(provider != null);
-
- // The channel's binding elements have already set the request's IsValid property
- // appropriately. We just copy it into the response message.
- this.IsValid = request.IsValid;
-
- // Confirm the RP should invalidate the association handle only if the association
- // really doesn't exist. OpenID 2.0 section 11.4.2.2.
- IndirectSignedResponse signedResponse = new IndirectSignedResponse(request, provider.Channel);
- string invalidateHandle = ((ITamperResistantOpenIdMessage)signedResponse).InvalidateHandle;
- if (!string.IsNullOrEmpty(invalidateHandle) && provider.AssociationStore.GetAssociation(AssociationRelyingPartyType.Smart, invalidateHandle) == null) {
- this.InvalidateHandle = invalidateHandle;
- }
- }
-
- /// <summary>
/// Gets or sets a value indicating whether the signature of the verification request is valid.
/// </summary>
[MessagePart("is_valid", IsRequired = true)]
diff --git a/src/DotNetOpenAuth/OpenId/Messages/CheckIdRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/CheckIdRequest.cs
index 09c36a5..0667dcb 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/CheckIdRequest.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/CheckIdRequest.cs
@@ -11,7 +11,6 @@ namespace DotNetOpenAuth.OpenId.Messages {
using System.Linq;
using System.Text;
using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.OpenId.RelyingParty;
/// <summary>
/// An authentication request from a Relying Party to a Provider.
diff --git a/src/DotNetOpenAuth/OpenId/Messages/DirectErrorResponse.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/DirectErrorResponse.cs
index ad20ff7..607a139 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/DirectErrorResponse.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/DirectErrorResponse.cs
@@ -36,6 +36,14 @@ namespace DotNetOpenAuth.OpenId.Messages {
get { return HttpStatusCode.BadRequest; }
}
+ /// <summary>
+ /// Gets the HTTP headers to add to the response.
+ /// </summary>
+ /// <value>May be an empty collection, but must not be <c>null</c>.</value>
+ WebHeaderCollection IHttpDirectResponse.Headers {
+ get { return new WebHeaderCollection(); }
+ }
+
#endregion
/// <summary>
diff --git a/src/DotNetOpenAuth/OpenId/Messages/DirectResponseBase.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/DirectResponseBase.cs
index e7619bc..da6a1f6 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/DirectResponseBase.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/DirectResponseBase.cs
@@ -54,7 +54,7 @@ namespace DotNetOpenAuth.OpenId.Messages {
/// <param name="responseVersion">The OpenID version of the response message.</param>
/// <param name="originatingRequest">The originating request. May be null in case the request is unrecognizable and this is an error response.</param>
protected DirectResponseBase(Version responseVersion, IDirectedProtocolMessage originatingRequest) {
- Contract.Requires<ArgumentNullException>(responseVersion != null);
+ Requires.NotNull(responseVersion, "responseVersion");
this.Version = responseVersion;
this.originatingRequest = originatingRequest;
diff --git a/src/DotNetOpenAuth/OpenId/Messages/IErrorMessage.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/IErrorMessage.cs
index 549b327..549b327 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/IErrorMessage.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/IErrorMessage.cs
diff --git a/src/DotNetOpenAuth/OpenId/Messages/IOpenIdMessageExtension.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/IOpenIdMessageExtension.cs
index 08e02ba..08e02ba 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/IOpenIdMessageExtension.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/IOpenIdMessageExtension.cs
diff --git a/src/DotNetOpenAuth/OpenId/Messages/IndirectErrorResponse.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/IndirectErrorResponse.cs
index eb006db..eb006db 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/IndirectErrorResponse.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/IndirectErrorResponse.cs
diff --git a/src/DotNetOpenAuth/OpenId/Messages/IndirectResponseBase.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/IndirectResponseBase.cs
index fce6028..f23d912 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/IndirectResponseBase.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/IndirectResponseBase.cs
@@ -29,7 +29,7 @@ namespace DotNetOpenAuth.OpenId.Messages {
/// <param name="mode">The value of the openid.mode parameter.</param>
protected IndirectResponseBase(SignedResponseRequest request, string mode)
: base(GetVersion(request), GetReturnTo(request), mode, MessageTransport.Indirect) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
this.OriginatingRequest = request;
}
@@ -91,7 +91,7 @@ namespace DotNetOpenAuth.OpenId.Messages {
/// instead of a <see cref="NullReferenceException"/>.
/// </remarks>
internal static Version GetVersion(IProtocolMessage message) {
- Contract.Requires<ArgumentNullException>(message != null);
+ Requires.NotNull(message, "message");
return message.Version;
}
@@ -105,7 +105,7 @@ namespace DotNetOpenAuth.OpenId.Messages {
/// instead of a <see cref="NullReferenceException"/>.
/// </remarks>
private static Uri GetReturnTo(SignedResponseRequest message) {
- Contract.Requires<ArgumentNullException>(message != null);
+ Requires.NotNull(message, "message");
ErrorUtilities.VerifyProtocol(message.ReturnTo != null, OpenIdStrings.ReturnToRequiredForResponse);
return message.ReturnTo;
}
diff --git a/src/DotNetOpenAuth/OpenId/Messages/IndirectSignedResponse.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/IndirectSignedResponse.cs
index baeae16..9a60757 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/IndirectSignedResponse.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/IndirectSignedResponse.cs
@@ -57,7 +57,7 @@ namespace DotNetOpenAuth.OpenId.Messages {
/// </param>
internal IndirectSignedResponse(SignedResponseRequest request)
: base(request, Protocol.Lookup(GetVersion(request)).Args.Mode.id_res) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
this.ReturnTo = request.ReturnTo;
this.ProviderEndpoint = request.Recipient.StripQueryArgumentsWithPrefix(Protocol.openid.Prefix);
@@ -72,7 +72,7 @@ namespace DotNetOpenAuth.OpenId.Messages {
/// <param name="channel">The channel. This is used only within the constructor and is not stored in a field.</param>
internal IndirectSignedResponse(CheckAuthenticationRequest previouslySignedMessage, Channel channel)
: base(GetVersion(previouslySignedMessage), previouslySignedMessage.ReturnTo, Protocol.Lookup(GetVersion(previouslySignedMessage)).Args.Mode.id_res) {
- Contract.Requires<ArgumentNullException>(channel != null);
+ Requires.NotNull(channel, "channel");
// Copy all message parts from the check_authentication message into this one,
// except for the openid.mode parameter.
@@ -324,7 +324,7 @@ namespace DotNetOpenAuth.OpenId.Messages {
/// cannot verify the private signature made by the relying party.
/// </remarks>
internal string GetReturnToArgument(string key) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(key));
+ Requires.NotNullOrEmpty(key, "key");
ErrorUtilities.VerifyInternal(this.ReturnTo != null, "ReturnTo was expected to be required but is null.");
string value;
@@ -350,7 +350,7 @@ namespace DotNetOpenAuth.OpenId.Messages {
/// A dictionary of the signed message parts.
/// </returns>
internal IDictionary<string, string> GetSignedMessageParts(Channel channel) {
- Contract.Requires<ArgumentNullException>(channel != null);
+ Requires.NotNull(channel, "channel");
ITamperResistantOpenIdMessage signedSelf = this;
if (signedSelf.SignedParameterOrder == null) {
diff --git a/src/DotNetOpenAuth/OpenId/Messages/NegativeAssertionResponse.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/NegativeAssertionResponse.cs
index 52ff884..a6303ab 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/NegativeAssertionResponse.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/NegativeAssertionResponse.cs
@@ -11,7 +11,6 @@ namespace DotNetOpenAuth.OpenId.Messages {
using System.Linq;
using System.Text;
using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.OpenId.RelyingParty;
/// <summary>
/// The message OpenID Providers send back to Relying Parties to refuse
@@ -115,8 +114,8 @@ namespace DotNetOpenAuth.OpenId.Messages {
/// <param name="channel">The channel to use to simulate construction of the message.</param>
/// <returns>The value to use for the user_setup_url parameter.</returns>
private static Uri ConstructUserSetupUrl(CheckIdRequest immediateRequest, Channel channel) {
- Contract.Requires<ArgumentNullException>(immediateRequest != null);
- Contract.Requires<ArgumentNullException>(channel != null);
+ Requires.NotNull(immediateRequest, "immediateRequest");
+ Requires.NotNull(channel, "channel");
ErrorUtilities.VerifyInternal(immediateRequest.Immediate, "Only immediate requests should be sent here.");
var setupRequest = new CheckIdRequest(immediateRequest.Version, immediateRequest.Recipient, AuthenticationRequestMode.Setup);
@@ -133,7 +132,7 @@ namespace DotNetOpenAuth.OpenId.Messages {
/// <param name="request">The request that we're responding to.</param>
/// <returns>The value of the openid.mode parameter to use.</returns>
private static string GetMode(SignedResponseRequest request) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
Protocol protocol = Protocol.Lookup(request.Version);
return request.Immediate ? protocol.Args.Mode.setup_needed : protocol.Args.Mode.cancel;
diff --git a/src/DotNetOpenAuth/OpenId/Messages/PositiveAssertionResponse.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/PositiveAssertionResponse.cs
index 006ea93..006ea93 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/PositiveAssertionResponse.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/PositiveAssertionResponse.cs
diff --git a/src/DotNetOpenAuth/OpenId/Messages/RequestBase.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/RequestBase.cs
index 8e4cb9d..a24c7db 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/RequestBase.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/RequestBase.cs
@@ -49,8 +49,8 @@ namespace DotNetOpenAuth.OpenId.Messages {
/// <param name="mode">The value for the openid.mode parameter.</param>
/// <param name="transport">A value indicating whether the message will be transmitted directly or indirectly.</param>
protected RequestBase(Version version, Uri providerEndpoint, string mode, MessageTransport transport) {
- Contract.Requires<ArgumentNullException>(providerEndpoint != null);
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(mode));
+ Requires.NotNull(providerEndpoint, "providerEndpoint");
+ Requires.NotNullOrEmpty(mode, "mode");
this.Recipient = providerEndpoint;
this.Mode = mode;
@@ -178,7 +178,7 @@ namespace DotNetOpenAuth.OpenId.Messages {
/// instead of a <see cref="NullReferenceException"/>.
/// </remarks>
protected static string GetProtocolConstant(Version protocolVersion, Func<Protocol, string> mode) {
- Contract.Requires<ArgumentNullException>(protocolVersion != null);
+ Requires.NotNull(protocolVersion, "protocolVersion");
return mode(Protocol.Lookup(protocolVersion));
}
}
diff --git a/src/DotNetOpenAuth/OpenId/Messages/SignedResponseRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/SignedResponseRequest.cs
index 7eb5407..3719f96 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/SignedResponseRequest.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/SignedResponseRequest.cs
@@ -12,7 +12,6 @@ namespace DotNetOpenAuth.OpenId.Messages {
using System.Linq;
using System.Text;
using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.OpenId.RelyingParty;
/// <summary>
/// An indirect request from a Relying Party to a Provider where the response
@@ -145,7 +144,7 @@ namespace DotNetOpenAuth.OpenId.Messages {
/// when and if a positive assertion comes back from the Provider.
/// </remarks>
internal void AddReturnToArguments(IEnumerable<KeyValuePair<string, string>> keysValues) {
- Contract.Requires<ArgumentNullException>(keysValues != null);
+ Requires.NotNull(keysValues, "keysValues");
ErrorUtilities.VerifyOperation(this.ReturnTo != null, OpenIdStrings.ReturnToRequiredForOperation);
UriBuilder returnToBuilder = new UriBuilder(this.ReturnTo);
returnToBuilder.AppendAndReplaceQueryArgs(keysValues);
@@ -176,7 +175,7 @@ namespace DotNetOpenAuth.OpenId.Messages {
/// </param>
/// <returns>checkid_immediate or checkid_setup</returns>
private static string GetMode(Version version, AuthenticationRequestMode mode) {
- Contract.Requires<ArgumentNullException>(version != null);
+ Requires.NotNull(version, "version");
Protocol protocol = Protocol.Lookup(version);
return mode == AuthenticationRequestMode.Immediate ? protocol.Args.Mode.checkid_immediate : protocol.Args.Mode.checkid_setup;
diff --git a/src/DotNetOpenAuth/OpenId/NoDiscoveryIdentifier.cs b/src/DotNetOpenAuth.OpenId/OpenId/NoDiscoveryIdentifier.cs
index 1a6e7e9..d1704fc 100644
--- a/src/DotNetOpenAuth/OpenId/NoDiscoveryIdentifier.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/NoDiscoveryIdentifier.cs
@@ -10,7 +10,6 @@ namespace DotNetOpenAuth.OpenId {
using System.Diagnostics.Contracts;
using System.Linq;
using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.OpenId.RelyingParty;
/// <summary>
/// Wraps an existing Identifier and prevents it from performing discovery.
@@ -30,7 +29,7 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="claimSsl">Whether this Identifier should claim to be SSL-secure, although no discovery will never generate service endpoints anyway.</param>
internal NoDiscoveryIdentifier(Identifier wrappedIdentifier, bool claimSsl)
: base(wrappedIdentifier.OriginalString, claimSsl) {
- Contract.Requires<ArgumentNullException>(wrappedIdentifier != null);
+ Requires.NotNull(wrappedIdentifier, "wrappedIdentifier");
this.wrappedIdentifier = wrappedIdentifier;
}
diff --git a/src/DotNetOpenAuth/OpenId/OpenIdStrings.Designer.cs b/src/DotNetOpenAuth.OpenId/OpenId/OpenIdStrings.Designer.cs
index f45af93..f45af93 100644
--- a/src/DotNetOpenAuth/OpenId/OpenIdStrings.Designer.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/OpenIdStrings.Designer.cs
diff --git a/src/DotNetOpenAuth/OpenId/OpenIdStrings.resx b/src/DotNetOpenAuth.OpenId/OpenId/OpenIdStrings.resx
index b700d76..b700d76 100644
--- a/src/DotNetOpenAuth/OpenId/OpenIdStrings.resx
+++ b/src/DotNetOpenAuth.OpenId/OpenId/OpenIdStrings.resx
diff --git a/src/DotNetOpenAuth/OpenId/OpenIdStrings.sr.resx b/src/DotNetOpenAuth.OpenId/OpenId/OpenIdStrings.sr.resx
index 0df62c0..0df62c0 100644
--- a/src/DotNetOpenAuth/OpenId/OpenIdStrings.sr.resx
+++ b/src/DotNetOpenAuth.OpenId/OpenId/OpenIdStrings.sr.resx
diff --git a/src/DotNetOpenAuth/OpenId/OpenIdUtilities.cs b/src/DotNetOpenAuth.OpenId/OpenId/OpenIdUtilities.cs
index 04eb23c..b7f857e 100644
--- a/src/DotNetOpenAuth/OpenId/OpenIdUtilities.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/OpenIdUtilities.cs
@@ -9,6 +9,7 @@ namespace DotNetOpenAuth.OpenId {
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
+ using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
@@ -17,8 +18,6 @@ namespace DotNetOpenAuth.OpenId {
using DotNetOpenAuth.OpenId.ChannelElements;
using DotNetOpenAuth.OpenId.Extensions;
using DotNetOpenAuth.OpenId.Messages;
- using DotNetOpenAuth.OpenId.Provider;
- using DotNetOpenAuth.OpenId.RelyingParty;
/// <summary>
/// A set of utilities especially useful to OpenID.
@@ -30,12 +29,25 @@ namespace DotNetOpenAuth.OpenId {
internal const string CustomParameterPrefix = "dnoa.";
/// <summary>
+ /// Creates a random association handle.
+ /// </summary>
+ /// <returns>The association handle.</returns>
+ public static string GenerateRandomAssociationHandle() {
+ Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>()));
+
+ // Generate the handle. It must be unique, and preferably unpredictable,
+ // so we use a time element and a random data element to generate it.
+ string uniq = MessagingUtilities.GetCryptoRandomDataAsBase64(4);
+ return string.Format(CultureInfo.InvariantCulture, "{{{0}}}{{{1}}}", DateTime.UtcNow.Ticks, uniq);
+ }
+
+ /// <summary>
/// Gets the OpenID protocol instance for the version in a message.
/// </summary>
/// <param name="message">The message.</param>
/// <returns>The OpenID protocol instance.</returns>
internal static Protocol GetProtocol(this IProtocolMessage message) {
- Contract.Requires<ArgumentNullException>(message != null);
+ Requires.NotNull(message, "message");
return Protocol.Lookup(message.Version);
}
@@ -104,8 +116,8 @@ namespace DotNetOpenAuth.OpenId {
/// <returns>The fully-qualified realm.</returns>
[SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "DotNetOpenAuth.OpenId.Realm", Justification = "Using ctor for validation.")]
internal static UriBuilder GetResolvedRealm(Page page, string realm, HttpRequestInfo requestContext) {
- Contract.Requires<ArgumentNullException>(page != null);
- Contract.Requires<ArgumentNullException>(requestContext != null);
+ Requires.NotNull(page, "page");
+ Requires.NotNull(requestContext, "requestContext");
// Allow for *. realm notation, as well as ASP.NET ~/ shortcuts.
@@ -141,13 +153,13 @@ namespace DotNetOpenAuth.OpenId {
/// <returns>The list of factories that will be used to generate extension instances.</returns>
/// <remarks>
/// This is an extension method on <see cref="Channel"/> rather than an instance
- /// method on <see cref="OpenIdChannel"/> because the <see cref="OpenIdRelyingParty"/>
- /// and <see cref="OpenIdProvider"/> classes don't strong-type to <see cref="OpenIdChannel"/>
+ /// method on <see cref="OpenIdChannel"/> because the OpenIdRelyingParty
+ /// and OpenIdProvider classes don't strong-type to <see cref="OpenIdChannel"/>
/// to allow flexibility in the specific type of channel the user (or tests)
/// can plug in.
/// </remarks>
internal static IList<IOpenIdExtensionFactory> GetExtensionFactories(this Channel channel) {
- Contract.Requires<ArgumentNullException>(channel != null);
+ Requires.NotNull(channel, "channel");
var extensionsBindingElement = channel.BindingElements.OfType<ExtensionsBindingElement>().SingleOrDefault();
ErrorUtilities.VerifyOperation(extensionsBindingElement != null, OpenIdStrings.UnsupportedChannelConfiguration);
diff --git a/src/DotNetOpenAuth.OpenId/OpenId/OpenIdXrdsHelper.cs b/src/DotNetOpenAuth.OpenId/OpenId/OpenIdXrdsHelper.cs
new file mode 100644
index 0000000..9f996a5
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId/OpenId/OpenIdXrdsHelper.cs
@@ -0,0 +1,68 @@
+//-----------------------------------------------------------------------
+// <copyright file="OpenIdXrdsHelper.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Xrds;
+
+ /// <summary>
+ /// Utility methods for working with XRDS documents.
+ /// </summary>
+ internal static class OpenIdXrdsHelper {
+ /// <summary>
+ /// Finds the Relying Party return_to receiving endpoints.
+ /// </summary>
+ /// <param name="xrds">The XrdsDocument instance to use in this process.</param>
+ /// <returns>A sequence of Relying Party descriptors for the return_to endpoints.</returns>
+ /// <remarks>
+ /// This is useful for Providers to send unsolicited assertions to Relying Parties,
+ /// or for Provider's to perform RP discovery/verification as part of authentication.
+ /// </remarks>
+ internal static IEnumerable<RelyingPartyEndpointDescription> FindRelyingPartyReceivingEndpoints(this XrdsDocument xrds) {
+ Requires.NotNull(xrds, "xrds");
+ Contract.Ensures(Contract.Result<IEnumerable<RelyingPartyEndpointDescription>>() != null);
+
+ return from service in xrds.FindReturnToServices()
+ from uri in service.UriElements
+ select new RelyingPartyEndpointDescription(uri.Uri, service.TypeElementUris);
+ }
+
+ /// <summary>
+ /// Finds the icons the relying party wants an OP to display as part of authentication,
+ /// per the UI extension spec.
+ /// </summary>
+ /// <param name="xrds">The XrdsDocument to search.</param>
+ /// <returns>A sequence of the icon URLs in preferred order.</returns>
+ internal static IEnumerable<Uri> FindRelyingPartyIcons(this XrdsDocument xrds) {
+ Requires.NotNull(xrds, "xrds");
+ Contract.Ensures(Contract.Result<IEnumerable<Uri>>() != null);
+
+ return from xrd in xrds.XrdElements
+ from service in xrd.OpenIdRelyingPartyIcons
+ from uri in service.UriElements
+ select uri.Uri;
+ }
+
+ /// <summary>
+ /// Enumerates the XRDS service elements that describe OpenID Relying Party return_to URLs
+ /// that can receive authentication assertions.
+ /// </summary>
+ /// <param name="xrds">The XrdsDocument instance to use in this process.</param>
+ /// <returns>A sequence of service elements.</returns>
+ private static IEnumerable<ServiceElement> FindReturnToServices(this XrdsDocument xrds) {
+ Requires.NotNull(xrds, "xrds");
+ Contract.Ensures(Contract.Result<IEnumerable<ServiceElement>>() != null);
+
+ return from xrd in xrds.XrdElements
+ from service in xrd.OpenIdRelyingPartyReturnToServices
+ select service;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/Protocol.cs b/src/DotNetOpenAuth.OpenId/OpenId/Protocol.cs
index 5aacfd2..a651f3c 100644
--- a/src/DotNetOpenAuth/OpenId/Protocol.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Protocol.cs
@@ -157,7 +157,7 @@ namespace DotNetOpenAuth.OpenId {
/// of an incoming OpenID <i>indirect</i> message or <i>direct request</i>.
/// </summary>
internal static Protocol Detect(IDictionary<string, string> query) {
- Contract.Requires<ArgumentNullException>(query != null);
+ Requires.NotNull(query, "query");
return query.ContainsKey(V20.openid.ns) ? V20 : V11;
}
/// <summary>
@@ -165,7 +165,7 @@ namespace DotNetOpenAuth.OpenId {
/// of an incoming OpenID <i>direct</i> response message.
/// </summary>
internal static Protocol DetectFromDirectResponse(IDictionary<string, string> query) {
- Contract.Requires<ArgumentNullException>(query != null);
+ Requires.NotNull(query, "query");
return query.ContainsKey(V20.openidnp.ns) ? V20 : V11;
}
/// <summary>
@@ -173,7 +173,7 @@ namespace DotNetOpenAuth.OpenId {
/// of XRDS Service Type URIs included for some service.
/// </summary>
internal static Protocol Detect(IEnumerable<string> serviceTypeURIs) {
- Contract.Requires<ArgumentNullException>(serviceTypeURIs != null);
+ Requires.NotNull(serviceTypeURIs, "serviceTypeURIs");
return FindBestVersion(p => p.OPIdentifierServiceTypeURI, serviceTypeURIs) ??
FindBestVersion(p => p.ClaimedIdentifierServiceTypeURI, serviceTypeURIs) ??
FindBestVersion(p => p.RPReturnToTypeURI, serviceTypeURIs);
diff --git a/src/DotNetOpenAuth/OpenId/Provider/IAuthenticationRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/Provider/IAuthenticationRequest.cs
index f59d436..1045282 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/IAuthenticationRequest.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Provider/IAuthenticationRequest.cs
@@ -176,8 +176,8 @@ namespace DotNetOpenAuth.OpenId.Provider {
set {
IAuthenticationRequest req = this;
- Contract.Requires<InvalidOperationException>(!req.IsDelegatedIdentifier, OpenIdStrings.ClaimedIdentifierCannotBeSetOnDelegatedAuthentication);
- Contract.Requires<InvalidOperationException>(!req.IsDirectedIdentity || !(req.LocalIdentifier != null && req.LocalIdentifier != value), OpenIdStrings.IdentifierSelectRequiresMatchingIdentifiers);
+ Requires.ValidState(!req.IsDelegatedIdentifier, OpenIdStrings.ClaimedIdentifierCannotBeSetOnDelegatedAuthentication);
+ Requires.ValidState(!req.IsDirectedIdentity || !(req.LocalIdentifier != null && req.LocalIdentifier != value), OpenIdStrings.IdentifierSelectRequiresMatchingIdentifiers);
}
}
@@ -260,7 +260,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// Gets or sets the security settings that apply to this request.
/// </summary>
/// <value>
- /// Defaults to the <see cref="OpenIdProvider.SecuritySettings"/> on the <see cref="OpenIdProvider"/>.
+ /// Defaults to the OpenIdProvider.SecuritySettings on the OpenIdProvider.
/// </value>
ProviderSecuritySettings IRequest.SecuritySettings {
get {
@@ -293,8 +293,8 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// request before the <see cref="IAuthenticationRequest.ClaimedIdentifier"/> property is set.
/// </exception>
void IAuthenticationRequest.SetClaimedIdentifierFragment(string fragment) {
- Contract.Requires<InvalidOperationException>(!(((IAuthenticationRequest)this).IsDirectedIdentity && ((IAuthenticationRequest)this).ClaimedIdentifier == null), OpenIdStrings.ClaimedIdentifierMustBeSetFirst);
- Contract.Requires<InvalidOperationException>(!(((IAuthenticationRequest)this).ClaimedIdentifier is XriIdentifier), OpenIdStrings.FragmentNotAllowedOnXRIs);
+ Requires.ValidState(!(((IAuthenticationRequest)this).IsDirectedIdentity && ((IAuthenticationRequest)this).ClaimedIdentifier == null), OpenIdStrings.ClaimedIdentifierMustBeSetFirst);
+ Requires.ValidState(!(((IAuthenticationRequest)this).ClaimedIdentifier is XriIdentifier), OpenIdStrings.FragmentNotAllowedOnXRIs);
throw new NotImplementedException();
}
@@ -306,7 +306,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// <summary>
/// Attempts to perform relying party discovery of the return URL claimed by the Relying Party.
/// </summary>
- /// <param name="provider">The OpenIdProvider that is performing the RP discovery.</param>
+ /// <param name="webRequestHandler">The web request handler to use for the RP discovery request.</param>
/// <returns>
/// The details of how successful the relying party discovery was.
/// </returns>
@@ -314,7 +314,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// <para>Return URL verification is only attempted if this method is called.</para>
/// <para>See OpenID Authentication 2.0 spec section 9.2.1.</para>
/// </remarks>
- RelyingPartyDiscoveryResult IHostProcessedRequest.IsReturnUrlDiscoverable(OpenIdProvider provider) {
+ RelyingPartyDiscoveryResult IHostProcessedRequest.IsReturnUrlDiscoverable(IDirectWebRequestHandler webRequestHandler) {
throw new NotImplementedException();
}
diff --git a/src/DotNetOpenAuth/OpenId/Provider/IHostProcessedRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/Provider/IHostProcessedRequest.cs
index 1c38d4b..809c0f3 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/IHostProcessedRequest.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Provider/IHostProcessedRequest.cs
@@ -46,15 +46,15 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// <summary>
/// Attempts to perform relying party discovery of the return URL claimed by the Relying Party.
/// </summary>
- /// <param name="provider">The OpenIdProvider that is performing the RP discovery.</param>
+ /// <param name="webRequestHandler">The web request handler.</param>
/// <returns>
- /// The details of how successful the relying party discovery was.
+ /// The details of how successful the relying party discovery was.
/// </returns>
/// <remarks>
- /// <para>Return URL verification is only attempted if this method is called.</para>
- /// <para>See OpenID Authentication 2.0 spec section 9.2.1.</para>
+ /// <para>Return URL verification is only attempted if this method is called.</para>
+ /// <para>See OpenID Authentication 2.0 spec section 9.2.1.</para>
/// </remarks>
- RelyingPartyDiscoveryResult IsReturnUrlDiscoverable(OpenIdProvider provider);
+ RelyingPartyDiscoveryResult IsReturnUrlDiscoverable(IDirectWebRequestHandler webRequestHandler);
}
/// <summary>
@@ -119,7 +119,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// Gets or sets the security settings that apply to this request.
/// </summary>
/// <value>
- /// Defaults to the <see cref="OpenIdProvider.SecuritySettings"/> on the <see cref="OpenIdProvider"/>.
+ /// Defaults to the OpenIdProvider.SecuritySettings on the OpenIdProvider.
/// </value>
ProviderSecuritySettings IRequest.SecuritySettings {
get { throw new NotImplementedException(); }
@@ -184,16 +184,16 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// <summary>
/// Attempts to perform relying party discovery of the return URL claimed by the Relying Party.
/// </summary>
- /// <param name="provider">The OpenIdProvider that is performing the RP discovery.</param>
+ /// <param name="webRequestHandler">The web request handler.</param>
/// <returns>
/// The details of how successful the relying party discovery was.
/// </returns>
/// <remarks>
- /// <para>Return URL verification is only attempted if this method is called.</para>
- /// <para>See OpenID Authentication 2.0 spec section 9.2.1.</para>
+ /// <para>Return URL verification is only attempted if this method is called.</para>
+ /// <para>See OpenID Authentication 2.0 spec section 9.2.1.</para>
/// </remarks>
- RelyingPartyDiscoveryResult IHostProcessedRequest.IsReturnUrlDiscoverable(OpenIdProvider provider) {
- Contract.Requires<ArgumentNullException>(provider != null);
+ RelyingPartyDiscoveryResult IHostProcessedRequest.IsReturnUrlDiscoverable(IDirectWebRequestHandler webRequestHandler) {
+ Requires.NotNull(webRequestHandler, "webRequestHandler");
throw new System.NotImplementedException();
}
diff --git a/src/DotNetOpenAuth/OpenId/Provider/IProviderBehavior.cs b/src/DotNetOpenAuth.OpenId/OpenId/Provider/IProviderBehavior.cs
index 01b4ac8..9750625 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/IProviderBehavior.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Provider/IProviderBehavior.cs
@@ -74,7 +74,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// incompatible with each other.
/// </remarks>
void IProviderBehavior.ApplySecuritySettings(ProviderSecuritySettings securitySettings) {
- Contract.Requires<ArgumentNullException>(securitySettings != null);
+ Requires.NotNull(securitySettings, "securitySettings");
throw new System.NotImplementedException();
}
@@ -92,7 +92,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// itself as that instance may be shared across many requests.
/// </remarks>
bool IProviderBehavior.OnIncomingRequest(IRequest request) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
throw new System.NotImplementedException();
}
@@ -105,7 +105,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// from handling it; <c>false</c> to allow other behaviors to process this request.
/// </returns>
bool IProviderBehavior.OnOutgoingResponse(IAuthenticationRequest request) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
throw new System.NotImplementedException();
}
diff --git a/src/DotNetOpenAuth/OpenId/Provider/IRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/Provider/IRequest.cs
index c231fa3..1870bfe 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/IRequest.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Provider/IRequest.cs
@@ -35,7 +35,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// <summary>
/// Gets or sets the security settings that apply to this request.
/// </summary>
- /// <value>Defaults to the <see cref="OpenIdProvider.SecuritySettings"/> on the <see cref="OpenIdProvider"/>.</value>
+ /// <value>Defaults to the OpenIdProvider.SecuritySettings on the OpenIdProvider.</value>
ProviderSecuritySettings SecuritySettings { get; set; }
/// <summary>
@@ -85,9 +85,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// <summary>
/// Gets or sets the security settings that apply to this request.
/// </summary>
- /// <value>
- /// Defaults to the <see cref="OpenIdProvider.SecuritySettings"/> on the <see cref="OpenIdProvider"/>.
- /// </value>
+ /// <value>Defaults to the OpenIdProvider.SecuritySettings on the OpenIdProvider.</value>
ProviderSecuritySettings IRequest.SecuritySettings {
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
@@ -109,7 +107,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// </summary>
/// <param name="extension">The extension to add to the response message.</param>
void IRequest.AddResponseExtension(IOpenIdMessageExtension extension) {
- Contract.Requires<ArgumentNullException>(extension != null);
+ Requires.NotNull(extension, "extension");
throw new NotImplementedException();
}
@@ -142,7 +140,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// An instance of the extension initialized with values passed in with the request.
/// </returns>
IOpenIdMessageExtension IRequest.GetExtension(Type extensionType) {
- Contract.Requires<ArgumentNullException>(extensionType != null);
+ Requires.NotNull(extensionType, "extensionType");
throw new NotImplementedException();
}
diff --git a/src/DotNetOpenAuth/OpenId/Provider/ProviderSecuritySettings.cs b/src/DotNetOpenAuth.OpenId/OpenId/Provider/ProviderSecuritySettings.cs
index d5fa4a9..130e6dd 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/ProviderSecuritySettings.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Provider/ProviderSecuritySettings.cs
@@ -24,6 +24,11 @@ namespace DotNetOpenAuth.OpenId.Provider {
internal const bool ProtectDownlevelReplayAttacksDefault = true;
/// <summary>
+ /// The default value for the <see cref="EncodeAssociationSecretsInHandles"/> property.
+ /// </summary>
+ internal const bool EncodeAssociationSecretsInHandlesDefault = true;
+
+ /// <summary>
/// The default value for the <see cref="SignOutgoingExtensions"/> property.
/// </summary>
internal const bool SignOutgoingExtensionsDefault = true;
@@ -102,6 +107,14 @@ namespace DotNetOpenAuth.OpenId.Provider {
public UnsolicitedAssertionVerificationLevel UnsolicitedAssertionVerification { get; set; }
/// <summary>
+ /// Gets or sets a value indicating whether the Provider should ease the burden of storing associations
+ /// by encoding them in signed, encrypted form into the association handles themselves, storing only
+ /// a few rotating, private symmetric keys in the Provider's store instead.
+ /// </summary>
+ /// <value>The default value for this property is <c>true</c>.</value>
+ public bool EncodeAssociationSecretsInHandles { get; set; }
+
+ /// <summary>
/// Gets or sets a value indicating whether OpenID 1.x relying parties that may not be
/// protecting their users from replay attacks are protected from
/// replay attacks by this provider.
diff --git a/src/DotNetOpenAuth/OpenId/Provider/RelyingPartyDiscoveryResult.cs b/src/DotNetOpenAuth.OpenId/OpenId/Provider/RelyingPartyDiscoveryResult.cs
index 4eca6d6..4eca6d6 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/RelyingPartyDiscoveryResult.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Provider/RelyingPartyDiscoveryResult.cs
diff --git a/src/DotNetOpenAuth/OpenId/ProviderEndpointDescription.cs b/src/DotNetOpenAuth.OpenId/OpenId/ProviderEndpointDescription.cs
index 6514ffd..092ec22 100644
--- a/src/DotNetOpenAuth/OpenId/ProviderEndpointDescription.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/ProviderEndpointDescription.cs
@@ -29,8 +29,8 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="providerEndpoint">The OpenID Provider endpoint URL.</param>
/// <param name="openIdVersion">The OpenID version supported by this particular endpoint.</param>
internal ProviderEndpointDescription(Uri providerEndpoint, Version openIdVersion) {
- Contract.Requires<ArgumentNullException>(providerEndpoint != null);
- Contract.Requires<ArgumentNullException>(openIdVersion != null);
+ Requires.NotNull(providerEndpoint, "providerEndpoint");
+ Requires.NotNull(openIdVersion, "openIdVersion");
this.Uri = providerEndpoint;
this.Version = openIdVersion;
@@ -43,8 +43,8 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="providerEndpoint">The URI the provider listens on for OpenID requests.</param>
/// <param name="serviceTypeURIs">The set of services offered by this endpoint.</param>
internal ProviderEndpointDescription(Uri providerEndpoint, IEnumerable<string> serviceTypeURIs) {
- Contract.Requires<ArgumentNullException>(providerEndpoint != null);
- Contract.Requires<ArgumentNullException>(serviceTypeURIs != null);
+ Requires.NotNull(providerEndpoint, "providerEndpoint");
+ Requires.NotNull(serviceTypeURIs, "serviceTypeURIs");
this.Uri = providerEndpoint;
this.Capabilities = new ReadOnlyCollection<string>(serviceTypeURIs.ToList());
diff --git a/src/DotNetOpenAuth/OpenId/Realm.cs b/src/DotNetOpenAuth.OpenId/OpenId/Realm.cs
index 98e3598..685b922 100644
--- a/src/DotNetOpenAuth/OpenId/Realm.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Realm.cs
@@ -16,6 +16,7 @@ namespace DotNetOpenAuth.OpenId {
using System.Web;
using System.Xml;
using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Reflection;
using DotNetOpenAuth.Xrds;
using DotNetOpenAuth.Yadis;
@@ -58,12 +59,23 @@ namespace DotNetOpenAuth.OpenId {
private Uri uri;
/// <summary>
+ /// Initializes static members of the <see cref="Realm"/> class.
+ /// </summary>
+ static Realm() {
+ Func<string, Realm> safeRealm = str => {
+ Contract.Assume(str != null);
+ return new Realm(str);
+ };
+ MessagePart.Map<Realm>(realm => realm.ToString(), realm => realm.OriginalString, safeRealm);
+ }
+
+ /// <summary>
/// Initializes a new instance of the <see cref="Realm"/> class.
/// </summary>
/// <param name="realmUrl">The realm URL to use in the new instance.</param>
[SuppressMessage("Microsoft.Design", "CA1057:StringUriOverloadsCallSystemUriOverloads", Justification = "Not all realms are valid URLs (because of wildcards).")]
public Realm(string realmUrl) {
- Contract.Requires<ArgumentNullException>(realmUrl != null); // not non-zero check so we throw UriFormatException later
+ Requires.NotNull(realmUrl, "realmUrl"); // not non-zero check so we throw UriFormatException later
this.DomainWildcard = Regex.IsMatch(realmUrl, WildcardDetectionPattern);
this.uri = new Uri(Regex.Replace(realmUrl, WildcardDetectionPattern, m => m.Groups[1].Value));
if (!this.uri.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase) &&
@@ -78,7 +90,7 @@ namespace DotNetOpenAuth.OpenId {
/// </summary>
/// <param name="realmUrl">The realm URL of the Relying Party.</param>
public Realm(Uri realmUrl) {
- Contract.Requires<ArgumentNullException>(realmUrl != null);
+ Requires.NotNull(realmUrl, "realmUrl");
this.uri = realmUrl;
if (!this.uri.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase) &&
!this.uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase)) {
@@ -111,7 +123,7 @@ namespace DotNetOpenAuth.OpenId {
/// </remarks>
public static Realm AutoDetect {
get {
- Contract.Requires<InvalidOperationException>(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
+ Requires.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
Contract.Ensures(Contract.Result<Realm>() != null);
HttpRequestInfo requestInfo = new HttpRequestInfo(HttpContext.Current.Request);
@@ -477,7 +489,7 @@ namespace DotNetOpenAuth.OpenId {
/// when we should be throwing an <see cref="ArgumentNullException"/>.
/// </remarks>
private static string SafeUriBuilderToString(UriBuilder realmUriBuilder) {
- Contract.Requires<ArgumentNullException>(realmUriBuilder != null);
+ Requires.NotNull(realmUriBuilder, "realmUriBuilder");
// Note: we MUST use ToString. Uri property throws if wildcard is present.
// Note that Uri.ToString() should generally be avoided, but UriBuilder.ToString()
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/AuthenticationStatus.cs b/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/AuthenticationStatus.cs
index d9e5d0a..89eca78 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/AuthenticationStatus.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/AuthenticationStatus.cs
@@ -24,7 +24,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// with a message stating that additional user agent interaction is required
/// before authentication can be completed.</para>
/// <para>Casting the <see cref="IAuthenticationResponse"/> to a
- /// <see cref="ISetupRequiredAuthenticationResponse"/> in this case can help
+ /// ISetupRequiredAuthenticationResponse in this case can help
/// you retry the authentication using setup (non-immediate) mode.</para>
/// </summary>
SetupRequired,
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/IAuthenticationRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationRequest.cs
index 65db0bd..fa58b7d 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/IAuthenticationRequest.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationRequest.cs
@@ -79,7 +79,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// to know that its user is over 21 years old, or perhaps a member of some organization.
/// OpenID extensions can provide this, without any need for asserting the identity of the user.</para>
/// <para>Constructing an OpenID request for only extensions can be done by calling
- /// <see cref="OpenIdRelyingParty.CreateRequest(Identifier)"/> with any valid OpenID identifier
+ /// OpenIdRelyingParty.CreateRequest with any valid OpenID identifier
/// (claimed identifier or OP identifier). But once this property is set to <c>true</c>,
/// the claimed identifier value in the request is not included in the transmitted message.</para>
/// <para>It is anticipated that an RP would only issue these types of requests to OPs that
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/IAuthenticationRequestContract.cs b/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationRequestContract.cs
index cd36cc7..fa16c41 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/IAuthenticationRequestContract.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationRequestContract.cs
@@ -73,26 +73,26 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
}
void IAuthenticationRequest.AddCallbackArguments(IDictionary<string, string> arguments) {
- Contract.Requires<ArgumentNullException>(arguments != null);
- Contract.Requires<ArgumentException>(arguments.Keys.All(k => !String.IsNullOrEmpty(k)));
- Contract.Requires<ArgumentException>(arguments.Values.All(v => v != null));
+ Requires.NotNull(arguments, "arguments");
+ Requires.True(arguments.Keys.All(k => !String.IsNullOrEmpty(k)), "arguments");
+ Requires.True(arguments.Values.All(v => v != null), "arguments");
throw new NotImplementedException();
}
void IAuthenticationRequest.AddCallbackArguments(string key, string value) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(key));
- Contract.Requires<ArgumentNullException>(value != null);
+ Requires.NotNullOrEmpty(key, "key");
+ Requires.NotNull(value, "value");
throw new NotImplementedException();
}
void IAuthenticationRequest.SetCallbackArgument(string key, string value) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(key));
- Contract.Requires<ArgumentNullException>(value != null);
+ Requires.NotNullOrEmpty(key, "key");
+ Requires.NotNull(value, "value");
throw new NotImplementedException();
}
void IAuthenticationRequest.AddExtension(IOpenIdMessageExtension extension) {
- Contract.Requires<ArgumentNullException>(extension != null);
+ Requires.NotNull(extension, "extension");
throw new NotImplementedException();
}
@@ -101,8 +101,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
}
void IAuthenticationRequest.SetUntrustedCallbackArgument(string key, string value) {
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(key));
- Contract.Requires<ArgumentNullException>(value != null);
+ Requires.NotNullOrEmpty(key, "key");
+ Requires.NotNull(value, "value");
throw new NotImplementedException();
}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/IAuthenticationResponse.cs b/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationResponse.cs
index a24220f..7b55f65 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/IAuthenticationResponse.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationResponse.cs
@@ -367,7 +367,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <para>Note that these values are NOT protected against tampering in transit.</para>
/// </remarks>
string IAuthenticationResponse.GetCallbackArgument(string key) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(key));
+ Requires.NotNullOrEmpty(key, "key");
throw new NotImplementedException();
}
@@ -432,8 +432,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// have not been tampered with since the Provider sent the message.</para>
/// </remarks>
IOpenIdMessageExtension IAuthenticationResponse.GetExtension(Type extensionType) {
- Contract.Requires<ArgumentNullException>(extensionType != null);
- Contract.Requires<ArgumentException>(typeof(IOpenIdMessageExtension).IsAssignableFrom(extensionType));
+ Requires.NotNullSubtype<IOpenIdMessageExtension>(extensionType, "extensionType");
////ErrorUtilities.VerifyArgument(typeof(IOpenIdMessageExtension).IsAssignableFrom(extensionType), string.Format(CultureInfo.CurrentCulture, OpenIdStrings.TypeMustImplementX, typeof(IOpenIdMessageExtension).FullName));
throw new NotImplementedException();
}
@@ -485,8 +484,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// have not been tampered with since the Provider sent the message.</para>
/// </remarks>
IOpenIdMessageExtension IAuthenticationResponse.GetUntrustedExtension(Type extensionType) {
- Contract.Requires<ArgumentNullException>(extensionType != null);
- Contract.Requires<ArgumentException>(typeof(IOpenIdMessageExtension).IsAssignableFrom(extensionType));
+ Requires.NotNullSubtype<IOpenIdMessageExtension>(extensionType, "extensionType");
////ErrorUtilities.VerifyArgument(typeof(IOpenIdMessageExtension).IsAssignableFrom(extensionType), string.Format(CultureInfo.CurrentCulture, OpenIdStrings.TypeMustImplementX, typeof(IOpenIdMessageExtension).FullName));
throw new NotImplementedException();
}
@@ -506,7 +504,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// used to make a security-sensitive decision.
/// </remarks>
string IAuthenticationResponse.GetUntrustedCallbackArgument(string key) {
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(key));
+ Requires.NotNullOrEmpty(key, "key");
throw new NotImplementedException();
}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/IRelyingPartyBehavior.cs b/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IRelyingPartyBehavior.cs
index 1bfa0db..28cad6d 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/IRelyingPartyBehavior.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IRelyingPartyBehavior.cs
@@ -64,7 +64,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// incompatible with each other.
/// </remarks>
void IRelyingPartyBehavior.ApplySecuritySettings(RelyingPartySecuritySettings securitySettings) {
- Contract.Requires<ArgumentNullException>(securitySettings != null);
+ Requires.NotNull(securitySettings, "securitySettings");
}
/// <summary>
@@ -76,7 +76,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// without malfunctioning.
/// </remarks>
void IRelyingPartyBehavior.OnOutgoingAuthenticationRequest(IAuthenticationRequest request) {
- Contract.Requires<ArgumentNullException>(request != null);
+ Requires.NotNull(request, "request");
}
/// <summary>
@@ -84,7 +84,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <param name="assertion">The positive assertion.</param>
void IRelyingPartyBehavior.OnIncomingPositiveAssertion(IAuthenticationResponse assertion) {
- Contract.Requires<ArgumentNullException>(assertion != null);
+ Requires.NotNull(assertion, "assertion");
}
#endregion
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/RelyingPartySecuritySettings.cs b/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/RelyingPartySecuritySettings.cs
index fc6d4c7..fc6d4c7 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/RelyingPartySecuritySettings.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/RelyingPartySecuritySettings.cs
diff --git a/src/DotNetOpenAuth/OpenId/RelyingPartyDescription.cs b/src/DotNetOpenAuth.OpenId/OpenId/RelyingPartyDescription.cs
index 7926e8f..ab0fd13 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingPartyDescription.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/RelyingPartyDescription.cs
@@ -28,8 +28,8 @@ namespace DotNetOpenAuth.OpenId {
/// The Type URIs of supported services advertised on a relying party's XRDS document.
/// </param>
internal RelyingPartyEndpointDescription(Uri returnTo, string[] supportedServiceTypeUris) {
- Contract.Requires<ArgumentNullException>(returnTo != null);
- Contract.Requires<ArgumentNullException>(supportedServiceTypeUris != null);
+ Requires.NotNull(returnTo, "returnTo");
+ Requires.NotNull(supportedServiceTypeUris, "supportedServiceTypeUris");
this.ReturnToEndpoint = returnTo;
this.Protocol = GetProtocolFromServices(supportedServiceTypeUris);
diff --git a/src/DotNetOpenAuth/OpenId/SecuritySettings.cs b/src/DotNetOpenAuth.OpenId/OpenId/SecuritySettings.cs
index 26f6d2a..a083cc6 100644
--- a/src/DotNetOpenAuth/OpenId/SecuritySettings.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/SecuritySettings.cs
@@ -88,7 +88,7 @@ namespace DotNetOpenAuth.OpenId {
/// <c>true</c> if the association is permitted given the security requirements; otherwise, <c>false</c>.
/// </returns>
internal bool IsAssociationInPermittedRange(Association association) {
- Contract.Requires<ArgumentNullException>(association != null);
+ Requires.NotNull(association, "association");
return association.HashBitLength >= this.MinimumHashBitLength && association.HashBitLength <= this.MaximumHashBitLength;
}
}
diff --git a/src/DotNetOpenAuth/OpenId/UriDiscoveryService.cs b/src/DotNetOpenAuth.OpenId/OpenId/UriDiscoveryService.cs
index 7d17fd9..7d17fd9 100644
--- a/src/DotNetOpenAuth/OpenId/UriDiscoveryService.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/UriDiscoveryService.cs
diff --git a/src/DotNetOpenAuth/OpenId/UriIdentifier.cs b/src/DotNetOpenAuth.OpenId/OpenId/UriIdentifier.cs
index 145a394..aa72869 100644
--- a/src/DotNetOpenAuth/OpenId/UriIdentifier.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/UriIdentifier.cs
@@ -17,7 +17,6 @@ namespace DotNetOpenAuth.OpenId {
using System.Web.UI.HtmlControls;
using System.Xml;
using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.Xrds;
using DotNetOpenAuth.Yadis;
@@ -100,7 +99,7 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="uri">The value this identifier will represent.</param>
internal UriIdentifier(string uri)
: this(uri, false) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(uri));
+ Requires.NotNullOrEmpty(uri, "uri");
}
/// <summary>
@@ -110,7 +109,7 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="requireSslDiscovery">if set to <c>true</c> [require SSL discovery].</param>
internal UriIdentifier(string uri, bool requireSslDiscovery)
: base(uri, requireSslDiscovery) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(uri));
+ Requires.NotNullOrEmpty(uri, "uri");
Uri canonicalUri;
bool schemePrepended;
if (!TryCanonicalize(uri, out canonicalUri, requireSslDiscovery, out schemePrepended)) {
@@ -138,7 +137,7 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="requireSslDiscovery">if set to <c>true</c> [require SSL discovery].</param>
internal UriIdentifier(Uri uri, bool requireSslDiscovery)
: base(uri != null ? uri.OriginalString : null, requireSslDiscovery) {
- Contract.Requires<ArgumentNullException>(uri != null);
+ Requires.NotNull(uri, "uri");
string uriAsString = uri.OriginalString;
if (schemeSubstitution) {
@@ -423,7 +422,7 @@ namespace DotNetOpenAuth.OpenId {
/// require network access are also done, such as lower-casing the hostname in the URI.
/// </remarks>
private static bool TryCanonicalize(string uri, out Uri canonicalUri, bool forceHttpsDefaultScheme, out bool schemePrepended) {
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(uri));
+ Requires.NotNullOrEmpty(uri, "uri");
canonicalUri = null;
try {
@@ -455,7 +454,7 @@ namespace DotNetOpenAuth.OpenId {
/// </remarks>
[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "The user will see the result of this operation and they want to see it in lower case.")]
private static bool TryCanonicalize(string uri, out Uri canonicalUri) {
- Contract.Requires<ArgumentNullException>(uri != null);
+ Requires.NotNull(uri, "uri");
if (schemeSubstitution) {
UriBuilder uriBuilder = new UriBuilder(uri);
@@ -476,9 +475,9 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="normal">The ordinary URL or scheme name.</param>
/// <returns>The non-compressing equivalent scheme or URL for the given value.</returns>
private static string NormalSchemeToSpecialRoundTrippingScheme(string normal) {
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(normal));
- Contract.Requires<InternalErrorException>(schemeSubstitution);
+ Requires.NotNullOrEmpty(normal, "normal");
Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()));
+ ErrorUtilities.VerifyInternal(schemeSubstitution, "Wrong schemeSubstitution value.");
int delimiterIndex = normal.IndexOf(Uri.SchemeDelimiter, StringComparison.Ordinal);
string normalScheme = delimiterIndex < 0 ? normal : normal.Substring(0, delimiterIndex);
@@ -504,7 +503,7 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="schemePrepended">if set to <c>true</c>, the scheme was prepended during normalization.</param>
/// <returns>The somewhat normalized URL.</returns>
private static string DoSimpleCanonicalize(string uri, bool forceHttpsDefaultScheme, out bool schemePrepended) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(uri));
+ Requires.NotNullOrEmpty(uri, "uri");
schemePrepended = false;
uri = uri.Trim();
@@ -547,7 +546,7 @@ namespace DotNetOpenAuth.OpenId {
/// </summary>
/// <param name="value">The value.</param>
internal SimpleUri(string value) {
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(value));
+ Requires.NotNullOrEmpty(value, "value");
bool schemePrepended;
value = DoSimpleCanonicalize(value, false, out schemePrepended);
@@ -665,7 +664,7 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="path">The path to normalize.</param>
/// <returns>The given path, with exactly those characters escaped which should be.</returns>
private static string NormalizePathEscaping(string path) {
- Contract.Requires<ArgumentNullException>(path != null);
+ Requires.NotNull(path, "path");
string[] segments = path.Split('/');
for (int i = 0; i < segments.Length; i++) {
@@ -696,7 +695,7 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="standardScheme">The standard scheme that this parser will be subverting.</param>
public NonPathCompressingUriParser(string standardScheme)
: base(GenericUriParserOptions.DontCompressPath | GenericUriParserOptions.IriParsing | GenericUriParserOptions.Idn) {
- Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(standardScheme));
+ Requires.NotNullOrEmpty(standardScheme, "standardScheme");
this.standardScheme = standardScheme;
}
diff --git a/src/DotNetOpenAuth/OpenId/XriDiscoveryProxyService.cs b/src/DotNetOpenAuth.OpenId/OpenId/XriDiscoveryProxyService.cs
index b1a3430..52bb92e 100644
--- a/src/DotNetOpenAuth/OpenId/XriDiscoveryProxyService.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/XriDiscoveryProxyService.cs
@@ -72,8 +72,8 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="requestHandler">The request handler.</param>
/// <returns>The XRDS document.</returns>
private static XrdsDocument DownloadXrds(XriIdentifier identifier, IDirectWebRequestHandler requestHandler) {
- Contract.Requires<ArgumentNullException>(identifier != null);
- Contract.Requires<ArgumentNullException>(requestHandler != null);
+ Requires.NotNull(identifier, "identifier");
+ Requires.NotNull(requestHandler, "requestHandler");
Contract.Ensures(Contract.Result<XrdsDocument>() != null);
XrdsDocument doc;
using (var xrdsResponse = Yadis.Request(requestHandler, GetXrdsUrl(identifier), identifier.IsDiscoverySecureEndToEnd)) {
@@ -89,7 +89,7 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="identifier">The identifier.</param>
/// <returns>The URI to HTTP GET from to get the services.</returns>
private static Uri GetXrdsUrl(XriIdentifier identifier) {
- ErrorUtilities.VerifyProtocol(DotNetOpenAuthSection.Configuration.OpenId.XriResolver.Enabled, OpenIdStrings.XriResolutionDisabled);
+ ErrorUtilities.VerifyProtocol(OpenIdElement.Configuration.XriResolver.Enabled, OpenIdStrings.XriResolutionDisabled);
string xriResolverProxy = XriResolverProxyTemplate;
if (identifier.IsDiscoverySecureEndToEnd) {
// Indicate to xri.net that we require SSL to be used for delegated resolution
@@ -102,7 +102,7 @@ namespace DotNetOpenAuth.OpenId {
CultureInfo.InvariantCulture,
xriResolverProxy,
identifier,
- DotNetOpenAuthSection.Configuration.OpenId.XriResolver.Proxy.Name));
+ OpenIdElement.Configuration.XriResolver.Proxy.Name));
}
}
}
diff --git a/src/DotNetOpenAuth/OpenId/XriIdentifier.cs b/src/DotNetOpenAuth.OpenId/OpenId/XriIdentifier.cs
index 729f603..28460f1 100644
--- a/src/DotNetOpenAuth/OpenId/XriIdentifier.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/XriIdentifier.cs
@@ -13,7 +13,6 @@ namespace DotNetOpenAuth.OpenId {
using System.Xml;
using DotNetOpenAuth.Configuration;
using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.Xrds;
using DotNetOpenAuth.Yadis;
@@ -45,8 +44,8 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="xri">The string value of the XRI.</param>
internal XriIdentifier(string xri)
: this(xri, false) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(xri));
- Contract.Requires<FormatException>(IsValidXri(xri), OpenIdStrings.InvalidXri);
+ Requires.NotNullOrEmpty(xri, "xri");
+ Requires.Format(IsValidXri(xri), OpenIdStrings.InvalidXri);
}
/// <summary>
@@ -59,8 +58,8 @@ namespace DotNetOpenAuth.OpenId {
/// </param>
internal XriIdentifier(string xri, bool requireSsl)
: base(xri, requireSsl) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(xri));
- Contract.Requires<FormatException>(IsValidXri(xri), OpenIdStrings.InvalidXri);
+ Requires.NotNullOrEmpty(xri, "xri");
+ Requires.Format(IsValidXri(xri), OpenIdStrings.InvalidXri);
Contract.Assume(xri != null); // Proven by IsValidXri
this.OriginalXri = xri;
this.canonicalXri = CanonicalizeXri(xri);
@@ -132,7 +131,7 @@ namespace DotNetOpenAuth.OpenId {
/// <c>true</c> if the given string constitutes a valid XRI; otherwise, <c>false</c>.
/// </returns>
internal static bool IsValidXri(string xri) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(xri));
+ Requires.NotNullOrEmpty(xri, "xri");
xri = xri.Trim();
// TODO: better validation code here
@@ -183,7 +182,7 @@ namespace DotNetOpenAuth.OpenId {
/// <returns>The canonicalized form of the XRI.</returns>
/// <remarks>The canonical form, per the OpenID spec, is no scheme and no whitespace on either end.</remarks>
private static string CanonicalizeXri(string xri) {
- Contract.Requires<ArgumentNullException>(xri != null);
+ Requires.NotNull(xri, "xri");
Contract.Ensures(Contract.Result<string>() != null);
xri = xri.Trim();
if (xri.StartsWith(XriScheme, StringComparison.OrdinalIgnoreCase)) {
diff --git a/src/DotNetOpenAuth/OpenId/OpenIdXrdsHelper.cs b/src/DotNetOpenAuth.OpenId/OpenIdXrdsHelper.cs
index 00468ed..617c467 100644
--- a/src/DotNetOpenAuth/OpenId/OpenIdXrdsHelper.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenIdXrdsHelper.cs
@@ -16,41 +16,7 @@ namespace DotNetOpenAuth.OpenId {
/// <summary>
/// Adds OpenID-specific extension methods to the XrdsDocument class.
/// </summary>
- internal static class OpenIdXrdsHelper {
- /// <summary>
- /// Finds the Relying Party return_to receiving endpoints.
- /// </summary>
- /// <param name="xrds">The XrdsDocument instance to use in this process.</param>
- /// <returns>A sequence of Relying Party descriptors for the return_to endpoints.</returns>
- /// <remarks>
- /// This is useful for Providers to send unsolicited assertions to Relying Parties,
- /// or for Provider's to perform RP discovery/verification as part of authentication.
- /// </remarks>
- internal static IEnumerable<RelyingPartyEndpointDescription> FindRelyingPartyReceivingEndpoints(this XrdsDocument xrds) {
- Contract.Requires<ArgumentNullException>(xrds != null);
- Contract.Ensures(Contract.Result<IEnumerable<RelyingPartyEndpointDescription>>() != null);
-
- return from service in xrds.FindReturnToServices()
- from uri in service.UriElements
- select new RelyingPartyEndpointDescription(uri.Uri, service.TypeElementUris);
- }
-
- /// <summary>
- /// Finds the icons the relying party wants an OP to display as part of authentication,
- /// per the UI extension spec.
- /// </summary>
- /// <param name="xrds">The XrdsDocument to search.</param>
- /// <returns>A sequence of the icon URLs in preferred order.</returns>
- internal static IEnumerable<Uri> FindRelyingPartyIcons(this XrdsDocument xrds) {
- Contract.Requires<ArgumentNullException>(xrds != null);
- Contract.Ensures(Contract.Result<IEnumerable<Uri>>() != null);
-
- return from xrd in xrds.XrdElements
- from service in xrd.OpenIdRelyingPartyIcons
- from uri in service.UriElements
- select uri.Uri;
- }
-
+ internal static class OpenIdXrdsHelperRelyingParty {
/// <summary>
/// Creates the service endpoints described in this document, useful for requesting
/// authentication of one of the OpenID Providers that result from it.
@@ -62,9 +28,9 @@ namespace DotNetOpenAuth.OpenId {
/// A sequence of OpenID Providers that can assert ownership of the <paramref name="claimedIdentifier"/>.
/// </returns>
internal static IEnumerable<IdentifierDiscoveryResult> CreateServiceEndpoints(this IEnumerable<XrdElement> xrds, UriIdentifier claimedIdentifier, UriIdentifier userSuppliedIdentifier) {
- Contract.Requires<ArgumentNullException>(xrds != null);
- Contract.Requires<ArgumentNullException>(claimedIdentifier != null);
- Contract.Requires<ArgumentNullException>(userSuppliedIdentifier != null);
+ Requires.NotNull(xrds, "xrds");
+ Requires.NotNull(claimedIdentifier, "claimedIdentifier");
+ Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier");
Contract.Ensures(Contract.Result<IEnumerable<IdentifierDiscoveryResult>>() != null);
var endpoints = new List<IdentifierDiscoveryResult>();
@@ -84,8 +50,8 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="userSuppliedIdentifier">The user-supplied i-name that was used to discover this XRDS document.</param>
/// <returns>A sequence of OpenID Providers that can assert ownership of the canonical ID given in this document.</returns>
internal static IEnumerable<IdentifierDiscoveryResult> CreateServiceEndpoints(this IEnumerable<XrdElement> xrds, XriIdentifier userSuppliedIdentifier) {
- Contract.Requires<ArgumentNullException>(xrds != null);
- Contract.Requires<ArgumentNullException>(userSuppliedIdentifier != null);
+ Requires.NotNull(xrds, "xrds");
+ Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier");
Contract.Ensures(Contract.Result<IEnumerable<IdentifierDiscoveryResult>>() != null);
var endpoints = new List<IdentifierDiscoveryResult>();
@@ -103,8 +69,8 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="opIdentifier">The OP Identifier entered (and resolved) by the user. Essentially the user-supplied identifier.</param>
/// <returns>A sequence of the providers that can offer directed identity services.</returns>
private static IEnumerable<IdentifierDiscoveryResult> GenerateOPIdentifierServiceEndpoints(this IEnumerable<XrdElement> xrds, Identifier opIdentifier) {
- Contract.Requires<ArgumentNullException>(xrds != null);
- Contract.Requires<ArgumentNullException>(opIdentifier != null);
+ Requires.NotNull(xrds, "xrds");
+ Requires.NotNull(opIdentifier, "opIdentifier");
Contract.Ensures(Contract.Result<IEnumerable<IdentifierDiscoveryResult>>() != null);
return from service in xrds.FindOPIdentifierServices()
from uri in service.UriElements
@@ -124,8 +90,8 @@ namespace DotNetOpenAuth.OpenId {
/// A sequence of the providers that can assert ownership of the given identifier.
/// </returns>
private static IEnumerable<IdentifierDiscoveryResult> GenerateClaimedIdentifierServiceEndpoints(this IEnumerable<XrdElement> xrds, UriIdentifier claimedIdentifier, UriIdentifier userSuppliedIdentifier) {
- Contract.Requires<ArgumentNullException>(xrds != null);
- Contract.Requires<ArgumentNullException>(claimedIdentifier != null);
+ Requires.NotNull(xrds, "xrds");
+ Requires.NotNull(claimedIdentifier, "claimedIdentifier");
Contract.Ensures(Contract.Result<IEnumerable<IdentifierDiscoveryResult>>() != null);
return from service in xrds.FindClaimedIdentifierServices()
@@ -144,7 +110,7 @@ namespace DotNetOpenAuth.OpenId {
/// <returns>A sequence of the providers that can assert ownership of the given identifier.</returns>
private static IEnumerable<IdentifierDiscoveryResult> GenerateClaimedIdentifierServiceEndpoints(this IEnumerable<XrdElement> xrds, XriIdentifier userSuppliedIdentifier) {
// Cannot use code contracts because this method uses yield return.
- ////Contract.Requires<ArgumentNullException>(xrds != null);
+ ////Requires.NotNull(xrds, "xrds");
////Contract.Ensures(Contract.Result<IEnumerable<IdentifierDiscoveryResult>>() != null);
ErrorUtilities.VerifyArgumentNotNull(xrds, "xrds");
@@ -171,7 +137,7 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="xrds">The XrdsDocument instance to use in this process.</param>
/// <returns>A sequence of service elements.</returns>
private static IEnumerable<ServiceElement> FindOPIdentifierServices(this IEnumerable<XrdElement> xrds) {
- Contract.Requires<ArgumentNullException>(xrds != null);
+ Requires.NotNull(xrds, "xrds");
Contract.Ensures(Contract.Result<IEnumerable<ServiceElement>>() != null);
return from xrd in xrds
@@ -186,27 +152,12 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="xrds">The XrdsDocument instance to use in this process.</param>
/// <returns>A sequence of the services offered.</returns>
private static IEnumerable<ServiceElement> FindClaimedIdentifierServices(this IEnumerable<XrdElement> xrds) {
- Contract.Requires<ArgumentNullException>(xrds != null);
+ Requires.NotNull(xrds, "xrds");
Contract.Ensures(Contract.Result<IEnumerable<ServiceElement>>() != null);
return from xrd in xrds
from service in xrd.OpenIdClaimedIdentifierServices
select service;
}
-
- /// <summary>
- /// Enumerates the XRDS service elements that describe OpenID Relying Party return_to URLs
- /// that can receive authentication assertions.
- /// </summary>
- /// <param name="xrds">The XrdsDocument instance to use in this process.</param>
- /// <returns>A sequence of service elements.</returns>
- private static IEnumerable<ServiceElement> FindReturnToServices(this XrdsDocument xrds) {
- Contract.Requires<ArgumentNullException>(xrds != null);
- Contract.Ensures(Contract.Result<IEnumerable<ServiceElement>>() != null);
-
- return from xrd in xrds.XrdElements
- from service in xrd.OpenIdRelyingPartyReturnToServices
- select service;
- }
}
}
diff --git a/src/DotNetOpenAuth.OpenId/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth.OpenId/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..c5226ed
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId/Properties/AssemblyInfo.cs
@@ -0,0 +1,66 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssemblyInfo.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+// We DON'T put an AssemblyVersionAttribute in here because it is generated in the build.
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Net;
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Security.Permissions;
+using System.Web.UI;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("DotNetOpenAuth OpenID")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DotNetOpenAuth")]
+[assembly: AssemblyCopyright("Copyright © 2008")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+[assembly: NeutralResourcesLanguage("en-US")]
+[assembly: CLSCompliant(true)]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("7d73990c-47c0-4256-9f20-a893add9e289")]
+
+[assembly: ContractVerification(true)]
+
+#if StrongNameSigned
+// See comment at top of this file. We need this so that strong-naming doesn't
+// keep this assembly from being useful to shared host (medium trust) web sites.
+[assembly: AllowPartiallyTrustedCallers]
+
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.UI, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.RelyingParty, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.RelyingParty.UI, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider.UI, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
+#else
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.UI")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.RelyingParty")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.RelyingParty.UI")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider.UI")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
+#endif
diff --git a/src/DotNetOpenAuth/Xrds/ServiceElement.cs b/src/DotNetOpenAuth.OpenId/Xrds/ServiceElement.cs
index 0acf2b5..0acf2b5 100644
--- a/src/DotNetOpenAuth/Xrds/ServiceElement.cs
+++ b/src/DotNetOpenAuth.OpenId/Xrds/ServiceElement.cs
diff --git a/src/DotNetOpenAuth/Xrds/TypeElement.cs b/src/DotNetOpenAuth.OpenId/Xrds/TypeElement.cs
index c413629..e1ad188 100644
--- a/src/DotNetOpenAuth/Xrds/TypeElement.cs
+++ b/src/DotNetOpenAuth.OpenId/Xrds/TypeElement.cs
@@ -20,8 +20,8 @@ namespace DotNetOpenAuth.Xrds {
/// <param name="parent">The parent.</param>
public TypeElement(XPathNavigator typeElement, ServiceElement parent) :
base(typeElement, parent) {
- Contract.Requires<ArgumentNullException>(typeElement != null);
- Contract.Requires<ArgumentNullException>(parent != null);
+ Requires.NotNull(typeElement, "typeElement");
+ Requires.NotNull(parent, "parent");
}
/// <summary>
diff --git a/src/DotNetOpenAuth/Xrds/UriElement.cs b/src/DotNetOpenAuth.OpenId/Xrds/UriElement.cs
index a67d259..a67d259 100644
--- a/src/DotNetOpenAuth/Xrds/UriElement.cs
+++ b/src/DotNetOpenAuth.OpenId/Xrds/UriElement.cs
diff --git a/src/DotNetOpenAuth/Xrds/XrdElement.cs b/src/DotNetOpenAuth.OpenId/Xrds/XrdElement.cs
index 2cdc720..2cdc720 100644
--- a/src/DotNetOpenAuth/Xrds/XrdElement.cs
+++ b/src/DotNetOpenAuth.OpenId/Xrds/XrdElement.cs
diff --git a/src/DotNetOpenAuth/Xrds/XrdsDocument.cs b/src/DotNetOpenAuth.OpenId/Xrds/XrdsDocument.cs
index 040c994..040c994 100644
--- a/src/DotNetOpenAuth/Xrds/XrdsDocument.cs
+++ b/src/DotNetOpenAuth.OpenId/Xrds/XrdsDocument.cs
diff --git a/src/DotNetOpenAuth/Xrds/XrdsNode.cs b/src/DotNetOpenAuth.OpenId/Xrds/XrdsNode.cs
index 39bd9b9..7a27a9c 100644
--- a/src/DotNetOpenAuth/Xrds/XrdsNode.cs
+++ b/src/DotNetOpenAuth.OpenId/Xrds/XrdsNode.cs
@@ -31,8 +31,8 @@ namespace DotNetOpenAuth.Xrds {
/// <param name="node">The node represented by this instance.</param>
/// <param name="parentNode">The parent node.</param>
protected XrdsNode(XPathNavigator node, XrdsNode parentNode) {
- Contract.Requires<ArgumentNullException>(node != null);
- Contract.Requires<ArgumentNullException>(parentNode != null);
+ Requires.NotNull(node, "node");
+ Requires.NotNull(parentNode, "parentNode");
this.Node = node;
this.ParentNode = parentNode;
@@ -44,8 +44,8 @@ namespace DotNetOpenAuth.Xrds {
/// </summary>
/// <param name="document">The document's root node, which this instance represents.</param>
protected XrdsNode(XPathNavigator document) {
- Contract.Requires<ArgumentNullException>(document != null);
- Contract.Requires<ArgumentException>(document.NameTable != null);
+ Requires.NotNull(document, "document");
+ Requires.True(document.NameTable != null, null);
this.Node = document;
this.XmlNamespaceResolver = new XmlNamespaceManager(document.NameTable);
diff --git a/src/DotNetOpenAuth/Xrds/XrdsStrings.Designer.cs b/src/DotNetOpenAuth.OpenId/Xrds/XrdsStrings.Designer.cs
index 2279b5f..2279b5f 100644
--- a/src/DotNetOpenAuth/Xrds/XrdsStrings.Designer.cs
+++ b/src/DotNetOpenAuth.OpenId/Xrds/XrdsStrings.Designer.cs
diff --git a/src/DotNetOpenAuth/Xrds/XrdsStrings.resx b/src/DotNetOpenAuth.OpenId/Xrds/XrdsStrings.resx
index acb43f2..acb43f2 100644
--- a/src/DotNetOpenAuth/Xrds/XrdsStrings.resx
+++ b/src/DotNetOpenAuth.OpenId/Xrds/XrdsStrings.resx
diff --git a/src/DotNetOpenAuth/Xrds/XrdsStrings.sr.resx b/src/DotNetOpenAuth.OpenId/Xrds/XrdsStrings.sr.resx
index 8e2d09a..8e2d09a 100644
--- a/src/DotNetOpenAuth/Xrds/XrdsStrings.sr.resx
+++ b/src/DotNetOpenAuth.OpenId/Xrds/XrdsStrings.sr.resx
diff --git a/src/DotNetOpenAuth/Yadis/ContentTypes.cs b/src/DotNetOpenAuth.OpenId/Yadis/ContentTypes.cs
index 30745ee..30745ee 100644
--- a/src/DotNetOpenAuth/Yadis/ContentTypes.cs
+++ b/src/DotNetOpenAuth.OpenId/Yadis/ContentTypes.cs
diff --git a/src/DotNetOpenAuth/Yadis/DiscoveryResult.cs b/src/DotNetOpenAuth.OpenId/Yadis/DiscoveryResult.cs
index 06c6fc7..06c6fc7 100644
--- a/src/DotNetOpenAuth/Yadis/DiscoveryResult.cs
+++ b/src/DotNetOpenAuth.OpenId/Yadis/DiscoveryResult.cs
diff --git a/src/DotNetOpenAuth/Yadis/HtmlParser.cs b/src/DotNetOpenAuth.OpenId/Yadis/HtmlParser.cs
index a6b64c1..9002acb 100644
--- a/src/DotNetOpenAuth/Yadis/HtmlParser.cs
+++ b/src/DotNetOpenAuth.OpenId/Yadis/HtmlParser.cs
@@ -98,8 +98,8 @@ namespace DotNetOpenAuth.Yadis {
/// <param name="attribute">The attribute.</param>
/// <returns>A filtered sequence of attributes.</returns>
internal static IEnumerable<T> WithAttribute<T>(this IEnumerable<T> sequence, string attribute) where T : HtmlControl {
- Contract.Requires<ArgumentNullException>(sequence != null);
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(attribute));
+ Requires.NotNull(sequence, "sequence");
+ Requires.NotNullOrEmpty(attribute, "attribute");
return sequence.Where(tag => tag.Attributes[attribute] != null);
}
diff --git a/src/DotNetOpenAuth/Yadis/Yadis.cs b/src/DotNetOpenAuth.OpenId/Yadis/Yadis.cs
index 357dd8d..955f2f4 100644
--- a/src/DotNetOpenAuth/Yadis/Yadis.cs
+++ b/src/DotNetOpenAuth.OpenId/Yadis/Yadis.cs
@@ -32,7 +32,7 @@ namespace DotNetOpenAuth.Yadis {
#if DEBUG
internal static readonly RequestCachePolicy IdentifierDiscoveryCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.BypassCache);
#else
- internal static readonly RequestCachePolicy IdentifierDiscoveryCachePolicy = new HttpRequestCachePolicy(DotNetOpenAuthSection.Configuration.OpenId.CacheDiscovery ? HttpRequestCacheLevel.CacheIfAvailable : HttpRequestCacheLevel.BypassCache);
+ internal static readonly RequestCachePolicy IdentifierDiscoveryCachePolicy = new HttpRequestCachePolicy(OpenIdElement.Configuration.CacheDiscovery ? HttpRequestCacheLevel.CacheIfAvailable : HttpRequestCacheLevel.BypassCache);
#endif
/// <summary>
@@ -135,8 +135,8 @@ namespace DotNetOpenAuth.Yadis {
/// <param name="acceptTypes">The value of the Accept HTTP header to include in the request.</param>
/// <returns>The HTTP response retrieved from the request.</returns>
internal static IncomingWebResponse Request(IDirectWebRequestHandler requestHandler, Uri uri, bool requireSsl, params string[] acceptTypes) {
- Contract.Requires<ArgumentNullException>(requestHandler != null);
- Contract.Requires<ArgumentNullException>(uri != null);
+ Requires.NotNull(requestHandler, "requestHandler");
+ Requires.NotNull(uri, "uri");
Contract.Ensures(Contract.Result<IncomingWebResponse>() != null);
Contract.Ensures(Contract.Result<IncomingWebResponse>().ResponseStream != null);
diff --git a/src/DotNetOpenAuth.OpenIdInfoCard.UI/DotNetOpenAuth.OpenIdInfoCard.UI.csproj b/src/DotNetOpenAuth.OpenIdInfoCard.UI/DotNetOpenAuth.OpenIdInfoCard.UI.csproj
new file mode 100644
index 0000000..e0a5267
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenIdInfoCard.UI/DotNetOpenAuth.OpenIdInfoCard.UI.csproj
@@ -0,0 +1,68 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))\EnlistmentInfo.props" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))' != '' " />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" />
+ <PropertyGroup>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{3A8347E8-59A5-4092-8842-95C75D7D2F36}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>DotNetOpenAuth</RootNamespace>
+ <AssemblyName>DotNetOpenAuth.OpenIdInfoCard.UI</AssemblyName>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" />
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="OpenId\RelyingParty\OpenIdInfoCardSelector.cs" />
+ <Compile Include="OpenId\RelyingParty\SelectorInfoCardButton.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\DotNetOpenAuth.InfoCard.UI\DotNetOpenAuth.InfoCard.UI.csproj">
+ <Project>{E040EB58-B4D2-457B-A023-AE6EF3BD34DE}</Project>
+ <Name>DotNetOpenAuth.InfoCard.UI</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.InfoCard\DotNetOpenAuth.InfoCard.csproj">
+ <Project>{408D10B8-34BA-4CBD-B7AA-FEB1907ABA4C}</Project>
+ <Name>DotNetOpenAuth.InfoCard</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.Core.UI\DotNetOpenAuth.Core.UI.csproj">
+ <Project>{173E7B8D-E751-46E2-A133-F72297C0D2F4}</Project>
+ <Name>DotNetOpenAuth.Core.UI</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.Core\DotNetOpenAuth.Core.csproj">
+ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project>
+ <Name>DotNetOpenAuth.Core</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OpenId.RelyingParty.UI\DotNetOpenAuth.OpenId.RelyingParty.UI.csproj">
+ <Project>{1ED8D424-F8AB-4050-ACEB-F27F4F909484}</Project>
+ <Name>DotNetOpenAuth.OpenId.RelyingParty.UI</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OpenId.RelyingParty\DotNetOpenAuth.OpenId.RelyingParty.csproj">
+ <Project>{F458AB60-BA1C-43D9-8CEF-EC01B50BE87B}</Project>
+ <Name>DotNetOpenAuth.OpenId.RelyingParty</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OpenId.UI\DotNetOpenAuth.OpenId.UI.csproj">
+ <Project>{75E13AAE-7D51-4421-ABFD-3F3DC91F576E}</Project>
+ <Name>DotNetOpenAuth.OpenId.UI</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OpenId\DotNetOpenAuth.OpenId.csproj">
+ <Project>{3896A32A-E876-4C23-B9B8-78E17D134CD3}</Project>
+ <Name>DotNetOpenAuth.OpenId</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\Org.Mentalis.Security.Cryptography\Org.Mentalis.Security.Cryptography.csproj">
+ <Project>{26DC877F-5987-48DD-9DDB-E62F2DE0E150}</Project>
+ <Name>Org.Mentalis.Security.Cryptography</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
+</Project> \ No newline at end of file
diff --git a/src/DotNetOpenAuth.OpenIdInfoCard.UI/OpenId/RelyingParty/OpenIdInfoCardSelector.cs b/src/DotNetOpenAuth.OpenIdInfoCard.UI/OpenId/RelyingParty/OpenIdInfoCardSelector.cs
new file mode 100644
index 0000000..8eb399b
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenIdInfoCard.UI/OpenId/RelyingParty/OpenIdInfoCardSelector.cs
@@ -0,0 +1,125 @@
+//-----------------------------------------------------------------------
+// <copyright file="OpenIdInfoCardSelector.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+[assembly: System.Web.UI.WebResource(DotNetOpenAuth.OpenId.RelyingParty.OpenIdSelector.EmbeddedScriptResourceName, "text/javascript")]
+[assembly: System.Web.UI.WebResource(DotNetOpenAuth.OpenId.RelyingParty.OpenIdSelector.EmbeddedStylesheetResourceName, "text/css")]
+
+namespace DotNetOpenAuth.OpenId.RelyingParty {
+ using System;
+ using System.Collections.Generic;
+ using System.Collections.ObjectModel;
+ using System.ComponentModel;
+ using System.Diagnostics.Contracts;
+ using System.Globalization;
+ using System.IdentityModel.Claims;
+ using System.Linq;
+ using System.Text;
+ using System.Web;
+ using System.Web.UI;
+ using System.Web.UI.HtmlControls;
+ using System.Web.UI.WebControls;
+ using DotNetOpenAuth.ComponentModel;
+ using DotNetOpenAuth.InfoCard;
+ ////using DotNetOpenAuth.InfoCard;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// An ASP.NET control that provides a user-friendly way of logging into a web site using OpenID.
+ /// </summary>
+ [ToolboxData("<{0}:OpenIdSelector runat=\"server\"></{0}:OpenIdSelector>")]
+ public class OpenIdInfoCardSelector : OpenIdSelector {
+ /// <summary>
+ /// The InfoCard selector button.
+ /// </summary>
+ private SelectorInfoCardButton selectorButton;
+
+ /// <summary>
+ /// Occurs when an InfoCard has been submitted and decoded.
+ /// </summary>
+ public event EventHandler<ReceivedTokenEventArgs> ReceivedToken;
+
+ /// <summary>
+ /// Occurs when [token processing error].
+ /// </summary>
+ public event EventHandler<TokenProcessingErrorEventArgs> TokenProcessingError;
+
+ /// <summary>
+ /// Ensures that the child controls have been built, but doesn't set control
+ /// properties that require executing <see cref="Control.EnsureID"/> in order to avoid
+ /// certain initialization order problems.
+ /// </summary>
+ /// <remarks>
+ /// We don't just call EnsureChildControls() and then set the property on
+ /// this.textBox itself because (apparently) setting this property in the ASPX
+ /// page and thus calling this EnsureID() via EnsureChildControls() this early
+ /// results in no ID.
+ /// </remarks>
+ protected override void EnsureChildControlsAreCreatedSafe() {
+ if (this.selectorButton == null) {
+ this.selectorButton = this.Buttons.OfType<SelectorInfoCardButton>().FirstOrDefault();
+ if (this.selectorButton != null) {
+ var selector = this.selectorButton.InfoCardSelector;
+ selector.ClaimsRequested.Add(new ClaimType { Name = ClaimTypes.PPID });
+ selector.ImageSize = InfoCardImageSize.Size60x42;
+ selector.ReceivedToken += this.InfoCardSelector_ReceivedToken;
+ selector.TokenProcessingError += this.InfoCardSelector_TokenProcessingError;
+ this.Controls.Add(selector);
+ }
+ }
+
+ base.EnsureChildControlsAreCreatedSafe();
+ }
+
+ /// <summary>
+ /// Fires the <see cref="ReceivedToken"/> event.
+ /// </summary>
+ /// <param name="e">The token, if it was decrypted.</param>
+ protected virtual void OnReceivedToken(ReceivedTokenEventArgs e) {
+ Contract.Requires(e != null);
+ ErrorUtilities.VerifyArgumentNotNull(e, "e");
+
+ var receivedInfoCard = this.ReceivedToken;
+ if (receivedInfoCard != null) {
+ receivedInfoCard(this, e);
+ }
+ }
+
+ /// <summary>
+ /// Raises the <see cref="E:TokenProcessingError"/> event.
+ /// </summary>
+ /// <param name="e">The <see cref="DotNetOpenAuth.InfoCard.TokenProcessingErrorEventArgs"/> instance containing the event data.</param>
+ protected virtual void OnTokenProcessingError(TokenProcessingErrorEventArgs e) {
+ Contract.Requires(e != null);
+ ErrorUtilities.VerifyArgumentNotNull(e, "e");
+
+ var tokenProcessingError = this.TokenProcessingError;
+ if (tokenProcessingError != null) {
+ tokenProcessingError(this, e);
+ }
+ }
+
+ /// <summary>
+ /// Handles the ReceivedToken event of the infoCardSelector control.
+ /// </summary>
+ /// <param name="sender">The source of the event.</param>
+ /// <param name="e">The <see cref="DotNetOpenAuth.InfoCard.ReceivedTokenEventArgs"/> instance containing the event data.</param>
+ private void InfoCardSelector_ReceivedToken(object sender, ReceivedTokenEventArgs e) {
+ this.Page.Response.SetCookie(new HttpCookie("openid_identifier", "infocard") {
+ Path = this.Page.Request.ApplicationPath,
+ });
+ this.OnReceivedToken(e);
+ }
+
+ /// <summary>
+ /// Handles the TokenProcessingError event of the infoCardSelector control.
+ /// </summary>
+ /// <param name="sender">The source of the event.</param>
+ /// <param name="e">The <see cref="DotNetOpenAuth.InfoCard.TokenProcessingErrorEventArgs"/> instance containing the event data.</param>
+ private void InfoCardSelector_TokenProcessingError(object sender, TokenProcessingErrorEventArgs e) {
+ this.OnTokenProcessingError(e);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/SelectorInfoCardButton.cs b/src/DotNetOpenAuth.OpenIdInfoCard.UI/OpenId/RelyingParty/SelectorInfoCardButton.cs
index c5dda1c..863c90a 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/SelectorInfoCardButton.cs
+++ b/src/DotNetOpenAuth.OpenIdInfoCard.UI/OpenId/RelyingParty/SelectorInfoCardButton.cs
@@ -43,7 +43,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
}
set {
- Contract.Requires<ArgumentNullException>(value != null);
+ Requires.NotNull(value, "value");
if (this.infoCardSelector != null) {
Logger.Library.WarnFormat("{0}.InfoCardSelector property is being set multiple times.", GetType().Name);
}
diff --git a/src/DotNetOpenAuth.OpenIdInfoCard.UI/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth.OpenIdInfoCard.UI/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..8700856
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenIdInfoCard.UI/Properties/AssemblyInfo.cs
@@ -0,0 +1,84 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssemblyInfo.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+// We DON'T put an AssemblyVersionAttribute in here because it is generated in the build.
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Net;
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Security.Permissions;
+using System.Web.UI;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("DotNetOpenAuth")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DotNetOpenAuth")]
+[assembly: AssemblyCopyright("Copyright © 2008")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+[assembly: NeutralResourcesLanguage("en-US")]
+[assembly: CLSCompliant(true)]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("7d73990c-47c0-4256-9f20-a893add9e289")]
+
+[assembly: ContractVerification(true)]
+
+#if StrongNameSigned
+// See comment at top of this file. We need this so that strong-naming doesn't
+// keep this assembly from being useful to shared host (medium trust) web sites.
+[assembly: AllowPartiallyTrustedCallers]
+
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.InfoCard, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.InfoCard.UI, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.UI, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.RelyingParty, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.RelyingParty.UI, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider.UI, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth.Consumer, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth.ServiceProvider, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2.AuthorizationServer, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2.ResourceServer, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2.Client, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
+#else
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.InfoCard")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.InfoCard.UI")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.UI")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.RelyingParty")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.RelyingParty.UI")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider.UI")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth.Consumer")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth.ServiceProvider")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2.AuthorizationServer")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2.ResourceServer")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2.Client")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
+#endif
diff --git a/src/DotNetOpenAuth.Test/App.config b/src/DotNetOpenAuth.Test/App.config
index b3da723..d0eb34e 100644
--- a/src/DotNetOpenAuth.Test/App.config
+++ b/src/DotNetOpenAuth.Test/App.config
@@ -2,7 +2,12 @@
<configuration>
<configSections>
<section name="uri" type="System.Configuration.UriSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
- <section name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth"/>
+ <sectionGroup name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth.Core">
+ <section name="openid" type="DotNetOpenAuth.Configuration.OpenIdElement, DotNetOpenAuth.OpenId" requirePermission="false" allowLocation="true" />
+ <section name="oauth" type="DotNetOpenAuth.Configuration.OAuthElement, DotNetOpenAuth.OAuth" requirePermission="false" allowLocation="true" />
+ <section name="messaging" type="DotNetOpenAuth.Configuration.MessagingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
+ <section name="reporting" type="DotNetOpenAuth.Configuration.ReportingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
+ </sectionGroup>
</configSections>
<!-- The uri section is necessary to turn on .NET 3.5 support for IDN (international domain names),
diff --git a/src/DotNetOpenAuth.Test/Configuration/SectionTests.cs b/src/DotNetOpenAuth.Test/Configuration/SectionTests.cs
index e423053..0cff4b7 100644
--- a/src/DotNetOpenAuth.Test/Configuration/SectionTests.cs
+++ b/src/DotNetOpenAuth.Test/Configuration/SectionTests.cs
@@ -15,7 +15,7 @@ namespace DotNetOpenAuth.Test.Configuration {
public class SectionTests {
[TestCase]
public void UntrustedWebRequest() {
- var uwr = DotNetOpenAuthSection.Configuration.Messaging.UntrustedWebRequest;
+ var uwr = DotNetOpenAuthSection.Messaging.UntrustedWebRequest;
Assert.AreEqual(TimeSpan.Parse("01:23:45"), uwr.Timeout);
Assert.AreEqual(TimeSpan.Parse("01:23:56"), uwr.ReadWriteTimeout);
@@ -31,12 +31,12 @@ namespace DotNetOpenAuth.Test.Configuration {
[TestCase]
public void OpenIdMaxAuthenticationTime() {
- Assert.AreEqual(TimeSpan.Parse("00:08:17"), DotNetOpenAuthSection.Configuration.OpenId.MaxAuthenticationTime);
+ Assert.AreEqual(TimeSpan.Parse("00:08:17"), OpenIdElement.Configuration.MaxAuthenticationTime);
}
[TestCase]
public void OpenIdRelyingParty() {
- var rp = DotNetOpenAuthSection.Configuration.OpenId.RelyingParty;
+ var rp = OpenIdElement.Configuration.RelyingParty;
Assert.IsNull(rp.ApplicationStore.CustomType);
Assert.AreEqual(ProtocolVersion.V10, rp.SecuritySettings.MinimumRequiredOpenIdVersion);
@@ -47,7 +47,7 @@ namespace DotNetOpenAuth.Test.Configuration {
[TestCase]
public void OpenIdProvider() {
- var op = DotNetOpenAuthSection.Configuration.OpenId.Provider;
+ var op = OpenIdElement.Configuration.Provider;
Assert.IsNull(op.ApplicationStore.CustomType);
Assert.IsTrue(op.SecuritySettings.ProtectDownlevelReplayAttacks);
diff --git a/src/DotNetOpenAuth.Test/CoordinatorBase.cs b/src/DotNetOpenAuth.Test/CoordinatorBase.cs
index f25964c..84d0ff1 100644
--- a/src/DotNetOpenAuth.Test/CoordinatorBase.cs
+++ b/src/DotNetOpenAuth.Test/CoordinatorBase.cs
@@ -18,8 +18,8 @@ namespace DotNetOpenAuth.Test {
private Action<T2> party2Action;
protected CoordinatorBase(Action<T1> party1Action, Action<T2> party2Action) {
- Contract.Requires<ArgumentNullException>(party1Action != null);
- Contract.Requires<ArgumentNullException>(party2Action != null);
+ Requires.NotNull(party1Action, "party1Action");
+ Requires.NotNull(party2Action, "party2Action");
this.party1Action = party1Action;
this.party2Action = party2Action;
diff --git a/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj
index 2067ede..46556f7 100644
--- a/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj
+++ b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj
@@ -5,7 +5,7 @@
<ProjectRoot Condition="'$(ProjectRoot)' == ''">$(MSBuildProjectDirectory)\..\..\</ProjectRoot>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
- <CodeContractsAssemblyMode>1</CodeContractsAssemblyMode>
+ <CodeContractsAssemblyMode>0</CodeContractsAssemblyMode>
</PropertyGroup>
<Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" />
<PropertyGroup>
@@ -44,7 +44,7 @@
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
- <CodeContractsEnableRuntimeChecking>True</CodeContractsEnableRuntimeChecking>
+ <CodeContractsEnableRuntimeChecking>False</CodeContractsEnableRuntimeChecking>
<CodeContractsCustomRewriterAssembly>
</CodeContractsCustomRewriterAssembly>
<CodeContractsCustomRewriterClass>
@@ -75,6 +75,10 @@
<CodeContractsExtraRewriteOptions />
<CodeContractsReferenceAssembly>%28none%29</CodeContractsReferenceAssembly>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+ <CodeContractsRuntimeSkipQuantifiers>False</CodeContractsRuntimeSkipQuantifiers>
+ <CodeContractsEnumObligations>False</CodeContractsEnumObligations>
+ <CodeContractsCacheAnalysisResults>False</CodeContractsCacheAnalysisResults>
+ <CodeContractsAnalysisWarningLevel>0</CodeContractsAnalysisWarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
@@ -82,12 +86,12 @@
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
- <CodeContractsEnableRuntimeChecking>True</CodeContractsEnableRuntimeChecking>
+ <CodeContractsEnableRuntimeChecking>False</CodeContractsEnableRuntimeChecking>
<CodeContractsCustomRewriterAssembly>
</CodeContractsCustomRewriterAssembly>
<CodeContractsCustomRewriterClass>
</CodeContractsCustomRewriterClass>
- <CodeContractsRuntimeCheckingLevel>None</CodeContractsRuntimeCheckingLevel>
+ <CodeContractsRuntimeCheckingLevel>Full</CodeContractsRuntimeCheckingLevel>
<CodeContractsRuntimeOnlyPublicSurface>False</CodeContractsRuntimeOnlyPublicSurface>
<CodeContractsRuntimeThrowOnFailure>True</CodeContractsRuntimeThrowOnFailure>
<CodeContractsRuntimeCallSiteRequires>False</CodeContractsRuntimeCallSiteRequires>
@@ -113,6 +117,10 @@
<CodeContractsExtraRewriteOptions />
<CodeContractsReferenceAssembly>%28none%29</CodeContractsReferenceAssembly>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+ <CodeContractsRuntimeSkipQuantifiers>False</CodeContractsRuntimeSkipQuantifiers>
+ <CodeContractsEnumObligations>False</CodeContractsEnumObligations>
+ <CodeContractsCacheAnalysisResults>False</CodeContractsCacheAnalysisResults>
+ <CodeContractsAnalysisWarningLevel>0</CodeContractsAnalysisWarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'CodeAnalysis|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@@ -173,7 +181,9 @@
<Reference Include="System.ServiceModel">
<RequiredTargetFramework>3.0</RequiredTargetFramework>
</Reference>
+ <Reference Include="System.ServiceModel.Web" />
<Reference Include="System.Web" />
+ <Reference Include="System.Web.Abstractions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" Condition=" '$(ClrVersion)' == '2' " />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
@@ -204,10 +214,12 @@
<Compile Include="Messaging\Bindings\StandardExpirationBindingElementTests.cs" />
<Compile Include="Messaging\Reflection\MessagePartTests.cs" />
<Compile Include="Messaging\Reflection\ValueMappingTests.cs" />
+ <Compile Include="Messaging\StandardMessageFactoryTests.cs" />
<Compile Include="Mocks\AssociateUnencryptedRequestNoSslCheck.cs" />
<Compile Include="Mocks\CoordinatingChannel.cs" />
<Compile Include="Mocks\CoordinatingHttpRequestInfo.cs" />
<Compile Include="Mocks\CoordinatingOutgoingWebResponse.cs" />
+ <Compile Include="Mocks\CoordinatingOAuthConsumerChannel.cs" />
<Compile Include="Mocks\InMemoryTokenManager.cs" />
<Compile Include="Mocks\MockHttpRequest.cs" />
<Compile Include="Mocks\MockIdentifier.cs" />
@@ -229,6 +241,9 @@
<Compile Include="Mocks\TestChannel.cs" />
<Compile Include="Mocks\TestMessage.cs" />
<Compile Include="Mocks\TestMessageFactory.cs" />
+ <Compile Include="OAuth2\MessageFactoryTests.cs" />
+ <Compile Include="OAuth2\OAuth2ChannelTests.cs" />
+ <Compile Include="OAuth2\OAuth2TestBase.cs" />
<Compile Include="OAuth\ChannelElements\HmacSha1SigningBindingElementTests.cs" />
<Compile Include="OAuth\ChannelElements\OAuthChannelTests.cs" />
<Compile Include="OAuth\ChannelElements\PlaintextSigningBindingElementTest.cs" />
@@ -238,7 +253,7 @@
<Compile Include="OAuth\ProtocolTests.cs" />
<Compile Include="OAuth\ServiceProviderDescriptionTests.cs" />
<Compile Include="OAuth\ServiceProviderTests.cs" />
- <Compile Include="OpenId\AssociationsTests.cs" />
+ <Compile Include="OpenId\RelyingParty\AssociationsTests.cs" />
<Compile Include="OpenId\AssociationTests.cs" />
<Compile Include="OpenId\AuthenticationTests.cs" />
<Compile Include="OpenId\ChannelElements\ExtensionsBindingElementTests.cs" />
@@ -310,7 +325,7 @@
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Messaging\ResponseTests.cs" />
<Compile Include="OAuth\AppendixScenarios.cs" />
- <Compile Include="Mocks\CoordinatingOAuthChannel.cs" />
+ <Compile Include="Mocks\CoordinatingOAuthServiceProviderChannel.cs" />
<Compile Include="OAuth\OAuthCoordinator.cs" />
<Compile Include="TestBase.cs" />
<Compile Include="TestUtilities.cs" />
@@ -318,12 +333,6 @@
<Compile Include="UtilTests.cs" />
</ItemGroup>
<ItemGroup>
- <ProjectReference Include="..\DotNetOpenAuth\DotNetOpenAuth.csproj">
- <Project>{3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}</Project>
- <Name>DotNetOpenAuth</Name>
- </ProjectReference>
- </ItemGroup>
- <ItemGroup>
<EmbeddedResource Include="Logging.config" />
</ItemGroup>
<ItemGroup>
@@ -359,6 +368,7 @@
<EmbeddedResource Include="OpenId\Discovery\xrdsdiscovery\xrds20dual.xml" />
</ItemGroup>
<ItemGroup>
+ <Folder Include="OAuth2\ChannelElements\" />
<Folder Include="OpenId\UI\" />
</ItemGroup>
<ItemGroup>
@@ -389,7 +399,89 @@
<ItemGroup>
<EmbeddedResource Include="OpenId\Discovery\htmldiscovery\html20provWithBadXrds.html" />
</ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\DotNetOpenAuth.InfoCard.UI\DotNetOpenAuth.InfoCard.UI.csproj">
+ <Project>{E040EB58-B4D2-457B-A023-AE6EF3BD34DE}</Project>
+ <Name>DotNetOpenAuth.InfoCard.UI</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.InfoCard\DotNetOpenAuth.InfoCard.csproj">
+ <Project>{408D10B8-34BA-4CBD-B7AA-FEB1907ABA4C}</Project>
+ <Name>DotNetOpenAuth.InfoCard</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.Core.UI\DotNetOpenAuth.Core.UI.csproj">
+ <Project>{173E7B8D-E751-46E2-A133-F72297C0D2F4}</Project>
+ <Name>DotNetOpenAuth.Core.UI</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.Core\DotNetOpenAuth.Core.csproj">
+ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project>
+ <Name>DotNetOpenAuth.Core</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OAuth.Consumer\DotNetOpenAuth.OAuth.Consumer.csproj">
+ <Project>{B202E40D-4663-4A2B-ACDA-865F88FF7CAA}</Project>
+ <Name>DotNetOpenAuth.OAuth.Consumer</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OAuth.ServiceProvider\DotNetOpenAuth.OAuth.ServiceProvider.csproj">
+ <Project>{FED1923A-6D70-49B5-A37A-FB744FEC1C86}</Project>
+ <Name>DotNetOpenAuth.OAuth.ServiceProvider</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OAuth2.AuthorizationServer\DotNetOpenAuth.OAuth2.AuthorizationServer.csproj">
+ <Project>{99BB7543-EA16-43EE-A7BC-D7A25A3B22F6}</Project>
+ <Name>DotNetOpenAuth.OAuth2.AuthorizationServer</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OAuth2.Client.UI\DotNetOpenAuth.OAuth2.Client.UI.csproj">
+ <Project>{ADC2CC8C-541E-4F86-ACB1-DD504A36FA4B}</Project>
+ <Name>DotNetOpenAuth.OAuth2.Client.UI</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OAuth2.Client\DotNetOpenAuth.OAuth2.Client.csproj">
+ <Project>{CDEDD439-7F35-4E6E-8605-4E70BDC4CC99}</Project>
+ <Name>DotNetOpenAuth.OAuth2.Client</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OAuth2.ResourceServer\DotNetOpenAuth.OAuth2.ResourceServer.csproj">
+ <Project>{A1A3150A-7B0E-4A34-8E35-045296CD3C76}</Project>
+ <Name>DotNetOpenAuth.OAuth2.ResourceServer</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OAuth2\DotNetOpenAuth.OAuth2.csproj">
+ <Project>{56459A6C-6BA2-4BAC-A9C0-27E3BD961FA6}</Project>
+ <Name>DotNetOpenAuth.OAuth2</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OAuth\DotNetOpenAuth.OAuth.csproj">
+ <Project>{A288FCC8-6FCF-46DA-A45E-5F9281556361}</Project>
+ <Name>DotNetOpenAuth.OAuth</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OpenId.Provider.UI\DotNetOpenAuth.OpenId.Provider.UI.csproj">
+ <Project>{9D0F8866-2131-4C2A-BC0E-16FEA5B50828}</Project>
+ <Name>DotNetOpenAuth.OpenId.Provider.UI</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OpenId.Provider\DotNetOpenAuth.OpenId.Provider.csproj">
+ <Project>{F8284738-3B5D-4733-A511-38C23F4A763F}</Project>
+ <Name>DotNetOpenAuth.OpenId.Provider</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OpenId.RelyingParty.UI\DotNetOpenAuth.OpenId.RelyingParty.UI.csproj">
+ <Project>{1ED8D424-F8AB-4050-ACEB-F27F4F909484}</Project>
+ <Name>DotNetOpenAuth.OpenId.RelyingParty.UI</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OpenId.RelyingParty\DotNetOpenAuth.OpenId.RelyingParty.csproj">
+ <Project>{F458AB60-BA1C-43D9-8CEF-EC01B50BE87B}</Project>
+ <Name>DotNetOpenAuth.OpenId.RelyingParty</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OpenId.UI\DotNetOpenAuth.OpenId.UI.csproj">
+ <Project>{75E13AAE-7D51-4421-ABFD-3F3DC91F576E}</Project>
+ <Name>DotNetOpenAuth.OpenId.UI</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\DotNetOpenAuth.OpenId\DotNetOpenAuth.OpenId.csproj">
+ <Project>{3896A32A-E876-4C23-B9B8-78E17D134CD3}</Project>
+ <Name>DotNetOpenAuth.OpenId</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\Mono.Math\Mono.Math.csproj">
+ <Project>{F4CD3C04-6037-4946-B7A5-34BFC96A75D2}</Project>
+ <Name>Mono.Math</Name>
+ </ProjectReference>
+ <ProjectReference Include="..\Org.Mentalis.Security.Cryptography\Org.Mentalis.Security.Cryptography.csproj">
+ <Project>{26DC877F-5987-48DD-9DDB-E62F2DE0E150}</Project>
+ <Name>Org.Mentalis.Security.Cryptography</Name>
+ </ProjectReference>
+ </ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
-</Project> \ No newline at end of file
+</Project>
diff --git a/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs b/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs
index 84b6654..2c3cae2 100644
--- a/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs
+++ b/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs
@@ -35,7 +35,7 @@ namespace DotNetOpenAuth.Test.Messaging.Bindings {
[TestCase]
public void VerifyFutureTimestampWithinClockSkewIsAccepted() {
this.Channel = CreateChannel(MessageProtections.Expiration);
- this.ParameterizedReceiveProtectedTest(DateTime.UtcNow + DotNetOpenAuthSection.Configuration.Messaging.MaximumClockSkew - TimeSpan.FromSeconds(1), false);
+ this.ParameterizedReceiveProtectedTest(DateTime.UtcNow + DotNetOpenAuthSection.Messaging.MaximumClockSkew - TimeSpan.FromSeconds(1), false);
}
[TestCase, ExpectedException(typeof(ExpiredMessageException))]
@@ -47,7 +47,7 @@ namespace DotNetOpenAuth.Test.Messaging.Bindings {
[TestCase, ExpectedException(typeof(ProtocolException))]
public void VerifyFutureTimestampIsRejected() {
this.Channel = CreateChannel(MessageProtections.Expiration);
- this.ParameterizedReceiveProtectedTest(DateTime.UtcNow + DotNetOpenAuthSection.Configuration.Messaging.MaximumClockSkew + TimeSpan.FromSeconds(2), false);
+ this.ParameterizedReceiveProtectedTest(DateTime.UtcNow + DotNetOpenAuthSection.Messaging.MaximumClockSkew + TimeSpan.FromSeconds(2), false);
}
}
}
diff --git a/src/DotNetOpenAuth.Test/Messaging/CollectionAssert.cs b/src/DotNetOpenAuth.Test/Messaging/CollectionAssert.cs
index 506a6b2..af542db 100644
--- a/src/DotNetOpenAuth.Test/Messaging/CollectionAssert.cs
+++ b/src/DotNetOpenAuth.Test/Messaging/CollectionAssert.cs
@@ -15,8 +15,8 @@ namespace DotNetOpenAuth.Test.Messaging {
internal class CollectionAssert<T> {
internal static void AreEquivalent(ICollection<T> expected, ICollection<T> actual) {
- Contract.Requires<ArgumentNullException>(expected != null);
- Contract.Requires<ArgumentNullException>(actual != null);
+ Requires.NotNull(expected, "expected");
+ Requires.NotNull(actual, "actual");
ICollection expectedNonGeneric = new List<T>(expected);
ICollection actualNonGeneric = new List<T>(actual);
@@ -24,8 +24,8 @@ namespace DotNetOpenAuth.Test.Messaging {
}
internal static void AreEquivalentByEquality(ICollection<T> expected, ICollection<T> actual) {
- Contract.Requires<ArgumentNullException>(expected != null);
- Contract.Requires<ArgumentNullException>(actual != null);
+ Requires.NotNull(expected, "expected");
+ Requires.NotNull(actual, "actual");
Assert.AreEqual(expected.Count, actual.Count);
foreach (T value in expected) {
@@ -34,7 +34,7 @@ namespace DotNetOpenAuth.Test.Messaging {
}
internal static void Contains(IEnumerable<T> sequence, T element) {
- Contract.Requires<ArgumentNullException>(sequence != null);
+ Requires.NotNull(sequence, "sequence");
if (!sequence.Contains(element)) {
Assert.Fail("Sequence did not include expected element '{0}'.", element);
diff --git a/src/DotNetOpenAuth.Test/Messaging/MessageSerializerTests.cs b/src/DotNetOpenAuth.Test/Messaging/MessageSerializerTests.cs
index 91cccf1..07743e1 100644
--- a/src/DotNetOpenAuth.Test/Messaging/MessageSerializerTests.cs
+++ b/src/DotNetOpenAuth.Test/Messaging/MessageSerializerTests.cs
@@ -7,6 +7,9 @@
namespace DotNetOpenAuth.Test.Messaging {
using System;
using System.Collections.Generic;
+ using System.IO;
+ using System.Runtime.Serialization.Json;
+ using System.Text;
using System.Xml;
using DotNetOpenAuth.Messaging;
using NUnit.Framework;
@@ -52,10 +55,38 @@ namespace DotNetOpenAuth.Test.Messaging {
Assert.IsFalse(actual.ContainsKey("EmptyMember"));
}
+ /// <summary>
+ /// Verifies JSON serialization
+ /// </summary>
+ [TestCase]
+ public void SerializeDeserializeJson() {
+ var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
+ var message = GetStandardTestMessage(FieldFill.CompleteBeforeBindings);
+
+ var ms = new MemoryStream();
+ var writer = JsonReaderWriterFactory.CreateJsonWriter(ms, Encoding.UTF8);
+ MessageSerializer.Serialize(this.MessageDescriptions.GetAccessor(message), writer);
+ writer.Flush();
+
+ string actual = Encoding.UTF8.GetString(ms.ToArray());
+ string expected = @"{""age"":15,""Name"":""Andrew"",""Location"":""http:\/\/localtest\/path"",""Timestamp"":""2008-09-19T08:00:00Z""}";
+ Assert.AreEqual(expected, actual);
+
+ ms.Position = 0;
+ var deserialized = new Mocks.TestDirectedMessage();
+ var reader = JsonReaderWriterFactory.CreateJsonReader(ms, XmlDictionaryReaderQuotas.Max);
+ MessageSerializer.Deserialize(this.MessageDescriptions.GetAccessor(deserialized), reader);
+ Assert.AreEqual(message.Age, deserialized.Age);
+ Assert.AreEqual(message.EmptyMember, deserialized.EmptyMember);
+ Assert.AreEqual(message.Location, deserialized.Location);
+ Assert.AreEqual(message.Name, deserialized.Name);
+ Assert.AreEqual(message.Timestamp, deserialized.Timestamp);
+ }
+
[TestCase, ExpectedException(typeof(ArgumentNullException))]
public void DeserializeNull() {
var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
- serializer.Deserialize(null, null);
+ MessageSerializer.Deserialize(null, null);
}
[TestCase]
diff --git a/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs b/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs
index 33970a5..2a683ed 100644
--- a/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs
+++ b/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs
@@ -98,7 +98,7 @@ namespace DotNetOpenAuth.Test.Messaging {
[TestCase, ExpectedException(typeof(ArgumentNullException))]
public void ApplyHeadersToResponseNullAspNetResponse() {
- MessagingUtilities.ApplyHeadersToResponse(new WebHeaderCollection(), (HttpResponse)null);
+ MessagingUtilities.ApplyHeadersToResponse(new WebHeaderCollection(), (HttpResponseBase)null);
}
[TestCase, ExpectedException(typeof(ArgumentNullException))]
@@ -108,7 +108,7 @@ namespace DotNetOpenAuth.Test.Messaging {
[TestCase, ExpectedException(typeof(ArgumentNullException))]
public void ApplyHeadersToResponseNullHeaders() {
- MessagingUtilities.ApplyHeadersToResponse(null, new HttpResponse(new StringWriter()));
+ MessagingUtilities.ApplyHeadersToResponse(null, new HttpResponseWrapper(new HttpResponse(new StringWriter())));
}
[TestCase]
@@ -116,7 +116,7 @@ namespace DotNetOpenAuth.Test.Messaging {
var headers = new WebHeaderCollection();
headers[HttpResponseHeader.ContentType] = "application/binary";
- var response = new HttpResponse(new StringWriter());
+ var response = new HttpResponseWrapper(new HttpResponse(new StringWriter()));
MessagingUtilities.ApplyHeadersToResponse(headers, response);
Assert.AreEqual(headers[HttpResponseHeader.ContentType], response.ContentType);
@@ -217,6 +217,18 @@ namespace DotNetOpenAuth.Test.Messaging {
MessagingUtilities.GetHttpDeliveryMethod("UNRECOGNIZED");
}
+ [TestCase]
+ public void EncryptDecrypt() {
+ const string PlainText = "Hi folks!";
+ byte[] key = MessagingUtilities.GetCryptoRandomData(128 / 8);
+ var cipher = MessagingUtilities.Encrypt(PlainText, key);
+
+ Console.WriteLine("Encrypted \"{0}\" ({1} length) to {2} encrypted bytes.", PlainText, PlainText.Length, cipher.Length);
+
+ string roundTripped = MessagingUtilities.Decrypt(cipher, key);
+ Assert.AreEqual(PlainText, roundTripped);
+ }
+
/// <summary>
/// Verifies that the time-independent string equality check works accurately.
/// </summary>
diff --git a/src/DotNetOpenAuth.Test/Messaging/Reflection/MessageDescriptionTests.cs b/src/DotNetOpenAuth.Test/Messaging/Reflection/MessageDescriptionTests.cs
index e57df65..92f39cc 100644
--- a/src/DotNetOpenAuth.Test/Messaging/Reflection/MessageDescriptionTests.cs
+++ b/src/DotNetOpenAuth.Test/Messaging/Reflection/MessageDescriptionTests.cs
@@ -73,6 +73,16 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection {
Assert.IsTrue(v30.Mapping["OptionalIn10RequiredIn25AndLater"].IsRequired);
}
+ /// <summary>
+ /// Verifies that the constructors cache is properly initialized.
+ /// </summary>
+ [TestCase]
+ public void CtorsCache() {
+ var message = new MessageDescription(typeof(MultiVersionMessage), new Version(1, 0));
+ Assert.IsNotNull(message.Constructors);
+ Assert.AreEqual(1, message.Constructors.Length);
+ }
+
private class MultiVersionMessage : Mocks.TestBaseMessage {
#pragma warning disable 0649 // these fields are never written to, but part of the test
[MessagePart]
diff --git a/src/DotNetOpenAuth.Test/Messaging/ResponseTests.cs b/src/DotNetOpenAuth.Test/Messaging/ResponseTests.cs
index 63be45a..037a68e 100644
--- a/src/DotNetOpenAuth.Test/Messaging/ResponseTests.cs
+++ b/src/DotNetOpenAuth.Test/Messaging/ResponseTests.cs
@@ -14,13 +14,13 @@ namespace DotNetOpenAuth.Test.Messaging {
[TestFixture]
public class ResponseTests : TestBase {
[TestCase, ExpectedException(typeof(InvalidOperationException))]
- public void SendWithoutAspNetContext() {
+ public void RespondWithoutAspNetContext() {
HttpContext.Current = null;
- new OutgoingWebResponse().Send();
+ new OutgoingWebResponse().Respond();
}
[TestCase]
- public void Send() {
+ public void Respond() {
StringWriter writer = new StringWriter();
HttpRequest httpRequest = new HttpRequest("file", "http://server", string.Empty);
HttpResponse httpResponse = new HttpResponse(writer);
@@ -31,7 +31,7 @@ namespace DotNetOpenAuth.Test.Messaging {
response.Status = System.Net.HttpStatusCode.OK;
response.Headers["someHeaderName"] = "someHeaderValue";
response.Body = "some body";
- response.Send();
+ response.Respond();
string results = writer.ToString();
// For some reason the only output in test is the body... the headers require a web host
Assert.AreEqual(response.Body, results);
diff --git a/src/DotNetOpenAuth.Test/Messaging/StandardMessageFactoryTests.cs b/src/DotNetOpenAuth.Test/Messaging/StandardMessageFactoryTests.cs
new file mode 100644
index 0000000..2b0b4e7
--- /dev/null
+++ b/src/DotNetOpenAuth.Test/Messaging/StandardMessageFactoryTests.cs
@@ -0,0 +1,178 @@
+//-----------------------------------------------------------------------
+// <copyright file="StandardMessageFactoryTests.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Test.Messaging {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Reflection;
+ using DotNetOpenAuth.Test.Mocks;
+ using NUnit.Framework;
+
+ [TestFixture]
+ public class StandardMessageFactoryTests : MessagingTestBase {
+ private static readonly Version V1 = new Version(1, 0);
+ private static readonly MessageReceivingEndpoint receiver = new MessageReceivingEndpoint("http://receiver", HttpDeliveryMethods.PostRequest);
+
+ private StandardMessageFactory factory;
+
+ public override void SetUp() {
+ base.SetUp();
+
+ this.factory = new StandardMessageFactory();
+ }
+
+ /// <summary>
+ /// Verifies that AddMessageTypes throws the appropriate exception on null input.
+ /// </summary>
+ [TestCase, ExpectedException(typeof(ArgumentNullException))]
+ public void AddMessageTypesNull() {
+ this.factory.AddMessageTypes(null);
+ }
+
+ /// <summary>
+ /// Verifies that AddMessageTypes throws the appropriate exception on null input.
+ /// </summary>
+ [TestCase, ExpectedException(typeof(ArgumentException))]
+ public void AddMessageTypesNullMessageDescription() {
+ this.factory.AddMessageTypes(new MessageDescription[] { null });
+ }
+
+ /// <summary>
+ /// Verifies very simple recognition of a single message type
+ /// </summary>
+ [TestCase]
+ public void SingleRequestMessageType() {
+ this.factory.AddMessageTypes(new MessageDescription[] { MessageDescriptions.Get(typeof(RequestMessageMock), V1) });
+ var fields = new Dictionary<string, string> {
+ { "random", "bits" },
+ };
+ Assert.IsNull(this.factory.GetNewRequestMessage(receiver, fields));
+ fields["Age"] = "18";
+ Assert.IsInstanceOf(typeof(RequestMessageMock), this.factory.GetNewRequestMessage(receiver, fields));
+ }
+
+ /// <summary>
+ /// Verifies very simple recognition of a single message type
+ /// </summary>
+ [TestCase]
+ public void SingleResponseMessageType() {
+ this.factory.AddMessageTypes(new MessageDescription[] { MessageDescriptions.Get(typeof(DirectResponseMessageMock), V1) });
+ var fields = new Dictionary<string, string> {
+ { "random", "bits" },
+ };
+ IDirectedProtocolMessage request = new RequestMessageMock(receiver.Location, V1);
+ Assert.IsNull(this.factory.GetNewResponseMessage(request, fields));
+ fields["Age"] = "18";
+ IDirectResponseProtocolMessage response = this.factory.GetNewResponseMessage(request, fields);
+ Assert.IsInstanceOf<DirectResponseMessageMock>(response);
+ Assert.AreSame(request, response.OriginatingRequest);
+
+ // Verify that we can instantiate a response with a derived-type of an expected request message.
+ request = new TestSignedDirectedMessage();
+ response = this.factory.GetNewResponseMessage(request, fields);
+ Assert.IsInstanceOf<DirectResponseMessageMock>(response);
+ Assert.AreSame(request, response.OriginatingRequest);
+ }
+
+ private class DirectResponseMessageMock : IDirectResponseProtocolMessage {
+ internal DirectResponseMessageMock(RequestMessageMock request) {
+ this.OriginatingRequest = request;
+ }
+
+ internal DirectResponseMessageMock(TestDirectedMessage request) {
+ this.OriginatingRequest = request;
+ }
+
+ [MessagePart(IsRequired = true)]
+ public int Age { get; set; }
+
+ #region IDirectResponseProtocolMessage Members
+
+ public IDirectedProtocolMessage OriginatingRequest { get; private set; }
+
+ #endregion
+
+ #region IProtocolMessage Members
+
+ public MessageProtections RequiredProtection {
+ get { throw new NotImplementedException(); }
+ }
+
+ public MessageTransport Transport {
+ get { throw new NotImplementedException(); }
+ }
+
+ #endregion
+
+ #region IMessage Members
+
+ public Version Version {
+ get { throw new NotImplementedException(); }
+ }
+
+ public System.Collections.Generic.IDictionary<string, string> ExtraData {
+ get { throw new NotImplementedException(); }
+ }
+
+ public void EnsureValidMessage() {
+ throw new NotImplementedException();
+ }
+
+ #endregion
+ }
+
+ private class RequestMessageMock : IDirectedProtocolMessage {
+ internal RequestMessageMock(Uri recipient, Version version) {
+ }
+
+ [MessagePart(IsRequired = true)]
+ public int Age { get; set; }
+
+ #region IDirectedProtocolMessage Members
+
+ public HttpDeliveryMethods HttpMethods {
+ get { throw new NotImplementedException(); }
+ }
+
+ public Uri Recipient {
+ get { throw new NotImplementedException(); }
+ }
+
+ #endregion
+
+ #region IProtocolMessage Members
+
+ public MessageProtections RequiredProtection {
+ get { throw new NotImplementedException(); }
+ }
+
+ public MessageTransport Transport {
+ get { throw new NotImplementedException(); }
+ }
+
+ #endregion
+
+ #region IMessage Members
+
+ public Version Version {
+ get { throw new NotImplementedException(); }
+ }
+
+ public System.Collections.Generic.IDictionary<string, string> ExtraData {
+ get { throw new NotImplementedException(); }
+ }
+
+ public void EnsureValidMessage() {
+ throw new NotImplementedException();
+ }
+
+ #endregion
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.Test/Mocks/CoordinatingChannel.cs b/src/DotNetOpenAuth.Test/Mocks/CoordinatingChannel.cs
index 99520a2..4d6f02b 100644
--- a/src/DotNetOpenAuth.Test/Mocks/CoordinatingChannel.cs
+++ b/src/DotNetOpenAuth.Test/Mocks/CoordinatingChannel.cs
@@ -85,7 +85,7 @@ namespace DotNetOpenAuth.Test.Mocks {
/// <param name="outgoingMessageFilter">The outgoing message filter. May be null.</param>
internal CoordinatingChannel(Channel wrappedChannel, Action<IProtocolMessage> incomingMessageFilter, Action<IProtocolMessage> outgoingMessageFilter)
: base(GetMessageFactory(wrappedChannel), wrappedChannel.BindingElements.ToArray()) {
- Contract.Requires<ArgumentNullException>(wrappedChannel != null);
+ Requires.NotNull(wrappedChannel, "wrappedChannel");
this.wrappedChannel = wrappedChannel;
this.incomingMessageFilter = incomingMessageFilter;
@@ -219,7 +219,7 @@ namespace DotNetOpenAuth.Test.Mocks {
/// channel since their message factory is not used.
/// </remarks>
protected virtual T CloneSerializedParts<T>(T message) where T : class, IProtocolMessage {
- Contract.Requires<ArgumentNullException>(message != null);
+ Requires.NotNull(message, "message");
IProtocolMessage clonedMessage;
var messageAccessor = this.MessageDescriptions.GetAccessor(message);
@@ -250,7 +250,7 @@ namespace DotNetOpenAuth.Test.Mocks {
}
private static IMessageFactory GetMessageFactory(Channel channel) {
- Contract.Requires<ArgumentNullException>(channel != null);
+ Requires.NotNull(channel, "channel");
return channel.MessageFactoryTestHook;
}
diff --git a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthChannel.cs b/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthConsumerChannel.cs
index 74e23bd..3fcce19 100644
--- a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthChannel.cs
+++ b/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthConsumerChannel.cs
@@ -1,5 +1,5 @@
//-----------------------------------------------------------------------
-// <copyright file="CoordinatingOAuthChannel.cs" company="Andrew Arnott">
+// <copyright file="CoordinatingOAuthConsumerChannel.cs" company="Andrew Arnott">
// Copyright (c) Andrew Arnott. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
@@ -16,18 +16,16 @@ namespace DotNetOpenAuth.Test.Mocks {
/// <summary>
/// A special channel used in test simulations to pass messages directly between two parties.
/// </summary>
- internal class CoordinatingOAuthChannel : OAuthChannel {
+ internal class CoordinatingOAuthConsumerChannel : OAuthConsumerChannel {
private EventWaitHandle incomingMessageSignal = new AutoResetEvent(false);
- private IProtocolMessage incomingMessage;
- private OutgoingWebResponse incomingRawResponse;
/// <summary>
- /// Initializes a new instance of the <see cref="CoordinatingOAuthChannel"/> class for Consumers.
+ /// Initializes a new instance of the <see cref="CoordinatingOAuthConsumerChannel"/> class.
/// </summary>
/// <param name="signingBindingElement">The signing element for the Consumer to use. Null for the Service Provider.</param>
/// <param name="tokenManager">The token manager to use.</param>
/// <param name="securitySettings">The security settings.</param>
- internal CoordinatingOAuthChannel(ITamperProtectionChannelBindingElement signingBindingElement, IConsumerTokenManager tokenManager, DotNetOpenAuth.OAuth.ConsumerSecuritySettings securitySettings)
+ internal CoordinatingOAuthConsumerChannel(ITamperProtectionChannelBindingElement signingBindingElement, IConsumerTokenManager tokenManager, DotNetOpenAuth.OAuth.ConsumerSecuritySettings securitySettings)
: base(
signingBindingElement,
new NonceMemoryStore(StandardExpirationBindingElement.MaximumMessageAge),
@@ -35,24 +33,18 @@ namespace DotNetOpenAuth.Test.Mocks {
securitySettings) {
}
- /// <summary>
- /// Initializes a new instance of the <see cref="CoordinatingOAuthChannel"/> class for Consumers.
- /// </summary>
- /// <param name="signingBindingElement">The signing element for the Consumer to use. Null for the Service Provider.</param>
- /// <param name="tokenManager">The token manager to use.</param>
- /// <param name="securitySettings">The security settings.</param>
- internal CoordinatingOAuthChannel(ITamperProtectionChannelBindingElement signingBindingElement, IServiceProviderTokenManager tokenManager, DotNetOpenAuth.OAuth.ServiceProviderSecuritySettings securitySettings)
- : base(
- signingBindingElement,
- new NonceMemoryStore(StandardExpirationBindingElement.MaximumMessageAge),
- tokenManager,
- securitySettings) {
+ internal EventWaitHandle IncomingMessageSignal {
+ get { return this.incomingMessageSignal; }
}
+ internal IProtocolMessage IncomingMessage { get; set; }
+
+ internal OutgoingWebResponse IncomingRawResponse { get; set; }
+
/// <summary>
/// Gets or sets the coordinating channel used by the other party.
/// </summary>
- internal CoordinatingOAuthChannel RemoteChannel { get; set; }
+ internal CoordinatingOAuthServiceProviderChannel RemoteChannel { get; set; }
internal OutgoingWebResponse RequestProtectedResource(AccessProtectedResourceRequest request) {
((ITamperResistantOAuthMessage)request).HttpMethod = this.GetHttpMethod(((ITamperResistantOAuthMessage)request).HttpMethods);
@@ -60,16 +52,11 @@ namespace DotNetOpenAuth.Test.Mocks {
HttpRequestInfo requestInfo = this.SpoofHttpMethod(request);
TestBase.TestLogger.InfoFormat("Sending protected resource request: {0}", requestInfo.Message);
// Drop the outgoing message in the other channel's in-slot and let them know it's there.
- this.RemoteChannel.incomingMessage = requestInfo.Message;
- this.RemoteChannel.incomingMessageSignal.Set();
+ this.RemoteChannel.IncomingMessage = requestInfo.Message;
+ this.RemoteChannel.IncomingMessageSignal.Set();
return this.AwaitIncomingRawResponse();
}
- internal void SendDirectRawResponse(OutgoingWebResponse response) {
- this.RemoteChannel.incomingRawResponse = response;
- this.RemoteChannel.incomingMessageSignal.Set();
- }
-
protected internal override HttpRequestInfo GetRequestFromContext() {
var directedMessage = (IDirectedProtocolMessage)this.AwaitIncomingMessage();
return new HttpRequestInfo(directedMessage, directedMessage.HttpMethods);
@@ -78,15 +65,15 @@ namespace DotNetOpenAuth.Test.Mocks {
protected override IProtocolMessage RequestCore(IDirectedProtocolMessage request) {
HttpRequestInfo requestInfo = this.SpoofHttpMethod(request);
// Drop the outgoing message in the other channel's in-slot and let them know it's there.
- this.RemoteChannel.incomingMessage = requestInfo.Message;
- this.RemoteChannel.incomingMessageSignal.Set();
+ this.RemoteChannel.IncomingMessage = requestInfo.Message;
+ this.RemoteChannel.IncomingMessageSignal.Set();
// Now wait for a response...
return this.AwaitIncomingMessage();
}
protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) {
- this.RemoteChannel.incomingMessage = CloneSerializedParts(response, null);
- this.RemoteChannel.incomingMessageSignal.Set();
+ this.RemoteChannel.IncomingMessage = CloneSerializedParts(response, null);
+ this.RemoteChannel.IncomingMessageSignal.Set();
return new OutgoingWebResponse(); // not used, but returning null is not allowed
}
@@ -122,20 +109,20 @@ namespace DotNetOpenAuth.Test.Mocks {
private IProtocolMessage AwaitIncomingMessage() {
this.incomingMessageSignal.WaitOne();
- IProtocolMessage response = this.incomingMessage;
- this.incomingMessage = null;
+ IProtocolMessage response = this.IncomingMessage;
+ this.IncomingMessage = null;
return response;
}
private OutgoingWebResponse AwaitIncomingRawResponse() {
this.incomingMessageSignal.WaitOne();
- OutgoingWebResponse response = this.incomingRawResponse;
- this.incomingRawResponse = null;
+ OutgoingWebResponse response = this.IncomingRawResponse;
+ this.IncomingRawResponse = null;
return response;
}
private T CloneSerializedParts<T>(T message, HttpRequestInfo requestInfo) where T : class, IProtocolMessage {
- Contract.Requires<ArgumentNullException>(message != null);
+ Requires.NotNull(message, "message");
IProtocolMessage clonedMessage;
var messageAccessor = this.MessageDescriptions.GetAccessor(message);
@@ -149,9 +136,9 @@ namespace DotNetOpenAuth.Test.Mocks {
recipient = new MessageReceivingEndpoint(directedMessage.Recipient, directedMessage.HttpMethods);
}
- clonedMessage = this.RemoteChannel.MessageFactory.GetNewRequestMessage(recipient, fields);
+ clonedMessage = this.RemoteChannel.MessageFactoryTestHook.GetNewRequestMessage(recipient, fields);
} else if (directResponse != null && directResponse.IsDirectResponse()) {
- clonedMessage = this.RemoteChannel.MessageFactory.GetNewResponseMessage(directResponse.OriginatingRequest, fields);
+ clonedMessage = this.RemoteChannel.MessageFactoryTestHook.GetNewResponseMessage(directResponse.OriginatingRequest, fields);
} else {
throw new InvalidOperationException("Totally expected a message to implement one of the two derived interface types.");
}
diff --git a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthServiceProviderChannel.cs b/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthServiceProviderChannel.cs
new file mode 100644
index 0000000..d07f794
--- /dev/null
+++ b/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthServiceProviderChannel.cs
@@ -0,0 +1,163 @@
+//-----------------------------------------------------------------------
+// <copyright file="CoordinatingOAuthServiceProviderChannel.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Test.Mocks {
+ using System;
+ using System.Diagnostics.Contracts;
+ using System.Threading;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+ using DotNetOpenAuth.OAuth.ChannelElements;
+ using DotNetOpenAuth.OAuth.Messages;
+
+ /// <summary>
+ /// A special channel used in test simulations to pass messages directly between two parties.
+ /// </summary>
+ internal class CoordinatingOAuthServiceProviderChannel : OAuthServiceProviderChannel {
+ private EventWaitHandle incomingMessageSignal = new AutoResetEvent(false);
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CoordinatingOAuthServiceProviderChannel"/> class.
+ /// </summary>
+ /// <param name="signingBindingElement">The signing element for the Consumer to use. Null for the Service Provider.</param>
+ /// <param name="tokenManager">The token manager to use.</param>
+ /// <param name="securitySettings">The security settings.</param>
+ internal CoordinatingOAuthServiceProviderChannel(ITamperProtectionChannelBindingElement signingBindingElement, IServiceProviderTokenManager tokenManager, DotNetOpenAuth.OAuth.ServiceProviderSecuritySettings securitySettings)
+ : base(
+ signingBindingElement,
+ new NonceMemoryStore(StandardExpirationBindingElement.MaximumMessageAge),
+ tokenManager,
+ securitySettings,
+ new OAuthServiceProviderMessageFactory(tokenManager)) {
+ }
+
+ internal EventWaitHandle IncomingMessageSignal {
+ get { return this.incomingMessageSignal; }
+ }
+
+ internal IProtocolMessage IncomingMessage { get; set; }
+
+ internal OutgoingWebResponse IncomingRawResponse { get; set; }
+
+ /// <summary>
+ /// Gets or sets the coordinating channel used by the other party.
+ /// </summary>
+ internal CoordinatingOAuthConsumerChannel RemoteChannel { get; set; }
+
+ internal OutgoingWebResponse RequestProtectedResource(AccessProtectedResourceRequest request) {
+ ((ITamperResistantOAuthMessage)request).HttpMethod = this.GetHttpMethod(((ITamperResistantOAuthMessage)request).HttpMethods);
+ this.ProcessOutgoingMessage(request);
+ HttpRequestInfo requestInfo = this.SpoofHttpMethod(request);
+ TestBase.TestLogger.InfoFormat("Sending protected resource request: {0}", requestInfo.Message);
+ // Drop the outgoing message in the other channel's in-slot and let them know it's there.
+ this.RemoteChannel.IncomingMessage = requestInfo.Message;
+ this.RemoteChannel.IncomingMessageSignal.Set();
+ return this.AwaitIncomingRawResponse();
+ }
+
+ internal void SendDirectRawResponse(OutgoingWebResponse response) {
+ this.RemoteChannel.IncomingRawResponse = response;
+ this.RemoteChannel.IncomingMessageSignal.Set();
+ }
+
+ protected internal override HttpRequestInfo GetRequestFromContext() {
+ var directedMessage = (IDirectedProtocolMessage)this.AwaitIncomingMessage();
+ return new HttpRequestInfo(directedMessage, directedMessage.HttpMethods);
+ }
+
+ protected override IProtocolMessage RequestCore(IDirectedProtocolMessage request) {
+ HttpRequestInfo requestInfo = this.SpoofHttpMethod(request);
+ // Drop the outgoing message in the other channel's in-slot and let them know it's there.
+ this.RemoteChannel.IncomingMessage = requestInfo.Message;
+ this.RemoteChannel.IncomingMessageSignal.Set();
+ // Now wait for a response...
+ return this.AwaitIncomingMessage();
+ }
+
+ protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) {
+ this.RemoteChannel.IncomingMessage = CloneSerializedParts(response, null);
+ this.RemoteChannel.IncomingMessageSignal.Set();
+ return new OutgoingWebResponse(); // not used, but returning null is not allowed
+ }
+
+ protected override OutgoingWebResponse PrepareIndirectResponse(IDirectedProtocolMessage message) {
+ // In this mock transport, direct and indirect messages are the same.
+ return this.PrepareDirectResponse(message);
+ }
+
+ protected override IDirectedProtocolMessage ReadFromRequestCore(HttpRequestInfo request) {
+ return request.Message;
+ }
+
+ /// <summary>
+ /// Spoof HTTP request information for signing/verification purposes.
+ /// </summary>
+ /// <param name="message">The message to add a pretend HTTP method to.</param>
+ /// <returns>A spoofed HttpRequestInfo that wraps the new message.</returns>
+ private HttpRequestInfo SpoofHttpMethod(IDirectedProtocolMessage message) {
+ HttpRequestInfo requestInfo = new HttpRequestInfo(message, message.HttpMethods);
+
+ var signedMessage = message as ITamperResistantOAuthMessage;
+ if (signedMessage != null) {
+ string httpMethod = this.GetHttpMethod(signedMessage.HttpMethods);
+ requestInfo.HttpMethod = httpMethod;
+ requestInfo.UrlBeforeRewriting = message.Recipient;
+ signedMessage.HttpMethod = httpMethod;
+ }
+
+ requestInfo.Message = this.CloneSerializedParts(message, requestInfo);
+
+ return requestInfo;
+ }
+
+ private IProtocolMessage AwaitIncomingMessage() {
+ this.IncomingMessageSignal.WaitOne();
+ IProtocolMessage response = this.IncomingMessage;
+ this.IncomingMessage = null;
+ return response;
+ }
+
+ private OutgoingWebResponse AwaitIncomingRawResponse() {
+ this.IncomingMessageSignal.WaitOne();
+ OutgoingWebResponse response = this.IncomingRawResponse;
+ this.IncomingRawResponse = null;
+ return response;
+ }
+
+ private T CloneSerializedParts<T>(T message, HttpRequestInfo requestInfo) where T : class, IProtocolMessage {
+ Requires.NotNull(message, "message");
+
+ IProtocolMessage clonedMessage;
+ var messageAccessor = this.MessageDescriptions.GetAccessor(message);
+ var fields = messageAccessor.Serialize();
+
+ MessageReceivingEndpoint recipient = null;
+ var directedMessage = message as IDirectedProtocolMessage;
+ var directResponse = message as IDirectResponseProtocolMessage;
+ if (directedMessage != null && directedMessage.IsRequest()) {
+ if (directedMessage.Recipient != null) {
+ recipient = new MessageReceivingEndpoint(directedMessage.Recipient, directedMessage.HttpMethods);
+ }
+
+ clonedMessage = this.RemoteChannel.MessageFactoryTestHook.GetNewRequestMessage(recipient, fields);
+ } else if (directResponse != null && directResponse.IsDirectResponse()) {
+ clonedMessage = this.RemoteChannel.MessageFactoryTestHook.GetNewResponseMessage(directResponse.OriginatingRequest, fields);
+ } else {
+ throw new InvalidOperationException("Totally expected a message to implement one of the two derived interface types.");
+ }
+
+ // Fill the cloned message with data.
+ var clonedMessageAccessor = this.MessageDescriptions.GetAccessor(clonedMessage);
+ clonedMessageAccessor.Deserialize(fields);
+
+ return (T)clonedMessage;
+ }
+
+ private string GetHttpMethod(HttpDeliveryMethods methods) {
+ return (methods & HttpDeliveryMethods.PostRequest) != 0 ? "POST" : "GET";
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOutgoingWebResponse.cs b/src/DotNetOpenAuth.Test/Mocks/CoordinatingOutgoingWebResponse.cs
index 62ea871..dc2c29f 100644
--- a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOutgoingWebResponse.cs
+++ b/src/DotNetOpenAuth.Test/Mocks/CoordinatingOutgoingWebResponse.cs
@@ -7,6 +7,7 @@
namespace DotNetOpenAuth.Test.Mocks {
using System;
using System.Collections.Generic;
+ using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
@@ -21,14 +22,19 @@ namespace DotNetOpenAuth.Test.Mocks {
/// <param name="message">The direct response message to send to the remote channel. This message will be cloned.</param>
/// <param name="receivingChannel">The receiving channel.</param>
internal CoordinatingOutgoingWebResponse(IProtocolMessage message, CoordinatingChannel receivingChannel) {
- Contract.Requires<ArgumentNullException>(message != null);
- Contract.Requires<ArgumentNullException>(receivingChannel != null);
+ Requires.NotNull(message, "message");
+ Requires.NotNull(receivingChannel, "receivingChannel");
this.receivingChannel = receivingChannel;
this.OriginalMessage = message;
}
+ [EditorBrowsable(EditorBrowsableState.Never)]
public override void Send() {
+ this.Respond();
+ }
+
+ public override void Respond() {
this.receivingChannel.PostMessage(this.OriginalMessage);
}
}
diff --git a/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs b/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs
index c18ea33..7048107 100644
--- a/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs
+++ b/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs
@@ -23,7 +23,7 @@ namespace DotNetOpenAuth.Test.Mocks {
private readonly Dictionary<Uri, IncomingWebResponse> registeredMockResponses = new Dictionary<Uri, IncomingWebResponse>();
private MockHttpRequest(IDirectWebRequestHandler mockHandler) {
- Contract.Requires<ArgumentNullException>(mockHandler != null);
+ Requires.NotNull(mockHandler, "mockHandler");
this.MockWebRequestHandler = mockHandler;
}
@@ -42,7 +42,7 @@ namespace DotNetOpenAuth.Test.Mocks {
}
internal void RegisterMockResponse(IncomingWebResponse response) {
- Contract.Requires<ArgumentNullException>(response != null);
+ Requires.NotNull(response, "response");
if (this.registeredMockResponses.ContainsKey(response.RequestUri)) {
Logger.Http.WarnFormat("Mock HTTP response already registered for {0}.", response.RequestUri);
} else {
@@ -59,9 +59,9 @@ namespace DotNetOpenAuth.Test.Mocks {
}
internal void RegisterMockResponse(Uri requestUri, Uri responseUri, string contentType, WebHeaderCollection headers, string responseBody) {
- Contract.Requires<ArgumentNullException>(requestUri != null);
- Contract.Requires<ArgumentNullException>(responseUri != null);
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(contentType));
+ Requires.NotNull(requestUri, "requestUri");
+ Requires.NotNull(responseUri, "responseUri");
+ Requires.NotNullOrEmpty(contentType, "contentType");
// Set up the redirect if appropriate
if (requestUri != responseUri) {
@@ -84,7 +84,7 @@ namespace DotNetOpenAuth.Test.Mocks {
}
internal void RegisterMockXrdsResponse(IdentifierDiscoveryResult endpoint) {
- Contract.Requires<ArgumentNullException>(endpoint != null);
+ Requires.NotNull(endpoint, "endpoint");
string identityUri;
if (endpoint.ClaimedIdentifier == endpoint.Protocol.ClaimedIdentifierForOPIdentifier) {
@@ -96,7 +96,7 @@ namespace DotNetOpenAuth.Test.Mocks {
}
internal void RegisterMockXrdsResponse(Uri respondingUri, IEnumerable<IdentifierDiscoveryResult> endpoints) {
- Contract.Requires<ArgumentNullException>(endpoints != null);
+ Requires.NotNull(endpoints, "endpoints");
StringBuilder xrds = new StringBuilder();
xrds.AppendLine(@"<xrds:XRDS xmlns:xrds='xri://$xrds' xmlns:openid='http://openid.net/xmlns/1.0' xmlns='xri://$xrd*($v*2.0)'>
diff --git a/src/DotNetOpenAuth.Test/Mocks/MockIdentifier.cs b/src/DotNetOpenAuth.Test/Mocks/MockIdentifier.cs
index 9f032b8..fe1cb81 100644
--- a/src/DotNetOpenAuth.Test/Mocks/MockIdentifier.cs
+++ b/src/DotNetOpenAuth.Test/Mocks/MockIdentifier.cs
@@ -26,9 +26,9 @@ namespace DotNetOpenAuth.Test.Mocks {
public MockIdentifier(Identifier wrappedIdentifier, MockHttpRequest mockHttpRequest, IEnumerable<IdentifierDiscoveryResult> endpoints)
: base(wrappedIdentifier.OriginalString, false) {
- Contract.Requires<ArgumentNullException>(wrappedIdentifier != null);
- Contract.Requires<ArgumentNullException>(mockHttpRequest != null);
- Contract.Requires<ArgumentNullException>(endpoints != null);
+ Requires.NotNull(wrappedIdentifier, "wrappedIdentifier");
+ Requires.NotNull(mockHttpRequest, "mockHttpRequest");
+ Requires.NotNull(endpoints, "endpoints");
this.wrappedIdentifier = wrappedIdentifier;
this.endpoints = endpoints;
diff --git a/src/DotNetOpenAuth.Test/Mocks/MockRealm.cs b/src/DotNetOpenAuth.Test/Mocks/MockRealm.cs
index dd17735..16ea337 100644
--- a/src/DotNetOpenAuth.Test/Mocks/MockRealm.cs
+++ b/src/DotNetOpenAuth.Test/Mocks/MockRealm.cs
@@ -21,7 +21,7 @@ namespace DotNetOpenAuth.Test.Mocks {
/// <param name="relyingPartyDescriptions">The relying party descriptions.</param>
internal MockRealm(Realm wrappedRealm, params RelyingPartyEndpointDescription[] relyingPartyDescriptions)
: base(wrappedRealm) {
- Contract.Requires<ArgumentNullException>(relyingPartyDescriptions != null);
+ Requires.NotNull(relyingPartyDescriptions, "relyingPartyDescriptions");
this.relyingPartyDescriptions = relyingPartyDescriptions;
}
diff --git a/src/DotNetOpenAuth.Test/Mocks/TestBadChannel.cs b/src/DotNetOpenAuth.Test/Mocks/TestBadChannel.cs
index 439acbb..515e69e 100644
--- a/src/DotNetOpenAuth.Test/Mocks/TestBadChannel.cs
+++ b/src/DotNetOpenAuth.Test/Mocks/TestBadChannel.cs
@@ -17,8 +17,8 @@ namespace DotNetOpenAuth.Test.Mocks {
: base(badConstructorParam ? null : new TestMessageFactory()) {
}
- internal new void Create301RedirectResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields) {
- base.Create301RedirectResponse(message, fields);
+ internal new void Create301RedirectResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields, bool payloadInFragment = false) {
+ base.Create301RedirectResponse(message, fields, payloadInFragment);
}
internal new void CreateFormPostResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields) {
diff --git a/src/DotNetOpenAuth.Test/Mocks/TestChannel.cs b/src/DotNetOpenAuth.Test/Mocks/TestChannel.cs
index 95fb90a..92fd9c6 100644
--- a/src/DotNetOpenAuth.Test/Mocks/TestChannel.cs
+++ b/src/DotNetOpenAuth.Test/Mocks/TestChannel.cs
@@ -25,6 +25,21 @@ namespace DotNetOpenAuth.Test.Mocks {
: base(messageTypeProvider, bindingElements) {
}
+ /// <summary>
+ /// Deserializes a dictionary of values into a message.
+ /// </summary>
+ /// <param name="fields">The dictionary of values that were read from an HTTP request or response.</param>
+ /// <param name="recipient">Information about where the message was directed. Null for direct response messages.</param>
+ /// <returns>
+ /// The deserialized message, or null if no message could be recognized in the provided data.
+ /// </returns>
+ /// <remarks>
+ /// This internal method exposes Receive directly to unit tests for easier deserialization of custom (possibly malformed) messages.
+ /// </remarks>
+ internal new IProtocolMessage Receive(Dictionary<string, string> fields, MessageReceivingEndpoint recipient) {
+ return base.Receive(fields, recipient);
+ }
+
protected override IDictionary<string, string> ReadFromResponseCore(IncomingWebResponse response) {
throw new NotImplementedException("ReadFromResponseInternal");
}
diff --git a/src/DotNetOpenAuth.Test/Mocks/TestDirectResponseMessageWithHttpStatus.cs b/src/DotNetOpenAuth.Test/Mocks/TestDirectResponseMessageWithHttpStatus.cs
index d692320..20fd6c4 100644
--- a/src/DotNetOpenAuth.Test/Mocks/TestDirectResponseMessageWithHttpStatus.cs
+++ b/src/DotNetOpenAuth.Test/Mocks/TestDirectResponseMessageWithHttpStatus.cs
@@ -8,6 +8,7 @@ namespace DotNetOpenAuth.Test.Mocks {
using System;
using System.Collections.Generic;
using System.Linq;
+ using System.Net;
using System.Text;
using DotNetOpenAuth.Messaging;
@@ -23,8 +24,15 @@ namespace DotNetOpenAuth.Test.Mocks {
/// <summary>
/// Gets or sets the HTTP status code that the direct respones should be sent with.
/// </summary>
- /// <value></value>
- public System.Net.HttpStatusCode HttpStatusCode { get; set; }
+ public HttpStatusCode HttpStatusCode { get; set; }
+
+ /// <summary>
+ /// Gets the HTTP headers to add to the response.
+ /// </summary>
+ /// <value>May be an empty collection, but must not be <c>null</c>.</value>
+ public WebHeaderCollection Headers {
+ get { return new WebHeaderCollection(); }
+ }
#endregion
}
diff --git a/src/DotNetOpenAuth.Test/OAuth/AppendixScenarios.cs b/src/DotNetOpenAuth.Test/OAuth/AppendixScenarios.cs
index 5584a7b..6322fe2 100644
--- a/src/DotNetOpenAuth.Test/OAuth/AppendixScenarios.cs
+++ b/src/DotNetOpenAuth.Test/OAuth/AppendixScenarios.cs
@@ -37,7 +37,7 @@ namespace DotNetOpenAuth.Test.OAuth {
consumer.Channel.PrepareResponse(consumer.PrepareRequestUserAuthorization(new Uri("http://printer.example.com/request_token_ready"), null, null)); // .Send() dropped because this is just a simulation
string accessToken = consumer.ProcessUserAuthorization().AccessToken;
var photoRequest = consumer.CreateAuthorizingMessage(accessPhotoEndpoint, accessToken);
- OutgoingWebResponse protectedPhoto = ((CoordinatingOAuthChannel)consumer.Channel).RequestProtectedResource(photoRequest);
+ OutgoingWebResponse protectedPhoto = ((CoordinatingOAuthConsumerChannel)consumer.Channel).RequestProtectedResource(photoRequest);
Assert.IsNotNull(protectedPhoto);
Assert.AreEqual(HttpStatusCode.OK, protectedPhoto.Status);
Assert.AreEqual("image/jpeg", protectedPhoto.Headers[HttpResponseHeader.ContentType]);
@@ -52,7 +52,7 @@ namespace DotNetOpenAuth.Test.OAuth {
var accessRequest = sp.ReadAccessTokenRequest();
sp.Channel.PrepareResponse(sp.PrepareAccessTokenMessage(accessRequest)); // .Send() dropped because this is just a simulation
string accessToken = sp.ReadProtectedResourceAuthorization().AccessToken;
- ((CoordinatingOAuthChannel)sp.Channel).SendDirectRawResponse(new OutgoingWebResponse {
+ ((CoordinatingOAuthServiceProviderChannel)sp.Channel).SendDirectRawResponse(new OutgoingWebResponse {
ResponseStream = new MemoryStream(new byte[] { 0x33, 0x66 }),
Headers = new WebHeaderCollection {
{ HttpResponseHeader.ContentType, "image/jpeg" },
diff --git a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs
index 34cc3a4..64eef0e 100644
--- a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs
+++ b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs
@@ -27,43 +27,43 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements {
private TestWebRequestHandler webRequestHandler;
private SigningBindingElementBase signingElement;
private INonceStore nonceStore;
- private DotNetOpenAuth.OAuth.ServiceProviderSecuritySettings serviceProviderSecuritySettings = DotNetOpenAuth.Configuration.DotNetOpenAuthSection.Configuration.OAuth.ServiceProvider.SecuritySettings.CreateSecuritySettings();
- private DotNetOpenAuth.OAuth.ConsumerSecuritySettings consumerSecuritySettings = DotNetOpenAuth.Configuration.DotNetOpenAuthSection.Configuration.OAuth.Consumer.SecuritySettings.CreateSecuritySettings();
+ private DotNetOpenAuth.OAuth.ServiceProviderSecuritySettings serviceProviderSecuritySettings = DotNetOpenAuth.Configuration.OAuthElement.Configuration.ServiceProvider.SecuritySettings.CreateSecuritySettings();
+ private DotNetOpenAuth.OAuth.ConsumerSecuritySettings consumerSecuritySettings = DotNetOpenAuth.Configuration.OAuthElement.Configuration.Consumer.SecuritySettings.CreateSecuritySettings();
[SetUp]
public override void SetUp() {
base.SetUp();
this.webRequestHandler = new TestWebRequestHandler();
- this.signingElement = new RsaSha1SigningBindingElement(new InMemoryTokenManager());
+ this.signingElement = new RsaSha1ServiceProviderSigningBindingElement(new InMemoryTokenManager());
this.nonceStore = new NonceMemoryStore(StandardExpirationBindingElement.MaximumMessageAge);
- this.channel = new OAuthChannel(this.signingElement, this.nonceStore, new InMemoryTokenManager(), this.serviceProviderSecuritySettings, new TestMessageFactory());
+ this.channel = new OAuthServiceProviderChannel(this.signingElement, this.nonceStore, new InMemoryTokenManager(), this.serviceProviderSecuritySettings, new TestMessageFactory());
this.channel.WebRequestHandler = this.webRequestHandler;
}
- [TestCase, ExpectedException(typeof(ArgumentNullException))]
+ [TestCase, ExpectedException(typeof(ArgumentException))]
public void CtorNullSigner() {
- new OAuthChannel(null, this.nonceStore, new InMemoryTokenManager(), this.consumerSecuritySettings, new TestMessageFactory());
+ new OAuthConsumerChannel(null, this.nonceStore, new InMemoryTokenManager(), this.consumerSecuritySettings, new TestMessageFactory());
}
[TestCase, ExpectedException(typeof(ArgumentNullException))]
public void CtorNullStore() {
- new OAuthChannel(new RsaSha1SigningBindingElement(new InMemoryTokenManager()), null, new InMemoryTokenManager(), this.consumerSecuritySettings, new TestMessageFactory());
+ new OAuthConsumerChannel(new RsaSha1ServiceProviderSigningBindingElement(new InMemoryTokenManager()), null, new InMemoryTokenManager(), this.consumerSecuritySettings, new TestMessageFactory());
}
[TestCase, ExpectedException(typeof(ArgumentNullException))]
public void CtorNullTokenManager() {
- new OAuthChannel(new RsaSha1SigningBindingElement(new InMemoryTokenManager()), this.nonceStore, null, this.consumerSecuritySettings, new TestMessageFactory());
+ new OAuthConsumerChannel(new RsaSha1ServiceProviderSigningBindingElement(new InMemoryTokenManager()), this.nonceStore, null, this.consumerSecuritySettings, new TestMessageFactory());
}
[TestCase]
public void CtorSimpleConsumer() {
- new OAuthChannel(new RsaSha1SigningBindingElement(new InMemoryTokenManager()), this.nonceStore, (IConsumerTokenManager)new InMemoryTokenManager(), this.consumerSecuritySettings);
+ new OAuthConsumerChannel(new RsaSha1ServiceProviderSigningBindingElement(new InMemoryTokenManager()), this.nonceStore, (IConsumerTokenManager)new InMemoryTokenManager(), this.consumerSecuritySettings);
}
[TestCase]
public void CtorSimpleServiceProvider() {
- new OAuthChannel(new RsaSha1SigningBindingElement(new InMemoryTokenManager()), this.nonceStore, (IServiceProviderTokenManager)new InMemoryTokenManager(), this.serviceProviderSecuritySettings);
+ new OAuthServiceProviderChannel(new RsaSha1ServiceProviderSigningBindingElement(new InMemoryTokenManager()), this.nonceStore, (IServiceProviderTokenManager)new InMemoryTokenManager(), this.serviceProviderSecuritySettings);
}
[TestCase]
@@ -248,7 +248,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements {
}
private static string CreateAuthorizationHeader(IDictionary<string, string> fields) {
- Contract.Requires<ArgumentNullException>(fields != null);
+ Requires.NotNull(fields, "fields");
StringBuilder authorization = new StringBuilder();
authorization.Append("OAuth ");
diff --git a/src/DotNetOpenAuth.Test/OAuth/OAuthCoordinator.cs b/src/DotNetOpenAuth.Test/OAuth/OAuthCoordinator.cs
index 6bcc583..067b364 100644
--- a/src/DotNetOpenAuth.Test/OAuth/OAuthCoordinator.cs
+++ b/src/DotNetOpenAuth.Test/OAuth/OAuthCoordinator.cs
@@ -19,8 +19,8 @@ namespace DotNetOpenAuth.Test.OAuth {
internal class OAuthCoordinator : CoordinatorBase<WebConsumer, ServiceProvider> {
private ConsumerDescription consumerDescription;
private ServiceProviderDescription serviceDescription;
- private DotNetOpenAuth.OAuth.ServiceProviderSecuritySettings serviceProviderSecuritySettings = DotNetOpenAuth.Configuration.DotNetOpenAuthSection.Configuration.OAuth.ServiceProvider.SecuritySettings.CreateSecuritySettings();
- private DotNetOpenAuth.OAuth.ConsumerSecuritySettings consumerSecuritySettings = DotNetOpenAuth.Configuration.DotNetOpenAuthSection.Configuration.OAuth.Consumer.SecuritySettings.CreateSecuritySettings();
+ private DotNetOpenAuth.OAuth.ServiceProviderSecuritySettings serviceProviderSecuritySettings = DotNetOpenAuth.Configuration.OAuthElement.Configuration.ServiceProvider.SecuritySettings.CreateSecuritySettings();
+ private DotNetOpenAuth.OAuth.ConsumerSecuritySettings consumerSecuritySettings = DotNetOpenAuth.Configuration.OAuthElement.Configuration.Consumer.SecuritySettings.CreateSecuritySettings();
/// <summary>Initializes a new instance of the <see cref="OAuthCoordinator"/> class.</summary>
/// <param name="consumerDescription">The description of the consumer.</param>
@@ -29,8 +29,8 @@ namespace DotNetOpenAuth.Test.OAuth {
/// <param name="serviceProviderAction">The code path of the Service Provider.</param>
internal OAuthCoordinator(ConsumerDescription consumerDescription, ServiceProviderDescription serviceDescription, Action<WebConsumer> consumerAction, Action<ServiceProvider> serviceProviderAction)
: base(consumerAction, serviceProviderAction) {
- Contract.Requires<ArgumentNullException>(consumerDescription != null);
- Contract.Requires<ArgumentNullException>(serviceDescription != null);
+ Requires.NotNull(consumerDescription, "consumerDescription");
+ Requires.NotNull(serviceDescription, "serviceDescription");
this.consumerDescription = consumerDescription;
this.serviceDescription = serviceDescription;
@@ -52,8 +52,8 @@ namespace DotNetOpenAuth.Test.OAuth {
serviceTokenManager.AddConsumer(this.consumerDescription);
// Prepare channels that will pass messages directly back and forth.
- CoordinatingOAuthChannel consumerChannel = new CoordinatingOAuthChannel(consumerSigningElement, (IConsumerTokenManager)consumerTokenManager, this.consumerSecuritySettings);
- CoordinatingOAuthChannel serviceProviderChannel = new CoordinatingOAuthChannel(spSigningElement, (IServiceProviderTokenManager)serviceTokenManager, this.serviceProviderSecuritySettings);
+ var consumerChannel = new CoordinatingOAuthConsumerChannel(consumerSigningElement, (IConsumerTokenManager)consumerTokenManager, this.consumerSecuritySettings);
+ var serviceProviderChannel = new CoordinatingOAuthServiceProviderChannel(spSigningElement, (IServiceProviderTokenManager)serviceTokenManager, this.serviceProviderSecuritySettings);
consumerChannel.RemoteChannel = serviceProviderChannel;
serviceProviderChannel.RemoteChannel = consumerChannel;
diff --git a/src/DotNetOpenAuth.Test/OAuth2/MessageFactoryTests.cs b/src/DotNetOpenAuth.Test/OAuth2/MessageFactoryTests.cs
new file mode 100644
index 0000000..e6237ca
--- /dev/null
+++ b/src/DotNetOpenAuth.Test/OAuth2/MessageFactoryTests.cs
@@ -0,0 +1,127 @@
+//-----------------------------------------------------------------------
+// <copyright file="MessageFactoryTests.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Test.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+ using DotNetOpenAuth.OAuth2.Messages;
+ using Moq;
+ using NUnit.Framework;
+
+ /// <summary>
+ /// Verifies that the WRAP message types are recognized.
+ /// </summary>
+ public class MessageFactoryTests : OAuth2TestBase {
+ private readonly MessageReceivingEndpoint recipient = new MessageReceivingEndpoint("http://who", HttpDeliveryMethods.PostRequest);
+ private OAuth2AuthorizationServerChannel channel;
+ private IMessageFactory messageFactory;
+
+ public override void SetUp() {
+ base.SetUp();
+
+ this.channel = new OAuth2AuthorizationServerChannel(new Mock<IAuthorizationServer>().Object);
+ this.messageFactory = this.channel.MessageFactoryTestHook;
+ }
+
+ #region End user authorization messages
+
+ [TestCase]
+ public void EndUserAuthorizationRequest() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.response_type, "code" },
+ { Protocol.client_id, "abc" },
+ { Protocol.redirect_uri, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(EndUserAuthorizationRequest), request);
+ }
+
+ [TestCase]
+ public void EndUserAuthorizationSuccessResponseWithCode() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.code, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(EndUserAuthorizationSuccessResponseBase), request);
+ }
+
+ [TestCase, Ignore("Not yet supported")]
+ public void EndUserAuthorizationSuccessResponseWithAccessToken() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.access_token, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(EndUserAuthorizationSuccessResponseBase), request);
+ }
+
+ [TestCase]
+ public void EndUserAuthorizationFailedResponse() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.error, "access-denied" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(EndUserAuthorizationFailedResponse), request);
+ }
+
+ #endregion
+
+ #region Access token request messages
+
+ [TestCase]
+ public void AccessTokenRefreshRequest() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.client_id, "abc" },
+ { Protocol.refresh_token, "abc" },
+ { Protocol.grant_type, "refresh-token" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(AccessTokenRefreshRequest), request);
+ }
+
+ [TestCase]
+ public void AccessTokenAuthorizationCodeRequest() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.client_id, "abc" },
+ { Protocol.code, "code" },
+ { Protocol.grant_type, "authorization-code" },
+ { Protocol.redirect_uri, "http://someUri" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(AccessTokenAuthorizationCodeRequest), request);
+ }
+
+ [TestCase]
+ public void AccessTokenBasicCredentialsRequest() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.client_id, "abc" },
+ { Protocol.client_secret, "abc" },
+ { Protocol.grant_type, "basic-credentials" },
+ { Protocol.username, "abc" },
+ { Protocol.password, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(AccessTokenResourceOwnerPasswordCredentialsRequest), request);
+ }
+
+ [TestCase]
+ public void AccessTokenClientCredentialsRequest() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.client_id, "abc" },
+ { Protocol.client_secret, "abc" },
+ { Protocol.grant_type, "none" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(AccessTokenClientCredentialsRequest), request);
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth.Test/OAuth2/OAuth2ChannelTests.cs b/src/DotNetOpenAuth.Test/OAuth2/OAuth2ChannelTests.cs
new file mode 100644
index 0000000..c263eb6
--- /dev/null
+++ b/src/DotNetOpenAuth.Test/OAuth2/OAuth2ChannelTests.cs
@@ -0,0 +1,21 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuth2ChannelTests.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Test.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+ using DotNetOpenAuth.OAuth2.Messages;
+ using NUnit.Framework;
+
+ [TestFixture]
+ public class OAuth2ChannelTests : OAuth2TestBase {
+ }
+}
diff --git a/src/DotNetOpenAuth.Test/OAuth2/OAuth2TestBase.cs b/src/DotNetOpenAuth.Test/OAuth2/OAuth2TestBase.cs
new file mode 100644
index 0000000..6c13c5e
--- /dev/null
+++ b/src/DotNetOpenAuth.Test/OAuth2/OAuth2TestBase.cs
@@ -0,0 +1,15 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuth2TestBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Test.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+
+ public class OAuth2TestBase : TestBase {
+ }
+}
diff --git a/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs b/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs
index 390a5f1..9c9e446 100644
--- a/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs
@@ -87,7 +87,7 @@ namespace DotNetOpenAuth.Test.OpenId {
// Ensure that the response is a suggestion that the RP try again with HMAC-SHA1
AssociateUnsuccessfulResponse renegotiateResponse = (AssociateUnsuccessfulResponse)req.ResponseMessageTestHook;
Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA1, renegotiateResponse.AssociationType);
- op.SendResponse(req);
+ op.Respond(req);
// Receive second attempt request for an HMAC-SHA1 association.
req = (AutoResponsiveRequest)op.GetRequest();
@@ -97,7 +97,7 @@ namespace DotNetOpenAuth.Test.OpenId {
// Ensure that the response is a success response.
AssociateSuccessfulResponse successResponse = (AssociateSuccessfulResponse)req.ResponseMessageTestHook;
Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA1, successResponse.AssociationType);
- op.SendResponse(req);
+ op.Respond(req);
});
coordinator.Run();
}
@@ -168,7 +168,7 @@ namespace DotNetOpenAuth.Test.OpenId {
AssociateUnsuccessfulResponse renegotiateResponse = new AssociateUnsuccessfulResponse(request.Version, request);
renegotiateResponse.AssociationType = "HMAC-UNKNOWN";
renegotiateResponse.SessionType = "DH-UNKNOWN";
- op.Channel.Send(renegotiateResponse);
+ op.Channel.Respond(renegotiateResponse);
});
coordinator.Run();
}
@@ -195,7 +195,7 @@ namespace DotNetOpenAuth.Test.OpenId {
AssociateUnsuccessfulResponse renegotiateResponse = new AssociateUnsuccessfulResponse(request.Version, request);
renegotiateResponse.AssociationType = protocol.Args.SignatureAlgorithm.HMAC_SHA1;
renegotiateResponse.SessionType = protocol.Args.SessionType.NoEncryption;
- op.Channel.Send(renegotiateResponse);
+ op.Channel.Respond(renegotiateResponse);
});
coordinator.Run();
}
@@ -220,7 +220,7 @@ namespace DotNetOpenAuth.Test.OpenId {
AssociateUnsuccessfulResponse renegotiateResponse = new AssociateUnsuccessfulResponse(request.Version, request);
renegotiateResponse.AssociationType = protocol.Args.SignatureAlgorithm.HMAC_SHA1;
renegotiateResponse.SessionType = protocol.Args.SessionType.DH_SHA256;
- op.Channel.Send(renegotiateResponse);
+ op.Channel.Respond(renegotiateResponse);
});
coordinator.Run();
}
@@ -245,7 +245,7 @@ namespace DotNetOpenAuth.Test.OpenId {
AssociateUnsuccessfulResponse renegotiateResponse = new AssociateUnsuccessfulResponse(request.Version, request);
renegotiateResponse.AssociationType = protocol.Args.SignatureAlgorithm.HMAC_SHA1;
renegotiateResponse.SessionType = protocol.Args.SessionType.DH_SHA1;
- op.Channel.Send(renegotiateResponse);
+ op.Channel.Respond(renegotiateResponse);
// Receive second-try
request = op.Channel.ReadFromRequest<AssociateRequest>();
@@ -254,7 +254,7 @@ namespace DotNetOpenAuth.Test.OpenId {
renegotiateResponse = new AssociateUnsuccessfulResponse(request.Version, request);
renegotiateResponse.AssociationType = protocol.Args.SignatureAlgorithm.HMAC_SHA256;
renegotiateResponse.SessionType = protocol.Args.SessionType.DH_SHA256;
- op.Channel.Send(renegotiateResponse);
+ op.Channel.Respond(renegotiateResponse);
});
coordinator.Run();
}
@@ -332,7 +332,7 @@ namespace DotNetOpenAuth.Test.OpenId {
IRequest req = op.GetRequest();
Assert.IsNotNull(req, "Expected incoming request but did not receive it.");
Assert.IsTrue(req.IsResponseReady);
- op.SendResponse(req);
+ op.Respond(req);
});
coordinator.IncomingMessageFilter = message => {
Assert.AreSame(opDescription.Version, message.Version, "The message was recognized as version {0} but was expected to be {1}.", message.Version, Protocol.Lookup(opDescription.Version).ProtocolVersion);
@@ -352,9 +352,10 @@ namespace DotNetOpenAuth.Test.OpenId {
if (expectSuccess) {
Assert.IsNotNull(rpAssociation);
- Assert.AreSame(rpAssociation, coordinator.RelyingParty.AssociationManager.AssociationStoreTestHook.GetAssociation(opDescription.Uri, rpAssociation.Handle));
- opAssociation = coordinator.Provider.AssociationStore.GetAssociation(AssociationRelyingPartyType.Smart, rpAssociation.Handle);
- Assert.IsNotNull(opAssociation, "The Provider should have stored the association.");
+ Association actual = coordinator.RelyingParty.AssociationManager.AssociationStoreTestHook.GetAssociation(opDescription.Uri, rpAssociation.Handle);
+ Assert.AreEqual(rpAssociation, actual);
+ opAssociation = coordinator.Provider.AssociationStore.Deserialize(new TestSignedDirectedMessage(), false, rpAssociation.Handle);
+ Assert.IsNotNull(opAssociation, "The Provider could not decode the association handle.");
Assert.AreEqual(opAssociation.Handle, rpAssociation.Handle);
Assert.AreEqual(expectedAssociationType, rpAssociation.GetAssociationType(protocol));
@@ -372,7 +373,6 @@ namespace DotNetOpenAuth.Test.OpenId {
}
} else {
Assert.IsNull(coordinator.RelyingParty.AssociationManager.AssociationStoreTestHook.GetAssociation(opDescription.Uri, new RelyingPartySecuritySettings()));
- Assert.IsNull(coordinator.Provider.AssociationStore.GetAssociation(AssociationRelyingPartyType.Smart, new ProviderSecuritySettings()));
}
}
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs b/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs
index 27db93e..a0d833d 100644
--- a/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs
@@ -136,10 +136,12 @@ namespace DotNetOpenAuth.Test.OpenId {
}
private void ParameterizedAuthenticationTest(Protocol protocol, bool statelessRP, bool sharedAssociation, bool positive, bool immediate, bool tamper) {
- Contract.Requires<ArgumentException>(!statelessRP || !sharedAssociation, "The RP cannot be stateless while sharing an association with the OP.");
- Contract.Requires<ArgumentException>(positive || !tamper, "Cannot tamper with a negative response.");
- ProviderSecuritySettings securitySettings = new ProviderSecuritySettings();
- Association association = sharedAssociation ? HmacShaAssociation.Create(protocol, protocol.Args.SignatureAlgorithm.Best, AssociationRelyingPartyType.Smart, securitySettings) : null;
+ Requires.True(!statelessRP || !sharedAssociation, null, "The RP cannot be stateless while sharing an association with the OP.");
+ Requires.True(positive || !tamper, null, "Cannot tamper with a negative response.");
+ var securitySettings = new ProviderSecuritySettings();
+ var cryptoKeyStore = new MemoryCryptoKeyStore();
+ var associationStore = new ProviderAssociationHandleEncoder(cryptoKeyStore);
+ Association association = sharedAssociation ? HmacShaAssociationProvider.Create(protocol, protocol.Args.SignatureAlgorithm.Best, AssociationRelyingPartyType.Smart, associationStore, securitySettings) : null;
var coordinator = new OpenIdCoordinator(
rp => {
var request = new CheckIdRequest(protocol.Version, OPUri, immediate ? AuthenticationRequestMode.Immediate : AuthenticationRequestMode.Setup);
@@ -153,7 +155,7 @@ namespace DotNetOpenAuth.Test.OpenId {
request.LocalIdentifier = "http://localid";
request.ReturnTo = RPUri;
request.Realm = RPUri;
- rp.Channel.Send(request);
+ rp.Channel.Respond(request);
if (positive) {
if (tamper) {
try {
@@ -197,7 +199,8 @@ namespace DotNetOpenAuth.Test.OpenId {
},
op => {
if (association != null) {
- op.AssociationStore.StoreAssociation(AssociationRelyingPartyType.Smart, association);
+ var key = cryptoKeyStore.GetCurrentKey(ProviderAssociationHandleEncoder.AssociationHandleEncodingSecretBucket, TimeSpan.FromSeconds(1));
+ op.CryptoKeyStore.StoreKey(ProviderAssociationHandleEncoder.AssociationHandleEncodingSecretBucket, key.Key, key.Value);
}
var request = op.Channel.ReadFromRequest<CheckIdRequest>();
@@ -208,20 +211,20 @@ namespace DotNetOpenAuth.Test.OpenId {
} else {
response = new NegativeAssertionResponse(request, op.Channel);
}
- op.Channel.Send(response);
+ op.Channel.Respond(response);
if (positive && (statelessRP || !sharedAssociation)) {
var checkauthRequest = op.Channel.ReadFromRequest<CheckAuthenticationRequest>();
var checkauthResponse = new CheckAuthenticationResponse(checkauthRequest.Version, checkauthRequest);
checkauthResponse.IsValid = checkauthRequest.IsValid;
- op.Channel.Send(checkauthResponse);
+ op.Channel.Respond(checkauthResponse);
if (!tamper) {
// Respond to the replay attack.
checkauthRequest = op.Channel.ReadFromRequest<CheckAuthenticationRequest>();
checkauthResponse = new CheckAuthenticationResponse(checkauthRequest.Version, checkauthRequest);
checkauthResponse.IsValid = checkauthRequest.IsValid;
- op.Channel.Send(checkauthResponse);
+ op.Channel.Respond(checkauthResponse);
}
}
});
diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs
index 5edd51f..a4291d6 100644
--- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs
@@ -32,7 +32,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
this.factory = new StandardOpenIdExtensionFactory();
this.factory.RegisterExtension(MockOpenIdExtension.Factory);
- this.rpElement = new ExtensionsBindingElement(this.factory, new RelyingPartySecuritySettings());
+ this.rpElement = new ExtensionsBindingElementRelyingParty(this.factory, new RelyingPartySecuritySettings());
this.rpElement.Channel = new TestChannel(this.MessageDescriptions);
this.request = new SignedResponseRequest(Protocol.Default.Version, OpenIdTestBase.OPUri, AuthenticationRequestMode.Immediate);
}
@@ -52,9 +52,9 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
Assert.AreSame(this.factory, this.rpElement.ExtensionFactory);
}
- [TestCase, ExpectedException(typeof(ArgumentNullException))]
+ [TestCase]
public void PrepareMessageForSendingNull() {
- this.rpElement.ProcessOutgoingMessage(null);
+ Assert.IsNull(this.rpElement.ProcessOutgoingMessage(null));
}
/// <summary>
@@ -128,11 +128,11 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
},
op => {
RegisterMockExtension(op.Channel);
- op.Channel.Send(CreateResponseWithExtensions(protocol));
- op.SendResponse(op.GetRequest()); // check_auth
+ op.Channel.Respond(CreateResponseWithExtensions(protocol));
+ op.Respond(op.GetRequest()); // check_auth
op.SecuritySettings.SignOutgoingExtensions = false;
- op.Channel.Send(CreateResponseWithExtensions(protocol));
- op.SendResponse(op.GetRequest()); // check_auth
+ op.Channel.Respond(CreateResponseWithExtensions(protocol));
+ op.Respond(op.GetRequest()); // check_auth
});
coordinator.Run();
}
@@ -168,7 +168,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
}
private static void RegisterMockExtension(Channel channel) {
- Contract.Requires<ArgumentNullException>(channel != null);
+ Requires.NotNull(channel, "channel");
ExtensionTestUtilities.RegisterExtension(channel, MockOpenIdExtension.Factory);
}
@@ -179,7 +179,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
/// <param name="protocol">The protocol to construct the message with.</param>
/// <returns>The message ready to send from OP to RP.</returns>
private IndirectSignedResponse CreateResponseWithExtensions(Protocol protocol) {
- Contract.Requires<ArgumentNullException>(protocol != null);
+ Requires.NotNull(protocol, "protocol");
IndirectSignedResponse response = new IndirectSignedResponse(protocol.Version, RPUri);
response.ProviderEndpoint = OPUri;
diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs
index eaaef34..059c80e 100644
--- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs
@@ -29,7 +29,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
[SetUp]
public void Setup() {
this.webHandler = new Mocks.TestWebRequestHandler();
- this.channel = new OpenIdChannel(new AssociationMemoryStore<Uri>(), new NonceMemoryStore(maximumMessageAge), new RelyingPartySecuritySettings());
+ this.channel = new OpenIdRelyingPartyChannel(new MemoryCryptoKeyStore(), new NonceMemoryStore(maximumMessageAge), new RelyingPartySecuritySettings());
this.channel.WebRequestHandler = this.webHandler;
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs
index 6160680..22714a9 100644
--- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs
@@ -6,12 +6,16 @@
namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
using System;
+ using System.Collections.Generic;
using System.Linq;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.ChannelElements;
using DotNetOpenAuth.OpenId.Messages;
using DotNetOpenAuth.OpenId.Provider;
using DotNetOpenAuth.Test.Mocks;
+ using Moq;
using NUnit.Framework;
[TestFixture]
@@ -23,18 +27,20 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
public void SignaturesMatchKnownGood() {
Protocol protocol = Protocol.V20;
var settings = new ProviderSecuritySettings();
- var store = new AssociationMemoryStore<AssociationRelyingPartyType>();
+ var cryptoStore = new MemoryCryptoKeyStore();
byte[] associationSecret = Convert.FromBase64String("rsSwv1zPWfjPRQU80hciu8FPDC+GONAMJQ/AvSo1a2M=");
- Association association = HmacShaAssociation.Create("mock", associationSecret, TimeSpan.FromDays(1));
- store.StoreAssociation(AssociationRelyingPartyType.Smart, association);
- SigningBindingElement signer = new SigningBindingElement(store, settings);
+ string handle = "mock";
+ cryptoStore.StoreKey(ProviderAssociationKeyStorage.SharedAssociationBucket, handle, new CryptoKey(associationSecret, DateTime.UtcNow.AddDays(1)));
+
+ var store = new ProviderAssociationKeyStorage(cryptoStore);
+ SigningBindingElement signer = new ProviderSigningBindingElement(store, settings);
signer.Channel = new TestChannel(this.MessageDescriptions);
IndirectSignedResponse message = new IndirectSignedResponse(protocol.Version, new Uri("http://rp"));
ITamperResistantOpenIdMessage signedMessage = message;
message.ProviderEndpoint = new Uri("http://provider");
signedMessage.UtcCreationDate = DateTime.Parse("1/1/2009");
- signedMessage.AssociationHandle = association.Handle;
+ signedMessage.AssociationHandle = handle;
Assert.IsNotNull(signer.ProcessOutgoingMessage(message));
Assert.AreEqual("o9+uN7qTaUS9v0otbHTuNAtbkpBm14+es9QnNo6IHD4=", signedMessage.Signature);
}
@@ -45,7 +51,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
[TestCase]
public void SignedResponsesIncludeExtraDataInSignature() {
Protocol protocol = Protocol.Default;
- SigningBindingElement sbe = new SigningBindingElement(new AssociationMemoryStore<AssociationRelyingPartyType>(), new ProviderSecuritySettings());
+ SigningBindingElement sbe = new ProviderSigningBindingElement(new ProviderAssociationHandleEncoder(new MemoryCryptoKeyStore()), new ProviderSecuritySettings());
sbe.Channel = new TestChannel(this.MessageDescriptions);
IndirectSignedResponse response = new IndirectSignedResponse(protocol.Version, RPUri);
response.ReturnTo = RPUri;
@@ -65,5 +71,37 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
Assert.IsTrue(signedParameters.Contains("somesigned"));
Assert.IsFalse(signedParameters.Contains("someunsigned"));
}
+
+ /// <summary>
+ /// Regression test for bug #45 (https://github.com/AArnott/dotnetopenid/issues/45)
+ /// </summary>
+ [TestCase, ExpectedException(typeof(ProtocolException))]
+ public void MissingSignedParameter() {
+ var cryptoStore = new MemoryCryptoKeyStore();
+ byte[] associationSecret = Convert.FromBase64String("rsSwv1zPWfjPRQU80hciu8FPDC+GONAMJQ/AvSo1a2M=");
+ string handle = "{634477555066085461}{TTYcIg==}{32}";
+ cryptoStore.StoreKey(ProviderAssociationKeyStorage.PrivateAssociationBucket, handle, new CryptoKey(associationSecret, DateTime.UtcNow.AddDays(1)));
+
+ var signer = new ProviderSigningBindingElement(new ProviderAssociationKeyStorage(cryptoStore), new ProviderSecuritySettings());
+ var testChannel = new TestChannel(new OpenIdProviderMessageFactory());
+ signer.Channel = testChannel;
+
+ var buggyRPMessage = new Dictionary<string, string>() {
+ { "openid.assoc_handle", "{634477555066085461}{TTYcIg==}{32}" },
+ { "openid.claimed_id", "https://openid.stackexchange.com/user/f5e91123-e5b4-43c5-871f-5f276c75d31a" },
+ { "openid.identity", "https://openid.stackexchange.com/user/f5e91123-e5b4-43c5-871f-5f276c75d31a" },
+ { "openid.mode", "check_authentication" },
+ { "openid.op_endpoint", "https://openid.stackexchange.com/openid/provider" },
+ { "openid.response_nonce", "2011-08-01T00:32:10Zvdyt3efw" },
+ { "openid.return_to", "http://openid-consumer.appspot.com/finish?session_id=1543025&janrain_nonce=2011-08-01T00%3A32%3A09ZIPGz7D" },
+ { "openid.sig", "b0Rll6Kt1KKBWWBEg/qBvW3sQYtmhOUmpI0/UREBVZ0=" },
+ { "openid.signed", "claimed_id,identity,assoc_handle,op_endpoint,return_to,response_nonce,ns.sreg,sreg.email,sreg.fullname" },
+ { "openid.sreg.email", "kevin.montrose@stackoverflow.com" },
+ { "openid.sreg.fullname", "Kevin K Montrose" },
+ };
+ var message = (CheckAuthenticationRequest)testChannel.Receive(buggyRPMessage, new MessageReceivingEndpoint(OPUri, HttpDeliveryMethods.PostRequest));
+ var originalResponse = new IndirectSignedResponse(message, signer.Channel);
+ signer.ProcessIncomingMessage(originalResponse);
+ }
}
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeRequestTests.cs
index 5cc8ec1..3a7ecd7 100644
--- a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeRequestTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeRequestTests.cs
@@ -25,7 +25,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
new AttributeRequest(string.Empty);
}
- [TestCase, ExpectedException(typeof(ArgumentException))]
+ [TestCase, ExpectedException(typeof(ArgumentNullException))]
public void CtorNullTypeUri() {
new AttributeRequest(null);
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs
index 334fc93..4a78fc1 100644
--- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs
@@ -10,6 +10,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
using System.Diagnostics.Contracts;
using System.Linq;
using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.ChannelElements;
using DotNetOpenAuth.OpenId.Extensions;
@@ -33,8 +34,10 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
Protocol protocol,
IEnumerable<IOpenIdMessageExtension> requests,
IEnumerable<IOpenIdMessageExtension> responses) {
- ProviderSecuritySettings securitySettings = new ProviderSecuritySettings();
- Association association = HmacShaAssociation.Create(protocol, protocol.Args.SignatureAlgorithm.Best, AssociationRelyingPartyType.Smart, securitySettings);
+ var securitySettings = new ProviderSecuritySettings();
+ var cryptoKeyStore = new MemoryCryptoKeyStore();
+ var associationStore = new ProviderAssociationHandleEncoder(cryptoKeyStore);
+ Association association = HmacShaAssociationProvider.Create(protocol, protocol.Args.SignatureAlgorithm.Best, AssociationRelyingPartyType.Smart, associationStore, securitySettings);
var coordinator = new OpenIdCoordinator(
rp => {
RegisterExtension(rp.Channel, Mocks.MockOpenIdExtension.Factory);
@@ -49,7 +52,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
requestBase.Extensions.Add(extension);
}
- rp.Channel.Send(requestBase);
+ rp.Channel.Respond(requestBase);
var response = rp.Channel.ReadFromRequest<PositiveAssertionResponse>();
var receivedResponses = response.Extensions.Cast<IOpenIdMessageExtension>();
@@ -57,7 +60,8 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
},
op => {
RegisterExtension(op.Channel, Mocks.MockOpenIdExtension.Factory);
- op.AssociationStore.StoreAssociation(AssociationRelyingPartyType.Smart, association);
+ var key = cryptoKeyStore.GetCurrentKey(ProviderAssociationHandleEncoder.AssociationHandleEncodingSecretBucket, TimeSpan.FromSeconds(1));
+ op.CryptoKeyStore.StoreKey(ProviderAssociationHandleEncoder.AssociationHandleEncodingSecretBucket, key.Key, key.Value);
var request = op.Channel.ReadFromRequest<CheckIdRequest>();
var response = new PositiveAssertionResponse(request);
var receivedRequests = request.Extensions.Cast<IOpenIdMessageExtension>();
@@ -67,13 +71,13 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
response.Extensions.Add(extensionResponse);
}
- op.Channel.Send(response);
+ op.Channel.Respond(response);
});
coordinator.Run();
}
internal static void RegisterExtension(Channel channel, StandardOpenIdExtensionFactory.CreateDelegate extensionFactory) {
- Contract.Requires<ArgumentNullException>(channel != null);
+ Requires.NotNull(channel, "channel");
var factory = (OpenIdExtensionFactoryAggregator)channel.BindingElements.OfType<ExtensionsBindingElement>().Single().ExtensionFactory;
factory.Factories.OfType<StandardOpenIdExtensionFactory>().Single().RegisterExtension(extensionFactory);
diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs
index bcafc41..8d7de0e 100644
--- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs
@@ -14,6 +14,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using DotNetOpenAuth.OpenId.Messages;
using DotNetOpenAuth.OpenId.Provider;
+ using DotNetOpenAuth.OpenId.Provider.Extensions;
using NUnit.Framework;
[TestFixture]
@@ -26,7 +27,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
base.SetUp();
var op = this.CreateProvider();
- var rpRequest = new CheckIdRequest(Protocol.Default.Version, OPUri, DotNetOpenAuth.OpenId.RelyingParty.AuthenticationRequestMode.Setup);
+ var rpRequest = new CheckIdRequest(Protocol.Default.Version, OPUri, DotNetOpenAuth.OpenId.AuthenticationRequestMode.Setup);
rpRequest.ReturnTo = RPUri;
this.extensions = rpRequest.Extensions;
this.request = new AuthenticationRequest(op, rpRequest);
diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs
index d477e9b..c70f023 100644
--- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs
@@ -12,7 +12,9 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using DotNetOpenAuth.OpenId.RelyingParty;
+ using DotNetOpenAuth.OpenId.RelyingParty.Extensions;
using NUnit.Framework;
+ using ExtensionsInteropProviderHelper = DotNetOpenAuth.OpenId.Provider.Extensions.ExtensionsInteropHelper;
[TestFixture]
public class ExtensionsInteropHelperRPRequestTests : OpenIdTestBase {
@@ -76,8 +78,8 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
ExtensionsInteropHelper.SpreadSregToAX(this.authReq, AXAttributeFormats.AXSchemaOrg | AXAttributeFormats.SchemaOpenIdNet);
var ax = this.authReq.AppliedExtensions.OfType<FetchRequest>().Single();
Assert.IsTrue(ax.Attributes.Contains(WellKnownAttributes.Name.Alias));
- Assert.IsTrue(ax.Attributes.Contains(ExtensionsInteropHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.Alias, AXAttributeFormats.SchemaOpenIdNet)));
- Assert.IsFalse(ax.Attributes.Contains(ExtensionsInteropHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.Alias, AXAttributeFormats.OpenIdNetSchema)));
+ Assert.IsTrue(ax.Attributes.Contains(ExtensionsInteropProviderHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.Alias, AXAttributeFormats.SchemaOpenIdNet)));
+ Assert.IsFalse(ax.Attributes.Contains(ExtensionsInteropProviderHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.Alias, AXAttributeFormats.OpenIdNetSchema)));
}
/// <summary>
@@ -100,7 +102,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
this.InjectAdvertisedTypeUri(WellKnownAttributes.Name.FullName);
ExtensionsInteropHelper.SpreadSregToAX(this.authReq, AXAttributeFormats.OpenIdNetSchema);
var ax = this.authReq.AppliedExtensions.OfType<FetchRequest>().Single();
- Assert.IsFalse(ax.Attributes.Contains(ExtensionsInteropHelper.TransformAXFormatTestHook(WellKnownAttributes.Contact.Email, AXAttributeFormats.OpenIdNetSchema)));
+ Assert.IsFalse(ax.Attributes.Contains(ExtensionsInteropProviderHelper.TransformAXFormatTestHook(WellKnownAttributes.Contact.Email, AXAttributeFormats.OpenIdNetSchema)));
Assert.IsTrue(ax.Attributes.Contains(WellKnownAttributes.Contact.Email));
}
@@ -109,9 +111,9 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
/// </summary>
[TestCase]
public void TransformAXFormatTest() {
- Assert.AreEqual(WellKnownAttributes.Name.Alias, ExtensionsInteropHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.Alias, AXAttributeFormats.AXSchemaOrg));
- Assert.AreEqual("http://schema.openid.net/namePerson/friendly", ExtensionsInteropHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.Alias, AXAttributeFormats.SchemaOpenIdNet));
- Assert.AreEqual("http://openid.net/schema/namePerson/friendly", ExtensionsInteropHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.Alias, AXAttributeFormats.OpenIdNetSchema));
+ Assert.AreEqual(WellKnownAttributes.Name.Alias, ExtensionsInteropProviderHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.Alias, AXAttributeFormats.AXSchemaOrg));
+ Assert.AreEqual("http://schema.openid.net/namePerson/friendly", ExtensionsInteropProviderHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.Alias, AXAttributeFormats.SchemaOpenIdNet));
+ Assert.AreEqual("http://openid.net/schema/namePerson/friendly", ExtensionsInteropProviderHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.Alias, AXAttributeFormats.OpenIdNetSchema));
}
/// <summary>
diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPResponseTests.cs
index e7db6e6..d8d1529 100644
--- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPResponseTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPResponseTests.cs
@@ -13,7 +13,9 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using DotNetOpenAuth.OpenId.Messages;
using DotNetOpenAuth.OpenId.RelyingParty;
+ using DotNetOpenAuth.OpenId.RelyingParty.Extensions;
using NUnit.Framework;
+ using ExtensionsInteropProviderHelper = DotNetOpenAuth.OpenId.Provider.Extensions.ExtensionsInteropHelper;
[TestFixture]
public class ExtensionsInteropHelperRPResponseTests : OpenIdTestBase {
@@ -74,7 +76,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
[TestCase]
public void UnifyExtensionsasSregFromSchemaOpenIdNet() {
var axInjected = new FetchResponse();
- axInjected.Attributes.Add(ExtensionsInteropHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.Alias, AXAttributeFormats.SchemaOpenIdNet), "nate");
+ axInjected.Attributes.Add(ExtensionsInteropProviderHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.Alias, AXAttributeFormats.SchemaOpenIdNet), "nate");
this.extensions.Add(axInjected);
var sreg = ExtensionsInteropHelper.UnifyExtensionsAsSreg(this.response, true);
Assert.AreEqual("nate", sreg.Nickname);
diff --git a/src/DotNetOpenAuth.Test/OpenId/IdentifierTests.cs b/src/DotNetOpenAuth.Test/OpenId/IdentifierTests.cs
index 01e2fdc..5d3a15e 100644
--- a/src/DotNetOpenAuth.Test/OpenId/IdentifierTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/IdentifierTests.cs
@@ -75,7 +75,7 @@ namespace DotNetOpenAuth.Test.OpenId {
Assert.AreEqual(this.uri, ((UriIdentifier)id).Uri.AbsoluteUri);
}
- [TestCase, ExpectedException(typeof(ArgumentException))]
+ [TestCase, ExpectedException(typeof(ArgumentNullException))]
public void ParseNull() {
Identifier.Parse(null);
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateRequestTests.cs
index f3c18d9..2d40f76 100644
--- a/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateRequestTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/Messages/AssociateRequestTests.cs
@@ -85,11 +85,11 @@ namespace DotNetOpenAuth.Test.OpenId.Messages {
securitySettings.MinimumHashBitLength = 160;
securitySettings.MaximumHashBitLength = 160;
ProviderEndpointDescription provider = new ProviderEndpointDescription(OPUri, protocol.Version);
- Assert.AreEqual(AssociateRequest.Create(securitySettings, provider).AssociationType, protocol.Args.SignatureAlgorithm.HMAC_SHA1);
+ Assert.AreEqual(AssociateRequestRelyingParty.Create(securitySettings, provider).AssociationType, protocol.Args.SignatureAlgorithm.HMAC_SHA1);
securitySettings.MinimumHashBitLength = 384;
securitySettings.MaximumHashBitLength = 384;
- Assert.AreEqual(AssociateRequest.Create(securitySettings, provider).AssociationType, protocol.Args.SignatureAlgorithm.HMAC_SHA384);
+ Assert.AreEqual(AssociateRequestRelyingParty.Create(securitySettings, provider).AssociationType, protocol.Args.SignatureAlgorithm.HMAC_SHA384);
}
}
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectSignedResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectSignedResponseTests.cs
index 406a48b..848c849 100644
--- a/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectSignedResponseTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/Messages/IndirectSignedResponseTests.cs
@@ -125,7 +125,7 @@ namespace DotNetOpenAuth.Test.OpenId.Messages {
}
}
- [TestCase, ExpectedException(typeof(ArgumentException))]
+ [TestCase, ExpectedException(typeof(ArgumentNullException))]
public void GetReturnToArgumentNullKey() {
this.response.GetReturnToArgument(null);
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/NonIdentityTests.cs b/src/DotNetOpenAuth.Test/OpenId/NonIdentityTests.cs
index 17ab090..6e3a289 100644
--- a/src/DotNetOpenAuth.Test/OpenId/NonIdentityTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/NonIdentityTests.cs
@@ -21,7 +21,7 @@ namespace DotNetOpenAuth.Test.OpenId {
var coordinator = new OpenIdCoordinator(
rp => {
var request = new SignedResponseRequest(protocol.Version, OPUri, mode);
- rp.Channel.Send(request);
+ rp.Channel.Respond(request);
},
op => {
var request = op.Channel.ReadFromRequest<SignedResponseRequest>();
@@ -38,18 +38,18 @@ namespace DotNetOpenAuth.Test.OpenId {
var request = rp.CreateRequest(GetMockIdentifier(protocol.ProtocolVersion), RPRealmUri, RPUri);
request.IsExtensionOnly = true;
- rp.Channel.Send(request.RedirectingResponse.OriginalMessage);
+ rp.Channel.Respond(request.RedirectingResponse.OriginalMessage);
IAuthenticationResponse response = rp.GetResponse();
Assert.AreEqual(AuthenticationStatus.ExtensionsOnly, response.Status);
},
op => {
var assocRequest = op.GetRequest();
- op.SendResponse(assocRequest);
+ op.Respond(assocRequest);
var request = (IAnonymousRequest)op.GetRequest();
request.IsApproved = true;
Assert.IsNotInstanceOf<CheckIdRequest>(request);
- op.SendResponse(request);
+ op.Respond(request);
});
coordinator.Run();
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/OpenIdCoordinator.cs b/src/DotNetOpenAuth.Test/OpenId/OpenIdCoordinator.cs
index d4884e8..e5c3c64 100644
--- a/src/DotNetOpenAuth.Test/OpenId/OpenIdCoordinator.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/OpenIdCoordinator.cs
@@ -37,7 +37,7 @@ namespace DotNetOpenAuth.Test.OpenId {
}
private static Action<OpenIdRelyingParty> WrapAction(Action<OpenIdRelyingParty> action) {
- Contract.Requires<ArgumentNullException>(action != null);
+ Requires.NotNull(action, "action");
return rp => {
action(rp);
@@ -46,7 +46,7 @@ namespace DotNetOpenAuth.Test.OpenId {
}
private static Action<OpenIdProvider> WrapAction(Action<OpenIdProvider> action) {
- Contract.Requires<ArgumentNullException>(action != null);
+ Requires.NotNull(action, "action");
return op => {
action(op);
diff --git a/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs b/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs
index 414585f..4b96d65 100644
--- a/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs
@@ -66,8 +66,8 @@ namespace DotNetOpenAuth.Test.OpenId {
public override void SetUp() {
base.SetUp();
- this.RelyingPartySecuritySettings = DotNetOpenAuthSection.Configuration.OpenId.RelyingParty.SecuritySettings.CreateSecuritySettings();
- this.ProviderSecuritySettings = DotNetOpenAuthSection.Configuration.OpenId.Provider.SecuritySettings.CreateSecuritySettings();
+ this.RelyingPartySecuritySettings = OpenIdElement.Configuration.RelyingParty.SecuritySettings.CreateSecuritySettings();
+ this.ProviderSecuritySettings = OpenIdElement.Configuration.Provider.SecuritySettings.CreateSecuritySettings();
this.MockResponder = MockHttpRequest.CreateUntrustedMockHttpHandler();
this.RequestHandler = this.MockResponder.MockWebRequestHandler;
@@ -171,7 +171,7 @@ namespace DotNetOpenAuth.Test.OpenId {
}
}
- provider.SendResponse(request);
+ provider.Respond(request);
}
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs
index 39b4355..d124c7a 100644
--- a/src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs
@@ -22,7 +22,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider {
// Construct a V1 immediate request
Protocol protocol = Protocol.V11;
OpenIdProvider provider = this.CreateProvider();
- CheckIdRequest immediateRequest = new CheckIdRequest(protocol.Version, OPUri, DotNetOpenAuth.OpenId.RelyingParty.AuthenticationRequestMode.Immediate);
+ CheckIdRequest immediateRequest = new CheckIdRequest(protocol.Version, OPUri, DotNetOpenAuth.OpenId.AuthenticationRequestMode.Immediate);
immediateRequest.Realm = RPRealmUri;
immediateRequest.ReturnTo = RPUri;
immediateRequest.LocalIdentifier = "http://somebody";
diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/HostProcessedRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/HostProcessedRequestTests.cs
index 9bb8095..66b2f53 100644
--- a/src/DotNetOpenAuth.Test/OpenId/Provider/HostProcessedRequestTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/Provider/HostProcessedRequestTests.cs
@@ -24,7 +24,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider {
this.protocol = Protocol.Default;
this.provider = this.CreateProvider();
- this.checkIdRequest = new CheckIdRequest(this.protocol.Version, OPUri, DotNetOpenAuth.OpenId.RelyingParty.AuthenticationRequestMode.Setup);
+ this.checkIdRequest = new CheckIdRequest(this.protocol.Version, OPUri, DotNetOpenAuth.OpenId.AuthenticationRequestMode.Setup);
this.checkIdRequest.Realm = RPRealmUri;
this.checkIdRequest.ReturnTo = RPUri;
this.request = new AuthenticationRequest(this.provider, this.checkIdRequest);
@@ -32,14 +32,14 @@ namespace DotNetOpenAuth.Test.OpenId.Provider {
[TestCase]
public void IsReturnUrlDiscoverableNoResponse() {
- Assert.AreEqual(RelyingPartyDiscoveryResult.NoServiceDocument, this.request.IsReturnUrlDiscoverable(this.provider));
+ Assert.AreEqual(RelyingPartyDiscoveryResult.NoServiceDocument, this.request.IsReturnUrlDiscoverable(this.provider.Channel.WebRequestHandler));
}
[TestCase]
public void IsReturnUrlDiscoverableValidResponse() {
this.MockResponder.RegisterMockRPDiscovery();
this.request = new AuthenticationRequest(this.provider, this.checkIdRequest);
- Assert.AreEqual(RelyingPartyDiscoveryResult.Success, this.request.IsReturnUrlDiscoverable(this.provider));
+ Assert.AreEqual(RelyingPartyDiscoveryResult.Success, this.request.IsReturnUrlDiscoverable(this.provider.Channel.WebRequestHandler));
}
/// <summary>
@@ -50,7 +50,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider {
public void IsReturnUrlDiscoverableNotSsl() {
this.provider.SecuritySettings.RequireSsl = true;
this.MockResponder.RegisterMockRPDiscovery();
- Assert.AreEqual(RelyingPartyDiscoveryResult.NoServiceDocument, this.request.IsReturnUrlDiscoverable(this.provider));
+ Assert.AreEqual(RelyingPartyDiscoveryResult.NoServiceDocument, this.request.IsReturnUrlDiscoverable(this.provider.Channel.WebRequestHandler));
}
/// <summary>
@@ -65,12 +65,12 @@ namespace DotNetOpenAuth.Test.OpenId.Provider {
// Try once with RequireSsl
this.provider.SecuritySettings.RequireSsl = true;
this.request = new AuthenticationRequest(this.provider, this.checkIdRequest);
- Assert.AreEqual(RelyingPartyDiscoveryResult.Success, this.request.IsReturnUrlDiscoverable(this.provider));
+ Assert.AreEqual(RelyingPartyDiscoveryResult.Success, this.request.IsReturnUrlDiscoverable(this.provider.Channel.WebRequestHandler));
// And again without RequireSsl
this.provider.SecuritySettings.RequireSsl = false;
this.request = new AuthenticationRequest(this.provider, this.checkIdRequest);
- Assert.AreEqual(RelyingPartyDiscoveryResult.Success, this.request.IsReturnUrlDiscoverable(this.provider));
+ Assert.AreEqual(RelyingPartyDiscoveryResult.Success, this.request.IsReturnUrlDiscoverable(this.provider.Channel.WebRequestHandler));
}
[TestCase]
@@ -79,7 +79,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider {
this.provider.SecuritySettings.RequireSsl = false; // reset for another failure test case
this.checkIdRequest.ReturnTo = new Uri("http://somerandom/host");
this.request = new AuthenticationRequest(this.provider, this.checkIdRequest);
- Assert.AreEqual(RelyingPartyDiscoveryResult.NoMatchingReturnTo, this.request.IsReturnUrlDiscoverable(this.provider));
+ Assert.AreEqual(RelyingPartyDiscoveryResult.NoMatchingReturnTo, this.request.IsReturnUrlDiscoverable(this.provider.Channel.WebRequestHandler));
}
}
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs
index 75d871c..98cabe9 100644
--- a/src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs
@@ -100,12 +100,12 @@ namespace DotNetOpenAuth.Test.OpenId.Provider {
// Test some non-empty request scenario.
OpenIdCoordinator coordinator = new OpenIdCoordinator(
rp => {
- rp.Channel.Request(AssociateRequest.Create(rp.SecuritySettings, providerDescription));
+ rp.Channel.Request(AssociateRequestRelyingParty.Create(rp.SecuritySettings, providerDescription));
},
op => {
IRequest request = op.GetRequest();
Assert.IsInstanceOf<AutoResponsiveRequest>(request);
- op.SendResponse(request);
+ op.Respond(request);
});
coordinator.Run();
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/PerformanceTests.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/PerformanceTests.cs
index 4530982..1e15bde 100644
--- a/src/DotNetOpenAuth.Test/OpenId/Provider/PerformanceTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/Provider/PerformanceTests.cs
@@ -74,12 +74,12 @@ namespace DotNetOpenAuth.Test.OpenId.Provider {
}
private void ParameterizedCheckIdTest(Protocol protocol, string assocType) {
- Association assoc = HmacShaAssociation.Create(
+ Association assoc = HmacShaAssociationProvider.Create(
protocol,
assocType,
AssociationRelyingPartyType.Smart,
+ this.provider.AssociationStore,
this.provider.SecuritySettings);
- this.provider.AssociationStore.StoreAssociation(AssociationRelyingPartyType.Smart, assoc);
var checkidRequest = this.CreateCheckIdRequest(true);
MeasurePerformance(
() => {
@@ -93,7 +93,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider {
private HttpRequestInfo CreateAssociateRequest(Uri opEndpoint) {
var rp = CreateRelyingParty(true);
- AssociateRequest associateMessage = AssociateRequest.Create(rp.SecuritySettings, new ProviderEndpointDescription(opEndpoint, Protocol.Default.Version));
+ AssociateRequest associateMessage = AssociateRequestRelyingParty.Create(rp.SecuritySettings, new ProviderEndpointDescription(opEndpoint, Protocol.Default.Version));
Channel rpChannel = rp.Channel;
MemoryStream ms = new MemoryStream();
StreamWriter mswriter = new StreamWriter(ms);
@@ -111,7 +111,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider {
CheckIdRequest checkidMessage = new CheckIdRequest(
Protocol.Default.Version,
OPUri,
- DotNetOpenAuth.OpenId.RelyingParty.AuthenticationRequestMode.Setup);
+ DotNetOpenAuth.OpenId.AuthenticationRequestMode.Setup);
if (sharedAssociation) {
checkidMessage.AssociationHandle = SharedAssociationHandle;
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/AssociationsTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/AssociationsTests.cs
index b3d7e4d..531fb45 100644
--- a/src/DotNetOpenAuth.Test/OpenId/AssociationsTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/AssociationsTests.cs
@@ -4,13 +4,14 @@
// </copyright>
//-----------------------------------------------------------------------
-namespace DotNetOpenAuth.Test.OpenId {
+namespace DotNetOpenAuth.Test.OpenId.RelyingParty {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using DotNetOpenAuth.OpenId;
+ using DotNetOpenAuth.OpenId.RelyingParty;
using NUnit.Framework;
[TestFixture]
diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/IdentifierDiscoveryResultTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/IdentifierDiscoveryResultTests.cs
index 896cf57..6d2de71 100644
--- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/IdentifierDiscoveryResultTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/IdentifierDiscoveryResultTests.cs
@@ -143,7 +143,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty {
Assert.IsFalse(se.IsTypeUriPresent("http://someother"));
}
- [TestCase, ExpectedException(typeof(ArgumentException))]
+ [TestCase, ExpectedException(typeof(ArgumentNullException))]
public void IsTypeUriPresentNull() {
IdentifierDiscoveryResult se = IdentifierDiscoveryResult.CreateForClaimedIdentifier(this.claimedXri, this.userSuppliedXri, this.localId, new ProviderEndpointDescription(this.providerEndpoint, this.v20TypeUris), this.servicePriority, this.uriPriority);
se.IsTypeUriPresent(null);
@@ -161,7 +161,7 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty {
se.IsExtensionSupported((Type)null);
}
- [TestCase, ExpectedException(typeof(ArgumentException))]
+ [TestCase, ExpectedException(typeof(ArgumentNullException))]
public void IsTypeUriPresentNullString() {
var se = IdentifierDiscoveryResult.CreateForProviderIdentifier(OPUri, new ProviderEndpointDescription(OPUri, this.v20TypeUris), null, null);
se.IsTypeUriPresent((string)null);
diff --git a/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs b/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs
index e6bed2f..427f890 100644
--- a/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs
@@ -31,7 +31,7 @@ namespace DotNetOpenAuth.Test.OpenId {
new UriIdentifier((Uri)null);
}
- [TestCase, ExpectedException(typeof(ArgumentException))]
+ [TestCase, ExpectedException(typeof(ArgumentNullException))]
public void CtorNullString() {
new UriIdentifier((string)null);
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/XriIdentifierTests.cs b/src/DotNetOpenAuth.Test/OpenId/XriIdentifierTests.cs
index 0c80821..e2acf34 100644
--- a/src/DotNetOpenAuth.Test/OpenId/XriIdentifierTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/XriIdentifierTests.cs
@@ -22,7 +22,7 @@ namespace DotNetOpenAuth.Test.OpenId {
base.SetUp();
}
- [TestCase, ExpectedException(typeof(ArgumentException))]
+ [TestCase, ExpectedException(typeof(ArgumentNullException))]
public void CtorNull() {
new XriIdentifier(null);
}
diff --git a/src/DotNetOpenAuth.TestWeb/OpenIdProviderEndpoint.ashx b/src/DotNetOpenAuth.TestWeb/OpenIdProviderEndpoint.ashx
index b282a3b..ca23eac 100644
--- a/src/DotNetOpenAuth.TestWeb/OpenIdProviderEndpoint.ashx
+++ b/src/DotNetOpenAuth.TestWeb/OpenIdProviderEndpoint.ashx
@@ -13,7 +13,7 @@ public class OpenIdProviderEndpoint : IHttpHandler {
authRequest.IsAuthenticated = true;
}
- provider.SendResponse(request);
+ provider.Respond(request);
}
}
diff --git a/src/DotNetOpenAuth.sln b/src/DotNetOpenAuth.sln
index cf7f97e..505ce7e 100644
--- a/src/DotNetOpenAuth.sln
+++ b/src/DotNetOpenAuth.sln
@@ -9,11 +9,12 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
..\doc\README.Bin.html = ..\doc\README.Bin.html
..\doc\README.html = ..\doc\README.html
..\samples\README.html = ..\samples\README.html
- ..\nuget\content\web.config.transform = ..\nuget\content\web.config.transform
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Specs", "Specs", "{CD57219F-24F4-4136-8741-6063D0D7A031}"
ProjectSection(SolutionItems) = preProject
+ ..\doc\specs\draft-ietf-oauth-v2-16.txt = ..\doc\specs\draft-ietf-oauth-v2-16.txt
+ ..\doc\specs\draft-ietf-oauth.html = ..\doc\specs\draft-ietf-oauth.html
..\doc\specs\ICAM_OpenID20Profile.pdf = ..\doc\specs\ICAM_OpenID20Profile.pdf
..\doc\specs\OAuth Core 1.0.htm = ..\doc\specs\OAuth Core 1.0.htm
..\doc\specs\OAuth Core 1.0a (Draft 3).htm = ..\doc\specs\OAuth Core 1.0a (Draft 3).htm
@@ -30,7 +31,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{B4C6
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "OpenID", "OpenID", "{034D5B5B-7D00-4A9D-8AFE-4A476E0575B1}"
EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "OAuth", "OAuth", "{1E2CBAA5-60A3-4AED-912E-541F5753CDC6}"
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "OAuth2", "OAuth2", "{1E2CBAA5-60A3-4AED-912E-541F5753CDC6}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "InfoCard", "InfoCard", "{8A5CEDB9-7F8A-4BE2-A1B9-97130F453277}"
EndProject
@@ -38,8 +39,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tools", "Tools", "{E9ED920D
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Project Templates", "Project Templates", "{B9EB8729-4B54-4453-B089-FE6761BA3057}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth", "DotNetOpenAuth\DotNetOpenAuth.csproj", "{3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}"
-EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.Test", "DotNetOpenAuth.Test\DotNetOpenAuth.Test.csproj", "{4376ECC9-C346-4A99-B13C-FA93C0FBD2C9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.ApplicationBlock", "..\samples\DotNetOpenAuth.ApplicationBlock\DotNetOpenAuth.ApplicationBlock.csproj", "{AA78D112-D889-414B-A7D4-467B34C7B663}"
@@ -47,7 +46,7 @@ EndProject
Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "DotNetOpenAuth.TestWeb", "DotNetOpenAuth.TestWeb\", "{47A84EF7-68C3-4D47-926A-9CCEA6518531}"
ProjectSection(WebsiteProperties) = preProject
TargetFrameworkMoniker = ".NETFramework,Version%3Dv3.5"
- ProjectReferences = "{3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}|DotNetOpenAuth.dll;{4376ECC9-C346-4A99-B13C-FA93C0FBD2C9}|DotNetOpenAuth.Test.dll;"
+ ProjectReferences = "{4376ECC9-C346-4A99-B13C-FA93C0FBD2C9}|DotNetOpenAuth.Test.dll;{408D10B8-34BA-4CBD-B7AA-FEB1907ABA4C}|DotNetOpenAuth.InfoCard.dll;{60426312-6AE5-4835-8667-37EDEA670222}|DotNetOpenAuth.Core.dll;{A288FCC8-6FCF-46DA-A45E-5F9281556361}|DotNetOpenAuth.OAuth.dll;{3896A32A-E876-4C23-B9B8-78E17D134CD3}|DotNetOpenAuth.OpenId.dll;{56459A6C-6BA2-4BAC-A9C0-27E3BD961FA6}|DotNetOpenAuth.OAuth2.dll;{26DC877F-5987-48DD-9DDB-E62F2DE0E150}|Org.Mentalis.Security.Cryptography.dll;{F4CD3C04-6037-4946-B7A5-34BFC96A75D2}|Mono.Math.dll;{173E7B8D-E751-46E2-A133-F72297C0D2F4}|DotNetOpenAuth.Core.UI.dll;{E040EB58-B4D2-457B-A023-AE6EF3BD34DE}|DotNetOpenAuth.InfoCard.UI.dll;{B202E40D-4663-4A2B-ACDA-865F88FF7CAA}|DotNetOpenAuth.OAuth.Consumer.dll;{FED1923A-6D70-49B5-A37A-FB744FEC1C86}|DotNetOpenAuth.OAuth.ServiceProvider.dll;{99BB7543-EA16-43EE-A7BC-D7A25A3B22F6}|DotNetOpenAuth.OAuth2.AuthorizationServer.dll;{CDEDD439-7F35-4E6E-8605-4E70BDC4CC99}|DotNetOpenAuth.OAuth2.Client.dll;{ADC2CC8C-541E-4F86-ACB1-DD504A36FA4B}|DotNetOpenAuth.OAuth2.Client.UI.dll;{A1A3150A-7B0E-4A34-8E35-045296CD3C76}|DotNetOpenAuth.OAuth2.ResourceServer.dll;{F8284738-3B5D-4733-A511-38C23F4A763F}|DotNetOpenAuth.OpenId.Provider.dll;{F458AB60-BA1C-43D9-8CEF-EC01B50BE87B}|DotNetOpenAuth.OpenId.RelyingParty.dll;{9D0F8866-2131-4C2A-BC0E-16FEA5B50828}|DotNetOpenAuth.OpenId.Provider.UI.dll;{75E13AAE-7D51-4421-ABFD-3F3DC91F576E}|DotNetOpenAuth.OpenId.UI.dll;{1ED8D424-F8AB-4050-ACEB-F27F4F909484}|DotNetOpenAuth.OpenId.RelyingParty.UI.dll;"
Debug.AspNetCompiler.VirtualPath = "/DotNetOpenAuth.TestWeb"
Debug.AspNetCompiler.PhysicalPath = "DotNetOpenAuth.TestWeb\"
Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\DotNetOpenAuth.TestWeb\"
@@ -74,7 +73,7 @@ EndProject
Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "InfoCardRelyingParty", "..\samples\InfoCardRelyingParty\", "{6EB90284-BD15-461C-BBF2-131CF55F7C8B}"
ProjectSection(WebsiteProperties) = preProject
TargetFrameworkMoniker = ".NETFramework,Version%3Dv3.5"
- ProjectReferences = "{3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}|DotNetOpenAuth.dll;"
+ ProjectReferences = "{408D10B8-34BA-4CBD-B7AA-FEB1907ABA4C}|DotNetOpenAuth.InfoCard.dll;{60426312-6AE5-4835-8667-37EDEA670222}|DotNetOpenAuth.Core.dll;{173E7B8D-E751-46E2-A133-F72297C0D2F4}|DotNetOpenAuth.Core.UI.dll;{26DC877F-5987-48DD-9DDB-E62F2DE0E150}|Org.Mentalis.Security.Cryptography.dll;{F4CD3C04-6037-4946-B7A5-34BFC96A75D2}|Mono.Math.dll;{E040EB58-B4D2-457B-A023-AE6EF3BD34DE}|DotNetOpenAuth.InfoCard.UI.dll;"
Debug.AspNetCompiler.VirtualPath = "/InfoCardRelyingParty"
Debug.AspNetCompiler.PhysicalPath = "..\samples\InfoCardRelyingParty\"
Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\InfoCardRelyingParty\"
@@ -140,12 +139,68 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenIdWebRingSsoProvider",
EndProject
Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "OpenIdRelyingPartyWebFormsVB", "..\samples\OpenIdRelyingPartyWebFormsVB\OpenIdRelyingPartyWebFormsVB.vbproj", "{F289B925-4307-4BEC-B411-885CE70E3379}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OAuthConsumer", "..\samples\OAuthConsumer\OAuthConsumer.csproj", "{9529606E-AF76-4387-BFB7-3D10A5B399AA}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OAuthClient", "..\samples\OAuthClient\OAuthClient.csproj", "{9529606E-AF76-4387-BFB7-3D10A5B399AA}"
ProjectSection(ProjectDependencies) = postProject
{E135F455-0669-49F8-9207-07FCA8C8FC79} = {E135F455-0669-49F8-9207-07FCA8C8FC79}
EndProjectSection
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OAuthServiceProvider", "..\samples\OAuthServiceProvider\OAuthServiceProvider.csproj", "{E135F455-0669-49F8-9207-07FCA8C8FC79}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OAuthResourceServer", "..\samples\OAuthResourceServer\OAuthResourceServer.csproj", "{E135F455-0669-49F8-9207-07FCA8C8FC79}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OAuthAuthorizationServer", "..\samples\OAuthAuthorizationServer\OAuthAuthorizationServer.csproj", "{C78E8235-1D46-43EB-A912-80B522C4E9AE}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.Core", "DotNetOpenAuth.Core\DotNetOpenAuth.Core.csproj", "{60426312-6AE5-4835-8667-37EDEA670222}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.OpenId", "DotNetOpenAuth.OpenId\DotNetOpenAuth.OpenId.csproj", "{3896A32A-E876-4C23-B9B8-78E17D134CD3}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.OAuth", "DotNetOpenAuth.OAuth\DotNetOpenAuth.OAuth.csproj", "{A288FCC8-6FCF-46DA-A45E-5F9281556361}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.InfoCard", "DotNetOpenAuth.InfoCard\DotNetOpenAuth.InfoCard.csproj", "{408D10B8-34BA-4CBD-B7AA-FEB1907ABA4C}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.OAuth2", "DotNetOpenAuth.OAuth2\DotNetOpenAuth.OAuth2.csproj", "{56459A6C-6BA2-4BAC-A9C0-27E3BD961FA6}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.OpenId.Provider", "DotNetOpenAuth.OpenId.Provider\DotNetOpenAuth.OpenId.Provider.csproj", "{F8284738-3B5D-4733-A511-38C23F4A763F}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.OpenId.RelyingParty", "DotNetOpenAuth.OpenId.RelyingParty\DotNetOpenAuth.OpenId.RelyingParty.csproj", "{F458AB60-BA1C-43D9-8CEF-EC01B50BE87B}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mono.Math", "Mono.Math\Mono.Math.csproj", "{F4CD3C04-6037-4946-B7A5-34BFC96A75D2}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.Mentalis.Security.Cryptography", "Org.Mentalis.Security.Cryptography\Org.Mentalis.Security.Cryptography.csproj", "{26DC877F-5987-48DD-9DDB-E62F2DE0E150}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.OpenId.RelyingParty.UI", "DotNetOpenAuth.OpenId.RelyingParty.UI\DotNetOpenAuth.OpenId.RelyingParty.UI.csproj", "{1ED8D424-F8AB-4050-ACEB-F27F4F909484}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.OpenId.Provider.UI", "DotNetOpenAuth.OpenId.Provider.UI\DotNetOpenAuth.OpenId.Provider.UI.csproj", "{9D0F8866-2131-4C2A-BC0E-16FEA5B50828}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.OpenId.UI", "DotNetOpenAuth.OpenId.UI\DotNetOpenAuth.OpenId.UI.csproj", "{75E13AAE-7D51-4421-ABFD-3F3DC91F576E}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.Core.UI", "DotNetOpenAuth.Core.UI\DotNetOpenAuth.Core.UI.csproj", "{173E7B8D-E751-46E2-A133-F72297C0D2F4}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Product", "Product", "{8D4236F7-C49B-49D3-BA71-6B86C9514BDE}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "OpenID", "OpenID", "{C7EF1823-3AA7-477E-8476-28929F5C05D2}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "OAuth", "OAuth", "{9AF74F53-10F5-49A2-B747-87B97CD559D3}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "InfoCard", "InfoCard", "{529B4262-6B5A-4EF9-BD3B-1D29A2597B67}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.InfoCard.UI", "DotNetOpenAuth.InfoCard.UI\DotNetOpenAuth.InfoCard.UI.csproj", "{E040EB58-B4D2-457B-A023-AE6EF3BD34DE}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "OAuth2", "OAuth2", "{238B6BA8-AD99-43C9-B8E2-D2BCE6CE04DC}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.OAuth.Consumer", "DotNetOpenAuth.OAuth.Consumer\DotNetOpenAuth.OAuth.Consumer.csproj", "{B202E40D-4663-4A2B-ACDA-865F88FF7CAA}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.OAuth.ServiceProvider", "DotNetOpenAuth.OAuth.ServiceProvider\DotNetOpenAuth.OAuth.ServiceProvider.csproj", "{FED1923A-6D70-49B5-A37A-FB744FEC1C86}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.OAuth2.AuthorizationServer", "DotNetOpenAuth.OAuth2.AuthorizationServer\DotNetOpenAuth.OAuth2.AuthorizationServer.csproj", "{99BB7543-EA16-43EE-A7BC-D7A25A3B22F6}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.OAuth2.Client", "DotNetOpenAuth.OAuth2.Client\DotNetOpenAuth.OAuth2.Client.csproj", "{CDEDD439-7F35-4E6E-8605-4E70BDC4CC99}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.OAuth2.ResourceServer", "DotNetOpenAuth.OAuth2.ResourceServer\DotNetOpenAuth.OAuth2.ResourceServer.csproj", "{A1A3150A-7B0E-4A34-8E35-045296CD3C76}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.OAuth2.Client.UI", "DotNetOpenAuth.OAuth2.Client.UI\DotNetOpenAuth.OAuth2.Client.UI.csproj", "{ADC2CC8C-541E-4F86-ACB1-DD504A36FA4B}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Combinations", "Combinations", "{57A7DD35-666C-4FA3-9A1B-38961E50CA27}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.OpenIdInfoCard.UI", "DotNetOpenAuth.OpenIdInfoCard.UI\DotNetOpenAuth.OpenIdInfoCard.UI.csproj", "{3A8347E8-59A5-4092-8842-95C75D7D2F36}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -155,14 +210,6 @@ Global
ReleaseNoUI|Any CPU = ReleaseNoUI|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU
- {3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU
- {3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}.Release|Any CPU.Build.0 = Release|Any CPU
- {3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}.ReleaseNoUI|Any CPU.ActiveCfg = ReleaseNoUI|Any CPU
- {3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}.ReleaseNoUI|Any CPU.Build.0 = ReleaseNoUI|Any CPU
{4376ECC9-C346-4A99-B13C-FA93C0FBD2C9}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU
{4376ECC9-C346-4A99-B13C-FA93C0FBD2C9}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU
{4376ECC9-C346-4A99-B13C-FA93C0FBD2C9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
@@ -306,6 +353,182 @@ Global
{E135F455-0669-49F8-9207-07FCA8C8FC79}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E135F455-0669-49F8-9207-07FCA8C8FC79}.Release|Any CPU.Build.0 = Release|Any CPU
{E135F455-0669-49F8-9207-07FCA8C8FC79}.ReleaseNoUI|Any CPU.ActiveCfg = Release|Any CPU
+ {C78E8235-1D46-43EB-A912-80B522C4E9AE}.CodeAnalysis|Any CPU.ActiveCfg = Release|Any CPU
+ {C78E8235-1D46-43EB-A912-80B522C4E9AE}.CodeAnalysis|Any CPU.Build.0 = Release|Any CPU
+ {C78E8235-1D46-43EB-A912-80B522C4E9AE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {C78E8235-1D46-43EB-A912-80B522C4E9AE}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {C78E8235-1D46-43EB-A912-80B522C4E9AE}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {C78E8235-1D46-43EB-A912-80B522C4E9AE}.Release|Any CPU.Build.0 = Release|Any CPU
+ {C78E8235-1D46-43EB-A912-80B522C4E9AE}.ReleaseNoUI|Any CPU.ActiveCfg = Release|Any CPU
+ {C78E8235-1D46-43EB-A912-80B522C4E9AE}.ReleaseNoUI|Any CPU.Build.0 = Release|Any CPU
+ {60426312-6AE5-4835-8667-37EDEA670222}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU
+ {60426312-6AE5-4835-8667-37EDEA670222}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU
+ {60426312-6AE5-4835-8667-37EDEA670222}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {60426312-6AE5-4835-8667-37EDEA670222}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {60426312-6AE5-4835-8667-37EDEA670222}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {60426312-6AE5-4835-8667-37EDEA670222}.Release|Any CPU.Build.0 = Release|Any CPU
+ {60426312-6AE5-4835-8667-37EDEA670222}.ReleaseNoUI|Any CPU.ActiveCfg = Release|Any CPU
+ {60426312-6AE5-4835-8667-37EDEA670222}.ReleaseNoUI|Any CPU.Build.0 = Release|Any CPU
+ {3896A32A-E876-4C23-B9B8-78E17D134CD3}.CodeAnalysis|Any CPU.ActiveCfg = Debug|Any CPU
+ {3896A32A-E876-4C23-B9B8-78E17D134CD3}.CodeAnalysis|Any CPU.Build.0 = Debug|Any CPU
+ {3896A32A-E876-4C23-B9B8-78E17D134CD3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {3896A32A-E876-4C23-B9B8-78E17D134CD3}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {3896A32A-E876-4C23-B9B8-78E17D134CD3}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {3896A32A-E876-4C23-B9B8-78E17D134CD3}.Release|Any CPU.Build.0 = Release|Any CPU
+ {3896A32A-E876-4C23-B9B8-78E17D134CD3}.ReleaseNoUI|Any CPU.ActiveCfg = Release|Any CPU
+ {3896A32A-E876-4C23-B9B8-78E17D134CD3}.ReleaseNoUI|Any CPU.Build.0 = Release|Any CPU
+ {A288FCC8-6FCF-46DA-A45E-5F9281556361}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU
+ {A288FCC8-6FCF-46DA-A45E-5F9281556361}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU
+ {A288FCC8-6FCF-46DA-A45E-5F9281556361}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {A288FCC8-6FCF-46DA-A45E-5F9281556361}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {A288FCC8-6FCF-46DA-A45E-5F9281556361}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {A288FCC8-6FCF-46DA-A45E-5F9281556361}.Release|Any CPU.Build.0 = Release|Any CPU
+ {A288FCC8-6FCF-46DA-A45E-5F9281556361}.ReleaseNoUI|Any CPU.ActiveCfg = Release|Any CPU
+ {A288FCC8-6FCF-46DA-A45E-5F9281556361}.ReleaseNoUI|Any CPU.Build.0 = Release|Any CPU
+ {408D10B8-34BA-4CBD-B7AA-FEB1907ABA4C}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU
+ {408D10B8-34BA-4CBD-B7AA-FEB1907ABA4C}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU
+ {408D10B8-34BA-4CBD-B7AA-FEB1907ABA4C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {408D10B8-34BA-4CBD-B7AA-FEB1907ABA4C}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {408D10B8-34BA-4CBD-B7AA-FEB1907ABA4C}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {408D10B8-34BA-4CBD-B7AA-FEB1907ABA4C}.Release|Any CPU.Build.0 = Release|Any CPU
+ {408D10B8-34BA-4CBD-B7AA-FEB1907ABA4C}.ReleaseNoUI|Any CPU.ActiveCfg = Release|Any CPU
+ {408D10B8-34BA-4CBD-B7AA-FEB1907ABA4C}.ReleaseNoUI|Any CPU.Build.0 = Release|Any CPU
+ {56459A6C-6BA2-4BAC-A9C0-27E3BD961FA6}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU
+ {56459A6C-6BA2-4BAC-A9C0-27E3BD961FA6}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU
+ {56459A6C-6BA2-4BAC-A9C0-27E3BD961FA6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {56459A6C-6BA2-4BAC-A9C0-27E3BD961FA6}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {56459A6C-6BA2-4BAC-A9C0-27E3BD961FA6}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {56459A6C-6BA2-4BAC-A9C0-27E3BD961FA6}.Release|Any CPU.Build.0 = Release|Any CPU
+ {56459A6C-6BA2-4BAC-A9C0-27E3BD961FA6}.ReleaseNoUI|Any CPU.ActiveCfg = Release|Any CPU
+ {56459A6C-6BA2-4BAC-A9C0-27E3BD961FA6}.ReleaseNoUI|Any CPU.Build.0 = Release|Any CPU
+ {F8284738-3B5D-4733-A511-38C23F4A763F}.CodeAnalysis|Any CPU.ActiveCfg = Debug|Any CPU
+ {F8284738-3B5D-4733-A511-38C23F4A763F}.CodeAnalysis|Any CPU.Build.0 = Debug|Any CPU
+ {F8284738-3B5D-4733-A511-38C23F4A763F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {F8284738-3B5D-4733-A511-38C23F4A763F}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {F8284738-3B5D-4733-A511-38C23F4A763F}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {F8284738-3B5D-4733-A511-38C23F4A763F}.Release|Any CPU.Build.0 = Release|Any CPU
+ {F8284738-3B5D-4733-A511-38C23F4A763F}.ReleaseNoUI|Any CPU.ActiveCfg = Release|Any CPU
+ {F8284738-3B5D-4733-A511-38C23F4A763F}.ReleaseNoUI|Any CPU.Build.0 = Release|Any CPU
+ {F458AB60-BA1C-43D9-8CEF-EC01B50BE87B}.CodeAnalysis|Any CPU.ActiveCfg = Debug|Any CPU
+ {F458AB60-BA1C-43D9-8CEF-EC01B50BE87B}.CodeAnalysis|Any CPU.Build.0 = Debug|Any CPU
+ {F458AB60-BA1C-43D9-8CEF-EC01B50BE87B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {F458AB60-BA1C-43D9-8CEF-EC01B50BE87B}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {F458AB60-BA1C-43D9-8CEF-EC01B50BE87B}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {F458AB60-BA1C-43D9-8CEF-EC01B50BE87B}.Release|Any CPU.Build.0 = Release|Any CPU
+ {F458AB60-BA1C-43D9-8CEF-EC01B50BE87B}.ReleaseNoUI|Any CPU.ActiveCfg = Release|Any CPU
+ {F458AB60-BA1C-43D9-8CEF-EC01B50BE87B}.ReleaseNoUI|Any CPU.Build.0 = Release|Any CPU
+ {F4CD3C04-6037-4946-B7A5-34BFC96A75D2}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU
+ {F4CD3C04-6037-4946-B7A5-34BFC96A75D2}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU
+ {F4CD3C04-6037-4946-B7A5-34BFC96A75D2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {F4CD3C04-6037-4946-B7A5-34BFC96A75D2}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {F4CD3C04-6037-4946-B7A5-34BFC96A75D2}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {F4CD3C04-6037-4946-B7A5-34BFC96A75D2}.Release|Any CPU.Build.0 = Release|Any CPU
+ {F4CD3C04-6037-4946-B7A5-34BFC96A75D2}.ReleaseNoUI|Any CPU.ActiveCfg = Release|Any CPU
+ {F4CD3C04-6037-4946-B7A5-34BFC96A75D2}.ReleaseNoUI|Any CPU.Build.0 = Release|Any CPU
+ {26DC877F-5987-48DD-9DDB-E62F2DE0E150}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU
+ {26DC877F-5987-48DD-9DDB-E62F2DE0E150}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU
+ {26DC877F-5987-48DD-9DDB-E62F2DE0E150}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {26DC877F-5987-48DD-9DDB-E62F2DE0E150}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {26DC877F-5987-48DD-9DDB-E62F2DE0E150}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {26DC877F-5987-48DD-9DDB-E62F2DE0E150}.Release|Any CPU.Build.0 = Release|Any CPU
+ {26DC877F-5987-48DD-9DDB-E62F2DE0E150}.ReleaseNoUI|Any CPU.ActiveCfg = Release|Any CPU
+ {26DC877F-5987-48DD-9DDB-E62F2DE0E150}.ReleaseNoUI|Any CPU.Build.0 = Release|Any CPU
+ {1ED8D424-F8AB-4050-ACEB-F27F4F909484}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU
+ {1ED8D424-F8AB-4050-ACEB-F27F4F909484}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU
+ {1ED8D424-F8AB-4050-ACEB-F27F4F909484}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {1ED8D424-F8AB-4050-ACEB-F27F4F909484}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {1ED8D424-F8AB-4050-ACEB-F27F4F909484}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {1ED8D424-F8AB-4050-ACEB-F27F4F909484}.Release|Any CPU.Build.0 = Release|Any CPU
+ {1ED8D424-F8AB-4050-ACEB-F27F4F909484}.ReleaseNoUI|Any CPU.ActiveCfg = Release|Any CPU
+ {1ED8D424-F8AB-4050-ACEB-F27F4F909484}.ReleaseNoUI|Any CPU.Build.0 = Release|Any CPU
+ {9D0F8866-2131-4C2A-BC0E-16FEA5B50828}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU
+ {9D0F8866-2131-4C2A-BC0E-16FEA5B50828}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU
+ {9D0F8866-2131-4C2A-BC0E-16FEA5B50828}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {9D0F8866-2131-4C2A-BC0E-16FEA5B50828}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {9D0F8866-2131-4C2A-BC0E-16FEA5B50828}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {9D0F8866-2131-4C2A-BC0E-16FEA5B50828}.Release|Any CPU.Build.0 = Release|Any CPU
+ {9D0F8866-2131-4C2A-BC0E-16FEA5B50828}.ReleaseNoUI|Any CPU.ActiveCfg = Release|Any CPU
+ {9D0F8866-2131-4C2A-BC0E-16FEA5B50828}.ReleaseNoUI|Any CPU.Build.0 = Release|Any CPU
+ {75E13AAE-7D51-4421-ABFD-3F3DC91F576E}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU
+ {75E13AAE-7D51-4421-ABFD-3F3DC91F576E}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU
+ {75E13AAE-7D51-4421-ABFD-3F3DC91F576E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {75E13AAE-7D51-4421-ABFD-3F3DC91F576E}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {75E13AAE-7D51-4421-ABFD-3F3DC91F576E}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {75E13AAE-7D51-4421-ABFD-3F3DC91F576E}.Release|Any CPU.Build.0 = Release|Any CPU
+ {75E13AAE-7D51-4421-ABFD-3F3DC91F576E}.ReleaseNoUI|Any CPU.ActiveCfg = Release|Any CPU
+ {75E13AAE-7D51-4421-ABFD-3F3DC91F576E}.ReleaseNoUI|Any CPU.Build.0 = Release|Any CPU
+ {173E7B8D-E751-46E2-A133-F72297C0D2F4}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU
+ {173E7B8D-E751-46E2-A133-F72297C0D2F4}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU
+ {173E7B8D-E751-46E2-A133-F72297C0D2F4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {173E7B8D-E751-46E2-A133-F72297C0D2F4}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {173E7B8D-E751-46E2-A133-F72297C0D2F4}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {173E7B8D-E751-46E2-A133-F72297C0D2F4}.Release|Any CPU.Build.0 = Release|Any CPU
+ {173E7B8D-E751-46E2-A133-F72297C0D2F4}.ReleaseNoUI|Any CPU.ActiveCfg = Release|Any CPU
+ {173E7B8D-E751-46E2-A133-F72297C0D2F4}.ReleaseNoUI|Any CPU.Build.0 = Release|Any CPU
+ {E040EB58-B4D2-457B-A023-AE6EF3BD34DE}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU
+ {E040EB58-B4D2-457B-A023-AE6EF3BD34DE}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU
+ {E040EB58-B4D2-457B-A023-AE6EF3BD34DE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {E040EB58-B4D2-457B-A023-AE6EF3BD34DE}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {E040EB58-B4D2-457B-A023-AE6EF3BD34DE}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {E040EB58-B4D2-457B-A023-AE6EF3BD34DE}.Release|Any CPU.Build.0 = Release|Any CPU
+ {E040EB58-B4D2-457B-A023-AE6EF3BD34DE}.ReleaseNoUI|Any CPU.ActiveCfg = Release|Any CPU
+ {E040EB58-B4D2-457B-A023-AE6EF3BD34DE}.ReleaseNoUI|Any CPU.Build.0 = Release|Any CPU
+ {B202E40D-4663-4A2B-ACDA-865F88FF7CAA}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU
+ {B202E40D-4663-4A2B-ACDA-865F88FF7CAA}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU
+ {B202E40D-4663-4A2B-ACDA-865F88FF7CAA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {B202E40D-4663-4A2B-ACDA-865F88FF7CAA}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {B202E40D-4663-4A2B-ACDA-865F88FF7CAA}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {B202E40D-4663-4A2B-ACDA-865F88FF7CAA}.Release|Any CPU.Build.0 = Release|Any CPU
+ {B202E40D-4663-4A2B-ACDA-865F88FF7CAA}.ReleaseNoUI|Any CPU.ActiveCfg = Release|Any CPU
+ {B202E40D-4663-4A2B-ACDA-865F88FF7CAA}.ReleaseNoUI|Any CPU.Build.0 = Release|Any CPU
+ {FED1923A-6D70-49B5-A37A-FB744FEC1C86}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU
+ {FED1923A-6D70-49B5-A37A-FB744FEC1C86}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU
+ {FED1923A-6D70-49B5-A37A-FB744FEC1C86}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {FED1923A-6D70-49B5-A37A-FB744FEC1C86}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {FED1923A-6D70-49B5-A37A-FB744FEC1C86}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {FED1923A-6D70-49B5-A37A-FB744FEC1C86}.Release|Any CPU.Build.0 = Release|Any CPU
+ {FED1923A-6D70-49B5-A37A-FB744FEC1C86}.ReleaseNoUI|Any CPU.ActiveCfg = Release|Any CPU
+ {FED1923A-6D70-49B5-A37A-FB744FEC1C86}.ReleaseNoUI|Any CPU.Build.0 = Release|Any CPU
+ {99BB7543-EA16-43EE-A7BC-D7A25A3B22F6}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU
+ {99BB7543-EA16-43EE-A7BC-D7A25A3B22F6}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU
+ {99BB7543-EA16-43EE-A7BC-D7A25A3B22F6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {99BB7543-EA16-43EE-A7BC-D7A25A3B22F6}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {99BB7543-EA16-43EE-A7BC-D7A25A3B22F6}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {99BB7543-EA16-43EE-A7BC-D7A25A3B22F6}.Release|Any CPU.Build.0 = Release|Any CPU
+ {99BB7543-EA16-43EE-A7BC-D7A25A3B22F6}.ReleaseNoUI|Any CPU.ActiveCfg = Release|Any CPU
+ {99BB7543-EA16-43EE-A7BC-D7A25A3B22F6}.ReleaseNoUI|Any CPU.Build.0 = Release|Any CPU
+ {CDEDD439-7F35-4E6E-8605-4E70BDC4CC99}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU
+ {CDEDD439-7F35-4E6E-8605-4E70BDC4CC99}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU
+ {CDEDD439-7F35-4E6E-8605-4E70BDC4CC99}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {CDEDD439-7F35-4E6E-8605-4E70BDC4CC99}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {CDEDD439-7F35-4E6E-8605-4E70BDC4CC99}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {CDEDD439-7F35-4E6E-8605-4E70BDC4CC99}.Release|Any CPU.Build.0 = Release|Any CPU
+ {CDEDD439-7F35-4E6E-8605-4E70BDC4CC99}.ReleaseNoUI|Any CPU.ActiveCfg = Release|Any CPU
+ {CDEDD439-7F35-4E6E-8605-4E70BDC4CC99}.ReleaseNoUI|Any CPU.Build.0 = Release|Any CPU
+ {A1A3150A-7B0E-4A34-8E35-045296CD3C76}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU
+ {A1A3150A-7B0E-4A34-8E35-045296CD3C76}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU
+ {A1A3150A-7B0E-4A34-8E35-045296CD3C76}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {A1A3150A-7B0E-4A34-8E35-045296CD3C76}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {A1A3150A-7B0E-4A34-8E35-045296CD3C76}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {A1A3150A-7B0E-4A34-8E35-045296CD3C76}.Release|Any CPU.Build.0 = Release|Any CPU
+ {A1A3150A-7B0E-4A34-8E35-045296CD3C76}.ReleaseNoUI|Any CPU.ActiveCfg = Release|Any CPU
+ {A1A3150A-7B0E-4A34-8E35-045296CD3C76}.ReleaseNoUI|Any CPU.Build.0 = Release|Any CPU
+ {ADC2CC8C-541E-4F86-ACB1-DD504A36FA4B}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU
+ {ADC2CC8C-541E-4F86-ACB1-DD504A36FA4B}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU
+ {ADC2CC8C-541E-4F86-ACB1-DD504A36FA4B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {ADC2CC8C-541E-4F86-ACB1-DD504A36FA4B}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {ADC2CC8C-541E-4F86-ACB1-DD504A36FA4B}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {ADC2CC8C-541E-4F86-ACB1-DD504A36FA4B}.Release|Any CPU.Build.0 = Release|Any CPU
+ {ADC2CC8C-541E-4F86-ACB1-DD504A36FA4B}.ReleaseNoUI|Any CPU.ActiveCfg = Release|Any CPU
+ {ADC2CC8C-541E-4F86-ACB1-DD504A36FA4B}.ReleaseNoUI|Any CPU.Build.0 = Release|Any CPU
+ {3A8347E8-59A5-4092-8842-95C75D7D2F36}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU
+ {3A8347E8-59A5-4092-8842-95C75D7D2F36}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU
+ {3A8347E8-59A5-4092-8842-95C75D7D2F36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {3A8347E8-59A5-4092-8842-95C75D7D2F36}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {3A8347E8-59A5-4092-8842-95C75D7D2F36}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {3A8347E8-59A5-4092-8842-95C75D7D2F36}.Release|Any CPU.Build.0 = Release|Any CPU
+ {3A8347E8-59A5-4092-8842-95C75D7D2F36}.ReleaseNoUI|Any CPU.ActiveCfg = Release|Any CPU
+ {3A8347E8-59A5-4092-8842-95C75D7D2F36}.ReleaseNoUI|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -327,11 +550,38 @@ Global
{6EC36418-DBC5-4AD1-A402-413604AA7A08} = {1E2CBAA5-60A3-4AED-912E-541F5753CDC6}
{9529606E-AF76-4387-BFB7-3D10A5B399AA} = {1E2CBAA5-60A3-4AED-912E-541F5753CDC6}
{E135F455-0669-49F8-9207-07FCA8C8FC79} = {1E2CBAA5-60A3-4AED-912E-541F5753CDC6}
+ {C78E8235-1D46-43EB-A912-80B522C4E9AE} = {1E2CBAA5-60A3-4AED-912E-541F5753CDC6}
{6EB90284-BD15-461C-BBF2-131CF55F7C8B} = {8A5CEDB9-7F8A-4BE2-A1B9-97130F453277}
{5C65603B-235F-47E6-B536-06385C60DE7F} = {E9ED920D-1F83-48C0-9A4B-09CCE505FE6D}
{A78F8FC6-7B03-4230-BE41-761E400D6810} = {B9EB8729-4B54-4453-B089-FE6761BA3057}
{17932639-1F50-48AF-B0A5-E2BF832F82CC} = {B9EB8729-4B54-4453-B089-FE6761BA3057}
{2B4261AC-25AC-4B8D-B459-1C42B6B1401D} = {B9EB8729-4B54-4453-B089-FE6761BA3057}
{152B7BAB-E884-4A59-8067-440971A682B3} = {B9EB8729-4B54-4453-B089-FE6761BA3057}
+ {C7EF1823-3AA7-477E-8476-28929F5C05D2} = {8D4236F7-C49B-49D3-BA71-6B86C9514BDE}
+ {9AF74F53-10F5-49A2-B747-87B97CD559D3} = {8D4236F7-C49B-49D3-BA71-6B86C9514BDE}
+ {529B4262-6B5A-4EF9-BD3B-1D29A2597B67} = {8D4236F7-C49B-49D3-BA71-6B86C9514BDE}
+ {238B6BA8-AD99-43C9-B8E2-D2BCE6CE04DC} = {8D4236F7-C49B-49D3-BA71-6B86C9514BDE}
+ {173E7B8D-E751-46E2-A133-F72297C0D2F4} = {8D4236F7-C49B-49D3-BA71-6B86C9514BDE}
+ {60426312-6AE5-4835-8667-37EDEA670222} = {8D4236F7-C49B-49D3-BA71-6B86C9514BDE}
+ {57A7DD35-666C-4FA3-9A1B-38961E50CA27} = {8D4236F7-C49B-49D3-BA71-6B86C9514BDE}
+ {F8284738-3B5D-4733-A511-38C23F4A763F} = {C7EF1823-3AA7-477E-8476-28929F5C05D2}
+ {F458AB60-BA1C-43D9-8CEF-EC01B50BE87B} = {C7EF1823-3AA7-477E-8476-28929F5C05D2}
+ {F4CD3C04-6037-4946-B7A5-34BFC96A75D2} = {C7EF1823-3AA7-477E-8476-28929F5C05D2}
+ {26DC877F-5987-48DD-9DDB-E62F2DE0E150} = {C7EF1823-3AA7-477E-8476-28929F5C05D2}
+ {1ED8D424-F8AB-4050-ACEB-F27F4F909484} = {C7EF1823-3AA7-477E-8476-28929F5C05D2}
+ {9D0F8866-2131-4C2A-BC0E-16FEA5B50828} = {C7EF1823-3AA7-477E-8476-28929F5C05D2}
+ {75E13AAE-7D51-4421-ABFD-3F3DC91F576E} = {C7EF1823-3AA7-477E-8476-28929F5C05D2}
+ {3896A32A-E876-4C23-B9B8-78E17D134CD3} = {C7EF1823-3AA7-477E-8476-28929F5C05D2}
+ {A288FCC8-6FCF-46DA-A45E-5F9281556361} = {9AF74F53-10F5-49A2-B747-87B97CD559D3}
+ {B202E40D-4663-4A2B-ACDA-865F88FF7CAA} = {9AF74F53-10F5-49A2-B747-87B97CD559D3}
+ {FED1923A-6D70-49B5-A37A-FB744FEC1C86} = {9AF74F53-10F5-49A2-B747-87B97CD559D3}
+ {408D10B8-34BA-4CBD-B7AA-FEB1907ABA4C} = {529B4262-6B5A-4EF9-BD3B-1D29A2597B67}
+ {E040EB58-B4D2-457B-A023-AE6EF3BD34DE} = {529B4262-6B5A-4EF9-BD3B-1D29A2597B67}
+ {56459A6C-6BA2-4BAC-A9C0-27E3BD961FA6} = {238B6BA8-AD99-43C9-B8E2-D2BCE6CE04DC}
+ {99BB7543-EA16-43EE-A7BC-D7A25A3B22F6} = {238B6BA8-AD99-43C9-B8E2-D2BCE6CE04DC}
+ {CDEDD439-7F35-4E6E-8605-4E70BDC4CC99} = {238B6BA8-AD99-43C9-B8E2-D2BCE6CE04DC}
+ {A1A3150A-7B0E-4A34-8E35-045296CD3C76} = {238B6BA8-AD99-43C9-B8E2-D2BCE6CE04DC}
+ {ADC2CC8C-541E-4F86-ACB1-DD504A36FA4B} = {238B6BA8-AD99-43C9-B8E2-D2BCE6CE04DC}
+ {3A8347E8-59A5-4092-8842-95C75D7D2F36} = {57A7DD35-666C-4FA3-9A1B-38961E50CA27}
EndGlobalSection
EndGlobal
diff --git a/src/DotNetOpenAuth/Configuration/DotNetOpenAuthSection.cs b/src/DotNetOpenAuth/Configuration/DotNetOpenAuthSection.cs
deleted file mode 100644
index 409fca9..0000000
--- a/src/DotNetOpenAuth/Configuration/DotNetOpenAuthSection.cs
+++ /dev/null
@@ -1,134 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="DotNetOpenAuthSection.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.Configuration {
- using System.Configuration;
- using System.Diagnostics.Contracts;
-
- /// <summary>
- /// Represents the section in the host's .config file that configures
- /// this library's settings.
- /// </summary>
- [ContractVerification(true)]
- public class DotNetOpenAuthSection : ConfigurationSection {
- /// <summary>
- /// The name of the section under which this library's settings must be found.
- /// </summary>
- private const string SectionName = "dotNetOpenAuth";
-
- /// <summary>
- /// The name of the &lt;messaging&gt; sub-element.
- /// </summary>
- private const string MessagingElementName = "messaging";
-
- /// <summary>
- /// The name of the &lt;openid&gt; sub-element.
- /// </summary>
- private const string OpenIdElementName = "openid";
-
- /// <summary>
- /// The name of the &lt;oauth&gt; sub-element.
- /// </summary>
- private const string OAuthElementName = "oauth";
-
- /// <summary>
- /// The name of the &lt;reporting&gt; sub-element.
- /// </summary>
- private const string ReportingElementName = "reporting";
-
- /// <summary>
- /// The name of the &lt;webResourceUrlProvider&gt; sub-element.
- /// </summary>
- private const string WebResourceUrlProviderName = "webResourceUrlProvider";
-
- /// <summary>
- /// Initializes a new instance of the <see cref="DotNetOpenAuthSection"/> class.
- /// </summary>
- internal DotNetOpenAuthSection() {
- Contract.Assume(this.SectionInformation != null);
- this.SectionInformation.AllowLocation = false;
- }
-
- /// <summary>
- /// Gets the configuration section from the .config file.
- /// </summary>
- public static DotNetOpenAuthSection Configuration {
- get {
- Contract.Ensures(Contract.Result<DotNetOpenAuthSection>() != null);
- return (DotNetOpenAuthSection)ConfigurationManager.GetSection(SectionName) ?? new DotNetOpenAuthSection();
- }
- }
-
- /// <summary>
- /// Gets or sets the configuration for the messaging framework.
- /// </summary>
- [ConfigurationProperty(MessagingElementName)]
- public MessagingElement Messaging {
- get {
- Contract.Ensures(Contract.Result<MessagingElement>() != null);
- return (MessagingElement)this[MessagingElementName] ?? new MessagingElement();
- }
-
- set {
- this[MessagingElementName] = value;
- }
- }
-
- /// <summary>
- /// Gets or sets the configuration for OpenID.
- /// </summary>
- [ConfigurationProperty(OpenIdElementName)]
- internal OpenIdElement OpenId {
- get {
- Contract.Ensures(Contract.Result<OpenIdElement>() != null);
- return (OpenIdElement)this[OpenIdElementName] ?? new OpenIdElement();
- }
-
- set {
- this[OpenIdElementName] = value;
- }
- }
-
- /// <summary>
- /// Gets or sets the configuration for OAuth.
- /// </summary>
- [ConfigurationProperty(OAuthElementName)]
- internal OAuthElement OAuth {
- get {
- Contract.Ensures(Contract.Result<OAuthElement>() != null);
- return (OAuthElement)this[OAuthElementName] ?? new OAuthElement();
- }
-
- set {
- this[OAuthElementName] = value;
- }
- }
-
- /// <summary>
- /// Gets or sets the configuration for reporting.
- /// </summary>
- [ConfigurationProperty(ReportingElementName)]
- internal ReportingElement Reporting {
- get {
- Contract.Ensures(Contract.Result<ReportingElement>() != null);
- return (ReportingElement)this[ReportingElementName] ?? new ReportingElement();
- }
-
- set {
- this[ReportingElementName] = value;
- }
- }
-
- /// <summary>
- /// Gets or sets the type to use for obtaining URLs that fetch embedded resource streams.
- /// </summary>
- [ConfigurationProperty(WebResourceUrlProviderName)]
- internal TypeConfigurationElement<IEmbeddedResourceRetrieval> EmbeddedResourceRetrievalProvider {
- get { return (TypeConfigurationElement<IEmbeddedResourceRetrieval>)this[WebResourceUrlProviderName] ?? new TypeConfigurationElement<IEmbeddedResourceRetrieval>(); }
- set { this[WebResourceUrlProviderName] = value; }
- }
- }
-}
diff --git a/src/DotNetOpenAuth/DotNetOpenAuth.csproj b/src/DotNetOpenAuth/DotNetOpenAuth.csproj
deleted file mode 100644
index fe09daf..0000000
--- a/src/DotNetOpenAuth/DotNetOpenAuth.csproj
+++ /dev/null
@@ -1,805 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))\EnlistmentInfo.props" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))' != '' " />
- <PropertyGroup>
- <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
- <CodeContractsAssemblyMode>1</CodeContractsAssemblyMode>
- </PropertyGroup>
- <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" />
- <PropertyGroup>
- <ProductVersion>9.0.30729</ProductVersion>
- <SchemaVersion>2.0</SchemaVersion>
- <ProjectGuid>{3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}</ProjectGuid>
- <OutputType>Library</OutputType>
- <AppDesignerFolder>Properties</AppDesignerFolder>
- <RootNamespace>DotNetOpenAuth</RootNamespace>
- <AssemblyName>DotNetOpenAuth</AssemblyName>
- <AssemblyName Condition=" '$(NoUIControls)' == 'true' ">DotNetOpenAuth.NoUI</AssemblyName>
- <FileAlignment>512</FileAlignment>
- <StandardCopyright>
-Copyright (c) 2009, Andrew Arnott. All rights reserved.
-Code licensed under the Ms-PL License:
-http://opensource.org/licenses/ms-pl.html
-</StandardCopyright>
- <FileUpgradeFlags>
- </FileUpgradeFlags>
- <OldToolsVersion>3.5</OldToolsVersion>
- <UpgradeBackupLocation />
- <IsWebBootstrapper>false</IsWebBootstrapper>
- <TargetFrameworkProfile />
- <PublishUrl>publish\</PublishUrl>
- <Install>true</Install>
- <InstallFrom>Disk</InstallFrom>
- <UpdateEnabled>false</UpdateEnabled>
- <UpdateMode>Foreground</UpdateMode>
- <UpdateInterval>7</UpdateInterval>
- <UpdateIntervalUnits>Days</UpdateIntervalUnits>
- <UpdatePeriodically>false</UpdatePeriodically>
- <UpdateRequired>false</UpdateRequired>
- <MapFileExtensions>true</MapFileExtensions>
- <ApplicationRevision>0</ApplicationRevision>
- <ApplicationVersion>1.0.0.%2a</ApplicationVersion>
- <UseApplicationTrust>false</UseApplicationTrust>
- <BootstrapperEnabled>true</BootstrapperEnabled>
- <ApplicationIcon>DotNetOpenAuth.ico</ApplicationIcon>
- <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
- <DebugSymbols>true</DebugSymbols>
- <DebugType>full</DebugType>
- <Optimize>false</Optimize>
- <DefineConstants>DEBUG;TRACE</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- <AllowUnsafeBlocks>false</AllowUnsafeBlocks>
- <RunCodeAnalysis>false</RunCodeAnalysis>
- <CodeAnalysisRules>
- </CodeAnalysisRules>
- <CodeContractsEnableRuntimeChecking>True</CodeContractsEnableRuntimeChecking>
- <CodeContractsCustomRewriterAssembly>
- </CodeContractsCustomRewriterAssembly>
- <CodeContractsCustomRewriterClass>
- </CodeContractsCustomRewriterClass>
- <CodeContractsRuntimeCheckingLevel>Full</CodeContractsRuntimeCheckingLevel>
- <CodeContractsRunCodeAnalysis>False</CodeContractsRunCodeAnalysis>
- <CodeContractsBuildReferenceAssembly>True</CodeContractsBuildReferenceAssembly>
- <CodeContractsNonNullObligations>True</CodeContractsNonNullObligations>
- <CodeContractsBoundsObligations>True</CodeContractsBoundsObligations>
- <CodeContractsLibPaths>
- </CodeContractsLibPaths>
- <CodeContractsPlatformPath>
- </CodeContractsPlatformPath>
- <CodeContractsExtraAnalysisOptions>
- </CodeContractsExtraAnalysisOptions>
- <CodeContractsBaseLineFile>
- </CodeContractsBaseLineFile>
- <CodeContractsUseBaseLine>False</CodeContractsUseBaseLine>
- <CodeContractsRunInBackground>True</CodeContractsRunInBackground>
- <CodeContractsShowSquigglies>True</CodeContractsShowSquigglies>
- <CodeContractsArithmeticObligations>False</CodeContractsArithmeticObligations>
- <CodeContractsRuntimeOnlyPublicSurface>False</CodeContractsRuntimeOnlyPublicSurface>
- <CodeContractsRuntimeThrowOnFailure>True</CodeContractsRuntimeThrowOnFailure>
- <CodeContractsRuntimeCallSiteRequires>False</CodeContractsRuntimeCallSiteRequires>
- <CodeContractsEmitXMLDocs>True</CodeContractsEmitXMLDocs>
- <CodeContractsRedundantAssumptions>False</CodeContractsRedundantAssumptions>
- <CodeContractsReferenceAssembly>Build</CodeContractsReferenceAssembly>
- <CodeAnalysisRuleSet>Migrated rules for DotNetOpenAuth.ruleset</CodeAnalysisRuleSet>
- <CodeContractsExtraRewriteOptions />
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
- <DebugType>pdbonly</DebugType>
- <Optimize>true</Optimize>
- <DefineConstants>TRACE</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- <AllowUnsafeBlocks>false</AllowUnsafeBlocks>
- <RunCodeAnalysis>true</RunCodeAnalysis>
- <CodeAnalysisRules>
- </CodeAnalysisRules>
- <CodeContractsEnableRuntimeChecking>True</CodeContractsEnableRuntimeChecking>
- <CodeContractsCustomRewriterAssembly>
- </CodeContractsCustomRewriterAssembly>
- <CodeContractsCustomRewriterClass>
- </CodeContractsCustomRewriterClass>
- <CodeContractsRuntimeCheckingLevel>ReleaseRequires</CodeContractsRuntimeCheckingLevel>
- <CodeContractsRunCodeAnalysis>False</CodeContractsRunCodeAnalysis>
- <CodeContractsBuildReferenceAssembly>True</CodeContractsBuildReferenceAssembly>
- <CodeContractsNonNullObligations>False</CodeContractsNonNullObligations>
- <CodeContractsBoundsObligations>False</CodeContractsBoundsObligations>
- <CodeContractsLibPaths>
- </CodeContractsLibPaths>
- <CodeContractsPlatformPath>
- </CodeContractsPlatformPath>
- <CodeContractsExtraAnalysisOptions>
- </CodeContractsExtraAnalysisOptions>
- <CodeContractsBaseLineFile>
- </CodeContractsBaseLineFile>
- <CodeContractsUseBaseLine>False</CodeContractsUseBaseLine>
- <CodeContractsRunInBackground>True</CodeContractsRunInBackground>
- <CodeContractsShowSquigglies>False</CodeContractsShowSquigglies>
- <CodeContractsArithmeticObligations>False</CodeContractsArithmeticObligations>
- <CodeContractsRuntimeOnlyPublicSurface>False</CodeContractsRuntimeOnlyPublicSurface>
- <CodeContractsRuntimeThrowOnFailure>True</CodeContractsRuntimeThrowOnFailure>
- <CodeContractsRuntimeCallSiteRequires>False</CodeContractsRuntimeCallSiteRequires>
- <CodeContractsEmitXMLDocs>True</CodeContractsEmitXMLDocs>
- <CodeContractsRedundantAssumptions>False</CodeContractsRedundantAssumptions>
- <CodeContractsReferenceAssembly>Build</CodeContractsReferenceAssembly>
- <CodeAnalysisRuleSet>Migrated rules for DotNetOpenAuth.ruleset</CodeAnalysisRuleSet>
- <CodeContractsExtraRewriteOptions />
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'ReleaseNoUI|AnyCPU'">
- <DefineConstants>TRACE;NoUIControls</DefineConstants>
- <NoUIControls>true</NoUIControls>
- <Optimize>true</Optimize>
- <NoWarn>;1607</NoWarn>
- <DebugType>pdbonly</DebugType>
- <PlatformTarget>AnyCPU</PlatformTarget>
- <ErrorReport>prompt</ErrorReport>
- <CodeContractsEnableRuntimeChecking>True</CodeContractsEnableRuntimeChecking>
- <CodeContractsCustomRewriterAssembly>
- </CodeContractsCustomRewriterAssembly>
- <CodeContractsCustomRewriterClass>
- </CodeContractsCustomRewriterClass>
- <CodeContractsRuntimeCheckingLevel>ReleaseRequires</CodeContractsRuntimeCheckingLevel>
- <CodeContractsRunCodeAnalysis>False</CodeContractsRunCodeAnalysis>
- <CodeContractsBuildReferenceAssembly>True</CodeContractsBuildReferenceAssembly>
- <CodeContractsNonNullObligations>False</CodeContractsNonNullObligations>
- <CodeContractsBoundsObligations>False</CodeContractsBoundsObligations>
- <CodeContractsLibPaths>
- </CodeContractsLibPaths>
- <CodeContractsPlatformPath>
- </CodeContractsPlatformPath>
- <CodeContractsExtraAnalysisOptions>
- </CodeContractsExtraAnalysisOptions>
- <CodeContractsBaseLineFile>
- </CodeContractsBaseLineFile>
- <CodeContractsUseBaseLine>False</CodeContractsUseBaseLine>
- <CodeContractsRunInBackground>True</CodeContractsRunInBackground>
- <CodeContractsShowSquigglies>False</CodeContractsShowSquigglies>
- <CodeContractsArithmeticObligations>False</CodeContractsArithmeticObligations>
- <CodeContractsRuntimeOnlyPublicSurface>False</CodeContractsRuntimeOnlyPublicSurface>
- <CodeContractsRuntimeThrowOnFailure>True</CodeContractsRuntimeThrowOnFailure>
- <CodeContractsRuntimeCallSiteRequires>False</CodeContractsRuntimeCallSiteRequires>
- <CodeContractsEmitXMLDocs>True</CodeContractsEmitXMLDocs>
- <CodeContractsRedundantAssumptions>False</CodeContractsRedundantAssumptions>
- <CodeContractsReferenceAssembly>Build</CodeContractsReferenceAssembly>
- <CodeContractsExtraRewriteOptions />
- <CodeAnalysisRuleSet>Migrated rules for DotNetOpenAuth.ruleset</CodeAnalysisRuleSet>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'CodeAnalysis|AnyCPU' ">
- <DebugSymbols>true</DebugSymbols>
- <DefineConstants>$(DefineConstants);CONTRACTS_FULL;DEBUG;TRACE</DefineConstants>
- <DebugType>full</DebugType>
- <PlatformTarget>AnyCPU</PlatformTarget>
- <CodeAnalysisRules>
- </CodeAnalysisRules>
- <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>
- <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>
- <ErrorReport>prompt</ErrorReport>
- <CodeContractsEnableRuntimeChecking>True</CodeContractsEnableRuntimeChecking>
- <CodeContractsCustomRewriterAssembly>
- </CodeContractsCustomRewriterAssembly>
- <CodeContractsCustomRewriterClass>
- </CodeContractsCustomRewriterClass>
- <CodeContractsRuntimeCheckingLevel>Preconditions</CodeContractsRuntimeCheckingLevel>
- <CodeContractsRunCodeAnalysis>True</CodeContractsRunCodeAnalysis>
- <CodeContractsBuildReferenceAssembly>True</CodeContractsBuildReferenceAssembly>
- <CodeContractsNonNullObligations>False</CodeContractsNonNullObligations>
- <CodeContractsBoundsObligations>False</CodeContractsBoundsObligations>
- <CodeContractsLibPaths>
- </CodeContractsLibPaths>
- <CodeContractsPlatformPath>
- </CodeContractsPlatformPath>
- <CodeContractsExtraAnalysisOptions>
- </CodeContractsExtraAnalysisOptions>
- <CodeContractsBaseLineFile>
- </CodeContractsBaseLineFile>
- <CodeContractsUseBaseLine>False</CodeContractsUseBaseLine>
- <CodeContractsRunInBackground>True</CodeContractsRunInBackground>
- <CodeContractsShowSquigglies>True</CodeContractsShowSquigglies>
- <RunCodeAnalysis>true</RunCodeAnalysis>
- <CodeContractsArithmeticObligations>False</CodeContractsArithmeticObligations>
- <CodeContractsRuntimeOnlyPublicSurface>False</CodeContractsRuntimeOnlyPublicSurface>
- <CodeContractsRuntimeThrowOnFailure>True</CodeContractsRuntimeThrowOnFailure>
- <CodeContractsRuntimeCallSiteRequires>False</CodeContractsRuntimeCallSiteRequires>
- <CodeContractsEmitXMLDocs>True</CodeContractsEmitXMLDocs>
- <CodeContractsRedundantAssumptions>False</CodeContractsRedundantAssumptions>
- <CodeContractsReferenceAssembly>Build</CodeContractsReferenceAssembly>
- <CodeAnalysisRuleSet>Migrated rules for DotNetOpenAuth.ruleset</CodeAnalysisRuleSet>
- <CodeContractsExtraRewriteOptions />
- </PropertyGroup>
- <ItemGroup>
- <Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL">
- <SpecificVersion>False</SpecificVersion>
- </Reference>
- <Reference Include="PresentationFramework">
- <RequiredTargetFramework>3.0</RequiredTargetFramework>
- </Reference>
- <Reference Include="System" />
- <Reference Include="System.configuration" />
- <Reference Include="System.Core">
- <RequiredTargetFramework>3.5</RequiredTargetFramework>
- </Reference>
- <Reference Include="System.Data" />
- <Reference Include="System.Drawing" />
- <Reference Include="System.IdentityModel">
- <RequiredTargetFramework>3.0</RequiredTargetFramework>
- </Reference>
- <Reference Include="System.IdentityModel.Selectors">
- <RequiredTargetFramework>3.0</RequiredTargetFramework>
- </Reference>
- <Reference Include="System.Runtime.Serialization">
- <RequiredTargetFramework>3.0</RequiredTargetFramework>
- </Reference>
- <Reference Include="System.ServiceModel">
- <RequiredTargetFramework>3.0</RequiredTargetFramework>
- </Reference>
- <Reference Include="System.ServiceModel.Web">
- <RequiredTargetFramework>3.5</RequiredTargetFramework>
- </Reference>
- <Reference Include="System.Web" />
- <Reference Include="System.Web.Abstractions">
- <RequiredTargetFramework>3.5</RequiredTargetFramework>
- </Reference>
- <Reference Include="System.Web.Extensions">
- <RequiredTargetFramework>3.5</RequiredTargetFramework>
- </Reference>
- <Reference Include="System.Web.Extensions.Design">
- <RequiredTargetFramework>3.5</RequiredTargetFramework>
- </Reference>
- <Reference Include="System.Web.Mobile" Condition=" '$(ClrVersion)' != '4' " />
- <Reference Include="System.Web.Routing">
- <RequiredTargetFramework>3.5</RequiredTargetFramework>
- </Reference>
- <Reference Include="System.Xaml" Condition=" '$(ClrVersion)' == '4' " />
- <Reference Include="System.XML" />
- <Reference Include="System.Xml.Linq">
- <RequiredTargetFramework>3.5</RequiredTargetFramework>
- </Reference>
- <Reference Include="WindowsBase">
- <RequiredTargetFramework>3.0</RequiredTargetFramework>
- </Reference>
- <Reference Include="System.ComponentModel.DataAnnotations">
- <RequiredTargetFramework>3.5</RequiredTargetFramework>
- </Reference>
- </ItemGroup>
- <ItemGroup Condition=" '$(ClrVersion)' == '4' ">
- <Reference Include="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
- </ItemGroup>
- <ItemGroup Condition=" '$(ClrVersion)' != '4' ">
- <!-- MVC 2 can run on CLR 2 (it doesn't require CLR 4) but since MVC 2 apps tend to use type forwarding,
- it's a more broadly consumable idea to bind against MVC 1 for the library unless we're building on CLR 4,
- which will definitely have MVC 2 available. -->
- <Reference Include="System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
- </ItemGroup>
- <ItemGroup>
- <Compile Include="ComponentModel\ClaimTypeSuggestions.cs" />
- <Compile Include="ComponentModel\ConverterBase.cs" />
- <Compile Include="ComponentModel\SuggestedStringsConverterContract.cs" />
- <Compile Include="ComponentModel\IssuersSuggestions.cs" />
- <Compile Include="ComponentModel\IdentifierConverter.cs" />
- <Compile Include="ComponentModel\SuggestedStringsConverter.cs" />
- <Compile Include="ComponentModel\UriConverter.cs" />
- <Compile Include="Configuration\AssociationTypeCollection.cs" />
- <Compile Include="Configuration\AssociationTypeElement.cs" />
- <Compile Include="Configuration\DotNetOpenAuthSection.cs" />
- <Compile Include="Configuration\MessagingElement.cs" />
- <Compile Include="Configuration\OAuthConsumerElement.cs" />
- <Compile Include="Configuration\OAuthConsumerSecuritySettingsElement.cs" />
- <Compile Include="Configuration\OAuthElement.cs" />
- <Compile Include="Configuration\OAuthServiceProviderElement.cs" />
- <Compile Include="Configuration\OAuthServiceProviderSecuritySettingsElement.cs" />
- <Compile Include="Configuration\OpenIdElement.cs" />
- <Compile Include="Configuration\OpenIdProviderElement.cs" />
- <Compile Include="Configuration\OpenIdProviderSecuritySettingsElement.cs" />
- <Compile Include="Configuration\OpenIdRelyingPartyElement.cs" />
- <Compile Include="Configuration\OpenIdRelyingPartySecuritySettingsElement.cs" />
- <Compile Include="Configuration\ReportingElement.cs" />
- <Compile Include="Configuration\TrustedProviderConfigurationCollection.cs" />
- <Compile Include="Configuration\TrustedProviderEndpointConfigurationElement.cs" />
- <Compile Include="Configuration\TypeConfigurationCollection.cs" />
- <Compile Include="Configuration\TypeConfigurationElement.cs" />
- <Compile Include="Configuration\UntrustedWebRequestElement.cs" />
- <Compile Include="Configuration\HostNameOrRegexCollection.cs" />
- <Compile Include="Configuration\HostNameElement.cs" />
- <Compile Include="Configuration\XriResolverElement.cs" />
- <Compile Include="IEmbeddedResourceRetrieval.cs" />
- <Compile Include="InfoCard\ClaimType.cs" />
- <Compile Include="InfoCard\InfoCardImage.cs" />
- <Compile Include="InfoCard\InfoCardStrings.Designer.cs">
- <AutoGen>True</AutoGen>
- <DesignTime>True</DesignTime>
- <DependentUpon>InfoCardStrings.resx</DependentUpon>
- </Compile>
- <Compile Include="InfoCard\Token\InformationCardException.cs" />
- <Compile Include="InfoCard\Token\Token.cs" />
- <Compile Include="InfoCard\Token\TokenUtility.cs" />
- <Compile Include="InfoCard\Token\TokenDecryptor.cs" />
- <Compile Include="InfoCard\WellKnownIssuers.cs" />
- <Compile Include="Messaging\CachedDirectWebResponse.cs" />
- <Compile Include="Messaging\ChannelContract.cs" />
- <Compile Include="Messaging\IMessageOriginalPayload.cs" />
- <Compile Include="Messaging\DirectWebRequestOptions.cs" />
- <Compile Include="Messaging\EnumerableCache.cs" />
- <Compile Include="Messaging\HostErrorException.cs" />
- <Compile Include="Messaging\IHttpDirectResponse.cs" />
- <Compile Include="Messaging\IExtensionMessage.cs" />
- <Compile Include="Messaging\IMessage.cs" />
- <Compile Include="Messaging\IncomingWebResponse.cs" />
- <Compile Include="Messaging\IDirectResponseProtocolMessage.cs" />
- <Compile Include="Messaging\EmptyDictionary.cs" />
- <Compile Include="Messaging\EmptyEnumerator.cs" />
- <Compile Include="Messaging\EmptyList.cs" />
- <Compile Include="Messaging\ErrorUtilities.cs" />
- <Compile Include="Messaging\IMessageWithEvents.cs" />
- <Compile Include="Messaging\IncomingWebResponseContract.cs" />
- <Compile Include="Messaging\IProtocolMessageWithExtensions.cs" />
- <Compile Include="Messaging\InternalErrorException.cs" />
- <Compile Include="Messaging\KeyedCollectionDelegate.cs" />
- <Compile Include="Messaging\MultipartPostPart.cs" />
- <Compile Include="Messaging\NetworkDirectWebResponse.cs" />
- <Compile Include="Messaging\OutgoingWebResponseActionResult.cs" />
- <Compile Include="Messaging\Reflection\IMessagePartEncoder.cs" />
- <Compile Include="Messaging\Reflection\IMessagePartNullEncoder.cs" />
- <Compile Include="Messaging\Reflection\IMessagePartOriginalEncoder.cs" />
- <Compile Include="Messaging\Reflection\MessageDescriptionCollection.cs" />
- <Compile Include="Mvc\OpenIdAjaxOptions.cs" />
- <Compile Include="OAuth\ChannelElements\ICombinedOpenIdProviderTokenManager.cs" />
- <Compile Include="OAuth\ChannelElements\IConsumerDescription.cs" />
- <Compile Include="OAuth\ChannelElements\IConsumerTokenManager.cs" />
- <Compile Include="OAuth\ChannelElements\IOpenIdOAuthTokenManager.cs" />
- <Compile Include="OAuth\ChannelElements\IServiceProviderAccessToken.cs" />
- <Compile Include="OAuth\ChannelElements\IServiceProviderTokenManager.cs" />
- <Compile Include="OAuth\ChannelElements\OAuthConsumerMessageFactory.cs" />
- <Compile Include="OAuth\ChannelElements\ITokenGenerator.cs" />
- <Compile Include="OAuth\ChannelElements\ITokenManager.cs" />
- <Compile Include="OAuth\ChannelElements\OAuthHttpMethodBindingElement.cs" />
- <Compile Include="OAuth\ChannelElements\OAuthIdentity.cs" />
- <Compile Include="OAuth\ChannelElements\OAuthPrincipal.cs" />
- <Compile Include="OAuth\ChannelElements\PlaintextSigningBindingElement.cs" />
- <Compile Include="OAuth\ChannelElements\HmacSha1SigningBindingElement.cs" />
- <Compile Include="OAuth\ChannelElements\IServiceProviderRequestToken.cs" />
- <Compile Include="OAuth\ChannelElements\SigningBindingElementBaseContract.cs" />
- <Compile Include="OAuth\ChannelElements\SigningBindingElementChain.cs" />
- <Compile Include="OAuth\ChannelElements\StandardTokenGenerator.cs" />
- <Compile Include="OAuth\ChannelElements\TokenType.cs" />
- <Compile Include="OAuth\ChannelElements\UriOrOobEncoding.cs" />
- <Compile Include="OAuth\ChannelElements\TokenHandlingBindingElement.cs" />
- <Compile Include="OAuth\ConsumerBase.cs" />
- <Compile Include="OAuth\ConsumerSecuritySettings.cs" />
- <Compile Include="OAuth\DesktopConsumer.cs" />
- <Compile Include="GlobalSuppressions.cs" />
- <Compile Include="Messaging\IMessageWithBinaryData.cs" />
- <Compile Include="OAuth\Messages\ITokenSecretContainingMessage.cs" />
- <Compile Include="Messaging\ChannelEventArgs.cs" />
- <Compile Include="Messaging\ITamperProtectionChannelBindingElement.cs" />
- <Compile Include="OAuth\OAuthStrings.Designer.cs">
- <AutoGen>True</AutoGen>
- <DesignTime>True</DesignTime>
- <DependentUpon>OAuthStrings.resx</DependentUpon>
- </Compile>
- <Compile Include="OAuth\SecuritySettings.cs" />
- <Compile Include="OAuth\ServiceProviderDescription.cs" />
- <Compile Include="OAuth\Messages\ITokenContainingMessage.cs" />
- <Compile Include="OAuth\Messages\SignedMessageBase.cs" />
- <Compile Include="Messaging\Bindings\NonceMemoryStore.cs" />
- <Compile Include="OAuth\ChannelElements\SigningBindingElementBase.cs" />
- <Compile Include="OAuth\ServiceProviderSecuritySettings.cs" />
- <Compile Include="OAuth\VerificationCodeFormat.cs" />
- <Compile Include="OAuth\WebConsumer.cs" />
- <Compile Include="Messaging\IDirectWebRequestHandler.cs" />
- <Compile Include="OAuth\ChannelElements\ITamperResistantOAuthMessage.cs" />
- <Compile Include="OAuth\Messages\MessageBase.cs" />
- <Compile Include="OAuth\Messages\AuthorizedTokenRequest.cs" />
- <Compile Include="Messaging\Bindings\INonceStore.cs" />
- <Compile Include="Messaging\Bindings\StandardReplayProtectionBindingElement.cs" />
- <Compile Include="Messaging\MessagePartAttribute.cs" />
- <Compile Include="Messaging\MessageProtections.cs" />
- <Compile Include="Messaging\IChannelBindingElement.cs" />
- <Compile Include="Messaging\Bindings\ReplayedMessageException.cs" />
- <Compile Include="Messaging\Bindings\ExpiredMessageException.cs" />
- <Compile Include="Messaging\Bindings\InvalidSignatureException.cs" />
- <Compile Include="Messaging\Bindings\IReplayProtectedProtocolMessage.cs" />
- <Compile Include="Messaging\Bindings\IExpiringProtocolMessage.cs" />
- <Compile Include="OAuth\Messages\AccessProtectedResourceRequest.cs" />
- <Compile Include="OAuth\Messages\AuthorizedTokenResponse.cs" />
- <Compile Include="OAuth\Messages\UserAuthorizationResponse.cs" />
- <Compile Include="OAuth\Messages\UserAuthorizationRequest.cs" />
- <Compile Include="OAuth\Messages\UnauthorizedTokenResponse.cs" />
- <Compile Include="Messaging\Channel.cs" />
- <Compile Include="Messaging\HttpRequestInfo.cs" />
- <Compile Include="Messaging\IDirectedProtocolMessage.cs" />
- <Compile Include="Messaging\IMessageFactory.cs" />
- <Compile Include="Messaging\ITamperResistantProtocolMessage.cs" />
- <Compile Include="Messaging\MessageSerializer.cs" />
- <Compile Include="Messaging\MessagingStrings.Designer.cs">
- <AutoGen>True</AutoGen>
- <DesignTime>True</DesignTime>
- <DependentUpon>MessagingStrings.resx</DependentUpon>
- </Compile>
- <Compile Include="Messaging\MessagingUtilities.cs" />
- <Compile Include="Messaging\Bindings\StandardExpirationBindingElement.cs" />
- <Compile Include="Messaging\Reflection\ValueMapping.cs" />
- <Compile Include="Messaging\Reflection\MessageDescription.cs" />
- <Compile Include="Messaging\Reflection\MessageDictionary.cs" />
- <Compile Include="Messaging\Reflection\MessagePart.cs" />
- <Compile Include="Messaging\UnprotectedMessageException.cs" />
- <Compile Include="OAuth\ChannelElements\OAuthChannel.cs" />
- <Compile Include="Messaging\OutgoingWebResponse.cs" />
- <Compile Include="Messaging\IProtocolMessage.cs" />
- <Compile Include="Logger.cs" />
- <Compile Include="Loggers\ILog.cs" />
- <Compile Include="Loggers\Log4NetLogger.cs" />
- <Compile Include="Loggers\NoOpLogger.cs" />
- <Compile Include="Loggers\TraceLogger.cs" />
- <Compile Include="Messaging\HttpDeliveryMethods.cs" />
- <Compile Include="Messaging\MessageTransport.cs" />
- <Compile Include="OAuth\ChannelElements\OAuthServiceProviderMessageFactory.cs" />
- <Compile Include="Messaging\ProtocolException.cs" />
- <Compile Include="OpenId\Association.cs" />
- <Compile Include="OpenId\AssociationMemoryStore.cs" />
- <Compile Include="OpenId\Associations.cs" />
- <Compile Include="OpenId\Behaviors\AXFetchAsSregTransform.cs" />
- <Compile Include="OpenId\Behaviors\BehaviorStrings.Designer.cs">
- <AutoGen>True</AutoGen>
- <DesignTime>True</DesignTime>
- <DependentUpon>BehaviorStrings.resx</DependentUpon>
- </Compile>
- <Compile Include="OpenId\Behaviors\PpidGeneration.cs" />
- <Compile Include="OpenId\ChannelElements\BackwardCompatibilityBindingElement.cs" />
- <Compile Include="OpenId\ChannelElements\ExtensionsBindingElement.cs" />
- <Compile Include="OpenId\ChannelElements\IOpenIdExtensionFactory.cs" />
- <Compile Include="OpenId\ChannelElements\ITamperResistantOpenIdMessage.cs" />
- <Compile Include="OpenId\ChannelElements\OriginalStringUriEncoder.cs" />
- <Compile Include="OpenId\ChannelElements\RelyingPartySecurityOptions.cs" />
- <Compile Include="OpenId\ChannelElements\ReturnToNonceBindingElement.cs" />
- <Compile Include="OpenId\ChannelElements\SigningBindingElement.cs" />
- <Compile Include="OpenId\ChannelElements\KeyValueFormEncoding.cs" />
- <Compile Include="OpenId\ChannelElements\OpenIdChannel.cs" />
- <Compile Include="OpenId\ChannelElements\OpenIdMessageFactory.cs" />
- <Compile Include="OpenId\ChannelElements\ReturnToSignatureBindingElement.cs" />
- <Compile Include="OpenId\ChannelElements\SkipSecurityBindingElement.cs" />
- <Compile Include="OpenId\AssociationContract.cs" />
- <Compile Include="OpenId\Extensions\AliasManager.cs" />
- <Compile Include="OpenId\Extensions\AttributeExchange\AttributeRequest.cs" />
- <Compile Include="OpenId\Extensions\AttributeExchange\AttributeValues.cs" />
- <Compile Include="OpenId\Extensions\AttributeExchange\AXAttributeFormats.cs" />
- <Compile Include="OpenId\Extensions\AttributeExchange\AXUtilities.cs" />
- <Compile Include="OpenId\Extensions\AttributeExchange\Constants.cs" />
- <Compile Include="OpenId\Extensions\AttributeExchange\FetchRequest.cs" />
- <Compile Include="OpenId\Extensions\AttributeExchange\FetchResponse.cs" />
- <Compile Include="OpenId\Extensions\AttributeExchange\StoreRequest.cs" />
- <Compile Include="OpenId\Extensions\AttributeExchange\StoreResponse.cs" />
- <Compile Include="OpenId\Extensions\AttributeExchange\WellKnownAttributes.cs" />
- <Compile Include="OpenId\Extensions\ExtensionBase.cs" />
- <Compile Include="OpenId\Extensions\ExtensionArgumentsManager.cs" />
- <Compile Include="OpenId\Extensions\IClientScriptExtensionResponse.cs" />
- <Compile Include="OpenId\Extensions\OAuth\AuthorizationRequest.cs" />
- <Compile Include="OpenId\Extensions\OAuth\AuthorizationApprovedResponse.cs" />
- <Compile Include="OpenId\Extensions\OAuth\Constants.cs" />
- <Compile Include="OpenId\Extensions\OAuth\AuthorizationDeclinedResponse.cs" />
- <Compile Include="OpenId\Extensions\OpenIdExtensionFactoryAggregator.cs" />
- <Compile Include="OpenId\Extensions\StandardOpenIdExtensionFactory.cs" />
- <Compile Include="OpenId\Extensions\ProviderAuthenticationPolicy\AuthenticationPolicies.cs" />
- <Compile Include="OpenId\Extensions\ProviderAuthenticationPolicy\Constants.cs" />
- <Compile Include="OpenId\Extensions\ProviderAuthenticationPolicy\DateTimeEncoder.cs" />
- <Compile Include="OpenId\Extensions\ProviderAuthenticationPolicy\NistAssuranceLevel.cs" />
- <Compile Include="OpenId\Extensions\ProviderAuthenticationPolicy\PapeUtilities.cs" />
- <Compile Include="OpenId\Extensions\ProviderAuthenticationPolicy\PolicyRequest.cs" />
- <Compile Include="OpenId\Extensions\ProviderAuthenticationPolicy\PolicyResponse.cs" />
- <Compile Include="OpenId\Extensions\ProviderAuthenticationPolicy\TimespanSecondsEncoder.cs" />
- <Compile Include="OpenId\Extensions\SimpleRegistration\ClaimsRequest.cs" />
- <Compile Include="OpenId\Extensions\SimpleRegistration\ClaimsResponse.cs" />
- <Compile Include="OpenId\Extensions\SimpleRegistration\Constants.cs" />
- <Compile Include="OpenId\Extensions\SimpleRegistration\DemandLevel.cs" />
- <Compile Include="OpenId\Extensions\SimpleRegistration\Gender.cs" />
- <Compile Include="OpenId\Extensions\UI\UIConstants.cs" />
- <Compile Include="OpenId\Extensions\UI\UIUtilities.cs" />
- <Compile Include="OpenId\Extensions\UI\UIModes.cs" />
- <Compile Include="OpenId\Extensions\UI\UIRequest.cs" />
- <Compile Include="OpenId\HostMetaDiscoveryService.cs" />
- <Compile Include="OpenId\Identifier.cs" />
- <Compile Include="OpenId\IdentifierContract.cs" />
- <Compile Include="OpenId\Extensions\ExtensionsInteropHelper.cs" />
- <Compile Include="OpenId\Interop\AuthenticationResponseShim.cs" />
- <Compile Include="OpenId\Interop\ClaimsResponseShim.cs" />
- <Compile Include="OpenId\Interop\OpenIdRelyingPartyShim.cs" />
- <Compile Include="OpenId\IIdentifierDiscoveryService.cs" />
- <Compile Include="OpenId\Messages\CheckAuthenticationRequest.cs" />
- <Compile Include="OpenId\Messages\CheckAuthenticationResponse.cs" />
- <Compile Include="OpenId\Messages\CheckIdRequest.cs" />
- <Compile Include="OpenId\Messages\AssociateSuccessfulResponseContract.cs" />
- <Compile Include="OpenId\Messages\IErrorMessage.cs" />
- <Compile Include="OpenId\Messages\IndirectResponseBase.cs" />
- <Compile Include="OpenId\Messages\IndirectSignedResponse.cs" />
- <Compile Include="OpenId\Messages\IOpenIdMessageExtension.cs" />
- <Compile Include="OpenId\Messages\NegativeAssertionResponse.cs" />
- <Compile Include="OpenId\Messages\PositiveAssertionResponse.cs" />
- <Compile Include="OpenId\Messages\SignedResponseRequest.cs" />
- <Compile Include="OpenId\NoDiscoveryIdentifier.cs" />
- <Compile Include="OpenId\OpenIdUtilities.cs" />
- <Compile Include="OpenId\Provider\PrivatePersonalIdentifierProviderBase.cs" />
- <Compile Include="OpenId\Provider\AnonymousRequest.cs" />
- <Compile Include="OpenId\Provider\AnonymousRequestEventArgs.cs" />
- <Compile Include="OpenId\Provider\AuthenticationChallengeEventArgs.cs" />
- <Compile Include="OpenId\Provider\AuthenticationRequest.cs" />
- <Compile Include="OpenId\Provider\AutoResponsiveRequest.cs" />
- <Compile Include="OpenId\Provider\HostProcessedRequest.cs" />
- <Compile Include="OpenId\Provider\IAnonymousRequest.cs" />
- <Compile Include="OpenId\Provider\IAuthenticationRequest.cs" />
- <Compile Include="OpenId\Provider\IDirectedIdentityIdentifierProvider.cs" />
- <Compile Include="OpenId\Provider\IHostProcessedRequest.cs" />
- <Compile Include="OpenId\Provider\IErrorReporting.cs" />
- <Compile Include="OpenId\Provider\IProviderApplicationStore.cs" />
- <Compile Include="OpenId\Provider\IProviderBehavior.cs" />
- <Compile Include="OpenId\Provider\IRequest.cs" />
- <Compile Include="OpenId\Provider\ProviderEndpoint.cs" />
- <Compile Include="OpenId\Provider\RelyingPartyDiscoveryResult.cs" />
- <Compile Include="OpenId\Provider\Request.cs" />
- <Compile Include="OpenId\Provider\RequestContract.cs" />
- <Compile Include="OpenId\Provider\StandardProviderApplicationStore.cs" />
- <Compile Include="OpenId\Realm.cs" />
- <Compile Include="OpenId\RelyingPartyDescription.cs" />
- <Compile Include="OpenId\DiffieHellmanUtilities.cs" />
- <Compile Include="OpenId\DiffieHellman\DHKeyGeneration.cs" />
- <Compile Include="OpenId\DiffieHellman\DHParameters.cs" />
- <Compile Include="OpenId\DiffieHellman\DiffieHellman.cs" />
- <Compile Include="OpenId\DiffieHellman\DiffieHellmanManaged.cs" />
- <Compile Include="OpenId\DiffieHellman\mono\BigInteger.cs" />
- <Compile Include="OpenId\DiffieHellman\mono\ConfidenceFactor.cs" />
- <Compile Include="OpenId\DiffieHellman\mono\NextPrimeFinder.cs" />
- <Compile Include="OpenId\DiffieHellman\mono\PrimalityTests.cs" />
- <Compile Include="OpenId\DiffieHellman\mono\PrimeGeneratorBase.cs" />
- <Compile Include="OpenId\DiffieHellman\mono\SequentialSearchPrimeGeneratorBase.cs" />
- <Compile Include="OpenId\HmacShaAssociation.cs" />
- <Compile Include="OpenId\IAssociationStore.cs" />
- <Compile Include="OpenId\Messages\AssociateUnencryptedRequest.cs" />
- <Compile Include="OpenId\Provider\OpenIdProvider.cs" />
- <Compile Include="OpenId\Messages\AssociateDiffieHellmanRequest.cs" />
- <Compile Include="OpenId\Messages\AssociateDiffieHellmanResponse.cs" />
- <Compile Include="OpenId\Messages\AssociateRequest.cs" />
- <Compile Include="OpenId\Messages\AssociateSuccessfulResponse.cs" />
- <Compile Include="OpenId\Messages\AssociateUnencryptedResponse.cs" />
- <Compile Include="OpenId\Messages\AssociateUnsuccessfulResponse.cs" />
- <Compile Include="OpenId\Messages\IndirectErrorResponse.cs" />
- <Compile Include="OpenId\Messages\DirectErrorResponse.cs" />
- <Compile Include="OpenId\Messages\RequestBase.cs" />
- <Compile Include="OpenId\Messages\DirectResponseBase.cs" />
- <Compile Include="OpenId\RelyingParty\AssociationManager.cs" />
- <Compile Include="OpenId\RelyingParty\AssociationPreference.cs" />
- <Compile Include="OpenId\RelyingParty\AuthenticationRequest.cs" />
- <Compile Include="OpenId\RelyingParty\AuthenticationRequestMode.cs" />
- <Compile Include="OpenId\RelyingParty\DuplicateRequestedHostsComparer.cs" />
- <Compile Include="OpenId\RelyingParty\IProviderEndpoint.cs" />
- <Compile Include="OpenId\RelyingParty\IRelyingPartyBehavior.cs" />
- <Compile Include="OpenId\RelyingParty\IAuthenticationRequestContract.cs" />
- <Compile Include="OpenId\RelyingParty\NegativeAuthenticationResponse.cs" />
- <Compile Include="OpenId\RelyingParty\OpenIdEventArgs.cs" />
- <Compile Include="OpenId\RelyingParty\PopupBehavior.cs" />
- <Compile Include="OpenId\RelyingParty\PositiveAnonymousResponse.cs" />
- <Compile Include="OpenId\RelyingParty\PositiveAuthenticationResponse.cs" />
- <Compile Include="OpenId\RelyingParty\AuthenticationStatus.cs" />
- <Compile Include="OpenId\RelyingParty\FailedAuthenticationResponse.cs" />
- <Compile Include="OpenId\RelyingParty\IAuthenticationRequest.cs" />
- <Compile Include="OpenId\RelyingParty\IAuthenticationResponse.cs" />
- <Compile Include="OpenId\RelyingParty\ISetupRequiredAuthenticationResponse.cs" />
- <Compile Include="OpenId\RelyingParty\OpenIdRelyingParty.cs" />
- <Compile Include="OpenId\OpenIdStrings.Designer.cs">
- <DependentUpon>OpenIdStrings.resx</DependentUpon>
- <DesignTime>True</DesignTime>
- <AutoGen>True</AutoGen>
- </Compile>
- <Compile Include="OpenId\Protocol.cs" />
- <Compile Include="OpenId\ProviderEndpointDescription.cs" />
- <Compile Include="OpenId\Provider\ProviderSecuritySettings.cs" />
- <Compile Include="OpenId\RelyingParty\IRelyingPartyApplicationStore.cs" />
- <Compile Include="OpenId\RelyingParty\PositiveAuthenticationResponseSnapshot.cs" />
- <Compile Include="OpenId\RelyingParty\PrivateSecretManager.cs" />
- <Compile Include="OpenId\RelyingParty\RelyingPartySecuritySettings.cs" />
- <Compile Include="OpenId\IdentifierDiscoveryResult.cs" />
- <Compile Include="OpenId\OpenIdXrdsHelper.cs" />
- <Compile Include="OpenId\RelyingParty\SimpleXrdsProviderEndpoint.cs" />
- <Compile Include="OpenId\RelyingParty\StandardRelyingPartyApplicationStore.cs" />
- <Compile Include="OpenId\Behaviors\GsaIcamProfile.cs" />
- <Compile Include="OpenId\RelyingParty\WellKnownProviders.cs" />
- <Compile Include="OpenId\SecuritySettings.cs" />
- <Compile Include="Messaging\UntrustedWebRequestHandler.cs" />
- <Compile Include="OpenId\UriDiscoveryService.cs" />
- <Compile Include="OpenId\UriIdentifier.cs" />
- <Compile Include="OpenId\XriDiscoveryProxyService.cs" />
- <Compile Include="OpenId\XriIdentifier.cs" />
- <Compile Include="Properties\AssemblyInfo.cs" />
- <Compile Include="OAuth\Messages\UnauthorizedTokenRequest.cs" />
- <Compile Include="OAuth\ChannelElements\RsaSha1SigningBindingElement.cs" />
- <Compile Include="Messaging\StandardWebRequestHandler.cs" />
- <Compile Include="Messaging\MessageReceivingEndpoint.cs" />
- <Compile Include="Reporting.cs" />
- <Compile Include="Util.cs" />
- <Compile Include="OAuth\Protocol.cs" />
- <Compile Include="OAuth\ServiceProvider.cs" />
- <Compile Include="Strings.Designer.cs">
- <AutoGen>True</AutoGen>
- <DesignTime>True</DesignTime>
- <DependentUpon>Strings.resx</DependentUpon>
- </Compile>
- <Compile Include="UriUtil.cs" />
- <Compile Include="Xrds\XrdsStrings.Designer.cs">
- <AutoGen>True</AutoGen>
- <DesignTime>True</DesignTime>
- <DependentUpon>XrdsStrings.resx</DependentUpon>
- </Compile>
- <Compile Include="Yadis\ContentTypes.cs" />
- <Compile Include="Yadis\DiscoveryResult.cs" />
- <Compile Include="Yadis\HtmlParser.cs" />
- <Compile Include="Xrds\ServiceElement.cs" />
- <Compile Include="Xrds\TypeElement.cs" />
- <Compile Include="Xrds\UriElement.cs" />
- <Compile Include="Xrds\XrdElement.cs" />
- <Compile Include="Xrds\XrdsDocument.cs" />
- <Compile Include="Xrds\XrdsNode.cs" />
- <Compile Include="Yadis\Yadis.cs" />
- </ItemGroup>
- <ItemGroup Condition=" '$(NoUIControls)' != 'true' ">
- <Compile Include="OpenId\RelyingParty\OpenIdTextBox.cs"/>
- <Compile Include="OpenId\RelyingParty\OpenIdLogin.cs"/>
- <Compile Include="OpenId\RelyingParty\OpenIdAjaxRelyingParty.cs"/>
- <Compile Include="OpenId\RelyingParty\SelectorButtonContract.cs"/>
- <Compile Include="OpenId\RelyingParty\SelectorProviderButton.cs"/>
- <Compile Include="OpenId\RelyingParty\SelectorOpenIdButton.cs"/>
- <Compile Include="XrdsPublisher.cs"/>
- <Compile Include="InfoCard\ReceivingTokenEventArgs.cs"/>
- <Compile Include="InfoCard\TokenProcessingErrorEventArgs.cs"/>
- <Compile Include="InfoCard\InfoCardSelector.cs"/>
- <Compile Include="InfoCard\ReceivedTokenEventArgs.cs"/>
- <Compile Include="Mvc\OpenIdHelper.cs"/>
- <Compile Include="OpenId\RelyingParty\SelectorButton.cs"/>
- <Compile Include="OpenId\Provider\IdentityEndpoint.cs"/>
- <Compile Include="OpenId\Provider\IdentityEndpointNormalizationEventArgs.cs"/>
- <Compile Include="OpenId\RelyingParty\SelectorInfoCardButton.cs"/>
- <Compile Include="OpenId\RelyingParty\OpenIdMobileTextBox.cs" Condition=" '$(ClrVersion)' != '4' "/>
- <Compile Include="OpenId\RelyingParty\OpenIdAjaxTextBox.cs"/>
- <Compile Include="OpenId\RelyingParty\OpenIdSelector.cs"/>
- <Compile Include="OpenId\RelyingParty\OpenIdRelyingPartyAjaxControlBase.cs"/>
- <Compile Include="OpenId\RelyingParty\OpenIdButton.cs"/>
- <Compile Include="OpenId\RelyingParty\OpenIdRelyingPartyControlBase.cs"/>
- </ItemGroup>
- <ItemGroup>
- <None Include="Configuration\DotNetOpenAuth.xsd" />
- <None Include="Migrated rules for DotNetOpenAuth.ruleset" />
- <None Include="OAuth\ClassDiagram.cd" />
- <None Include="OAuth\Messages\OAuth Messages.cd" />
- <None Include="Messaging\Bindings\Bindings.cd" />
- <None Include="Messaging\Exceptions.cd" />
- <None Include="Messaging\Messaging.cd" />
- <None Include="OpenId\RelyingParty\Controls.cd" />
- <None Include="OpenId\RelyingParty\OpenIdRelyingParty.cd" />
- </ItemGroup>
- <ItemGroup>
- <EmbeddedResource Include="Messaging\MessagingStrings.resx">
- <Generator>ResXFileCodeGenerator</Generator>
- <LastGenOutput>MessagingStrings.Designer.cs</LastGenOutput>
- </EmbeddedResource>
- <EmbeddedResource Include="OAuth\OAuthStrings.resx">
- <Generator>ResXFileCodeGenerator</Generator>
- <LastGenOutput>OAuthStrings.Designer.cs</LastGenOutput>
- </EmbeddedResource>
- <EmbeddedResource Include="OpenId\OpenIdStrings.resx">
- <Generator>ResXFileCodeGenerator</Generator>
- <LastGenOutput>OpenIdStrings.Designer.cs</LastGenOutput>
- </EmbeddedResource>
- <EmbeddedResource Include="Strings.resx">
- <Generator>ResXFileCodeGenerator</Generator>
- <LastGenOutput>Strings.Designer.cs</LastGenOutput>
- <SubType>Designer</SubType>
- </EmbeddedResource>
- <EmbeddedResource Include="Xrds\XrdsStrings.resx">
- <Generator>ResXFileCodeGenerator</Generator>
- <LastGenOutput>XrdsStrings.Designer.cs</LastGenOutput>
- </EmbeddedResource>
- </ItemGroup>
- <ItemGroup>
- <EmbeddedResource Include="OpenId\RelyingParty\openid_login.png" />
- </ItemGroup>
- <ItemGroup>
- <EmbeddedResource Include="OpenId\RelyingParty\login_failure.png" />
- <EmbeddedResource Include="OpenId\RelyingParty\login_success %28lock%29.png" />
- <EmbeddedResource Include="OpenId\RelyingParty\login_success.png" />
- <EmbeddedResource Include="OpenId\RelyingParty\OpenIdAjaxTextBox.js">
- <Copyright>$(StandardCopyright)</Copyright>
- </EmbeddedResource>
- <EmbeddedResource Include="OpenId\RelyingParty\spinner.gif" />
- </ItemGroup>
- <ItemGroup>
- <EmbeddedResource Include="InfoCard\InfoCardStrings.resx">
- <Generator>ResXFileCodeGenerator</Generator>
- <LastGenOutput>InfoCardStrings.Designer.cs</LastGenOutput>
- </EmbeddedResource>
- <EmbeddedResource Include="InfoCard\infocard_114x80.png" />
- <EmbeddedResource Include="InfoCard\infocard_14x10.png" />
- <EmbeddedResource Include="InfoCard\infocard_214x150.png" />
- <EmbeddedResource Include="InfoCard\infocard_23x16.png" />
- <EmbeddedResource Include="InfoCard\infocard_300x210.png" />
- <EmbeddedResource Include="InfoCard\infocard_34x24.png" />
- <EmbeddedResource Include="InfoCard\infocard_365x256.png" />
- <EmbeddedResource Include="InfoCard\infocard_41x29.png" />
- <EmbeddedResource Include="InfoCard\infocard_50x35.png" />
- <EmbeddedResource Include="InfoCard\infocard_60x42.png" />
- <EmbeddedResource Include="InfoCard\infocard_71x50.png" />
- <EmbeddedResource Include="InfoCard\infocard_81x57.png" />
- <EmbeddedResource Include="InfoCard\infocard_92x64.png" />
- <EmbeddedResource Include="InfoCard\SupportingScript.js">
- <Copyright>$(StandardCopyright)</Copyright>
- </EmbeddedResource>
- </ItemGroup>
- <ItemGroup>
- <EmbeddedResource Include="OpenId\RelyingParty\OpenIdRelyingPartyControlBase.js">
- <Copyright>$(StandardCopyright)</Copyright>
- </EmbeddedResource>
- </ItemGroup>
- <ItemGroup>
- <EmbeddedResource Include="InfoCard\InfoCardStrings.sr.resx" />
- <EmbeddedResource Include="Messaging\MessagingStrings.sr.resx" />
- <EmbeddedResource Include="OAuth\OAuthStrings.sr.resx" />
- <EmbeddedResource Include="OpenId\Behaviors\BehaviorStrings.resx">
- <Generator>ResXFileCodeGenerator</Generator>
- <LastGenOutput>BehaviorStrings.Designer.cs</LastGenOutput>
- </EmbeddedResource>
- <EmbeddedResource Include="OpenId\Behaviors\BehaviorStrings.sr.resx" />
- <EmbeddedResource Include="OpenId\OpenIdStrings.sr.resx" />
- <EmbeddedResource Include="OpenId\RelyingParty\OpenIdRelyingPartyAjaxControlBase.js">
- <Copyright>$(StandardCopyright)</Copyright>
- </EmbeddedResource>
- <EmbeddedResource Include="Strings.sr.resx" />
- <EmbeddedResource Include="Xrds\XrdsStrings.sr.resx" />
- </ItemGroup>
- <ItemGroup>
- <EmbeddedResource Include="OpenId\RelyingParty\OpenIdAjaxTextBox.css" />
- </ItemGroup>
- <ItemGroup>
- <EmbeddedResource Include="OpenId\RelyingParty\OpenIdSelector.js" />
- </ItemGroup>
- <ItemGroup>
- <EmbeddedResource Include="OpenId\RelyingParty\OpenIdSelector.css" />
- </ItemGroup>
- <ItemGroup>
- <BootstrapperPackage Include="Microsoft.Net.Client.3.5">
- <Visible>False</Visible>
- <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
- <Install>false</Install>
- </BootstrapperPackage>
- <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
- <Visible>False</Visible>
- <ProductName>.NET Framework 3.5 SP1</ProductName>
- <Install>true</Install>
- </BootstrapperPackage>
- <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">
- <Visible>False</Visible>
- <ProductName>Windows Installer 3.1</ProductName>
- <Install>true</Install>
- </BootstrapperPackage>
- <Content Include="DotNetOpenAuth.ico" />
- </ItemGroup>
- <ItemGroup>
- <SignDependsOn Include="BuildUnifiedProduct" />
- <DelaySignedAssemblies Include="$(ILMergeOutputAssembly);&#xD;&#xA; $(OutputPath)CodeContracts\$(ProductName).Contracts.dll;&#xD;&#xA; " />
- </ItemGroup>
- <PropertyGroup>
- <!-- Don't sign the non-unified version of the assembly. -->
- <SuppressTargetPathDelaySignedAssembly>true</SuppressTargetPathDelaySignedAssembly>
- </PropertyGroup>
- <Target Name="BuildUnifiedProduct" DependsOnTargets="Build" Inputs="@(ILMergeInputAssemblies)" Outputs="$(ILMergeOutputAssembly)">
- <MakeDir Directories="$(ILMergeOutputAssemblyDirectory)" />
- <ILMerge ExcludeFile="$(ProjectRoot)ILMergeInternalizeExceptions.txt"
- InputAssemblies="@(ILMergeInputAssemblies)"
- OutputFile="$(ILMergeOutputAssembly)"
- KeyFile="$(PublicKeyFile)"
- DelaySign="true"
- ToolPath="$(ProjectRoot)tools\ILMerge"
- TargetPlatformVersion="$(ClrVersion).0"
- TargetPlatformDirectory="$(ILMergeTargetPlatformDirectory)" />
- </Target>
- <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
- <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
- <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
-</Project>
diff --git a/src/DotNetOpenAuth/DotNetOpenAuth.proj b/src/DotNetOpenAuth/DotNetOpenAuth.proj
new file mode 100644
index 0000000..0ae9c17
--- /dev/null
+++ b/src/DotNetOpenAuth/DotNetOpenAuth.proj
@@ -0,0 +1,78 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0" DefaultTargets="BuildUnifiedProduct">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))\EnlistmentInfo.props" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))' != '' " />
+
+ <PropertyGroup>
+ <SuppressBuildTarget>true</SuppressBuildTarget>
+ <AddContractsAssemblyForDelaySigning>false</AddContractsAssemblyForDelaySigning>
+ </PropertyGroup>
+
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" />
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" />
+
+ <UsingTask AssemblyFile="$(ProjectRoot)lib\MSBuild.Community.Tasks.dll" TaskName="ILMerge"/>
+
+ <PropertyGroup>
+ <TargetPath>$(ILMergeOutputAssembly)</TargetPath>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="@(ProductProjects)">
+ <PrimaryProductOutput Condition=" '%(MergeIntoUnifiedAssembly)' != 'false' ">true</PrimaryProductOutput>
+ </ProjectReference>
+ <SignDependsOn Include="BuildUnifiedProduct" />
+ <DelaySignedAssemblies Include="$(ILMergeOutputContractAssembly)"
+ Condition=" '$(BuildCodeContractsReferenceAssemblies)' == 'true' "/>
+ </ItemGroup>
+
+ <Target Name="BuildILMergeInputs" DependsOnTargets="ResolveReferences">
+ <ItemGroup>
+ <ILMergeProductInputAssemblies Include="@(ReferencePath)"
+ Condition=" '%(ReferencePath.PrimaryProductOutput)' == 'true' "/>
+ <ILMergeInputContractAssemblies Include="@(ILMergeProductInputAssemblies->'%(RootDir)%(Directory)CodeContracts\%(FileName).Contracts%(Extension)')"
+ Condition=" '%(FileName)' != 'Microsoft.Contracts' "/>
+ </ItemGroup>
+ </Target>
+
+ <Target Name="BuildUnifiedContractAssembly" DependsOnTargets="BuildILMergeInputs"
+ Condition=" '$(BuildCodeContractsReferenceAssemblies)' == 'true' "
+ Inputs="@(ILMergeInputContractAssemblies)" Outputs="$(ILMergeOutputContractAssembly)">
+
+ <MakeDir Directories="$(ILMergeOutputContractAssemblyDirectory)" />
+
+ <Message Text="Merging $(ILMergeOutputContractAssembly)" Importance="high" />
+ <ILMerge
+ ExcludeFile="$(ProjectRoot)ILMergeInternalizeExceptions.txt"
+ InputAssemblies="@(ILMergeInputContractAssemblies)"
+ OutputFile="$(ILMergeOutputContractAssembly)"
+ SearchDirectories="$(OutputPath);@(ILMergeSearchDirectories)"
+ KeyFile="$(PublicKeyFile)"
+ DelaySign="true"
+ ToolPath="$(ProjectRoot)tools\ILMerge"
+ TargetPlatformVersion="$(ClrVersion).0"
+ TargetPlatformDirectory="$(ILMergeTargetPlatformDirectory)" />
+ </Target>
+
+ <Target Name="BuildUnifiedProductAssembly" DependsOnTargets="BuildILMergeInputs"
+ Inputs="@(ILMergeProductInputAssemblies);@(ILMergeInputAssemblies)" Outputs="$(ILMergeOutputAssembly);$(ILMergeOutputXmlDocs)">
+ <MakeDir Directories="$(ILMergeOutputAssemblyDirectory)" />
+ <Message Text="Merging $(ILMergeOutputAssembly)" Importance="high" />
+ <ILMerge
+ ExcludeFile="$(ProjectRoot)ILMergeInternalizeExceptions.txt"
+ InputAssemblies="@(ILMergeProductInputAssemblies);@(ILMergeInputAssemblies)"
+ OutputFile="$(ILMergeOutputAssembly)"
+ SearchDirectories="@(ILMergeSearchDirectories)"
+ KeyFile="$(PublicKeyFile)"
+ DelaySign="true"
+ XmlDocumentation="true"
+ ToolPath="$(ProjectRoot)tools\ILMerge"
+ TargetPlatformVersion="$(ClrVersion).0"
+ TargetPlatformDirectory="$(ILMergeTargetPlatformDirectory)" />
+ </Target>
+
+ <Target Name="BuildUnifiedProduct" DependsOnTargets="BuildUnifiedProductAssembly;BuildUnifiedContractAssembly" />
+
+ <Import Project="$(MSBuildToolsPath)\Microsoft.Common.targets" />
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
+</Project> \ No newline at end of file
diff --git a/src/DotNetOpenAuth/Messaging/Reflection/MessageDescription.cs b/src/DotNetOpenAuth/Messaging/Reflection/MessageDescription.cs
deleted file mode 100644
index f783803..0000000
--- a/src/DotNetOpenAuth/Messaging/Reflection/MessageDescription.cs
+++ /dev/null
@@ -1,177 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="MessageDescription.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.Messaging.Reflection {
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Globalization;
- using System.Linq;
- using System.Reflection;
-
- /// <summary>
- /// A mapping between serialized key names and <see cref="MessagePart"/> instances describing
- /// those key/values pairs.
- /// </summary>
- internal class MessageDescription {
- /// <summary>
- /// The type of message this instance was generated from.
- /// </summary>
- private Type messageType;
-
- /// <summary>
- /// The message version this instance was generated from.
- /// </summary>
- private Version messageVersion;
-
- /// <summary>
- /// A mapping between the serialized key names and their
- /// describing <see cref="MessagePart"/> instances.
- /// </summary>
- private Dictionary<string, MessagePart> mapping;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="MessageDescription"/> class.
- /// </summary>
- /// <param name="messageType">Type of the message.</param>
- /// <param name="messageVersion">The message version.</param>
- internal MessageDescription(Type messageType, Version messageVersion) {
- Contract.Requires<ArgumentNullException>(messageType != null);
- Contract.Requires<ArgumentException>(typeof(IMessage).IsAssignableFrom(messageType));
- Contract.Requires<ArgumentNullException>(messageVersion != null);
-
- this.messageType = messageType;
- this.messageVersion = messageVersion;
- this.ReflectMessageType();
- }
-
- /// <summary>
- /// Gets the mapping between the serialized key names and their describing
- /// <see cref="MessagePart"/> instances.
- /// </summary>
- internal IDictionary<string, MessagePart> Mapping {
- get { return this.mapping; }
- }
-
- /// <summary>
- /// Gets a dictionary that provides read/write access to a message.
- /// </summary>
- /// <param name="message">The message the dictionary should provide access to.</param>
- /// <returns>The dictionary accessor to the message</returns>
- [Pure]
- internal MessageDictionary GetDictionary(IMessage message) {
- Contract.Requires<ArgumentNullException>(message != null);
- Contract.Ensures(Contract.Result<MessageDictionary>() != null);
- return this.GetDictionary(message, false);
- }
-
- /// <summary>
- /// Gets a dictionary that provides read/write access to a message.
- /// </summary>
- /// <param name="message">The message the dictionary should provide access to.</param>
- /// <param name="getOriginalValues">A value indicating whether this message dictionary will retrieve original values instead of normalized ones.</param>
- /// <returns>The dictionary accessor to the message</returns>
- [Pure]
- internal MessageDictionary GetDictionary(IMessage message, bool getOriginalValues) {
- Contract.Requires<ArgumentNullException>(message != null);
- Contract.Ensures(Contract.Result<MessageDictionary>() != null);
- return new MessageDictionary(message, this, getOriginalValues);
- }
-
- /// <summary>
- /// Reflects over some <see cref="IMessage"/>-implementing type
- /// and prepares to serialize/deserialize instances of that type.
- /// </summary>
- internal void ReflectMessageType() {
- this.mapping = new Dictionary<string, MessagePart>();
-
- Type currentType = this.messageType;
- do {
- foreach (MemberInfo member in currentType.GetMembers(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)) {
- if (member is PropertyInfo || member is FieldInfo) {
- MessagePartAttribute partAttribute =
- (from a in member.GetCustomAttributes(typeof(MessagePartAttribute), true).OfType<MessagePartAttribute>()
- orderby a.MinVersionValue descending
- where a.MinVersionValue <= this.messageVersion
- where a.MaxVersionValue >= this.messageVersion
- select a).FirstOrDefault();
- if (partAttribute != null) {
- MessagePart part = new MessagePart(member, partAttribute);
- if (this.mapping.ContainsKey(part.Name)) {
- Logger.Messaging.WarnFormat(
- "Message type {0} has more than one message part named {1}. Inherited members will be hidden.",
- this.messageType.Name,
- part.Name);
- } else {
- this.mapping.Add(part.Name, part);
- }
- }
- }
- }
- currentType = currentType.BaseType;
- } while (currentType != null);
- }
-
- /// <summary>
- /// Ensures the message parts pass basic validation.
- /// </summary>
- /// <param name="parts">The key/value pairs of the serialized message.</param>
- internal void EnsureMessagePartsPassBasicValidation(IDictionary<string, string> parts) {
- try {
- this.EnsureRequiredMessagePartsArePresent(parts.Keys);
- this.EnsureRequiredProtocolMessagePartsAreNotEmpty(parts);
- } catch (ProtocolException) {
- Logger.Messaging.ErrorFormat(
- "Error while performing basic validation of {0} ({3}) with these message parts:{1}{2}",
- this.messageType.Name,
- Environment.NewLine,
- parts.ToStringDeferred(),
- this.messageVersion);
- throw;
- }
- }
-
- /// <summary>
- /// Verifies that a given set of keys include all the required parameters
- /// for this message type or throws an exception.
- /// </summary>
- /// <param name="keys">The names of all parameters included in a message.</param>
- /// <exception cref="ProtocolException">Thrown when required parts of a message are not in <paramref name="keys"/></exception>
- private void EnsureRequiredMessagePartsArePresent(IEnumerable<string> keys) {
- var missingKeys = (from part in this.Mapping.Values
- where part.IsRequired && !keys.Contains(part.Name)
- select part.Name).ToArray();
- if (missingKeys.Length > 0) {
- throw new ProtocolException(
- string.Format(
- CultureInfo.CurrentCulture,
- MessagingStrings.RequiredParametersMissing,
- this.messageType.FullName,
- string.Join(", ", missingKeys)));
- }
- }
-
- /// <summary>
- /// Ensures the protocol message parts that must not be empty are in fact not empty.
- /// </summary>
- /// <param name="partValues">A dictionary of key/value pairs that make up the serialized message.</param>
- private void EnsureRequiredProtocolMessagePartsAreNotEmpty(IDictionary<string, string> partValues) {
- string value;
- var emptyValuedKeys = (from part in this.Mapping.Values
- where !part.AllowEmpty && partValues.TryGetValue(part.Name, out value) && value != null && value.Length == 0
- select part.Name).ToArray();
- if (emptyValuedKeys.Length > 0) {
- throw new ProtocolException(
- string.Format(
- CultureInfo.CurrentCulture,
- MessagingStrings.RequiredNonEmptyParameterWasEmpty,
- this.messageType.FullName,
- string.Join(", ", emptyValuedKeys)));
- }
- }
- }
-}
diff --git a/src/DotNetOpenAuth/OpenId/AssociationMemoryStore.cs b/src/DotNetOpenAuth/OpenId/AssociationMemoryStore.cs
deleted file mode 100644
index 7a20fd5..0000000
--- a/src/DotNetOpenAuth/OpenId/AssociationMemoryStore.cs
+++ /dev/null
@@ -1,133 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="AssociationMemoryStore.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.OpenId {
- using System.Collections.Generic;
- using System.Linq;
-
- /// <summary>
- /// Manages a set of associations in memory only (no database).
- /// </summary>
- /// <typeparam name="TKey">The type of the key.</typeparam>
- /// <remarks>
- /// This class should be used for low-to-medium traffic relying party sites that can afford to lose associations
- /// if the app pool was ever restarted. High traffic relying parties and providers should write their own
- /// implementation of <see cref="IAssociationStore&lt;TKey&gt;"/> that works against their own database schema
- /// to allow for persistance and recall of associations across servers in a web farm and server restarts.
- /// </remarks>
- internal class AssociationMemoryStore<TKey> : IAssociationStore<TKey> {
- /// <summary>
- /// How many association store requests should occur between each spring cleaning.
- /// </summary>
- private const int PeriodicCleaningFrequency = 10;
-
- /// <summary>
- /// For Relying Parties, this maps OP Endpoints to a set of associations with that endpoint.
- /// For Providers, this keeps smart and dumb associations in two distinct pools.
- /// </summary>
- private Dictionary<TKey, Associations> serverAssocsTable = new Dictionary<TKey, Associations>();
-
- /// <summary>
- /// A counter to track how close we are to an expired association cleaning run.
- /// </summary>
- private int periodicCleaning;
-
- /// <summary>
- /// Stores a given association for later recall.
- /// </summary>
- /// <param name="distinguishingFactor">The distinguishing factor, either an OP Endpoint or smart/dumb mode.</param>
- /// <param name="association">The association to store.</param>
- public void StoreAssociation(TKey distinguishingFactor, Association association) {
- lock (this) {
- if (!this.serverAssocsTable.ContainsKey(distinguishingFactor)) {
- this.serverAssocsTable.Add(distinguishingFactor, new Associations());
- }
- Associations server_assocs = this.serverAssocsTable[distinguishingFactor];
-
- server_assocs.Set(association);
-
- unchecked {
- this.periodicCleaning++;
- }
- if (this.periodicCleaning % PeriodicCleaningFrequency == 0) {
- this.ClearExpiredAssociations();
- }
- }
- }
-
- /// <summary>
- /// Gets the best association (the one with the longest remaining life) for a given key.
- /// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- /// <param name="securitySettings">The security settings.</param>
- /// <returns>
- /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key.
- /// </returns>
- public Association GetAssociation(TKey distinguishingFactor, SecuritySettings securitySettings) {
- lock (this) {
- return this.GetServerAssociations(distinguishingFactor).Best.FirstOrDefault(assoc => securitySettings.IsAssociationInPermittedRange(assoc));
- }
- }
-
- /// <summary>
- /// Gets the association for a given key and handle.
- /// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- /// <param name="handle">The handle of the specific association that must be recalled.</param>
- /// <returns>
- /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key and handle.
- /// </returns>
- public Association GetAssociation(TKey distinguishingFactor, string handle) {
- lock (this) {
- return this.GetServerAssociations(distinguishingFactor).Get(handle);
- }
- }
-
- /// <summary>
- /// Removes a specified handle that may exist in the store.
- /// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- /// <param name="handle">The handle of the specific association that must be deleted.</param>
- /// <returns>
- /// True if the association existed in this store previous to this call.
- /// </returns>
- /// <remarks>
- /// No exception should be thrown if the association does not exist in the store
- /// before this call.
- /// </remarks>
- public bool RemoveAssociation(TKey distinguishingFactor, string handle) {
- lock (this) {
- return this.GetServerAssociations(distinguishingFactor).Remove(handle);
- }
- }
-
- /// <summary>
- /// Gets the server associations for a given OP Endpoint or dumb/smart mode.
- /// </summary>
- /// <param name="distinguishingFactor">The distinguishing factor, either an OP Endpoint (for relying parties) or smart/dumb (for providers).</param>
- /// <returns>The collection of associations that fit the <paramref name="distinguishingFactor"/>.</returns>
- internal Associations GetServerAssociations(TKey distinguishingFactor) {
- lock (this) {
- if (!this.serverAssocsTable.ContainsKey(distinguishingFactor)) {
- this.serverAssocsTable.Add(distinguishingFactor, new Associations());
- }
-
- return this.serverAssocsTable[distinguishingFactor];
- }
- }
-
- /// <summary>
- /// Clears all expired associations from the store.
- /// </summary>
- private void ClearExpiredAssociations() {
- lock (this) {
- foreach (Associations assocs in this.serverAssocsTable.Values) {
- assocs.ClearExpired();
- }
- }
- }
- }
-}
diff --git a/src/DotNetOpenAuth/OpenId/ChannelElements/SigningBindingElement.cs b/src/DotNetOpenAuth/OpenId/ChannelElements/SigningBindingElement.cs
deleted file mode 100644
index 30310ac..0000000
--- a/src/DotNetOpenAuth/OpenId/ChannelElements/SigningBindingElement.cs
+++ /dev/null
@@ -1,415 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="SigningBindingElement.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.OpenId.ChannelElements {
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Globalization;
- using System.Linq;
- using System.Net.Security;
- using System.Web;
- using DotNetOpenAuth.Loggers;
- using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.Messaging.Bindings;
- using DotNetOpenAuth.Messaging.Reflection;
- using DotNetOpenAuth.OpenId.Messages;
- using DotNetOpenAuth.OpenId.Provider;
- using DotNetOpenAuth.OpenId.RelyingParty;
-
- /// <summary>
- /// Signs and verifies authentication assertions.
- /// </summary>
- internal class SigningBindingElement : IChannelBindingElement {
- /// <summary>
- /// The association store used by Relying Parties to look up the secrets needed for signing.
- /// </summary>
- private readonly IAssociationStore<Uri> rpAssociations;
-
- /// <summary>
- /// The association store used by Providers to look up the secrets needed for signing.
- /// </summary>
- private readonly IAssociationStore<AssociationRelyingPartyType> opAssociations;
-
- /// <summary>
- /// The security settings at the Provider.
- /// Only defined when this element is instantiated to service a Provider.
- /// </summary>
- private readonly ProviderSecuritySettings opSecuritySettings;
-
- /// <summary>
- /// Initializes a new instance of the SigningBindingElement class for use by a Relying Party.
- /// </summary>
- /// <param name="associationStore">The association store used to look up the secrets needed for signing. May be null for dumb Relying Parties.</param>
- internal SigningBindingElement(IAssociationStore<Uri> associationStore) {
- this.rpAssociations = associationStore;
- }
-
- /// <summary>
- /// Initializes a new instance of the SigningBindingElement class for use by a Provider.
- /// </summary>
- /// <param name="associationStore">The association store used to look up the secrets needed for signing.</param>
- /// <param name="securitySettings">The security settings.</param>
- internal SigningBindingElement(IAssociationStore<AssociationRelyingPartyType> associationStore, ProviderSecuritySettings securitySettings) {
- Contract.Requires<ArgumentNullException>(associationStore != null);
- Contract.Requires<ArgumentNullException>(securitySettings != null);
-
- this.opAssociations = associationStore;
- this.opSecuritySettings = securitySettings;
- }
-
- #region IChannelBindingElement Properties
-
- /// <summary>
- /// Gets the protection offered (if any) by this binding element.
- /// </summary>
- /// <value><see cref="MessageProtections.TamperProtection"/></value>
- public MessageProtections Protection {
- get { return MessageProtections.TamperProtection; }
- }
-
- /// <summary>
- /// Gets or sets the channel that this binding element belongs to.
- /// </summary>
- public Channel Channel { get; set; }
-
- #endregion
-
- /// <summary>
- /// Gets a value indicating whether this binding element is on a Provider channel.
- /// </summary>
- private bool IsOnProvider {
- get { return this.opAssociations != null; }
- }
-
- #region IChannelBindingElement Methods
-
- /// <summary>
- /// Prepares a message for sending based on the rules of this channel binding element.
- /// </summary>
- /// <param name="message">The message to prepare for sending.</param>
- /// <returns>
- /// The protections (if any) that this binding element applied to the message.
- /// Null if this binding element did not even apply to this binding element.
- /// </returns>
- public MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) {
- var signedMessage = message as ITamperResistantOpenIdMessage;
- if (signedMessage != null) {
- Logger.Bindings.DebugFormat("Signing {0} message.", message.GetType().Name);
- Association association = this.GetAssociation(signedMessage);
- signedMessage.AssociationHandle = association.Handle;
- signedMessage.SignedParameterOrder = this.GetSignedParameterOrder(signedMessage);
- signedMessage.Signature = this.GetSignature(signedMessage, association);
- return MessageProtections.TamperProtection;
- }
-
- return null;
- }
-
- /// <summary>
- /// Performs any transformation on an incoming message that may be necessary and/or
- /// validates an incoming message based on the rules of this channel binding element.
- /// </summary>
- /// <param name="message">The incoming message to process.</param>
- /// <returns>
- /// The protections (if any) that this binding element applied to the message.
- /// Null if this binding element did not even apply to this binding element.
- /// </returns>
- /// <exception cref="ProtocolException">
- /// Thrown when the binding element rules indicate that this message is invalid and should
- /// NOT be processed.
- /// </exception>
- public MessageProtections? ProcessIncomingMessage(IProtocolMessage message) {
- var signedMessage = message as ITamperResistantOpenIdMessage;
- if (signedMessage != null) {
- Logger.Bindings.DebugFormat("Verifying incoming {0} message signature of: {1}", message.GetType().Name, signedMessage.Signature);
- MessageProtections protectionsApplied = MessageProtections.TamperProtection;
-
- this.EnsureParametersRequiringSignatureAreSigned(signedMessage);
-
- Association association = this.GetSpecificAssociation(signedMessage);
- if (association != null) {
- string signature = this.GetSignature(signedMessage, association);
- if (!MessagingUtilities.EqualsConstantTime(signedMessage.Signature, signature)) {
- Logger.Bindings.Error("Signature verification failed.");
- throw new InvalidSignatureException(message);
- }
- } else {
- ErrorUtilities.VerifyInternal(this.Channel != null, "Cannot verify private association signature because we don't have a channel.");
-
- // If we're on the Provider, then the RP sent us a check_auth with a signature
- // we don't have an association for. (It may have expired, or it may be a faulty RP).
- if (this.IsOnProvider) {
- throw new InvalidSignatureException(message);
- }
-
- // We did not recognize the association the provider used to sign the message.
- // Ask the provider to check the signature then.
- var indirectSignedResponse = (IndirectSignedResponse)signedMessage;
- var checkSignatureRequest = new CheckAuthenticationRequest(indirectSignedResponse, this.Channel);
- var checkSignatureResponse = this.Channel.Request<CheckAuthenticationResponse>(checkSignatureRequest);
- if (!checkSignatureResponse.IsValid) {
- Logger.Bindings.Error("Provider reports signature verification failed.");
- throw new InvalidSignatureException(message);
- }
-
- // If the OP confirms that a handle should be invalidated as well, do that.
- if (!string.IsNullOrEmpty(checkSignatureResponse.InvalidateHandle)) {
- if (this.rpAssociations != null) {
- this.rpAssociations.RemoveAssociation(indirectSignedResponse.ProviderEndpoint, checkSignatureResponse.InvalidateHandle);
- }
- }
-
- // When we're in dumb mode we can't provide our own replay protection,
- // but for OpenID 2.0 Providers we can rely on them providing it as part
- // of signature verification.
- if (message.Version.Major >= 2) {
- protectionsApplied |= MessageProtections.ReplayProtection;
- }
- }
-
- return protectionsApplied;
- }
-
- return null;
- }
-
- #endregion
-
- /// <summary>
- /// Determines whether the relying party sending an authentication request is
- /// vulnerable to replay attacks.
- /// </summary>
- /// <param name="request">The request message from the Relying Party. Useful, but may be null for conservative estimate results.</param>
- /// <param name="response">The response message to be signed.</param>
- /// <returns>
- /// <c>true</c> if the relying party is vulnerable; otherwise, <c>false</c>.
- /// </returns>
- private static bool IsRelyingPartyVulnerableToReplays(SignedResponseRequest request, IndirectSignedResponse response) {
- Contract.Requires<ArgumentNullException>(response != null);
-
- // OpenID 2.0 includes replay protection as part of the protocol.
- if (response.Version.Major >= 2) {
- return false;
- }
-
- // This library's RP may be on the remote end, and may be using 1.x merely because
- // discovery on the Claimed Identifier suggested this was a 1.x OP.
- // Since this library's RP has a built-in request_nonce parameter for replay
- // protection, we'll allow for that.
- var returnToArgs = HttpUtility.ParseQueryString(response.ReturnTo.Query);
- if (!string.IsNullOrEmpty(returnToArgs[ReturnToNonceBindingElement.NonceParameter])) {
- return false;
- }
-
- // If the OP endpoint _AND_ RP return_to URL uses HTTPS then no one
- // can steal and replay the positive assertion.
- // We can only ascertain this if the request message was handed to us
- // so we know what our own OP endpoint is. If we don't have a request
- // message, then we'll default to assuming it's insecure.
- if (request != null) {
- if (request.Recipient.IsTransportSecure() && response.Recipient.IsTransportSecure()) {
- return false;
- }
- }
-
- // Nothing left to protect against replays. RP is vulnerable.
- return true;
- }
-
- /// <summary>
- /// Ensures that all message parameters that must be signed are in fact included
- /// in the signature.
- /// </summary>
- /// <param name="signedMessage">The signed message.</param>
- private void EnsureParametersRequiringSignatureAreSigned(ITamperResistantOpenIdMessage signedMessage) {
- // Verify that the signed parameter order includes the mandated fields.
- // We do this in such a way that derived classes that add mandated fields automatically
- // get included in the list of checked parameters.
- Protocol protocol = Protocol.Lookup(signedMessage.Version);
- var partsRequiringProtection = from part in this.Channel.MessageDescriptions.Get(signedMessage).Mapping.Values
- where part.RequiredProtection != ProtectionLevel.None
- where part.IsRequired || part.IsNondefaultValueSet(signedMessage)
- select part.Name;
- ErrorUtilities.VerifyInternal(partsRequiringProtection.All(name => name.StartsWith(protocol.openid.Prefix, StringComparison.Ordinal)), "Signing only works when the parameters start with the 'openid.' prefix.");
- string[] signedParts = signedMessage.SignedParameterOrder.Split(',');
- var unsignedParts = from partName in partsRequiringProtection
- where !signedParts.Contains(partName.Substring(protocol.openid.Prefix.Length))
- select partName;
- ErrorUtilities.VerifyProtocol(!unsignedParts.Any(), OpenIdStrings.SignatureDoesNotIncludeMandatoryParts, string.Join(", ", unsignedParts.ToArray()));
- }
-
- /// <summary>
- /// Calculates the signature for a given message.
- /// </summary>
- /// <param name="signedMessage">The message to sign or verify.</param>
- /// <param name="association">The association to use to sign the message.</param>
- /// <returns>The calculated signature of the method.</returns>
- private string GetSignature(ITamperResistantOpenIdMessage signedMessage, Association association) {
- Contract.Requires<ArgumentNullException>(signedMessage != null);
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(signedMessage.SignedParameterOrder));
- Contract.Requires<ArgumentNullException>(association != null);
-
- // Prepare the parts to sign, taking care to replace an openid.mode value
- // of check_authentication with its original id_res so the signature matches.
- MessageDictionary dictionary = this.Channel.MessageDescriptions.GetAccessor(signedMessage);
- var parametersToSign = from name in signedMessage.SignedParameterOrder.Split(',')
- let prefixedName = Protocol.V20.openid.Prefix + name
- select new KeyValuePair<string, string>(name, dictionary[prefixedName]);
-
- byte[] dataToSign = KeyValueFormEncoding.GetBytes(parametersToSign);
- string signature = Convert.ToBase64String(association.Sign(dataToSign));
-
- if (Logger.Signatures.IsDebugEnabled) {
- Logger.Signatures.DebugFormat(
- "Signing these message parts: {0}{1}{0}Base64 representation of signed data: {2}{0}Signature: {3}",
- Environment.NewLine,
- parametersToSign.ToStringDeferred(),
- Convert.ToBase64String(dataToSign),
- signature);
- }
-
- return signature;
- }
-
- /// <summary>
- /// Gets the value to use for the openid.signed parameter.
- /// </summary>
- /// <param name="signedMessage">The signable message.</param>
- /// <returns>
- /// A comma-delimited list of parameter names, omitting the 'openid.' prefix, that determines
- /// the inclusion and order of message parts that will be signed.
- /// </returns>
- private string GetSignedParameterOrder(ITamperResistantOpenIdMessage signedMessage) {
- Contract.Requires<InvalidOperationException>(this.Channel != null);
- Contract.Requires<ArgumentNullException>(signedMessage != null);
-
- Protocol protocol = Protocol.Lookup(signedMessage.Version);
-
- MessageDescription description = this.Channel.MessageDescriptions.Get(signedMessage);
- var signedParts = from part in description.Mapping.Values
- where (part.RequiredProtection & System.Net.Security.ProtectionLevel.Sign) != 0
- && part.GetValue(signedMessage) != null
- select part.Name;
- string prefix = Protocol.V20.openid.Prefix;
- ErrorUtilities.VerifyInternal(signedParts.All(name => name.StartsWith(prefix, StringComparison.Ordinal)), "All signed message parts must start with 'openid.'.");
-
- if (this.opSecuritySettings.SignOutgoingExtensions) {
- // Tack on any ExtraData parameters that start with 'openid.'.
- List<string> extraSignedParameters = new List<string>(signedMessage.ExtraData.Count);
- foreach (string key in signedMessage.ExtraData.Keys) {
- if (key.StartsWith(protocol.openid.Prefix, StringComparison.Ordinal)) {
- extraSignedParameters.Add(key);
- } else {
- Logger.Signatures.DebugFormat("The extra parameter '{0}' will not be signed because it does not start with 'openid.'.", key);
- }
- }
- signedParts = signedParts.Concat(extraSignedParameters);
- }
-
- int skipLength = prefix.Length;
- string signedFields = string.Join(",", signedParts.Select(name => name.Substring(skipLength)).ToArray());
- return signedFields;
- }
-
- /// <summary>
- /// Gets the association to use to sign or verify a message.
- /// </summary>
- /// <param name="signedMessage">The message to sign or verify.</param>
- /// <returns>The association to use to sign or verify the message.</returns>
- private Association GetAssociation(ITamperResistantOpenIdMessage signedMessage) {
- Contract.Requires<ArgumentNullException>(signedMessage != null);
-
- if (this.IsOnProvider) {
- // We're on a Provider to either sign (smart/dumb) or verify a dumb signature.
- bool signing = string.IsNullOrEmpty(signedMessage.Signature);
-
- if (signing) {
- // If the RP has no replay protection, coerce use of a private association
- // instead of a shared one (if security settings indicate)
- // to protect the authenticating user from replay attacks.
- bool forcePrivateAssociation = this.opSecuritySettings.ProtectDownlevelReplayAttacks
- && IsRelyingPartyVulnerableToReplays(null, (IndirectSignedResponse)signedMessage);
-
- if (forcePrivateAssociation) {
- if (!string.IsNullOrEmpty(signedMessage.AssociationHandle)) {
- Logger.Signatures.Info("An OpenID 1.x authentication request with a shared association handle will be responded to with a private association in order to provide OP-side replay protection.");
- }
-
- return this.GetDumbAssociationForSigning();
- } else {
- return this.GetSpecificAssociation(signedMessage) ?? this.GetDumbAssociationForSigning();
- }
- } else {
- return this.GetSpecificAssociation(signedMessage);
- }
- } else {
- // We're on a Relying Party verifying a signature.
- IDirectedProtocolMessage directedMessage = (IDirectedProtocolMessage)signedMessage;
- if (this.rpAssociations != null) {
- return this.rpAssociations.GetAssociation(directedMessage.Recipient, signedMessage.AssociationHandle);
- } else {
- return null;
- }
- }
- }
-
- /// <summary>
- /// Gets a specific association referenced in a given message's association handle.
- /// </summary>
- /// <param name="signedMessage">The signed message whose association handle should be used to lookup the association to return.</param>
- /// <returns>The referenced association; or <c>null</c> if such an association cannot be found.</returns>
- /// <remarks>
- /// If the association handle set in the message does not match any valid association,
- /// the association handle property is cleared, and the
- /// <see cref="ITamperResistantOpenIdMessage.InvalidateHandle"/> property is set to the
- /// handle that could not be found.
- /// </remarks>
- private Association GetSpecificAssociation(ITamperResistantOpenIdMessage signedMessage) {
- Association association = null;
-
- if (!string.IsNullOrEmpty(signedMessage.AssociationHandle)) {
- IndirectSignedResponse indirectSignedMessage = signedMessage as IndirectSignedResponse;
- if (this.IsOnProvider) {
- // Since we have an association handle, we're either signing with a smart association,
- // or verifying a dumb one.
- bool signing = string.IsNullOrEmpty(signedMessage.Signature);
- AssociationRelyingPartyType type = signing ? AssociationRelyingPartyType.Smart : AssociationRelyingPartyType.Dumb;
- association = this.opAssociations.GetAssociation(type, signedMessage.AssociationHandle);
- if (association == null) {
- // There was no valid association with the requested handle.
- // Let's tell the RP to forget about that association.
- signedMessage.InvalidateHandle = signedMessage.AssociationHandle;
- signedMessage.AssociationHandle = null;
- }
- } else if (this.rpAssociations != null) { // if on a smart RP
- Uri providerEndpoint = indirectSignedMessage.ProviderEndpoint;
- association = this.rpAssociations.GetAssociation(providerEndpoint, signedMessage.AssociationHandle);
- }
- }
-
- return association;
- }
-
- /// <summary>
- /// Gets a private Provider association used for signing messages in "dumb" mode.
- /// </summary>
- /// <returns>An existing or newly created association.</returns>
- private Association GetDumbAssociationForSigning() {
- // If no assoc_handle was given or it was invalid, the only thing
- // left to do is sign a message using a 'dumb' mode association.
- Protocol protocol = Protocol.Default;
- Association association = this.opAssociations.GetAssociation(AssociationRelyingPartyType.Dumb, this.opSecuritySettings);
- if (association == null) {
- association = HmacShaAssociation.Create(protocol, protocol.Args.SignatureAlgorithm.HMAC_SHA256, AssociationRelyingPartyType.Dumb, this.opSecuritySettings);
- this.opAssociations.StoreAssociation(AssociationRelyingPartyType.Dumb, association);
- }
-
- return association;
- }
- }
-}
diff --git a/src/DotNetOpenAuth/OpenId/DiffieHellman/DHParameters.cs b/src/DotNetOpenAuth/OpenId/DiffieHellman/DHParameters.cs
deleted file mode 100644
index 2772d7a..0000000
--- a/src/DotNetOpenAuth/OpenId/DiffieHellman/DHParameters.cs
+++ /dev/null
@@ -1,31 +0,0 @@
-// <auto-generated />
-
-//
-// DHParameters.cs: Defines a structure that holds the parameters of the Diffie-Hellman algorithm
-//
-// Author:
-// Pieter Philippaerts (Pieter@mentalis.org)
-//
-// (C) 2003 The Mentalis.org Team (http://www.mentalis.org/)
-//
-
-
-namespace Org.Mentalis.Security.Cryptography {
- /// <summary>
- /// Represents the parameters of the Diffie-Hellman algorithm.
- /// </summary>
- internal struct DHParameters {
- /// <summary>
- /// Represents the public <b>P</b> parameter of the Diffie-Hellman algorithm.
- /// </summary>
- public byte[] P;
- /// <summary>
- /// Represents the public <b>G</b> parameter of the Diffie-Hellman algorithm.
- /// </summary>
- public byte[] G;
- /// <summary>
- /// Represents the private <b>X</b> parameter of the Diffie-Hellman algorithm.
- /// </summary>
- public byte[] X;
- }
-} \ No newline at end of file
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/ExtensionsInteropHelper.cs b/src/DotNetOpenAuth/OpenId/Extensions/ExtensionsInteropHelper.cs
deleted file mode 100644
index 5e1003a..0000000
--- a/src/DotNetOpenAuth/OpenId/Extensions/ExtensionsInteropHelper.cs
+++ /dev/null
@@ -1,383 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="ExtensionsInteropHelper.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.OpenId.Extensions {
- using System;
- using System.Collections.Generic;
- using System.Diagnostics.CodeAnalysis;
- using System.Diagnostics.Contracts;
- using System.Linq;
- using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
- using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
- using DotNetOpenAuth.OpenId.Messages;
-
- /// <summary>
- /// A set of methods designed to assist in improving interop across different
- /// OpenID implementations and their extensions.
- /// </summary>
- public static class ExtensionsInteropHelper {
- /// <summary>
- /// The gender decoder to translate AX genders to Sreg.
- /// </summary>
- private static GenderEncoder genderEncoder = new GenderEncoder();
-
- /// <summary>
- /// Adds an Attribute Exchange (AX) extension to the authentication request
- /// that asks for the same attributes as the Simple Registration (sreg) extension
- /// that is already applied.
- /// </summary>
- /// <param name="request">The authentication request.</param>
- /// <param name="attributeFormats">The attribute formats to use in the AX request.</param>
- /// <remarks>
- /// <para>If discovery on the user-supplied identifier yields hints regarding which
- /// extensions and attribute formats the Provider supports, this method MAY ignore the
- /// <paramref name="attributeFormats"/> argument and accomodate the Provider to minimize
- /// the size of the request.</para>
- /// <para>If the request does not carry an sreg extension, the method logs a warning but
- /// otherwise quietly returns doing nothing.</para>
- /// </remarks>
- [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sreg", Justification = "Abbreviation")]
- public static void SpreadSregToAX(this RelyingParty.IAuthenticationRequest request, AXAttributeFormats attributeFormats) {
- Contract.Requires<ArgumentNullException>(request != null);
-
- var req = (RelyingParty.AuthenticationRequest)request;
- var sreg = req.AppliedExtensions.OfType<ClaimsRequest>().SingleOrDefault();
- if (sreg == null) {
- Logger.OpenId.Debug("No Simple Registration (ClaimsRequest) extension present in the request to spread to AX.");
- return;
- }
-
- if (req.DiscoveryResult.IsExtensionSupported<ClaimsRequest>()) {
- Logger.OpenId.Debug("Skipping generation of AX request because the Identifier advertises the Provider supports the Sreg extension.");
- return;
- }
-
- var ax = req.AppliedExtensions.OfType<FetchRequest>().SingleOrDefault();
- if (ax == null) {
- ax = new FetchRequest();
- req.AddExtension(ax);
- }
-
- // Try to use just one AX Type URI format if we can figure out which type the OP accepts.
- AXAttributeFormats detectedFormat;
- if (TryDetectOPAttributeFormat(request, out detectedFormat)) {
- Logger.OpenId.Debug("Detected OP support for AX but not for Sreg. Removing Sreg extension request and using AX instead.");
- attributeFormats = detectedFormat;
- req.Extensions.Remove(sreg);
- } else {
- Logger.OpenId.Debug("Could not determine whether OP supported Sreg or AX. Using both extensions.");
- }
-
- foreach (AXAttributeFormats format in ForEachFormat(attributeFormats)) {
- FetchAttribute(ax, format, WellKnownAttributes.BirthDate.WholeBirthDate, sreg.BirthDate);
- FetchAttribute(ax, format, WellKnownAttributes.Contact.HomeAddress.Country, sreg.Country);
- FetchAttribute(ax, format, WellKnownAttributes.Contact.Email, sreg.Email);
- FetchAttribute(ax, format, WellKnownAttributes.Name.FullName, sreg.FullName);
- FetchAttribute(ax, format, WellKnownAttributes.Person.Gender, sreg.Gender);
- FetchAttribute(ax, format, WellKnownAttributes.Preferences.Language, sreg.Language);
- FetchAttribute(ax, format, WellKnownAttributes.Name.Alias, sreg.Nickname);
- FetchAttribute(ax, format, WellKnownAttributes.Contact.HomeAddress.PostalCode, sreg.PostalCode);
- FetchAttribute(ax, format, WellKnownAttributes.Preferences.TimeZone, sreg.TimeZone);
- }
- }
-
- /// <summary>
- /// Looks for Simple Registration and Attribute Exchange (all known formats)
- /// response extensions and returns them as a Simple Registration extension.
- /// </summary>
- /// <param name="response">The authentication response.</param>
- /// <param name="allowUnsigned">if set to <c>true</c> unsigned extensions will be included in the search.</param>
- /// <returns>
- /// The Simple Registration response if found,
- /// or a fabricated one based on the Attribute Exchange extension if found,
- /// or just an empty <see cref="ClaimsResponse"/> if there was no data.
- /// Never <c>null</c>.</returns>
- [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sreg", Justification = "Abbreviation")]
- public static ClaimsResponse UnifyExtensionsAsSreg(this RelyingParty.IAuthenticationResponse response, bool allowUnsigned) {
- Contract.Requires<ArgumentNullException>(response != null);
-
- var resp = (RelyingParty.IAuthenticationResponse)response;
- var sreg = allowUnsigned ? resp.GetUntrustedExtension<ClaimsResponse>() : resp.GetExtension<ClaimsResponse>();
- if (sreg != null) {
- return sreg;
- }
-
- AXAttributeFormats formats = AXAttributeFormats.All;
- sreg = new ClaimsResponse();
- var fetchResponse = allowUnsigned ? resp.GetUntrustedExtension<FetchResponse>() : resp.GetExtension<FetchResponse>();
- if (fetchResponse != null) {
- ((IOpenIdMessageExtension)sreg).IsSignedByRemoteParty = fetchResponse.IsSignedByProvider;
- sreg.BirthDateRaw = fetchResponse.GetAttributeValue(WellKnownAttributes.BirthDate.WholeBirthDate, formats);
- sreg.Country = fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.HomeAddress.Country, formats);
- sreg.PostalCode = fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.HomeAddress.PostalCode, formats);
- sreg.Email = fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Email, formats);
- sreg.FullName = fetchResponse.GetAttributeValue(WellKnownAttributes.Name.FullName, formats);
- sreg.Language = fetchResponse.GetAttributeValue(WellKnownAttributes.Preferences.Language, formats);
- sreg.Nickname = fetchResponse.GetAttributeValue(WellKnownAttributes.Name.Alias, formats);
- sreg.TimeZone = fetchResponse.GetAttributeValue(WellKnownAttributes.Preferences.TimeZone, formats);
- string gender = fetchResponse.GetAttributeValue(WellKnownAttributes.Person.Gender, formats);
- if (gender != null) {
- sreg.Gender = (Gender)genderEncoder.Decode(gender);
- }
- }
-
- return sreg;
- }
-
- /// <summary>
- /// Looks for Simple Registration and Attribute Exchange (all known formats)
- /// request extensions and returns them as a Simple Registration extension,
- /// and adds the new extension to the original request message if it was absent.
- /// </summary>
- /// <param name="request">The authentication request.</param>
- /// <returns>
- /// The Simple Registration request if found,
- /// or a fabricated one based on the Attribute Exchange extension if found,
- /// or <c>null</c> if no attribute extension request is found.</returns>
- internal static ClaimsRequest UnifyExtensionsAsSreg(this Provider.IHostProcessedRequest request) {
- Contract.Requires<ArgumentNullException>(request != null);
-
- var req = (Provider.HostProcessedRequest)request;
- var sreg = req.GetExtension<ClaimsRequest>();
- if (sreg != null) {
- return sreg;
- }
-
- var ax = req.GetExtension<FetchRequest>();
- if (ax != null) {
- sreg = new ClaimsRequest(SimpleRegistration.Constants.sreg_ns);
- sreg.Synthesized = true;
- ((IProtocolMessageWithExtensions)req.RequestMessage).Extensions.Add(sreg);
- sreg.BirthDate = GetDemandLevelFor(ax, WellKnownAttributes.BirthDate.WholeBirthDate);
- sreg.Country = GetDemandLevelFor(ax, WellKnownAttributes.Contact.HomeAddress.Country);
- sreg.Email = GetDemandLevelFor(ax, WellKnownAttributes.Contact.Email);
- sreg.FullName = GetDemandLevelFor(ax, WellKnownAttributes.Name.FullName);
- sreg.Gender = GetDemandLevelFor(ax, WellKnownAttributes.Person.Gender);
- sreg.Language = GetDemandLevelFor(ax, WellKnownAttributes.Preferences.Language);
- sreg.Nickname = GetDemandLevelFor(ax, WellKnownAttributes.Name.Alias);
- sreg.PostalCode = GetDemandLevelFor(ax, WellKnownAttributes.Contact.HomeAddress.PostalCode);
- sreg.TimeZone = GetDemandLevelFor(ax, WellKnownAttributes.Preferences.TimeZone);
- }
-
- return sreg;
- }
-
- /// <summary>
- /// Converts the Simple Registration extension response to whatever format the original
- /// attribute request extension came in.
- /// </summary>
- /// <param name="request">The authentication request with the response extensions already added.</param>
- /// <remarks>
- /// If the original attribute request came in as AX, the Simple Registration extension is converted
- /// to an AX response and then the Simple Registration extension is removed from the response.
- /// </remarks>
- internal static void ConvertSregToMatchRequest(this Provider.IHostProcessedRequest request) {
- var req = (Provider.HostProcessedRequest)request;
- var response = req.Response as IProtocolMessageWithExtensions; // negative responses don't support extensions.
- var sregRequest = request.GetExtension<ClaimsRequest>();
- if (sregRequest != null && response != null) {
- if (sregRequest.Synthesized) {
- var axRequest = request.GetExtension<FetchRequest>();
- ErrorUtilities.VerifyInternal(axRequest != null, "How do we have a synthesized Sreg request without an AX request?");
-
- var sregResponse = response.Extensions.OfType<ClaimsResponse>().SingleOrDefault();
- if (sregResponse == null) {
- // No Sreg response to copy from.
- return;
- }
-
- // Remove the sreg response since the RP didn't ask for it.
- response.Extensions.Remove(sregResponse);
-
- AXAttributeFormats format = DetectAXFormat(axRequest.Attributes.Select(att => att.TypeUri));
- if (format == AXAttributeFormats.None) {
- // No recognized AX attributes were requested.
- return;
- }
-
- var axResponse = response.Extensions.OfType<FetchResponse>().SingleOrDefault();
- if (axResponse == null) {
- axResponse = new FetchResponse();
- response.Extensions.Add(axResponse);
- }
-
- AddAXAttributeValue(axResponse, WellKnownAttributes.BirthDate.WholeBirthDate, format, sregResponse.BirthDateRaw);
- AddAXAttributeValue(axResponse, WellKnownAttributes.Contact.HomeAddress.Country, format, sregResponse.Country);
- AddAXAttributeValue(axResponse, WellKnownAttributes.Contact.HomeAddress.PostalCode, format, sregResponse.PostalCode);
- AddAXAttributeValue(axResponse, WellKnownAttributes.Contact.Email, format, sregResponse.Email);
- AddAXAttributeValue(axResponse, WellKnownAttributes.Name.FullName, format, sregResponse.FullName);
- AddAXAttributeValue(axResponse, WellKnownAttributes.Name.Alias, format, sregResponse.Nickname);
- AddAXAttributeValue(axResponse, WellKnownAttributes.Preferences.TimeZone, format, sregResponse.TimeZone);
- AddAXAttributeValue(axResponse, WellKnownAttributes.Preferences.Language, format, sregResponse.Language);
- if (sregResponse.Gender.HasValue) {
- AddAXAttributeValue(axResponse, WellKnownAttributes.Person.Gender, format, genderEncoder.Encode(sregResponse.Gender));
- }
- }
- }
- }
-
- /// <summary>
- /// Gets the attribute value if available.
- /// </summary>
- /// <param name="fetchResponse">The AX fetch response extension to look for the attribute value.</param>
- /// <param name="typeUri">The type URI of the attribute, using the axschema.org format of <see cref="WellKnownAttributes"/>.</param>
- /// <param name="formats">The AX type URI formats to search.</param>
- /// <returns>
- /// The first value of the attribute, if available.
- /// </returns>
- internal static string GetAttributeValue(this FetchResponse fetchResponse, string typeUri, AXAttributeFormats formats) {
- return ForEachFormat(formats).Select(format => fetchResponse.GetAttributeValue(TransformAXFormat(typeUri, format))).FirstOrDefault(s => s != null);
- }
-
- /// <summary>
- /// Transforms an AX attribute type URI from the axschema.org format into a given format.
- /// </summary>
- /// <param name="axSchemaOrgFormatTypeUri">The ax schema org format type URI.</param>
- /// <param name="targetFormat">The target format. Only one flag should be set.</param>
- /// <returns>The AX attribute type URI in the target format.</returns>
- internal static string TransformAXFormatTestHook(string axSchemaOrgFormatTypeUri, AXAttributeFormats targetFormat) {
- return TransformAXFormat(axSchemaOrgFormatTypeUri, targetFormat);
- }
-
- /// <summary>
- /// Adds the AX attribute value to the response if it is non-empty.
- /// </summary>
- /// <param name="ax">The AX Fetch response to add the attribute value to.</param>
- /// <param name="typeUri">The attribute type URI in axschema.org format.</param>
- /// <param name="format">The target format of the actual attribute to write out.</param>
- /// <param name="value">The value of the attribute.</param>
- private static void AddAXAttributeValue(FetchResponse ax, string typeUri, AXAttributeFormats format, string value) {
- if (!string.IsNullOrEmpty(value)) {
- string targetTypeUri = TransformAXFormat(typeUri, format);
- if (!ax.Attributes.Contains(targetTypeUri)) {
- ax.Attributes.Add(targetTypeUri, value);
- }
- }
- }
-
- /// <summary>
- /// Gets the demand level for an AX attribute.
- /// </summary>
- /// <param name="ax">The AX fetch request to search for the attribute.</param>
- /// <param name="typeUri">The type URI of the attribute in axschema.org format.</param>
- /// <returns>The demand level for the attribute.</returns>
- private static DemandLevel GetDemandLevelFor(FetchRequest ax, string typeUri) {
- Contract.Requires<ArgumentNullException>(ax != null);
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(typeUri));
-
- foreach (AXAttributeFormats format in ForEachFormat(AXAttributeFormats.All)) {
- string typeUriInFormat = TransformAXFormat(typeUri, format);
- if (ax.Attributes.Contains(typeUriInFormat)) {
- return ax.Attributes[typeUriInFormat].IsRequired ? DemandLevel.Require : DemandLevel.Request;
- }
- }
-
- return DemandLevel.NoRequest;
- }
-
- /// <summary>
- /// Tries to find the exact format of AX attribute Type URI supported by the Provider.
- /// </summary>
- /// <param name="request">The authentication request.</param>
- /// <param name="attributeFormat">The attribute formats the RP will try if this discovery fails.</param>
- /// <returns>The AX format(s) to use based on the Provider's advertised AX support.</returns>
- private static bool TryDetectOPAttributeFormat(RelyingParty.IAuthenticationRequest request, out AXAttributeFormats attributeFormat) {
- Contract.Requires<ArgumentNullException>(request != null);
- attributeFormat = DetectAXFormat(request.DiscoveryResult.Capabilities);
- return attributeFormat != AXAttributeFormats.None;
- }
-
- /// <summary>
- /// Detects the AX attribute type URI format from a given sample.
- /// </summary>
- /// <param name="typeURIs">The type URIs to scan for recognized formats.</param>
- /// <returns>The first AX type URI format recognized in the list.</returns>
- private static AXAttributeFormats DetectAXFormat(IEnumerable<string> typeURIs) {
- Contract.Requires<ArgumentNullException>(typeURIs != null);
-
- if (typeURIs.Any(uri => uri.StartsWith("http://axschema.org/", StringComparison.Ordinal))) {
- return AXAttributeFormats.AXSchemaOrg;
- }
-
- if (typeURIs.Any(uri => uri.StartsWith("http://schema.openid.net/", StringComparison.Ordinal))) {
- return AXAttributeFormats.SchemaOpenIdNet;
- }
-
- if (typeURIs.Any(uri => uri.StartsWith("http://openid.net/schema/", StringComparison.Ordinal))) {
- return AXAttributeFormats.OpenIdNetSchema;
- }
-
- return AXAttributeFormats.None;
- }
-
- /// <summary>
- /// Transforms an AX attribute type URI from the axschema.org format into a given format.
- /// </summary>
- /// <param name="axSchemaOrgFormatTypeUri">The ax schema org format type URI.</param>
- /// <param name="targetFormat">The target format. Only one flag should be set.</param>
- /// <returns>The AX attribute type URI in the target format.</returns>
- private static string TransformAXFormat(string axSchemaOrgFormatTypeUri, AXAttributeFormats targetFormat) {
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(axSchemaOrgFormatTypeUri));
-
- switch (targetFormat) {
- case AXAttributeFormats.AXSchemaOrg:
- return axSchemaOrgFormatTypeUri;
- case AXAttributeFormats.SchemaOpenIdNet:
- return axSchemaOrgFormatTypeUri.Replace("axschema.org", "schema.openid.net");
- case AXAttributeFormats.OpenIdNetSchema:
- return axSchemaOrgFormatTypeUri.Replace("axschema.org", "openid.net/schema");
- default:
- throw new ArgumentOutOfRangeException("targetFormat");
- }
- }
-
- /// <summary>
- /// Splits the AX attribute format flags into individual values for processing.
- /// </summary>
- /// <param name="formats">The formats to split up into individual flags.</param>
- /// <returns>A sequence of individual flags.</returns>
- private static IEnumerable<AXAttributeFormats> ForEachFormat(AXAttributeFormats formats) {
- if ((formats & AXAttributeFormats.AXSchemaOrg) != 0) {
- yield return AXAttributeFormats.AXSchemaOrg;
- }
-
- if ((formats & AXAttributeFormats.OpenIdNetSchema) != 0) {
- yield return AXAttributeFormats.OpenIdNetSchema;
- }
-
- if ((formats & AXAttributeFormats.SchemaOpenIdNet) != 0) {
- yield return AXAttributeFormats.SchemaOpenIdNet;
- }
- }
-
- /// <summary>
- /// Adds an attribute fetch request if it is not already present in the AX request.
- /// </summary>
- /// <param name="ax">The AX request to add the attribute request to.</param>
- /// <param name="format">The format of the attribute's Type URI to use.</param>
- /// <param name="axSchemaOrgFormatAttribute">The attribute in axschema.org format.</param>
- /// <param name="demandLevel">The demand level.</param>
- private static void FetchAttribute(FetchRequest ax, AXAttributeFormats format, string axSchemaOrgFormatAttribute, DemandLevel demandLevel) {
- Contract.Requires<ArgumentNullException>(ax != null);
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(axSchemaOrgFormatAttribute));
-
- string typeUri = TransformAXFormat(axSchemaOrgFormatAttribute, format);
- if (!ax.Attributes.Contains(typeUri)) {
- switch (demandLevel) {
- case DemandLevel.Request:
- ax.Attributes.AddOptional(typeUri);
- break;
- case DemandLevel.Require:
- ax.Attributes.AddRequired(typeUri);
- break;
- default:
- break;
- }
- }
- }
- }
-}
diff --git a/src/DotNetOpenAuth/OpenId/IAssociationStore.cs b/src/DotNetOpenAuth/OpenId/IAssociationStore.cs
deleted file mode 100644
index fb4487c..0000000
--- a/src/DotNetOpenAuth/OpenId/IAssociationStore.cs
+++ /dev/null
@@ -1,189 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="IAssociationStore.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.OpenId {
- using System;
- using System.Diagnostics.Contracts;
-
- /// <summary>
- /// An enumeration that can specify how a given <see cref="Association"/> is used.
- /// </summary>
- public enum AssociationRelyingPartyType {
- /// <summary>
- /// The <see cref="Association"/> manages a shared secret between
- /// Provider and Relying Party sites that allows the RP to verify
- /// the signature on a message from an OP.
- /// </summary>
- Smart,
-
- /// <summary>
- /// The <see cref="Association"/> manages a secret known alone by
- /// a Provider that allows the Provider to verify its own signatures
- /// for "dumb" (stateless) relying parties.
- /// </summary>
- Dumb
- }
-
- /// <summary>
- /// Stores <see cref="Association"/>s for lookup by their handle, keeping
- /// associations separated by a given distinguishing factor (like which server the
- /// association is with).
- /// </summary>
- /// <typeparam name="TKey">
- /// <see cref="System.Uri"/> for consumers (to distinguish associations across servers) or
- /// <see cref="AssociationRelyingPartyType"/> for providers (to distinguish dumb and smart client associations).
- /// </typeparam>
- /// <remarks>
- /// Expired associations should be periodically cleared out of an association store.
- /// This should be done frequently enough to avoid a memory leak, but sparingly enough
- /// to not be a performance drain. Because this balance can vary by host, it is the
- /// responsibility of the host to initiate this cleaning.
- /// </remarks>
- ////[ContractClass(typeof(IAssociationStoreContract<>))]
- public interface IAssociationStore<TKey> {
- /// <summary>
- /// Saves an <see cref="Association"/> for later recall.
- /// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for providers).</param>
- /// <param name="association">The association to store.</param>
- /// <remarks>
- /// TODO: what should implementations do on association handle conflict?
- /// </remarks>
- void StoreAssociation(TKey distinguishingFactor, Association association);
-
- /// <summary>
- /// Gets the best association (the one with the longest remaining life) for a given key.
- /// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- /// <param name="securityRequirements">The security requirements that the returned association must meet.</param>
- /// <returns>
- /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key.
- /// </returns>
- /// <remarks>
- /// In the event that multiple associations exist for the given
- /// <paramref name="distinguishingFactor"/>, it is important for the
- /// implementation for this method to use the <paramref name="securityRequirements"/>
- /// to pick the best (highest grade or longest living as the host's policy may dictate)
- /// association that fits the security requirements.
- /// Associations that are returned that do not meet the security requirements will be
- /// ignored and a new association created.
- /// </remarks>
- Association GetAssociation(TKey distinguishingFactor, SecuritySettings securityRequirements);
-
- /// <summary>
- /// Gets the association for a given key and handle.
- /// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- /// <param name="handle">The handle of the specific association that must be recalled.</param>
- /// <returns>The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key and handle.</returns>
- Association GetAssociation(TKey distinguishingFactor, string handle);
-
- /// <summary>Removes a specified handle that may exist in the store.</summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- /// <param name="handle">The handle of the specific association that must be deleted.</param>
- /// <returns>True if the association existed in this store previous to this call.</returns>
- /// <remarks>
- /// No exception should be thrown if the association does not exist in the store
- /// before this call.
- /// </remarks>
- bool RemoveAssociation(TKey distinguishingFactor, string handle);
- }
-
- // For some odd reason, having this next class causes our test project to fail to build with this error:
- // Error 42 Method 'StoreAssociation' in type 'DotNetOpenAuth.OpenId.IAssociationStoreContract_Accessor`1' from assembly 'DotNetOpenAuth_Accessor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation. DotNetOpenAuth.Test
- /////// <summary>
- /////// Code Contract for the <see cref="IAssociationStore&lt;TKey&gt;"/> class.
- /////// </summary>
- /////// <typeparam name="TKey">The type of the key.</typeparam>
- ////[ContractClassFor(typeof(IAssociationStore<>))]
- ////internal abstract class IAssociationStoreContract<TKey> : IAssociationStore<TKey> {
- //// #region IAssociationStore<TKey> Members
-
- //// /// <summary>
- //// /// Saves an <see cref="Association"/> for later recall.
- //// /// </summary>
- //// /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for providers).</param>
- //// /// <param name="association">The association to store.</param>
- //// /// <remarks>
- //// /// TODO: what should implementations do on association handle conflict?
- //// /// </remarks>
- //// void IAssociationStore<TKey>.StoreAssociation(TKey distinguishingFactor, Association association) {
- //// Contract.Requires<ArgumentNullException>(distinguishingFactor != null);
- //// Contract.Requires<ArgumentNullException>(association != null);
- //// throw new NotImplementedException();
- //// }
-
- //// /// <summary>
- //// /// Gets the best association (the one with the longest remaining life) for a given key.
- //// /// </summary>
- //// /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- //// /// <param name="securityRequirements">The security requirements that the returned association must meet.</param>
- //// /// <returns>
- //// /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key.
- //// /// </returns>
- //// /// <remarks>
- //// /// In the event that multiple associations exist for the given
- //// /// <paramref name="distinguishingFactor"/>, it is important for the
- //// /// implementation for this method to use the <paramref name="securityRequirements"/>
- //// /// to pick the best (highest grade or longest living as the host's policy may dictate)
- //// /// association that fits the security requirements.
- //// /// Associations that are returned that do not meet the security requirements will be
- //// /// ignored and a new association created.
- //// /// </remarks>
- //// Association IAssociationStore<TKey>.GetAssociation(TKey distinguishingFactor, SecuritySettings securityRequirements) {
- //// Contract.Requires<ArgumentNullException>(distinguishingFactor != null);
- //// Contract.Requires<ArgumentNullException>(securityRequirements != null);
- //// throw new NotImplementedException();
- //// }
-
- //// /// <summary>
- //// /// Gets the association for a given key and handle.
- //// /// </summary>
- //// /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- //// /// <param name="handle">The handle of the specific association that must be recalled.</param>
- //// /// <returns>
- //// /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key and handle.
- //// /// </returns>
- //// Association IAssociationStore<TKey>.GetAssociation(TKey distinguishingFactor, string handle) {
- //// Contract.Requires<ArgumentNullException>(distinguishingFactor != null);
- //// Contract.Requires(!String.IsNullOrEmpty(handle));
- //// throw new NotImplementedException();
- //// }
-
- //// /// <summary>
- //// /// Removes a specified handle that may exist in the store.
- //// /// </summary>
- //// /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- //// /// <param name="handle">The handle of the specific association that must be deleted.</param>
- //// /// <returns>
- //// /// True if the association existed in this store previous to this call.
- //// /// </returns>
- //// /// <remarks>
- //// /// No exception should be thrown if the association does not exist in the store
- //// /// before this call.
- //// /// </remarks>
- //// bool IAssociationStore<TKey>.RemoveAssociation(TKey distinguishingFactor, string handle) {
- //// Contract.Requires<ArgumentNullException>(distinguishingFactor != null);
- //// Contract.Requires(!String.IsNullOrEmpty(handle));
- //// throw new NotImplementedException();
- //// }
-
- //// /// <summary>
- //// /// Clears all expired associations from the store.
- //// /// </summary>
- //// /// <remarks>
- //// /// If another algorithm is in place to periodically clear out expired associations,
- //// /// this method call may be ignored.
- //// /// This should be done frequently enough to avoid a memory leak, but sparingly enough
- //// /// to not be a performance drain.
- //// /// </remarks>
- //// void IAssociationStore<TKey>.ClearExpiredAssociations() {
- //// throw new NotImplementedException();
- //// }
-
- //// #endregion
- ////}
-}
diff --git a/src/DotNetOpenAuth/OpenId/Messages/AssociateRequest.cs b/src/DotNetOpenAuth/OpenId/Messages/AssociateRequest.cs
deleted file mode 100644
index 3fd9424..0000000
--- a/src/DotNetOpenAuth/OpenId/Messages/AssociateRequest.cs
+++ /dev/null
@@ -1,215 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="AssociateRequest.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.OpenId.Messages {
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Linq;
- using System.Text;
- using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.OpenId.Provider;
- using DotNetOpenAuth.OpenId.RelyingParty;
-
- /// <summary>
- /// An OpenID direct request from Relying Party to Provider to initiate an association.
- /// </summary>
- [DebuggerDisplay("OpenID {Version} {Mode} {AssociationType} {SessionType}")]
- internal abstract class AssociateRequest : RequestBase {
- /// <summary>
- /// Initializes a new instance of the <see cref="AssociateRequest"/> class.
- /// </summary>
- /// <param name="version">The OpenID version this message must comply with.</param>
- /// <param name="providerEndpoint">The OpenID Provider endpoint.</param>
- protected AssociateRequest(Version version, Uri providerEndpoint)
- : base(version, providerEndpoint, GetProtocolConstant(version, p => p.Args.Mode.associate), MessageTransport.Direct) {
- }
-
- /// <summary>
- /// Gets or sets the preferred association type. The association type defines the algorithm to be used to sign subsequent messages.
- /// </summary>
- /// <value>Value: A valid association type from Section 8.3.</value>
- [MessagePart("openid.assoc_type", IsRequired = true, AllowEmpty = false)]
- internal string AssociationType { get; set; }
-
- /// <summary>
- /// Gets or sets the preferred association session type. This defines the method used to encrypt the association's MAC key in transit.
- /// </summary>
- /// <value>Value: A valid association session type from Section 8.4 (Association Session Types). </value>
- /// <remarks>Note: Unless using transport layer encryption, "no-encryption" MUST NOT be used. </remarks>
- [MessagePart("openid.session_type", IsRequired = false, AllowEmpty = true)]
- [MessagePart("openid.session_type", IsRequired = true, AllowEmpty = false, MinVersion = "2.0")]
- internal string SessionType { get; set; }
-
- /// <summary>
- /// Checks the message state for conformity to the protocol specification
- /// and throws an exception if the message is invalid.
- /// </summary>
- /// <remarks>
- /// <para>Some messages have required fields, or combinations of fields that must relate to each other
- /// in specialized ways. After deserializing a message, this method checks the state of the
- /// message to see if it conforms to the protocol.</para>
- /// <para>Note that this property should <i>not</i> check signatures or perform any state checks
- /// outside this scope of this particular message.</para>
- /// </remarks>
- /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception>
- public override void EnsureValidMessage() {
- base.EnsureValidMessage();
-
- ErrorUtilities.VerifyProtocol(
- !string.Equals(this.SessionType, Protocol.Args.SessionType.NoEncryption, StringComparison.Ordinal) || this.Recipient.IsTransportSecure(),
- OpenIdStrings.NoEncryptionSessionRequiresHttps,
- this);
- }
-
- /// <summary>
- /// Creates an association request message that is appropriate for a given Provider.
- /// </summary>
- /// <param name="securityRequirements">The set of requirements the selected association type must comply to.</param>
- /// <param name="provider">The provider to create an association with.</param>
- /// <returns>
- /// The message to send to the Provider to request an association.
- /// Null if no association could be created that meet the security requirements
- /// and the provider OpenID version.
- /// </returns>
- internal static AssociateRequest Create(SecuritySettings securityRequirements, IProviderEndpoint provider) {
- Contract.Requires<ArgumentNullException>(securityRequirements != null);
- Contract.Requires<ArgumentNullException>(provider != null);
-
- // Apply our knowledge of the endpoint's transport, OpenID version, and
- // security requirements to decide the best association.
- bool unencryptedAllowed = provider.Uri.IsTransportSecure();
- bool useDiffieHellman = !unencryptedAllowed;
- string associationType, sessionType;
- if (!HmacShaAssociation.TryFindBestAssociation(Protocol.Lookup(provider.Version), true, securityRequirements, useDiffieHellman, out associationType, out sessionType)) {
- // There are no associations that meet all requirements.
- Logger.OpenId.Warn("Security requirements and protocol combination knock out all possible association types. Dumb mode forced.");
- return null;
- }
-
- return Create(securityRequirements, provider, associationType, sessionType);
- }
-
- /// <summary>
- /// Creates an association request message that is appropriate for a given Provider.
- /// </summary>
- /// <param name="securityRequirements">The set of requirements the selected association type must comply to.</param>
- /// <param name="provider">The provider to create an association with.</param>
- /// <param name="associationType">Type of the association.</param>
- /// <param name="sessionType">Type of the session.</param>
- /// <returns>
- /// The message to send to the Provider to request an association.
- /// Null if no association could be created that meet the security requirements
- /// and the provider OpenID version.
- /// </returns>
- internal static AssociateRequest Create(SecuritySettings securityRequirements, IProviderEndpoint provider, string associationType, string sessionType) {
- Contract.Requires<ArgumentNullException>(securityRequirements != null);
- Contract.Requires<ArgumentNullException>(provider != null);
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(associationType));
- Contract.Requires<ArgumentNullException>(sessionType != null);
-
- bool unencryptedAllowed = provider.Uri.IsTransportSecure();
- if (unencryptedAllowed) {
- var associateRequest = new AssociateUnencryptedRequest(provider.Version, provider.Uri);
- associateRequest.AssociationType = associationType;
- return associateRequest;
- } else {
- var associateRequest = new AssociateDiffieHellmanRequest(provider.Version, provider.Uri);
- associateRequest.AssociationType = associationType;
- associateRequest.SessionType = sessionType;
- associateRequest.InitializeRequest();
- return associateRequest;
- }
- }
-
- /// <summary>
- /// Creates a Provider's response to an incoming association request.
- /// </summary>
- /// <param name="associationStore">The association store where a new association (if created) will be stored. Must not be null.</param>
- /// <param name="securitySettings">The security settings on the Provider.</param>
- /// <returns>
- /// The appropriate association response that is ready to be sent back to the Relying Party.
- /// </returns>
- /// <remarks>
- /// <para>If an association is created, it will be automatically be added to the provided
- /// association store.</para>
- /// <para>Successful association response messages will derive from <see cref="AssociateSuccessfulResponse"/>.
- /// Failed association response messages will derive from <see cref="AssociateUnsuccessfulResponse"/>.</para>
- /// </remarks>
- internal IProtocolMessage CreateResponse(IAssociationStore<AssociationRelyingPartyType> associationStore, ProviderSecuritySettings securitySettings) {
- Contract.Requires<ArgumentNullException>(associationStore != null);
- Contract.Requires<ArgumentNullException>(securitySettings != null);
-
- IProtocolMessage response;
- if (securitySettings.IsAssociationInPermittedRange(Protocol, this.AssociationType) &&
- HmacShaAssociation.IsDHSessionCompatible(Protocol, this.AssociationType, this.SessionType)) {
- response = this.CreateResponseCore();
-
- // Create and store the association if this is a successful response.
- var successResponse = response as AssociateSuccessfulResponse;
- if (successResponse != null) {
- Association association = successResponse.CreateAssociation(this, securitySettings);
- associationStore.StoreAssociation(AssociationRelyingPartyType.Smart, association);
- }
- } else {
- response = this.CreateUnsuccessfulResponse(securitySettings);
- }
-
- return response;
- }
-
- /// <summary>
- /// Creates a Provider's response to an incoming association request.
- /// </summary>
- /// <returns>
- /// The appropriate association response message.
- /// </returns>
- /// <remarks>
- /// <para>If an association can be successfully created, the
- /// <see cref="AssociateSuccessfulResponse.CreateAssociation"/> method must not be
- /// called by this method.</para>
- /// <para>Successful association response messages will derive from <see cref="AssociateSuccessfulResponse"/>.
- /// Failed association response messages will derive from <see cref="AssociateUnsuccessfulResponse"/>.</para>
- /// </remarks>
- protected abstract IProtocolMessage CreateResponseCore();
-
- /// <summary>
- /// Creates a response that notifies the Relying Party that the requested
- /// association type is not supported by this Provider, and offers
- /// an alternative association type, if possible.
- /// </summary>
- /// <param name="securitySettings">The security settings that apply to this Provider.</param>
- /// <returns>The response to send to the Relying Party.</returns>
- private AssociateUnsuccessfulResponse CreateUnsuccessfulResponse(ProviderSecuritySettings securitySettings) {
- Contract.Requires<ArgumentNullException>(securitySettings != null);
-
- var unsuccessfulResponse = new AssociateUnsuccessfulResponse(this.Version, this);
-
- // The strategy here is to suggest that the RP try again with the lowest
- // permissible security settings, giving the RP the best chance of being
- // able to match with a compatible request.
- bool unencryptedAllowed = this.Recipient.IsTransportSecure();
- bool useDiffieHellman = !unencryptedAllowed;
- string associationType, sessionType;
- if (HmacShaAssociation.TryFindBestAssociation(Protocol, false, securitySettings, useDiffieHellman, out associationType, out sessionType)) {
- ErrorUtilities.VerifyInternal(this.AssociationType != associationType, "The RP asked for an association that should have been allowed, but the OP is trying to suggest the same one as an alternative!");
- unsuccessfulResponse.AssociationType = associationType;
- unsuccessfulResponse.SessionType = sessionType;
- Logger.OpenId.InfoFormat(
- "Association requested of type '{0}' and session '{1}', which the Provider does not support. Sending back suggested alternative of '{0}' with session '{1}'.",
- this.AssociationType,
- this.SessionType,
- unsuccessfulResponse.AssociationType,
- unsuccessfulResponse.SessionType);
- } else {
- Logger.OpenId.InfoFormat("Association requested of type '{0}' and session '{1}', which the Provider does not support. No alternative association type qualified for suggesting back to the Relying Party.", this.AssociationType, this.SessionType);
- }
-
- return unsuccessfulResponse;
- }
- }
-}
diff --git a/src/DotNetOpenAuth/OpenId/Messages/AssociateSuccessfulResponseContract.cs b/src/DotNetOpenAuth/OpenId/Messages/AssociateSuccessfulResponseContract.cs
deleted file mode 100644
index dd37da6..0000000
--- a/src/DotNetOpenAuth/OpenId/Messages/AssociateSuccessfulResponseContract.cs
+++ /dev/null
@@ -1,29 +0,0 @@
-// <auto-generated />
-
-namespace DotNetOpenAuth.OpenId.Messages {
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Linq;
- using System.Text;
- using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.OpenId.Provider;
-
- [ContractClassFor(typeof(AssociateSuccessfulResponse))]
- internal abstract class AssociateSuccessfulResponseContract : AssociateSuccessfulResponse {
- protected AssociateSuccessfulResponseContract() : base(null, null) {
- }
-
- protected override Association CreateAssociationAtProvider(AssociateRequest request, ProviderSecuritySettings securitySettings) {
- Contract.Requires<ArgumentNullException>(request != null);
- Contract.Requires<ArgumentNullException>(securitySettings != null);
- throw new NotImplementedException();
- }
-
- protected override Association CreateAssociationAtRelyingParty(AssociateRequest request) {
- Contract.Requires<ArgumentNullException>(request != null);
- throw new NotImplementedException();
- }
- }
-}
diff --git a/src/DotNetOpenAuth/OpenId/Messages/AssociateUnencryptedResponse.cs b/src/DotNetOpenAuth/OpenId/Messages/AssociateUnencryptedResponse.cs
deleted file mode 100644
index 493fe6b..0000000
--- a/src/DotNetOpenAuth/OpenId/Messages/AssociateUnencryptedResponse.cs
+++ /dev/null
@@ -1,67 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="AssociateUnencryptedResponse.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.OpenId.Messages {
- using System;
- using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.Messaging.Reflection;
- using DotNetOpenAuth.OpenId.Provider;
-
- /// <summary>
- /// The successful unencrypted association response message.
- /// </summary>
- /// <remarks>
- /// Association response messages are described in OpenID 2.0 section 8.2. This type covers section 8.2.2.
- /// </remarks>
- internal class AssociateUnencryptedResponse : AssociateSuccessfulResponse {
- /// <summary>
- /// Initializes a new instance of the <see cref="AssociateUnencryptedResponse"/> class.
- /// </summary>
- /// <param name="responseVersion">The OpenID version of the response message.</param>
- /// <param name="originatingRequest">The originating request.</param>
- internal AssociateUnencryptedResponse(Version responseVersion, AssociateUnencryptedRequest originatingRequest)
- : base(responseVersion, originatingRequest) {
- SessionType = Protocol.Args.SessionType.NoEncryption;
- }
-
- /// <summary>
- /// Gets or sets the MAC key (shared secret) for this association, Base 64 (Josefsson, S., “The Base16, Base32, and Base64 Data Encodings,” .) [RFC3548] encoded.
- /// </summary>
- [MessagePart("mac_key", IsRequired = true, AllowEmpty = false)]
- internal byte[] MacKey { get; set; }
-
- /// <summary>
- /// Called to create the Association based on a request previously given by the Relying Party.
- /// </summary>
- /// <param name="request">The prior request for an association.</param>
- /// <param name="securitySettings">The security settings of the Provider.</param>
- /// <returns>The created association.</returns>
- /// <remarks>
- /// <para>The caller will update this message's
- /// <see cref="AssociateSuccessfulResponse.ExpiresIn"/> and
- /// <see cref="AssociateSuccessfulResponse.AssociationHandle"/>
- /// properties based on the <see cref="Association"/> returned by this method, but any other
- /// association type specific properties must be set by this method.</para>
- /// <para>The response message is updated to include the details of the created association by this method,
- /// but the resulting association is <i>not</i> added to the association store and must be done by the caller.</para>
- /// </remarks>
- protected override Association CreateAssociationAtProvider(AssociateRequest request, ProviderSecuritySettings securitySettings) {
- Association association = HmacShaAssociation.Create(Protocol, this.AssociationType, AssociationRelyingPartyType.Smart, securitySettings);
- this.MacKey = association.SecretKey;
- return association;
- }
-
- /// <summary>
- /// Called to create the Association based on a request previously given by the Relying Party.
- /// </summary>
- /// <param name="request">The prior request for an association.</param>
- /// <returns>The created association.</returns>
- protected override Association CreateAssociationAtRelyingParty(AssociateRequest request) {
- Association association = HmacShaAssociation.Create(Protocol, this.AssociationType, this.AssociationHandle, this.MacKey, TimeSpan.FromSeconds(this.ExpiresIn));
- return association;
- }
- }
-}
diff --git a/src/DotNetOpenAuth/OpenId/Provider/IProviderApplicationStore.cs b/src/DotNetOpenAuth/OpenId/Provider/IProviderApplicationStore.cs
deleted file mode 100644
index c16f1f9..0000000
--- a/src/DotNetOpenAuth/OpenId/Provider/IProviderApplicationStore.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="IProviderApplicationStore.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.OpenId.Provider {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using DotNetOpenAuth.Messaging.Bindings;
-
- /// <summary>
- /// A hybrid of all the store interfaces that a Provider requires in order
- /// to operate in "smart" mode.
- /// </summary>
- public interface IProviderApplicationStore : IAssociationStore<AssociationRelyingPartyType>, INonceStore {
- }
-}
diff --git a/src/DotNetOpenAuth/OpenId/Provider/StandardProviderApplicationStore.cs b/src/DotNetOpenAuth/OpenId/Provider/StandardProviderApplicationStore.cs
deleted file mode 100644
index 4fa2d64..0000000
--- a/src/DotNetOpenAuth/OpenId/Provider/StandardProviderApplicationStore.cs
+++ /dev/null
@@ -1,131 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="StandardProviderApplicationStore.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.OpenId.Provider {
- using System;
- using DotNetOpenAuth.Configuration;
- using DotNetOpenAuth.Messaging.Bindings;
-
- /// <summary>
- /// An in-memory store for Providers, suitable for single server, single process
- /// ASP.NET web sites.
- /// </summary>
- /// <remarks>
- /// This class provides only a basic implementation that is likely to work
- /// out of the box on most single-server web sites. It is highly recommended
- /// that high traffic web sites consider using a database to store the information
- /// used by an OpenID Provider and write a custom implementation of the
- /// <see cref="IProviderApplicationStore"/> interface to use instead of this
- /// class.
- /// </remarks>
- public class StandardProviderApplicationStore : IProviderApplicationStore {
- /// <summary>
- /// The nonce store to use.
- /// </summary>
- private readonly INonceStore nonceStore;
-
- /// <summary>
- /// The association store to use.
- /// </summary>
- private readonly IAssociationStore<AssociationRelyingPartyType> associationStore;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="StandardProviderApplicationStore"/> class.
- /// </summary>
- public StandardProviderApplicationStore() {
- this.nonceStore = new NonceMemoryStore(DotNetOpenAuthSection.Configuration.OpenId.MaxAuthenticationTime);
- this.associationStore = new AssociationMemoryStore<AssociationRelyingPartyType>();
- }
-
- #region IAssociationStore<AssociationRelyingPartyType> Members
-
- /// <summary>
- /// Saves an <see cref="Association"/> for later recall.
- /// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for providers).</param>
- /// <param name="association">The association to store.</param>
- public void StoreAssociation(AssociationRelyingPartyType distinguishingFactor, Association association) {
- this.associationStore.StoreAssociation(distinguishingFactor, association);
- }
-
- /// <summary>
- /// Gets the best association (the one with the longest remaining life) for a given key.
- /// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- /// <param name="securityRequirements">The security requirements that the returned association must meet.</param>
- /// <returns>
- /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key.
- /// </returns>
- /// <remarks>
- /// In the event that multiple associations exist for the given
- /// <paramref name="distinguishingFactor"/>, it is important for the
- /// implementation for this method to use the <paramref name="securityRequirements"/>
- /// to pick the best (highest grade or longest living as the host's policy may dictate)
- /// association that fits the security requirements.
- /// Associations that are returned that do not meet the security requirements will be
- /// ignored and a new association created.
- /// </remarks>
- public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor, SecuritySettings securityRequirements) {
- return this.associationStore.GetAssociation(distinguishingFactor, securityRequirements);
- }
-
- /// <summary>
- /// Gets the association for a given key and handle.
- /// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- /// <param name="handle">The handle of the specific association that must be recalled.</param>
- /// <returns>
- /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key and handle.
- /// </returns>
- public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor, string handle) {
- return this.associationStore.GetAssociation(distinguishingFactor, handle);
- }
-
- /// <summary>
- /// Removes a specified handle that may exist in the store.
- /// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- /// <param name="handle">The handle of the specific association that must be deleted.</param>
- /// <returns>
- /// True if the association existed in this store previous to this call.
- /// </returns>
- /// <remarks>
- /// No exception should be thrown if the association does not exist in the store
- /// before this call.
- /// </remarks>
- public bool RemoveAssociation(AssociationRelyingPartyType distinguishingFactor, string handle) {
- return this.associationStore.RemoveAssociation(distinguishingFactor, handle);
- }
-
- #endregion
-
- #region INonceStore Members
-
- /// <summary>
- /// Stores a given nonce and timestamp.
- /// </summary>
- /// <param name="context">The context, or namespace, within which the <paramref name="nonce"/> must be unique.</param>
- /// <param name="nonce">A series of random characters.</param>
- /// <param name="timestampUtc">The timestamp that together with the nonce string make it unique.
- /// The timestamp may also be used by the data store to clear out old nonces.</param>
- /// <returns>
- /// True if the nonce+timestamp (combination) was not previously in the database.
- /// False if the nonce was stored previously with the same timestamp.
- /// </returns>
- /// <remarks>
- /// The nonce must be stored for no less than the maximum time window a message may
- /// be processed within before being discarded as an expired message.
- /// If the binding element is applicable to your channel, this expiration window
- /// is retrieved or set using the
- /// <see cref="StandardExpirationBindingElement.MaximumMessageAge"/> property.
- /// </remarks>
- public bool StoreNonce(string context, string nonce, DateTime timestampUtc) {
- return this.nonceStore.StoreNonce(context, nonce, timestampUtc);
- }
-
- #endregion
- }
-}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/IRelyingPartyApplicationStore.cs b/src/DotNetOpenAuth/OpenId/RelyingParty/IRelyingPartyApplicationStore.cs
deleted file mode 100644
index 77838c8..0000000
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/IRelyingPartyApplicationStore.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="IRelyingPartyApplicationStore.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.OpenId.RelyingParty {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using DotNetOpenAuth.Messaging.Bindings;
- using DotNetOpenAuth.OpenId.ChannelElements;
-
- /// <summary>
- /// A hybrid of all the store interfaces that a Relying Party requires in order
- /// to operate in "smart" mode.
- /// </summary>
- public interface IRelyingPartyApplicationStore : IAssociationStore<Uri>, INonceStore {
- }
-}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/PrivateSecretManager.cs b/src/DotNetOpenAuth/OpenId/RelyingParty/PrivateSecretManager.cs
deleted file mode 100644
index 6d55e39..0000000
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/PrivateSecretManager.cs
+++ /dev/null
@@ -1,122 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="PrivateSecretManager.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.OpenId.RelyingParty {
- using System;
- using System.Diagnostics.Contracts;
- using DotNetOpenAuth.Configuration;
- using DotNetOpenAuth.Messaging;
-
- /// <summary>
- /// Manages signing at the RP using private secrets.
- /// </summary>
- internal class PrivateSecretManager {
- /// <summary>
- /// The optimal length for a private secret used for signing using the HMACSHA256 class.
- /// </summary>
- /// <remarks>
- /// The 64-byte length is optimized for highest security when used with HMACSHA256.
- /// See HMACSHA256.HMACSHA256(byte[]) documentation for more information.
- /// </remarks>
- private const int OptimalPrivateSecretLength = 64;
-
- /// <summary>
- /// The URI to use for private associations at this RP.
- /// </summary>
- private static readonly Uri SecretUri = new Uri("https://localhost/dnoa/secret");
-
- /// <summary>
- /// The security settings that apply to this Relying Party.
- /// </summary>
- private RelyingPartySecuritySettings securitySettings;
-
- /// <summary>
- /// The association store
- /// </summary>
- private IAssociationStore<Uri> store;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="PrivateSecretManager"/> class.
- /// </summary>
- /// <param name="securitySettings">The security settings.</param>
- /// <param name="store">The association store.</param>
- internal PrivateSecretManager(RelyingPartySecuritySettings securitySettings, IAssociationStore<Uri> store) {
- Contract.Requires<ArgumentNullException>(securitySettings != null);
- Contract.Requires<ArgumentNullException>(store != null);
-
- this.securitySettings = securitySettings;
- this.store = store;
- }
-
- /// <summary>
- /// Gets the handle of the association to use for private signatures.
- /// </summary>
- /// <returns>
- /// An string made up of plain ASCII characters.
- /// </returns>
- internal string CurrentHandle {
- get {
- Association association = this.GetAssociation();
- return association.Handle;
- }
- }
-
- /// <summary>
- /// Used to verify a signature previously written.
- /// </summary>
- /// <param name="buffer">The data whose signature is to be verified.</param>
- /// <param name="handle">The handle to the private association used to sign the data.</param>
- /// <returns>
- /// The signature for the given buffer using the provided handle.
- /// </returns>
- /// <exception cref="ProtocolException">Thrown when an association with the given handle could not be found.
- /// This most likely happens if the association was near the end of its life and the user took too long to log in.</exception>
- internal byte[] Sign(byte[] buffer, string handle) {
- Contract.Requires<ArgumentNullException>(buffer != null);
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(handle));
-
- Association association = this.store.GetAssociation(SecretUri, handle);
- ErrorUtilities.VerifyProtocol(association != null, OpenIdStrings.PrivateRPSecretNotFound, handle);
- return association.Sign(buffer);
- }
-
- /// <summary>
- /// Creates the new association handle.
- /// </summary>
- /// <returns>The ASCII-encoded handle name.</returns>
- private static string CreateNewAssociationHandle() {
- string uniq = MessagingUtilities.GetCryptoRandomDataAsBase64(4);
- string handle = "{" + DateTime.UtcNow.Ticks + "}{" + uniq + "}";
- return handle;
- }
-
- /// <summary>
- /// Gets an association to use for signing new data.
- /// </summary>
- /// <returns>
- /// The association, which may have previously existed or
- /// may have been created as a result of this call.
- /// </returns>
- private Association GetAssociation() {
- Association privateAssociation = this.store.GetAssociation(SecretUri, this.securitySettings);
- if (privateAssociation == null || !privateAssociation.HasUsefulLifeRemaining) {
- int secretLength = HmacShaAssociation.GetSecretLength(Protocol.Default, Protocol.Default.Args.SignatureAlgorithm.Best);
- byte[] secret = MessagingUtilities.GetCryptoRandomData(secretLength);
- privateAssociation = HmacShaAssociation.Create(CreateNewAssociationHandle(), secret, this.securitySettings.PrivateSecretMaximumAge);
- if (!privateAssociation.HasUsefulLifeRemaining) {
- Logger.OpenId.WarnFormat(
- "Brand new private association has a shorter lifespan ({0}) than the maximum allowed authentication time for a user ({1}). This may lead to login failures.",
- this.securitySettings.PrivateSecretMaximumAge,
- DotNetOpenAuthSection.Configuration.OpenId.MaxAuthenticationTime);
- }
-
- this.store.StoreAssociation(SecretUri, privateAssociation);
- }
-
- return privateAssociation;
- }
- }
-}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/StandardRelyingPartyApplicationStore.cs b/src/DotNetOpenAuth/OpenId/RelyingParty/StandardRelyingPartyApplicationStore.cs
deleted file mode 100644
index fdb6931..0000000
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/StandardRelyingPartyApplicationStore.cs
+++ /dev/null
@@ -1,115 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="StandardRelyingPartyApplicationStore.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.OpenId.RelyingParty {
- using System;
- using DotNetOpenAuth.Configuration;
- using DotNetOpenAuth.Messaging.Bindings;
- using DotNetOpenAuth.OpenId.ChannelElements;
-
- /// <summary>
- /// An in-memory store for Relying Parties, suitable for single server, single process
- /// ASP.NET web sites.
- /// </summary>
- public class StandardRelyingPartyApplicationStore : IRelyingPartyApplicationStore {
- /// <summary>
- /// The nonce store to use.
- /// </summary>
- private readonly INonceStore nonceStore;
-
- /// <summary>
- /// The association store to use.
- /// </summary>
- private readonly IAssociationStore<Uri> associationStore;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="StandardRelyingPartyApplicationStore"/> class.
- /// </summary>
- public StandardRelyingPartyApplicationStore() {
- this.nonceStore = new NonceMemoryStore(DotNetOpenAuthSection.Configuration.OpenId.MaxAuthenticationTime);
- this.associationStore = new AssociationMemoryStore<Uri>();
- }
-
- #region IAssociationStore<Uri> Members
-
- /// <summary>
- /// Saves an <see cref="Association"/> for later recall.
- /// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for providers).</param>
- /// <param name="association">The association to store.</param>
- public void StoreAssociation(Uri distinguishingFactor, Association association) {
- this.associationStore.StoreAssociation(distinguishingFactor, association);
- }
-
- /// <summary>
- /// Gets the best association (the one with the longest remaining life) for a given key.
- /// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- /// <param name="securityRequirements">The security settings.</param>
- /// <returns>
- /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key.
- /// </returns>
- public Association GetAssociation(Uri distinguishingFactor, SecuritySettings securityRequirements) {
- return this.associationStore.GetAssociation(distinguishingFactor, securityRequirements);
- }
-
- /// <summary>
- /// Gets the association for a given key and handle.
- /// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- /// <param name="handle">The handle of the specific association that must be recalled.</param>
- /// <returns>
- /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key and handle.
- /// </returns>
- public Association GetAssociation(Uri distinguishingFactor, string handle) {
- return this.associationStore.GetAssociation(distinguishingFactor, handle);
- }
-
- /// <summary>
- /// Removes a specified handle that may exist in the store.
- /// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- /// <param name="handle">The handle of the specific association that must be deleted.</param>
- /// <returns>
- /// True if the association existed in this store previous to this call.
- /// </returns>
- /// <remarks>
- /// No exception should be thrown if the association does not exist in the store
- /// before this call.
- /// </remarks>
- public bool RemoveAssociation(Uri distinguishingFactor, string handle) {
- return this.associationStore.RemoveAssociation(distinguishingFactor, handle);
- }
-
- #endregion
-
- #region INonceStore Members
-
- /// <summary>
- /// Stores a given nonce and timestamp.
- /// </summary>
- /// <param name="context">The context, or namespace, within which the <paramref name="nonce"/> must be unique.</param>
- /// <param name="nonce">A series of random characters.</param>
- /// <param name="timestampUtc">The timestamp that together with the nonce string make it unique.
- /// The timestamp may also be used by the data store to clear out old nonces.</param>
- /// <returns>
- /// True if the nonce+timestamp (combination) was not previously in the database.
- /// False if the nonce was stored previously with the same timestamp.
- /// </returns>
- /// <remarks>
- /// The nonce must be stored for no less than the maximum time window a message may
- /// be processed within before being discarded as an expired message.
- /// If the binding element is applicable to your channel, this expiration window
- /// is retrieved or set using the
- /// <see cref="StandardExpirationBindingElement.MaximumMessageAge"/> property.
- /// </remarks>
- public bool StoreNonce(string context, string nonce, DateTime timestampUtc) {
- return this.nonceStore.StoreNonce(context, nonce, timestampUtc);
- }
-
- #endregion
- }
-}
diff --git a/src/DotNetOpenAuth/OpenId/DiffieHellman/mono/BigInteger.cs b/src/Mono.Math/BigInteger.cs
index 33df8df..33df8df 100644
--- a/src/DotNetOpenAuth/OpenId/DiffieHellman/mono/BigInteger.cs
+++ b/src/Mono.Math/BigInteger.cs
diff --git a/src/DotNetOpenAuth/OpenId/DiffieHellman/mono/ConfidenceFactor.cs b/src/Mono.Math/ConfidenceFactor.cs
index fd0747d..fd0747d 100644
--- a/src/DotNetOpenAuth/OpenId/DiffieHellman/mono/ConfidenceFactor.cs
+++ b/src/Mono.Math/ConfidenceFactor.cs
diff --git a/src/Mono.Math/Mono.Math.csproj b/src/Mono.Math/Mono.Math.csproj
new file mode 100644
index 0000000..c0d66b6
--- /dev/null
+++ b/src/Mono.Math/Mono.Math.csproj
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))\EnlistmentInfo.props" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))' != '' " />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" />
+ <PropertyGroup>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{F4CD3C04-6037-4946-B7A5-34BFC96A75D2}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>Mono.Math</RootNamespace>
+ <AssemblyName>Mono.Math</AssemblyName>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" />
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="BigInteger.cs">
+ <SubType>Code</SubType>
+ </Compile>
+ <Compile Include="ConfidenceFactor.cs">
+ <SubType>Code</SubType>
+ </Compile>
+ <Compile Include="NextPrimeFinder.cs">
+ <SubType>Code</SubType>
+ </Compile>
+ <Compile Include="PrimalityTests.cs">
+ <SubType>Code</SubType>
+ </Compile>
+ <Compile Include="PrimeGeneratorBase.cs">
+ <SubType>Code</SubType>
+ </Compile>
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ <Compile Include="SequentialSearchPrimeGeneratorBase.cs">
+ <SubType>Code</SubType>
+ </Compile>
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
+</Project> \ No newline at end of file
diff --git a/src/DotNetOpenAuth/OpenId/DiffieHellman/mono/NextPrimeFinder.cs b/src/Mono.Math/NextPrimeFinder.cs
index 19433f2..19433f2 100644
--- a/src/DotNetOpenAuth/OpenId/DiffieHellman/mono/NextPrimeFinder.cs
+++ b/src/Mono.Math/NextPrimeFinder.cs
diff --git a/src/DotNetOpenAuth/OpenId/DiffieHellman/mono/PrimalityTests.cs b/src/Mono.Math/PrimalityTests.cs
index b2ddc74..b2ddc74 100644
--- a/src/DotNetOpenAuth/OpenId/DiffieHellman/mono/PrimalityTests.cs
+++ b/src/Mono.Math/PrimalityTests.cs
diff --git a/src/DotNetOpenAuth/OpenId/DiffieHellman/mono/PrimeGeneratorBase.cs b/src/Mono.Math/PrimeGeneratorBase.cs
index 12b6a69..12b6a69 100644
--- a/src/DotNetOpenAuth/OpenId/DiffieHellman/mono/PrimeGeneratorBase.cs
+++ b/src/Mono.Math/PrimeGeneratorBase.cs
diff --git a/src/Mono.Math/Properties/AssemblyInfo.cs b/src/Mono.Math/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..cea21c0
--- /dev/null
+++ b/src/Mono.Math/Properties/AssemblyInfo.cs
@@ -0,0 +1,52 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssemblyInfo.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+// We DON'T put an AssemblyVersionAttribute in here because it is generated in the build.
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Net;
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Security.Permissions;
+using System.Web.UI;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("Mono Math")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DotNetOpenAuth")]
+[assembly: AssemblyCopyright("Copyright © 2008")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+[assembly: NeutralResourcesLanguage("en-US")]
+[assembly: CLSCompliant(true)]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("7d73990c-47c0-4256-9f20-a893add9e289")]
+
+[assembly: ContractVerification(true)]
+
+#if StrongNameSigned
+// See comment at top of this file. We need this so that strong-naming doesn't
+// keep this assembly from being useful to shared host (medium trust) web sites.
+[assembly: AllowPartiallyTrustedCallers]
+
+[assembly: InternalsVisibleTo("Org.Mentalis.Security.Cryptography, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+#else
+[assembly: InternalsVisibleTo("Org.Mentalis.Security.Cryptography")]
+#endif
diff --git a/src/DotNetOpenAuth/OpenId/DiffieHellman/mono/SequentialSearchPrimeGeneratorBase.cs b/src/Mono.Math/SequentialSearchPrimeGeneratorBase.cs
index a017ee4..a017ee4 100644
--- a/src/DotNetOpenAuth/OpenId/DiffieHellman/mono/SequentialSearchPrimeGeneratorBase.cs
+++ b/src/Mono.Math/SequentialSearchPrimeGeneratorBase.cs
diff --git a/src/DotNetOpenAuth/OpenId/DiffieHellman/DHKeyGeneration.cs b/src/Org.Mentalis.Security.Cryptography/DHKeyGeneration.cs
index c48151b..6eca6a0 100644
--- a/src/DotNetOpenAuth/OpenId/DiffieHellman/DHKeyGeneration.cs
+++ b/src/Org.Mentalis.Security.Cryptography/DHKeyGeneration.cs
@@ -8,6 +8,14 @@
//
// (C) 2003 The Mentalis.org Team (http://www.mentalis.org/)
//
+// Source Code License
+// Copyright 2002-2007, The Mentalis.org Team
+// All rights reserved.
+// http://www.mentalis.org/
+// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+// - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+// - Neither the name of the Mentalis.org Team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace Org.Mentalis.Security.Cryptography {
diff --git a/src/Org.Mentalis.Security.Cryptography/DHParameters.cs b/src/Org.Mentalis.Security.Cryptography/DHParameters.cs
new file mode 100644
index 0000000..8105125
--- /dev/null
+++ b/src/Org.Mentalis.Security.Cryptography/DHParameters.cs
@@ -0,0 +1,38 @@
+// <auto-generated />
+
+//
+// DHParameters.cs: Defines a structure that holds the parameters of the Diffie-Hellman algorithm
+//
+// Author:
+// Pieter Philippaerts (Pieter@mentalis.org)
+//
+// (C) 2003 The Mentalis.org Team (http://www.mentalis.org/)
+//
+// Source Code License
+// Copyright 2002-2007, The Mentalis.org Team
+// All rights reserved.
+// http://www.mentalis.org/
+// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+// - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+// - Neither the name of the Mentalis.org Team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+namespace Org.Mentalis.Security.Cryptography {
+ /// <summary>
+ /// Represents the parameters of the Diffie-Hellman algorithm.
+ /// </summary>
+ internal struct DHParameters {
+ /// <summary>
+ /// Represents the public <b>P</b> parameter of the Diffie-Hellman algorithm.
+ /// </summary>
+ public byte[] P;
+ /// <summary>
+ /// Represents the public <b>G</b> parameter of the Diffie-Hellman algorithm.
+ /// </summary>
+ public byte[] G;
+ /// <summary>
+ /// Represents the private <b>X</b> parameter of the Diffie-Hellman algorithm.
+ /// </summary>
+ public byte[] X;
+ }
+} \ No newline at end of file
diff --git a/src/DotNetOpenAuth/OpenId/DiffieHellman/DiffieHellman.cs b/src/Org.Mentalis.Security.Cryptography/DiffieHellman.cs
index 6438135..5019f70 100644
--- a/src/DotNetOpenAuth/OpenId/DiffieHellman/DiffieHellman.cs
+++ b/src/Org.Mentalis.Security.Cryptography/DiffieHellman.cs
@@ -8,6 +8,15 @@
//
// (C) 2003 The Mentalis.org Team (http://www.mentalis.org/)
//
+//
+// Source Code License
+// Copyright 2002-2007, The Mentalis.org Team
+// All rights reserved.
+// http://www.mentalis.org/
+// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+// - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+// - Neither the name of the Mentalis.org Team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Security.Cryptography;
diff --git a/src/DotNetOpenAuth/OpenId/DiffieHellman/DiffieHellmanManaged.cs b/src/Org.Mentalis.Security.Cryptography/DiffieHellmanManaged.cs
index 75787c3..6ac28df 100644
--- a/src/DotNetOpenAuth/OpenId/DiffieHellman/DiffieHellmanManaged.cs
+++ b/src/Org.Mentalis.Security.Cryptography/DiffieHellmanManaged.cs
@@ -11,6 +11,15 @@
// References:
// - PKCS#3 [http://www.rsasecurity.com/rsalabs/pkcs/pkcs-3/]
//
+//
+// Source Code License
+// Copyright 2002-2007, The Mentalis.org Team
+// All rights reserved.
+// http://www.mentalis.org/
+// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+// - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+// - Neither the name of the Mentalis.org Team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Security.Cryptography;
diff --git a/src/Org.Mentalis.Security.Cryptography/Org.Mentalis.Security.Cryptography.csproj b/src/Org.Mentalis.Security.Cryptography/Org.Mentalis.Security.Cryptography.csproj
new file mode 100644
index 0000000..c2b1055
--- /dev/null
+++ b/src/Org.Mentalis.Security.Cryptography/Org.Mentalis.Security.Cryptography.csproj
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))\EnlistmentInfo.props" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.props))' != '' " />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" />
+ <PropertyGroup>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{26DC877F-5987-48DD-9DDB-E62F2DE0E150}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>Org.Mentalis.Security.Cryptography</RootNamespace>
+ <AssemblyName>Org.Mentalis.Security.Cryptography</AssemblyName>
+ </PropertyGroup>
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" />
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="DHKeyGeneration.cs" />
+ <Compile Include="DHParameters.cs" />
+ <Compile Include="DiffieHellman.cs" />
+ <Compile Include="DiffieHellmanManaged.cs" />
+ <Compile Include="Properties\AssemblyInfo.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\Mono.Math\Mono.Math.csproj">
+ <Project>{F4CD3C04-6037-4946-B7A5-34BFC96A75D2}</Project>
+ <Name>Mono.Math</Name>
+ </ProjectReference>
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
+</Project> \ No newline at end of file
diff --git a/src/Org.Mentalis.Security.Cryptography/Properties/AssemblyInfo.cs b/src/Org.Mentalis.Security.Cryptography/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..45a2fda
--- /dev/null
+++ b/src/Org.Mentalis.Security.Cryptography/Properties/AssemblyInfo.cs
@@ -0,0 +1,60 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssemblyInfo.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+// We DON'T put an AssemblyVersionAttribute in here because it is generated in the build.
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Net;
+using System.Reflection;
+using System.Resources;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Security.Permissions;
+using System.Web.UI;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("Org.Mentalis.Security.Cryptography")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DotNetOpenAuth")]
+[assembly: AssemblyCopyright("Copyright © 2008")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+[assembly: NeutralResourcesLanguage("en-US")]
+[assembly: CLSCompliant(true)]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("7d73990c-47c0-4256-9f20-a893add9e289")]
+
+[assembly: ContractVerification(true)]
+
+#if StrongNameSigned
+// See comment at top of this file. We need this so that strong-naming doesn't
+// keep this assembly from being useful to shared host (medium trust) web sites.
+[assembly: AllowPartiallyTrustedCallers]
+
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.RelyingParty, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
+#else
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.Provider")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.OpenId.RelyingParty")]
+[assembly: InternalsVisibleTo("DotNetOpenAuth.Test")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
+#endif
diff --git a/src/version.txt b/src/version.txt
index 7921bd0..fcdb2e1 100644
--- a/src/version.txt
+++ b/src/version.txt
@@ -1 +1 @@
-3.4.8
+4.0.0