summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Settings.StyleCop1
-rw-r--r--doc/README.Bin.html3
-rw-r--r--doc/specs/draft-ietf-oauth.html3072
-rw-r--r--projecttemplates/MvcRelyingParty/Controllers/AccountController.cs69
-rw-r--r--projecttemplates/MvcRelyingParty/Models/AccountAuthorizeModel.cs6
-rw-r--r--projecttemplates/MvcRelyingParty/Models/AccountInfoModel.cs4
-rw-r--r--projecttemplates/MvcRelyingParty/MvcRelyingParty.csproj10
-rw-r--r--projecttemplates/MvcRelyingParty/OAuth.ashx1
-rw-r--r--projecttemplates/MvcRelyingParty/OAuth.ashx.cs66
-rw-r--r--projecttemplates/MvcRelyingParty/OAuthTokenEndpoint.ashx1
-rw-r--r--projecttemplates/MvcRelyingParty/OAuthTokenEndpoint.ashx.cs51
-rw-r--r--projecttemplates/MvcRelyingParty/Views/Account/Authorize.aspx18
-rw-r--r--projecttemplates/MvcRelyingParty/Views/Account/AuthorizeApproved.aspx24
-rw-r--r--projecttemplates/MvcRelyingParty/Views/Account/AuthorizeDenied.aspx13
-rw-r--r--projecttemplates/MvcRelyingParty/Views/Account/AuthorizedApps.ascx2
-rw-r--r--projecttemplates/RelyingPartyDatabase/Properties/Database.sqlcmdvars2
-rw-r--r--projecttemplates/RelyingPartyDatabase/RelyingPartyDatabase.dbproj39
-rw-r--r--projecttemplates/RelyingPartyDatabase/Schema Comparisons/SchemaComparison1.scmp328
-rw-r--r--projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Client.table.sql12
-rw-r--r--projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/ClientAuthorization.table.sql9
-rw-r--r--projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Constraints/DF_IssuedToken_CreatedOn.defconst.sql4
-rw-r--r--projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Constraints/DF_IssuedToken_CreatedOn_1.defconst.sql3
-rw-r--r--projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Constraints/DF_IssuedToken_IsAccessToken.defconst.sql4
-rw-r--r--projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Consumer.table.sql4
-rw-r--r--projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Indexes/IX_Consumer.index.sql4
-rw-r--r--projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Indexes/IX_Consumer_1.index.sql4
-rw-r--r--projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Indexes/IX_IssuedToken.index.sql4
-rw-r--r--projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/IssuedToken.table.sql4
-rw-r--r--projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/FK_IssuedToken_Consumer.fkey.sql4
-rw-r--r--projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/FK_IssuedToken_Consumer_1.fkey.sql3
-rw-r--r--projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/FK_IssuedToken_User.fkey.sql4
-rw-r--r--projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/FK_IssuedToken_User_1.fkey.sql3
-rw-r--r--projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/PK_Consumer.pkey.sql4
-rw-r--r--projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/PK_Consumer_1.pkey.sql3
-rw-r--r--projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/PK_IssuedToken.pkey.sql4
-rw-r--r--projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/PK_IssuedToken_1.pkey.sql3
-rw-r--r--projecttemplates/RelyingPartyLogic/Model.Client.cs29
-rw-r--r--projecttemplates/RelyingPartyLogic/Model.ClientAuthorization.cs (renamed from projecttemplates/RelyingPartyLogic/Model.IssuedToken.cs)6
-rw-r--r--projecttemplates/RelyingPartyLogic/Model.Consumer.cs40
-rw-r--r--projecttemplates/RelyingPartyLogic/Model.Designer.cs1061
-rw-r--r--projecttemplates/RelyingPartyLogic/Model.IssuedAccessToken.cs74
-rw-r--r--projecttemplates/RelyingPartyLogic/Model.IssuedRequestToken.cs63
-rw-r--r--projecttemplates/RelyingPartyLogic/Model.edmx292
-rw-r--r--projecttemplates/RelyingPartyLogic/OAuthAuthenticationModule.cs17
-rw-r--r--projecttemplates/RelyingPartyLogic/OAuthAuthorizationManager.cs21
-rw-r--r--projecttemplates/RelyingPartyLogic/OAuthAuthorizationServer.cs173
-rw-r--r--projecttemplates/RelyingPartyLogic/OAuthConsumerTokenManager.cs48
-rw-r--r--projecttemplates/RelyingPartyLogic/OAuthPrincipalAuthorizationPolicy.cs5
-rw-r--r--projecttemplates/RelyingPartyLogic/OAuthServiceProvider.cs99
-rw-r--r--projecttemplates/RelyingPartyLogic/OAuthServiceProviderTokenManager.cs112
-rw-r--r--projecttemplates/RelyingPartyLogic/OAuthTokenManager.cs141
-rw-r--r--projecttemplates/RelyingPartyLogic/RelyingPartyLogic.csproj23
-rw-r--r--projecttemplates/RelyingPartyLogic/SpecialAccessTokenAnalyzer.cs36
-rw-r--r--projecttemplates/WebFormsRelyingParty/Members/AccountInfo.aspx8
-rw-r--r--projecttemplates/WebFormsRelyingParty/Members/AccountInfo.aspx.cs20
-rw-r--r--projecttemplates/WebFormsRelyingParty/Members/AccountInfo.aspx.designer.cs3
-rw-r--r--projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx114
-rw-r--r--projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx.cs66
-rw-r--r--projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx.designer.cs119
-rw-r--r--projecttemplates/WebFormsRelyingParty/Members/Web.config2
-rw-r--r--projecttemplates/WebFormsRelyingParty/OAuth.ashx1
-rw-r--r--projecttemplates/WebFormsRelyingParty/OAuth.ashx.cs66
-rw-r--r--projecttemplates/WebFormsRelyingParty/OAuthTokenEndpoint.ashx1
-rw-r--r--projecttemplates/WebFormsRelyingParty/OAuthTokenEndpoint.ashx.cs51
-rw-r--r--projecttemplates/WebFormsRelyingParty/WebFormsRelyingParty.csproj6
-rw-r--r--samples/DotNetOpenAuth.ApplicationBlock/DotNetOpenAuth.ApplicationBlock.csproj6
-rw-r--r--samples/DotNetOpenAuth.ApplicationBlock/Facebook/FacebookClient.cs29
-rw-r--r--samples/DotNetOpenAuth.ApplicationBlock/Facebook/FacebookGraph.cs54
-rw-r--r--samples/DotNetOpenAuth.ApplicationBlock/InMemoryClientAuthorizationTracker.cs51
-rw-r--r--samples/DotNetOpenAuth.ApplicationBlock/TokenManager.cs18
-rw-r--r--samples/OAuthConsumer/Default.aspx1
-rw-r--r--samples/OAuthConsumer/Facebook.aspx16
-rw-r--r--samples/OAuthConsumer/Facebook.aspx.cs32
-rw-r--r--samples/OAuthConsumer/Facebook.aspx.designer.cs33
-rw-r--r--samples/OAuthConsumer/OAuthConsumer.csproj16
-rw-r--r--samples/OAuthConsumer/SampleWcf.aspx2
-rw-r--r--samples/OAuthConsumer/SampleWcf.aspx.cs8
-rw-r--r--samples/OAuthConsumer/SampleWcf2.aspx23
-rw-r--r--samples/OAuthConsumer/SampleWcf2.aspx.cs119
-rw-r--r--samples/OAuthConsumer/SampleWcf2.aspx.designer.cs96
-rw-r--r--samples/OAuthConsumer/Web.config8
-rw-r--r--samples/OAuthConsumerWpf/Authorize2.xaml11
-rw-r--r--samples/OAuthConsumerWpf/Authorize2.xaml.cs76
-rw-r--r--samples/OAuthConsumerWpf/MainWindow.xaml322
-rw-r--r--samples/OAuthConsumerWpf/MainWindow.xaml.cs67
-rw-r--r--samples/OAuthConsumerWpf/OAuthConsumerWpf.csproj18
-rw-r--r--samples/OAuthServiceProvider/Code/DatabaseNonceStore.cs3
-rw-r--r--samples/OAuthServiceProvider/Code/Global.cs10
-rw-r--r--samples/OAuthServiceProvider/Code/OAuth2AuthorizationServer.cs59
-rw-r--r--samples/OAuthServiceProvider/Code/OAuthAuthorizationManager.cs66
-rw-r--r--samples/OAuthServiceProvider/Code/OAuthConsumer.cs14
-rw-r--r--samples/OAuthServiceProvider/Login.aspx8
-rw-r--r--samples/OAuthServiceProvider/Members/Authorize.aspx2
-rw-r--r--samples/OAuthServiceProvider/Members/Authorize2.aspx53
-rw-r--r--samples/OAuthServiceProvider/Members/Authorize2.aspx.cs55
-rw-r--r--samples/OAuthServiceProvider/Members/Authorize2.aspx.designer.cs123
-rw-r--r--samples/OAuthServiceProvider/OAuth.ashx2
-rw-r--r--samples/OAuthServiceProvider/OAuth2.ashx1
-rw-r--r--samples/OAuthServiceProvider/OAuth2.ashx.cs48
-rw-r--r--samples/OAuthServiceProvider/OAuthServiceProvider.csproj13
-rw-r--r--samples/OAuthServiceProvider/Web.config5
-rw-r--r--src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj6
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/MessageSerializerTests.cs31
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs12
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/Reflection/MessageDescriptionTests.cs10
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/StandardMessageFactoryTests.cs178
-rw-r--r--src/DotNetOpenAuth.Test/Mocks/TestDirectResponseMessageWithHttpStatus.cs12
-rw-r--r--src/DotNetOpenAuth.Test/OAuth2/MessageFactoryTests.cs139
-rw-r--r--src/DotNetOpenAuth.Test/OAuth2/OAuth2ChannelTests.cs21
-rw-r--r--src/DotNetOpenAuth.Test/OAuth2/OAuth2TestBase.cs15
-rw-r--r--src/DotNetOpenAuth.sln1
-rw-r--r--src/DotNetOpenAuth/Configuration/DotNetOpenAuth.xsd8
-rw-r--r--src/DotNetOpenAuth/Configuration/MessagingElement.cs15
-rw-r--r--src/DotNetOpenAuth/DotNetOpenAuth.csproj117
-rw-r--r--src/DotNetOpenAuth/Messaging/Bindings/ExpiredMessageException.cs1
-rw-r--r--src/DotNetOpenAuth/Messaging/Channel.cs111
-rw-r--r--src/DotNetOpenAuth/Messaging/IDirectWebRequestHandler.cs.orig222
-rw-r--r--src/DotNetOpenAuth/Messaging/IHttpDirectResponse.cs10
-rw-r--r--src/DotNetOpenAuth/Messaging/IHttpDirectResponseContract.cs43
-rw-r--r--src/DotNetOpenAuth/Messaging/IHttpIndirectResponse.cs22
-rw-r--r--src/DotNetOpenAuth/Messaging/MessageSerializer.cs111
-rw-r--r--src/DotNetOpenAuth/Messaging/MessagingStrings.Designer.cs27
-rw-r--r--src/DotNetOpenAuth/Messaging/MessagingStrings.resx9
-rw-r--r--src/DotNetOpenAuth/Messaging/MessagingUtilities.cs463
-rw-r--r--src/DotNetOpenAuth/Messaging/Reflection/MessageDescription.cs233
-rw-r--r--src/DotNetOpenAuth/Messaging/Reflection/MessageDescriptionCollection.cs32
-rw-r--r--src/DotNetOpenAuth/Messaging/Reflection/MessagePart.cs30
-rw-r--r--src/DotNetOpenAuth/Messaging/StandardMessageFactory.cs298
-rw-r--r--src/DotNetOpenAuth/Messaging/StandardMessageFactoryChannel.cs111
-rw-r--r--src/DotNetOpenAuth/Messaging/StandardWebRequestHandler.cs9
-rw-r--r--src/DotNetOpenAuth/Messaging/TimespanSecondsEncoder.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/TimespanSecondsEncoder.cs)9
-rw-r--r--src/DotNetOpenAuth/OAuth/ChannelElements/OAuthChannel.cs43
-rw-r--r--src/DotNetOpenAuth/OAuth/ChannelElements/OAuthPrincipal.cs18
-rw-r--r--src/DotNetOpenAuth/OAuth/Protocol.cs2
-rw-r--r--src/DotNetOpenAuth/OAuth2/AuthorizationServer.cs154
-rw-r--r--src/DotNetOpenAuth/OAuth2/AuthorizationServerBase.cs83
-rw-r--r--src/DotNetOpenAuth/OAuth2/AuthorizationServerDescription.cs62
-rw-r--r--src/DotNetOpenAuth/OAuth2/AuthorizationState.cs92
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/AccessRequestBindingElement.cs144
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/AccessToken.cs80
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/AuthServerAllFlowsBindingElement.cs83
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/AuthServerBindingElementBase.cs92
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationCode.cs92
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationCodeBindingElement.cs100
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationDataBag.cs55
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/DataBag.cs71
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/EndUserAuthorizationResponseTypeEncoder.cs67
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/GrantTypeEncoder.cs75
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/IAuthorizationDescription.cs90
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/IDataBagFormatter.cs54
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/ITokenCarryingRequest.cs54
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2AuthorizationServerChannel.cs107
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ChannelBase.cs48
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ClientChannel.cs91
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ResourceServerChannel.cs152
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/RefreshToken.cs47
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/ScopeEncoder.cs51
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/TimestampEncoder.cs61
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/UriStyleMessageFormatter.cs306
-rw-r--r--src/DotNetOpenAuth/OAuth2/ClientBase.cs226
-rw-r--r--src/DotNetOpenAuth/OAuth2/IAccessTokenAnalyzer.cs61
-rw-r--r--src/DotNetOpenAuth/OAuth2/IAuthorizationServer.cs169
-rw-r--r--src/DotNetOpenAuth/OAuth2/IAuthorizationState.cs67
-rw-r--r--src/DotNetOpenAuth/OAuth2/IClientAuthorizationTracker.cs53
-rw-r--r--src/DotNetOpenAuth/OAuth2/IConsumerDescription.cs25
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessProtectedResourceRequest.cs119
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessTokenAssertionRequest.cs37
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessTokenAuthorizationCodeRequest.cs77
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessTokenClientCredentialsRequest.cs54
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessTokenFailedResponse.cs86
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessTokenRefreshRequest.cs71
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessTokenRequestBase.cs60
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessTokenResourceOwnerPasswordCredentialsRequest.cs42
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessTokenSuccessResponse.cs83
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AuthenticatedClientRequestBase.cs42
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationFailedResponse.cs70
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationRequest.cs93
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationResponseType.cs31
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessAccessTokenResponse.cs64
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessAuthCodeResponse.cs67
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessResponseBase.cs76
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/GrantType.cs42
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/IMessageWithClientState.cs21
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/MessageBase.cs210
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/UnauthorizedResponse.cs115
-rw-r--r--src/DotNetOpenAuth/OAuth2/OAuthStrings.Designer.cs135
-rw-r--r--src/DotNetOpenAuth/OAuth2/OAuthStrings.resx144
-rw-r--r--src/DotNetOpenAuth/OAuth2/OAuthUtilities.cs117
-rw-r--r--src/DotNetOpenAuth/OAuth2/Protocol.cs330
-rw-r--r--src/DotNetOpenAuth/OAuth2/ResourceServer.cs144
-rw-r--r--src/DotNetOpenAuth/OAuth2/StandardAccessTokenAnalyzer.cs62
-rw-r--r--src/DotNetOpenAuth/OAuth2/UserAgentClient.cs107
-rw-r--r--src/DotNetOpenAuth/OAuth2/WebServerClient.cs126
-rw-r--r--src/DotNetOpenAuth/OpenId/Behaviors/GsaIcamProfile.cs8
-rw-r--r--src/DotNetOpenAuth/OpenId/Extensions/SimpleRegistration/Gender.cs2
-rw-r--r--src/DotNetOpenAuth/OpenId/Messages/DirectErrorResponse.cs8
-rw-r--r--src/version.txt2
197 files changed, 13642 insertions, 2239 deletions
diff --git a/Settings.StyleCop b/Settings.StyleCop
index 7ba99fa..a408101 100644
--- a/Settings.StyleCop
+++ b/Settings.StyleCop
@@ -56,6 +56,7 @@
<AnalyzerSettings>
<CollectionProperty Name="Hungarian">
<Value>ax</Value>
+ <Value>iv</Value>
<Value>op</Value>
<Value>rp</Value>
<Value>sp</Value>
diff --git a/doc/README.Bin.html b/doc/README.Bin.html
index de05333..b475d95 100644
--- a/doc/README.Bin.html
+++ b/doc/README.Bin.html
@@ -71,11 +71,10 @@
</th>
<td>Provides Intellisense for the web.config or app.config files of projects using this library.&nbsp;
To activate Intellisense, modify your <span class="style1">
- %PROGRAMFILES%\Microsoft Visual Studio 9.0\Xml\Schemas\catalog.xml</span> file
+ %PROGRAMFILES%\Microsoft Visual Studio 10.0\Xml\Schemas\catalog.xml</span> file
to include this entry:<br />
<span class="style1">&lt;Association extension=&quot;config&quot; schema=&quot;</span><span
class="style2">permanent-directory</span><span class="style1">\DotNetOpenAuth.xsd&quot;
- condition=&quot;%TargetFrameworkVersion% != 2.0 and %TargetFrameworkVersion% != 3.0&quot;
/&gt; </span>&nbsp;</td>
</tr>
</table>
diff --git a/doc/specs/draft-ietf-oauth.html b/doc/specs/draft-ietf-oauth.html
new file mode 100644
index 0000000..6cc7582
--- /dev/null
+++ b/doc/specs/draft-ietf-oauth.html
@@ -0,0 +1,3072 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+<!-- saved from url=(0052)http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html -->
+<HTML lang="en"><HEAD><META http-equiv="Content-Type" content="text/html; charset=UTF-8"><TITLE>The OAuth 2.0 Protocol</TITLE>
+
+<META name="description" content="The OAuth 2.0 Protocol">
+<META name="generator" content="xml2rfc v1.35 (http://xml.resource.org/)">
+<META name="viewport" content="width=600;">
+<STYLE type="text/css"><!--
+ body {
+ font-family: verdana, charcoal, helvetica, arial, sans-serif;
+ font-size: 85%;
+ max-width: 80ex;
+ color: #000; background-color: #FFF;
+ margin: 2em;
+ }
+ h1, h2, h3, h4, h5, h6 {
+ font-family: helvetica, monaco, "MS Sans Serif", arial, sans-serif;
+ font-weight: bold; font-style: normal;
+ }
+ h1 { color: #900; background-color: transparent; text-align: right; }
+ h3 { color: #333; background-color: transparent; }
+
+ td.RFCbug {
+ font-size: x-small; text-decoration: none;
+ width: 30px; height: 30px; padding-top: 2px;
+ text-align: justify; vertical-align: middle;
+ background-color: #000;
+ }
+ td.RFCbug span.RFC {
+ font-family: monaco, charcoal, geneva, "MS Sans Serif", helvetica, verdana, sans-serif;
+ font-weight: bold; color: #666;
+ }
+ td.RFCbug span.hotText {
+ font-family: charcoal, monaco, geneva, "MS Sans Serif", helvetica, verdana, sans-serif;
+ font-weight: normal; text-align: center; color: #FFF;
+ }
+
+ table.TOCbug { width: 30px; height: 15px; }
+ td.TOCbug {
+ text-align: center; width: 30px; height: 15px;
+ color: #FFF; background-color: #900;
+ }
+ td.TOCbug a {
+ font-family: monaco, charcoal, geneva, "MS Sans Serif", helvetica, sans-serif;
+ font-weight: bold; font-size: x-small; text-decoration: none;
+ color: #FFF; background-color: transparent;
+ }
+
+ td.header {
+ font-family: arial, helvetica, sans-serif; font-size: x-small;
+ vertical-align: top; width: 33%;
+ color: #FFF; background-color: #666;
+ }
+ td.author { font-weight: bold; font-size: x-small; margin-left: 4em; }
+ td.author-text { font-size: x-small; }
+
+ /* info code from SantaKlauss at http://www.madaboutstyle.com/tooltip2.html */
+ a.info {
+ /* This is the key. */
+ position: relative;
+ z-index: 24;
+ text-decoration: none;
+ }
+ a.info:hover {
+ z-index: 25;
+ color: #FFF; background-color: #900;
+ }
+ a.info span { display: none; }
+ a.info:hover span.info {
+ /* The span will display just on :hover state. */
+ display: block;
+ position: absolute;
+ font-size: smaller;
+ top: 2em; left: -5em; width: 15em;
+ padding: 2px; border: 1px solid #333;
+ color: #900; background-color: #EEE;
+ text-align: left;
+ }
+
+ a { font-weight: bold; }
+ a:link { color: #900; background-color: transparent; }
+ a:visited { color: #633; background-color: transparent; }
+ a:active { color: #633; background-color: transparent; }
+
+ p { margin-left: 2em; margin-right: 2em; }
+ p.copyright { font-size: x-small; }
+ p.toc { font-size: 85%;
+ max-width: 80ex;
+ font-weight: bold; margin-left: 3em; }
+ table.toc { margin: 0 0 0 3em; padding: 0; border: 0; vertical-align: text-top; }
+ td.toc { font-size: 85%;
+ max-width: 80ex;
+ font-weight: bold; vertical-align: text-top; }
+
+ ol.text { margin-left: 2em; margin-right: 2em; }
+ ul.text { margin-left: 2em; margin-right: 2em; }
+ li { margin-left: 3em; }
+
+ /* RFC-2629 <spanx>s and <artwork>s. */
+ em { font-style: italic; }
+ strong { font-weight: bold; }
+ dfn { font-weight: bold; font-style: normal; }
+ cite { font-weight: normal; font-style: normal; }
+ tt { color: #036; }
+ tt, pre, pre dfn, pre em, pre cite, pre span {
+ font-family: "Courier New", Courier, monospace; font-size: small;
+ }
+ pre {
+ text-align: left; padding: 4px;
+ color: #000; background-color: #CCC;
+ }
+ pre dfn { color: #900; }
+ pre em { color: #66F; background-color: #FFC; font-weight: normal; }
+ pre .key { color: #33C; font-weight: bold; }
+ pre .id { color: #900; }
+ pre .str { color: #000; background-color: #CFF; }
+ pre .val { color: #066; }
+ pre .rep { color: #909; }
+ pre .oth { color: #000; background-color: #FCF; }
+ pre .err { background-color: #FCC; }
+
+ /* RFC-2629 <texttable>s. */
+ table.all, table.full, table.headers, table.none {
+ font-size: 85%;
+ max-width: 80ex;
+ text-align: center; border-width: 2px;
+ vertical-align: top; border-collapse: collapse;
+ }
+ table.all, table.full { border-style: solid; border-color: black; }
+ table.headers, table.none { border-style: none; }
+ th {
+ font-weight: bold; border-color: black;
+ border-width: 2px 2px 3px 2px;
+ }
+ table.all th, table.full th { border-style: solid; }
+ table.headers th { border-style: none none solid none; }
+ table.none th { border-style: none; }
+ table.all td {
+ border-style: solid; border-color: #333;
+ border-width: 1px 2px;
+ }
+ table.full td, table.headers td, table.none td { border-style: none; }
+
+ hr { height: 1px; }
+ hr.insert {
+ width: 80%; border-style: none; border-width: 0;
+ color: #CCC; background-color: #CCC;
+ }
+--></STYLE>
+</HEAD><BODY>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<TABLE summary="layout" width="66%" border="0" cellpadding="0" cellspacing="0"><TBODY><TR><TD><TABLE summary="layout" width="100%" border="0" cellpadding="2" cellspacing="1">
+<TBODY><TR><TD class="header">Network Working Group</TD><TD class="header">E. Hammer-Lahav, Ed.</TD></TR>
+<TR><TD class="header">Internet-Draft</TD><TD class="header">Yahoo!</TD></TR>
+<TR><TD class="header">Obsoletes: <A href="http://tools.ietf.org/html/rfc5849">5849</A> (if&nbsp;approved)</TD><TD class="header">D. Recordon</TD></TR>
+<TR><TD class="header">Intended status: Standards Track</TD><TD class="header">Facebook</TD></TR>
+<TR><TD class="header">Expires: January 12, 2011</TD><TD class="header">D. Hardt</TD></TR>
+<TR><TD class="header">&nbsp;</TD><TD class="header">Microsoft</TD></TR>
+<TR><TD class="header">&nbsp;</TD><TD class="header">July 11, 2010</TD></TR>
+</TBODY></TABLE></TD></TR></TBODY></TABLE>
+<H1><BR>The OAuth 2.0 Protocol<BR>draft-ietf-oauth-v2-10</H1>
+
+<H3>Abstract</H3>
+
+<P>
+ This specification describes the OAuth 2.0 protocol.
+
+</P>
+<H3>Status of this Memo</H3>
+<P>
+This Internet-Draft is submitted in full
+conformance with the provisions of BCP&nbsp;78 and BCP&nbsp;79.</P>
+<P>
+Internet-Drafts are working documents of the Internet Engineering
+Task Force (IETF). Note that other groups may also distribute
+working documents as Internet-Drafts. The list of current
+Internet-Drafts is at http://datatracker.ietf.org/drafts/current/.</P>
+<P>
+Internet-Drafts are draft documents valid for a maximum of six months
+and may be updated, replaced, or obsoleted by other documents at any time.
+It is inappropriate to use Internet-Drafts as reference material or to cite
+them other than as “work in progress.”</P>
+<P>
+This Internet-Draft will expire on January 12, 2011.</P>
+
+<H3>Copyright Notice</H3>
+<P>
+Copyright (c) 2010 IETF Trust and the persons identified as the
+document authors. All rights reserved.</P>
+<P>
+This document is subject to BCP 78 and the IETF Trust's Legal
+Provisions Relating to IETF Documents
+(http://trustee.ietf.org/license-info) in effect on the date of
+publication of this document. Please review these documents
+carefully, as they describe your rights and restrictions with respect
+to this document. Code Components extracted from this document must
+include Simplified BSD License text as described in Section 4.e of
+the Trust Legal Provisions and are provided without warranty as
+described in the Simplified BSD License.</P>
+<A name="toc"></A><BR><HR>
+<H3>Table of Contents</H3>
+<P class="toc">
+<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor1">1.</A>&nbsp;
+Introduction<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor2">1.1.</A>&nbsp;
+Notational Conventions<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor3">1.2.</A>&nbsp;
+Terminology<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor4">1.3.</A>&nbsp;
+Overview<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor5">1.4.</A>&nbsp;
+Client Profiles<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor6">1.4.1.</A>&nbsp;
+Web Server<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#user-agent">1.4.2.</A>&nbsp;
+User-Agent<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor7">1.4.3.</A>&nbsp;
+Native Application<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor8">1.4.4.</A>&nbsp;
+Autonomous<BR>
+<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#client-authentication">2.</A>&nbsp;
+Client Credentials<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor9">2.1.</A>&nbsp;
+Client Password Credentials<BR>
+<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#user-authorization">3.</A>&nbsp;
+Obtaining End-User Authorization<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor10">3.1.</A>&nbsp;
+Authorization Response<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#auth-error">3.2.</A>&nbsp;
+Error Response<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#auth-error-codes">3.2.1.</A>&nbsp;
+Error Codes<BR>
+<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#obtaining-token">4.</A>&nbsp;
+Obtaining an Access Token<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#access-grant-types">4.1.</A>&nbsp;
+Access Grant Types<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor11">4.1.1.</A>&nbsp;
+Authorization Code<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor12">4.1.2.</A>&nbsp;
+Resource Owner Password Credentials<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor13">4.1.3.</A>&nbsp;
+Assertion<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#token-refresh">4.1.4.</A>&nbsp;
+Refresh Token<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#access-token-response">4.2.</A>&nbsp;
+Access Token Response<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#token-error">4.3.</A>&nbsp;
+Error Response<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#token-error-codes">4.3.1.</A>&nbsp;
+Error Codes<BR>
+<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#access-resource">5.</A>&nbsp;
+Accessing a Protected Resource<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor14">5.1.</A>&nbsp;
+Authenticated Requests<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#authz-header">5.1.1.</A>&nbsp;
+The Authorization Request Header Field<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#query-param">5.1.2.</A>&nbsp;
+URI Query Parameter<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#body-param">5.1.3.</A>&nbsp;
+Form-Encoded Body Parameter<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#authn-header">5.2.</A>&nbsp;
+The WWW-Authenticate Response Header Field<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#resource-error-codes">5.2.1.</A>&nbsp;
+Error Codes<BR>
+<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor15">6.</A>&nbsp;
+Extensibility<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor16">6.1.</A>&nbsp;
+Defining New Client Credentials Types<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor17">6.2.</A>&nbsp;
+Defining New Endpoint Parameters<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor18">6.3.</A>&nbsp;
+Defining New Header Field Parameters<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor19">6.4.</A>&nbsp;
+Defining New Access Grant Types<BR>
+<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor20">7.</A>&nbsp;
+Security Considerations<BR>
+<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor21">8.</A>&nbsp;
+IANA Considerations<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#parameters-registry">8.1.</A>&nbsp;
+The OAuth Parameters Registry<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor22">8.1.1.</A>&nbsp;
+Registration Template<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor23">8.1.2.</A>&nbsp;
+Example<BR>
+<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor24">Appendix&nbsp;A.</A>&nbsp;
+Examples<BR>
+<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor25">Appendix&nbsp;B.</A>&nbsp;
+Contributors<BR>
+<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor26">Appendix&nbsp;C.</A>&nbsp;
+Acknowledgements<BR>
+<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#anchor27">Appendix&nbsp;D.</A>&nbsp;
+Document History<BR>
+<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#rfc.references1">9.</A>&nbsp;
+References<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#rfc.references1">9.1.</A>&nbsp;
+Normative References<BR>
+&nbsp;&nbsp;&nbsp;&nbsp;<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#rfc.references2">9.2.</A>&nbsp;
+Informative References<BR>
+<A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#rfc.authors">§</A>&nbsp;
+Authors' Addresses<BR>
+</P>
+<BR clear="all">
+
+<A name="anchor1"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.1"></A><H3>1.&nbsp;
+Introduction</H3>
+
+<P>
+ With the increasing use of distributed web services and cloud computing, third-party
+ applications require access to server-hosted resources. These resources are usually
+ protected and require authentication using the resource owner's credentials (typically a
+ username and password).
+
+</P>
+<P>
+ In the traditional client-server authentication model, the client accesses a protected
+ resource on the server by authenticating with the server using the resource owner's
+ credentials. In order to provide third-party applications access to protected resources,
+ the resource owner shares its credentials with the third-party. This creates several
+ problems and limitations:
+
+ </P>
+<UL class="text">
+<LI>
+ Third-party applications are required to store the resource-owner's credentials
+ for future use, typically a password in clear-text.
+
+</LI>
+<LI>
+ Servers are required to support password (symmetric) authentication, despite the
+ security weaknesses created by passwords.
+
+</LI>
+<LI>
+ Third-party applications gain overly broad access to the resource-owner's protected
+ resources, leaving resource owners without any ability to restrict access to a limited
+ subset of resources, to limit access duration, or to limit access to the methods
+ supported by these resources.
+
+</LI>
+<LI>
+ Resource owners cannot revoke access to an individual third-party without revoking
+ access to all third-parties, and must do so by changing their password.
+
+</LI>
+</UL><P>
+
+</P>
+<P>
+ OAuth address these issues by separating the role of the client from that of the
+ resource owner. In OAuth, the client (which is usually not the resource owner, but is
+ acting on the resource owner's behalf) requests access to resources controlled by the
+ resource owner and hosted by the resource server, and is issued a different set of
+ credentials than those of the resource owner.
+
+</P>
+<P>
+ Instead of using the resource owner's credentials to access protected resources, clients
+ obtain an access token (a string which denotes a specific scope, duration, and other
+ attributes). The format and structure of access tokens is beyond the scope of this
+ specification.
+
+</P>
+<P>
+ Tokens are issued to third-party clients by an authorization server with the approval of
+ the resource owner. The client uses the access token to access the protected resources
+ hosted by the resource server. The interaction between the authorization server and
+ resource server is beyond the scope of this specification.
+
+</P>
+<P>
+ For example, a web user (resource owner) can grant a printing service (client) access to
+ her protected photos stored at a photo sharing service (resource server), without sharing
+ her username and password with the printing service. Instead, she authenticates directly
+ with an authentication service trusted by the photo sharing service (authorization server)
+ which issues the printing service delegation-specific credentials (token).
+
+</P>
+<P>
+ This specification defines the use of OAuth over <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#RFC2616">HTTP<SPAN> (</SPAN><SPAN class="info">Fielding, R., Gettys, J., Mogul, J., Frystyk, H., Masinter, L., Leach, P., and T. Berners-Lee, “Hypertext Transfer Protocol -- HTTP/1.1,” June&nbsp;1999.</SPAN><SPAN>)</SPAN></A> [RFC2616]
+ (or HTTP over TLS as defined by <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#RFC2818">[RFC2818]<SPAN> (</SPAN><SPAN class="info">Rescorla, E., “HTTP Over TLS,” May&nbsp;2000.</SPAN><SPAN>)</SPAN></A>). Other specifications may
+ extend it for use with other transport protocols.
+
+</P>
+<A name="anchor2"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.1.1"></A><H3>1.1.&nbsp;
+Notational Conventions</H3>
+
+<P>
+ The key words 'MUST', 'MUST NOT', 'REQUIRED', 'SHALL', 'SHALL NOT', 'SHOULD', 'SHOULD
+ NOT', 'RECOMMENDED', 'MAY', and 'OPTIONAL' in this document are to be interpreted as
+ described in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#RFC2119">[RFC2119]<SPAN> (</SPAN><SPAN class="info">Bradner, S., “Key words for use in RFCs to Indicate Requirement Levels,” March&nbsp;1997.</SPAN><SPAN>)</SPAN></A>.
+
+</P>
+<P>
+ This document uses the Augmented Backus-Naur Form (ABNF) notation of
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#I-D.ietf-httpbis-p1-messaging">[I‑D.ietf‑httpbis‑p1‑messaging]<SPAN> (</SPAN><SPAN class="info">Fielding, R., Gettys, J., Mogul, J., Nielsen, H., Masinter, L., Leach, P., Berners-Lee, T., and J. Reschke, “HTTP/1.1, part 1: URIs, Connections, and Message Parsing,” March&nbsp;2010.</SPAN><SPAN>)</SPAN></A>. Additionally, the following rules are
+ included from <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#RFC2617">[RFC2617]<SPAN> (</SPAN><SPAN class="info">Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P., Luotonen, A., and L. Stewart, “HTTP Authentication: Basic and Digest Access Authentication,” June&nbsp;1999.</SPAN><SPAN>)</SPAN></A>: realm, auth-param; from
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#RFC3986">[RFC3986]<SPAN> (</SPAN><SPAN class="info">Berners-Lee, T., Fielding, R., and L. Masinter, “Uniform Resource Identifier (URI): Generic Syntax,” January&nbsp;2005.</SPAN><SPAN>)</SPAN></A>: URI-Reference; and from
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#I-D.ietf-httpbis-p1-messaging">[I‑D.ietf‑httpbis‑p1‑messaging]<SPAN> (</SPAN><SPAN class="info">Fielding, R., Gettys, J., Mogul, J., Nielsen, H., Masinter, L., Leach, P., Berners-Lee, T., and J. Reschke, “HTTP/1.1, part 1: URIs, Connections, and Message Parsing,” March&nbsp;2010.</SPAN><SPAN>)</SPAN></A>: OWS, RWS, and quoted-string.
+
+</P>
+<P>
+ Unless otherwise noted, all the protocol parameter names and values are case sensitive.
+
+</P>
+<A name="anchor3"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.1.2"></A><H3>1.2.&nbsp;
+Terminology</H3>
+
+<P>
+ </P>
+<BLOCKQUOTE class="text"><DL>
+<DT>protected resource</DT>
+<DD>
+
+ An access-restricted resource which can be obtained using an OAuth-authenticated
+ request.
+
+</DD>
+<DT>resource server</DT>
+<DD>
+
+ A server capable of accepting and responding to protected resource requests.
+
+</DD>
+<DT>client</DT>
+<DD>
+
+ An application obtaining authorization and making protected resource requests.
+
+</DD>
+<DT>resource owner</DT>
+<DD>
+
+ An entity capable of granting access to a protected resource.
+
+</DD>
+<DT>end-user</DT>
+<DD>
+
+ A human resource owner.
+
+</DD>
+<DT>token</DT>
+<DD>
+
+ A string representing an access authorization issued to the client. The string is
+ usually opaque to the client. Tokens represent specific scopes and durations of
+ access, granted by the resource owner, and enforced by the resource server and
+ authorization servers. The token may denote an identifier used to retrieve the
+ authorization information, or self-contain the authorization information in a
+ verifiable manner (i.e. a token string consisting of some data and a signature).
+ Tokens may be pure capabilities. Specific additional authentication credentials may
+ be required in order for a client to use a token.
+
+</DD>
+<DT>access token</DT>
+<DD>
+
+ A token used by the client to make authenticated requests on behalf of the resource
+ owner.
+
+</DD>
+<DT>refresh token</DT>
+<DD>
+
+ A token used by the client to obtain a new access token without having to involve
+ the resource owner.
+
+</DD>
+<DT>authorization code</DT>
+<DD>
+ A short-lived token representing the access grant provided by the end-user. The
+ authorization code is used to obtain an access token and a refresh token.
+
+</DD>
+<DT>authorization server</DT>
+<DD>
+
+ A server capable of issuing tokens after successfully authenticating the resource
+ owner and obtaining authorization. The authorization server may be the same server as
+ the resource server, or a separate entity.
+
+</DD>
+<DT>end-user authorization endpoint</DT>
+<DD>
+
+ The authorization server's HTTP endpoint capable of authenticating the end-user and
+ obtaining authorization. The end-user authorization endpoint is described in
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#user-authorization">Section&nbsp;3<SPAN> (</SPAN><SPAN class="info">Obtaining End-User Authorization</SPAN><SPAN>)</SPAN></A>.
+
+</DD>
+<DT>token endpoint</DT>
+<DD>
+
+ The authorization server's HTTP endpoint capable of issuing tokens and refreshing
+ expired tokens. The token endpoint is described in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#obtaining-token">Section&nbsp;4<SPAN> (</SPAN><SPAN class="info">Obtaining an Access Token</SPAN><SPAN>)</SPAN></A>.
+
+</DD>
+<DT>client identifier</DT>
+<DD>
+
+ A unique identifier issued to the client to identify itself to the authorization
+ server. Client identifiers may have a matching secret. The client identifier is
+ described in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#client-authentication">Section&nbsp;2<SPAN> (</SPAN><SPAN class="info">Client Credentials</SPAN><SPAN>)</SPAN></A>.
+
+</DD>
+</DL></BLOCKQUOTE><P>
+
+</P>
+<A name="anchor4"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.1.3"></A><H3>1.3.&nbsp;
+Overview</H3>
+
+<P>
+ OAuth provides a method for clients to access a protected resource on behalf of a
+ resource owner. Before a client can access a protected resource, it must first obtain
+ authorization from the resource owner, then exchange the access grant for an access token
+ (representing the grant's scope, duration, and other attributes). The client accesses the
+ protected resource by presenting the access token to the resource server.
+
+</P><BR><HR class="insert">
+<A name="Figure 1"></A>
+<DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ +--------+ +---------------+
+ | |--(A)-- Authorization Request ---&gt;| Resource |
+ | | | Owner |
+ | |&lt;-(B)------ Access Grant ---------| |
+ | | +---------------+
+ | |
+ | | Client Credentials &amp; +---------------+
+ | |--(C)------ Access Grant --------&gt;| Authorization |
+ | Client | | Server |
+ | |&lt;-(D)------ Access Token ---------| |
+ | | (w/ Optional Refresh Token) +---------------+
+ | |
+ | | +---------------+
+ | |--(E)------ Access Token --------&gt;| Resource |
+ | | | Server |
+ | |&lt;-(F)---- Protected Resource -----| |
+ +--------+ +---------------+
+
+</PRE></DIV><TABLE border="0" cellpadding="0" cellspacing="2" align="center"><TBODY><TR><TD align="center"><FONT face="monaco, MS Sans Serif" size="1"><B>&nbsp;Figure&nbsp;1: Abstract Protocol Flow&nbsp;</B></FONT><BR></TD></TR></TBODY></TABLE><HR class="insert">
+
+<P>
+ The abstract flow illustrated in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#Figure 1">Figure&nbsp;1<SPAN> (</SPAN><SPAN class="info">Abstract Protocol Flow</SPAN><SPAN>)</SPAN></A> includes the following
+ steps:
+
+ </P>
+<BLOCKQUOTE class="text"><DL>
+<DT>(A)</DT>
+<DD>
+ The client requests authorization from the resource owner. The client should not
+ request the resource owner's credentials directly. Instead, it should request
+ authorization via an authorization server or other entities. For example, the client
+ directs the resource owner to the authorization server which in turn issues it an
+ access grant. When unavoidable, the client interacts directly with the end-user,
+ asking for the end-user's username and password. If the client is acting
+ autonomously, the authorization request is beyond the scope of this specification.
+
+</DD>
+<DT>(B)</DT>
+<DD>
+ The client is issued an access grant which represents the authorization provided by
+ the resource owner. The access grant can be expressed as:
+
+
+<UL class="text">
+<LI>
+ Authorization code - an access grant obtained via an authorization server.
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#user-authorization">Section&nbsp;3<SPAN> (</SPAN><SPAN class="info">Obtaining End-User Authorization</SPAN><SPAN>)</SPAN></A> describes how to obtain an authorization
+ code when the end-user is present and using a user-agent.
+
+</LI>
+<LI>
+ Assertion - an access grant obtained using a different trust framework.
+ Assertions enable the client to utilize existing trust relationships to obtain an
+ access token. They provide a bridge between OAuth and other trust frameworks. The
+ access grant represented by an assertion depends on the assertion type, its
+ content, and how it was issued, which are beyond the scope of this specification.
+
+</LI>
+<LI>
+ Resource owner password credentials - obtained when interacting directly with a
+ resource-owner. Resource owner password credentials (i.e. a username and
+ password) should only be used when there is a high degree of trust between the
+ resource owner and the client (e.g. its computer operating system or a highly
+ privileged application). However, unlike the HTTP Basic authentication scheme
+ defined in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#RFC2617">[RFC2617]<SPAN> (</SPAN><SPAN class="info">Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P., Luotonen, A., and L. Stewart, “HTTP Authentication: Basic and Digest Access Authentication,” June&nbsp;1999.</SPAN><SPAN>)</SPAN></A>, the resource owner's credentials are used
+ for a single request and are exchanged for an access token and refresh token.
+ This eliminates the need for the client to store the resource-owner's credentials
+ for future use.
+
+</LI>
+</UL>
+
+</DD>
+<DT>(C)</DT>
+<DD>
+ The client requests an access token by authenticating with the authorization server,
+ and presenting the access grant. The token request is described in
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#obtaining-token">Section&nbsp;4<SPAN> (</SPAN><SPAN class="info">Obtaining an Access Token</SPAN><SPAN>)</SPAN></A>.
+
+</DD>
+<DT>(D)</DT>
+<DD>
+ The authorization server validates the client credentials and the access grant, and
+ issues an access token with an optional refresh token. Access tokens usually have a
+ shorter lifetime than the access grant. Refresh tokens usually have a lifetime equal
+ to the duration of the access grant. When an access token expires, the refresh token
+ is used to obtain a new access token without having to request another access grant
+ from the resource owner.
+
+</DD>
+<DT>(E)</DT>
+<DD>
+ The client makes a protected resource request to the resource server, and presents
+ the access token in order to gain access. Accessing a protected resource is described
+ in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#access-resource">Section&nbsp;5<SPAN> (</SPAN><SPAN class="info">Accessing a Protected Resource</SPAN><SPAN>)</SPAN></A>.
+
+</DD>
+<DT>(F)</DT>
+<DD>
+ The resource server validates the access token, and if valid, serves the request.
+
+</DD>
+</DL></BLOCKQUOTE><P>
+
+</P>
+<P>
+ When the client is acting on its own behalf (the client is also the resource owner),
+ the client does not obtain an access grant. The simplified protocol flow is illustrated
+ in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#Figure 2">Figure&nbsp;2<SPAN> (</SPAN><SPAN class="info">Protocol Flow for Client Acting On Its Own Behalf</SPAN><SPAN>)</SPAN></A>:
+
+</P><BR><HR class="insert">
+<A name="Figure 2"></A>
+<DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ +--------+ +---------------+
+ | |--(C)--- Client Credentials -----&gt;| Authorization |
+ | | | Server |
+ | |&lt;-(D)------ Access Token ---------| |
+ | | +---------------+
+ | Client |
+ | | +---------------+
+ | |--(E)------ Access Token --------&gt;| Resource |
+ | | | Server |
+ | |&lt;-(F)---- Protected Resource -----| |
+ +--------+ +---------------+
+
+</PRE></DIV><TABLE border="0" cellpadding="0" cellspacing="2" align="center"><TBODY><TR><TD align="center"><FONT face="monaco, MS Sans Serif" size="1"><B>&nbsp;Figure&nbsp;2: Protocol Flow for Client Acting On Its Own Behalf&nbsp;</B></FONT><BR></TD></TR></TBODY></TABLE><HR class="insert">
+
+<P>
+ When the client uses the user-agent profile (described in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#user-agent">Section&nbsp;1.4.2<SPAN> (</SPAN><SPAN class="info">User-Agent</SPAN><SPAN>)</SPAN></A>),
+ the authorization request results in an access token, as illustrated in
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#Figure 3">Figure&nbsp;3<SPAN> (</SPAN><SPAN class="info">Indirect Access Grant Protocol Flow</SPAN><SPAN>)</SPAN></A>:
+
+</P><BR><HR class="insert">
+<A name="Figure 3"></A>
+<DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ +--------+ +----------+ +---------------+
+ | |--(A)-- Authorization --+- -+--&gt;| |
+ | | Request | Resource | | Authorization |
+ | | | Owner | | Server |
+ | |&lt;-(D)-- Access Token ---+- -+---| |
+ | | +----------+ +---------------+
+ | Client |
+ | | +---------------+
+ | |--(E)-------- Access Token -----------&gt;| Resource |
+ | | | Server |
+ | |&lt;-(F)------ Protected Resource --------| |
+ +--------+ +---------------+
+
+</PRE></DIV><TABLE border="0" cellpadding="0" cellspacing="2" align="center"><TBODY><TR><TD align="center"><FONT face="monaco, MS Sans Serif" size="1"><B>&nbsp;Figure&nbsp;3: Indirect Access Grant Protocol Flow&nbsp;</B></FONT><BR></TD></TR></TBODY></TABLE><HR class="insert">
+
+<A name="anchor5"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.1.4"></A><H3>1.4.&nbsp;
+Client Profiles</H3>
+
+<P>
+ OAuth supports a wide range of client types by providing a rich and extensible framework
+ for establishing authorization and exchanging it for an access token. The methods detailed
+ in this specification were designed to accommodate four client types: web servers,
+ user-agents, native applications, and autonomous clients. Additional authorization flows
+ and client profiles may be defined by other specifications to cover additional scenarios
+ and client types.
+
+</P>
+<A name="anchor6"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.1.4.1"></A><H3>1.4.1.&nbsp;
+Web Server</H3>
+
+<P>
+ The web server profile is suitable for clients capable of interacting with the end-user's
+ user-agent (typically a web browser) and capable of receiving incoming requests from the
+ authorization server (capable of acting as an HTTP server).
+
+</P><BR><HR class="insert">
+<A name="Figure 4"></A>
+<DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ +----------+ Client Identifier +---------------+
+ | -+----(A)--- &amp; Redirect URI ------&gt;| |
+ | End-user | | Authorization |
+ | at |&lt;---(B)-- User authenticates ---&gt;| Server |
+ | Browser | | |
+ | -+----(C)-- Authorization Code ---&lt;| |
+ +-|----|---+ +---------------+
+ | | ^ v
+ (A) (C) | |
+ | | | |
+ ^ v | |
+ +---------+ | |
+ | |&gt;---(D)-- Client Credentials, --------' |
+ | Web | Authorization Code, |
+ | Client | &amp; Redirect URI |
+ | | |
+ | |&lt;---(E)----- Access Token -------------------'
+ +---------+ (w/ Optional Refresh Token)
+
+</PRE></DIV><TABLE border="0" cellpadding="0" cellspacing="2" align="center"><TBODY><TR><TD align="center"><FONT face="monaco, MS Sans Serif" size="1"><B>&nbsp;Figure&nbsp;4: Web Server Flow&nbsp;</B></FONT><BR></TD></TR></TBODY></TABLE><HR class="insert">
+
+<P>
+ The web server flow illustrated in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#Figure 4">Figure&nbsp;4<SPAN> (</SPAN><SPAN class="info">Web Server Flow</SPAN><SPAN>)</SPAN></A> includes the following
+ steps:
+
+ </P>
+<BLOCKQUOTE class="text"><DL>
+<DT>(A)</DT>
+<DD>
+ The web client initiates the flow by redirecting the end-user's user-agent to the
+ end-user authorization endpoint as described in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#user-authorization">Section&nbsp;3<SPAN> (</SPAN><SPAN class="info">Obtaining End-User Authorization</SPAN><SPAN>)</SPAN></A>.
+ The client includes its client identifier, requested scope, local state, and a
+ redirect URI to which the authorization server will send the end-user back once
+ access is granted (or denied).
+
+</DD>
+<DT>(B)</DT>
+<DD>
+ The authorization server authenticates the end-user (via the user-agent) and
+ establishes whether the end-user grants or denies the client's access request.
+
+</DD>
+<DT>(C)</DT>
+<DD>
+ Assuming the end-user granted access, the authorization server redirects the
+ user-agent back to the client to the redirection URI provided earlier. The
+ authorization includes an authorization code for the client to use to obtain an
+ access token.
+
+</DD>
+<DT>(D)</DT>
+<DD>
+ The client requests an access token from the authorization server by authenticating
+ and including the authorization code received in the previous step as described in
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#obtaining-token">Section&nbsp;4<SPAN> (</SPAN><SPAN class="info">Obtaining an Access Token</SPAN><SPAN>)</SPAN></A>.
+
+</DD>
+<DT>(E)</DT>
+<DD>
+ The authorization server validates the client credentials and the authorization
+ code and responds back with the access token.
+
+</DD>
+</DL></BLOCKQUOTE><P>
+
+</P>
+<A name="user-agent"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.1.4.2"></A><H3>1.4.2.&nbsp;
+User-Agent</H3>
+
+<P>
+ The user-agent profile is suitable for client applications residing in a user-agent,
+ typically implemented in a browser using a scripting language such as JavaScript. These
+ clients cannot keep client secrets confidential and the authentication of the client is
+ based on the user-agent's same-origin policy.
+
+</P>
+<P>
+ Unlike other profiles in which the client makes separate requests for end-user
+ authorization and access token, the client receives the access token as a result of the
+ end-user authorization request in the form of an HTTP redirection. The client requests
+ the authorization server to redirect the user-agent to another web server or local
+ resource accessible to the user-agent which is capable of extracting the access token
+ from the response and passing it to the client.
+
+</P>
+<P>
+ This user-agent profile does not utilize the client secret since the client executables
+ reside on the end-user's computer or device which makes the client secret accessible
+ and exploitable. Because the access token is encoded into the redirection URI, it may
+ be exposed to the end-user and other applications residing on the computer or device.
+
+</P><BR><HR class="insert">
+<A name="Figure 5"></A>
+<DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ +----------+ Client Identifier +----------------+
+ | |&gt;---(A)-- &amp; Redirection URI ---&gt;| |
+ | | | |
+ End &lt;--+ - - - +----(B)-- User authenticates --&gt;| Authorization |
+ User | | | Server |
+ | |&lt;---(C)--- Redirect URI -------&lt;| |
+ | Client | with Access Token | |
+ | in | in Fragment +----------------+
+ | Browser |
+ | | +----------------+
+ | |&gt;---(D)--- Redirect URI -------&gt;| |
+ | | without Fragment | Web Server |
+ | | | with Client |
+ | (F) |&lt;---(E)--- Web Page with ------&lt;| Resource |
+ | Access | Script | |
+ | Token | +----------------+
+ +----------+
+
+</PRE></DIV><TABLE border="0" cellpadding="0" cellspacing="2" align="center"><TBODY><TR><TD align="center"><FONT face="monaco, MS Sans Serif" size="1"><B>&nbsp;Figure&nbsp;5: User-Agent Flow&nbsp;</B></FONT><BR></TD></TR></TBODY></TABLE><HR class="insert">
+
+<P>
+ The user-agent flow illustrated in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#Figure 5">Figure&nbsp;5<SPAN> (</SPAN><SPAN class="info">User-Agent Flow</SPAN><SPAN>)</SPAN></A> includes the following
+ steps:
+
+ </P>
+<BLOCKQUOTE class="text"><DL>
+<DT>(A)</DT>
+<DD>
+ The client sends the user-agent to the end-user authorization endpoint as described
+ in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#user-authorization">Section&nbsp;3<SPAN> (</SPAN><SPAN class="info">Obtaining End-User Authorization</SPAN><SPAN>)</SPAN></A>. The client includes its client identifier,
+ requested scope, local state, and a redirect URI to which the authorization server
+ will send the end-user back once authorization is granted (or denied).
+
+</DD>
+<DT>(B)</DT>
+<DD>
+ The authorization server authenticates the end-user (via the user-agent) and
+ establishes whether the end-user grants or denies the client's access request.
+
+</DD>
+<DT>(C)</DT>
+<DD>
+ If the end-user granted access, the authorization server redirects the
+ user-agent to the redirection URI provided earlier. The redirection URI includes
+ the access token in the URI fragment.
+
+</DD>
+<DT>(D)</DT>
+<DD>
+ The user-agent follows the redirection instructions by making a request to the web
+ server which does not include the fragment. The user-agent retains the fragment
+ information locally.
+
+</DD>
+<DT>(E)</DT>
+<DD>
+ The web server returns a web page (typically an HTML page with an embedded script)
+ capable of accessing the full redirection URI including the fragment retained by the
+ user-agent, and extracting the access token (and other parameters) contained in the
+ fragment.
+
+</DD>
+<DT>(F)</DT>
+<DD>
+ The user-agent executes the script provided by the web server locally, which
+ extracts the access token and passes it to the client.
+
+</DD>
+</DL></BLOCKQUOTE><P>
+
+</P>
+<A name="anchor7"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.1.4.3"></A><H3>1.4.3.&nbsp;
+Native Application</H3>
+
+<P>
+ Native application are clients running as native code on the end-user's computer or
+ device (i.e. executing outside a user-agent or as a desktop program). These clients are
+ often capable of interacting with (or embedding) the end-user's user-agent but are
+ limited in how such interaction affects their end-user experience. In many cases,
+ native applications are incapable of receiving direct callback requests from the
+ server (e.g. firewall, operating system restrictions).
+
+</P>
+<P>
+ Native application clients can be implemented in different ways based on their
+ requirements and desired end-user experience. Native application clients can:
+
+ </P>
+<UL class="text">
+<LI>
+ Utilize the end-user authorization endpoint as described in
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#user-authorization">Section&nbsp;3<SPAN> (</SPAN><SPAN class="info">Obtaining End-User Authorization</SPAN><SPAN>)</SPAN></A> by launching an external user-agent. The
+ client can capture the response by providing a redirection URI with a custom URI
+ scheme (registered with the operating system to invoke the client application), or
+ by providing a redirection URI pointing to a server-hosted resource under the
+ client's control which makes the response available to the client (e.g. using the
+ window title or other locations accessible from outside the user-agent).
+
+</LI>
+<LI>
+ Utilize the end-user authorization endpoint as described in
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#user-authorization">Section&nbsp;3<SPAN> (</SPAN><SPAN class="info">Obtaining End-User Authorization</SPAN><SPAN>)</SPAN></A> by using an embedded user-agent. The client
+ obtains the response by directly communicating with the embedded user-agent.
+
+</LI>
+<LI>
+ Prompt end-users for their password and use them directly to obtain an access
+ token. This is generally discouraged, as it hands the end-user's password directly
+ to the third-party client which in turn has to store it in clear-text. It also
+ requires the server to support password-based authentication.
+
+</LI>
+</UL><P>
+
+</P>
+<P>
+ When choosing between launching an external browser and an embedded user-agent,
+ developers should consider the following:
+
+ </P>
+<UL class="text">
+<LI>
+ External user-agents may improve completion rate as the end-user may already be
+ logged-in and not have to re-authenticate.
+
+</LI>
+<LI>
+ Embedded user-agents often offer a better end-user flow, as they remove the need to
+ switch context and open new windows.
+
+</LI>
+<LI>
+ Embedded user-agents pose a security challenge because users are authenticating in
+ an unidentified window without access to the visual protections offered by many
+ user-agents.
+
+</LI>
+</UL><P>
+
+</P>
+<A name="anchor8"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.1.4.4"></A><H3>1.4.4.&nbsp;
+Autonomous</H3>
+
+<P>
+ Autonomous clients utilize an existing trust relationship or framework to establish
+ authorization. Autonomous clients can be implemented in different ways based on their
+ requirements and the existing trust framework they rely upon. Autonomous clients can:
+
+ </P>
+<UL class="text">
+<LI>
+ Obtain an access token by authenticating with the authorization server using their
+ client credentials. The scope of the access token is limited to the protected
+ resources under the control of the client, or that of another resource owner
+ previously arranged with the authorization server.
+
+</LI>
+<LI>
+ Use an existing access grant expressed as an assertion using an assertion format
+ supported by the authorization server. Using assertions requires the client to
+ obtain a assertion (such as a <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#OASIS.saml-core-2.0-os">SAML<SPAN> (</SPAN><SPAN class="info">Cantor, S., Kemp, J., Philpott, R., and E. Maler, “Assertions and Protocol for the OASIS Security Assertion Markup Language (SAML) V2.0,” March&nbsp;2005.</SPAN><SPAN>)</SPAN></A> [OASIS.saml‑core‑2.0‑os]
+ assertion) from an assertion issuer or to self-issue an assertion. The assertion
+ format, the process by which the assertion is obtained, and the method of
+ validating the assertion are defined by the assertion issuer and the authorization
+ server, and are beyond the scope of this specification.
+
+</LI>
+</UL><P>
+
+</P>
+<A name="client-authentication"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.2"></A><H3>2.&nbsp;
+Client Credentials</H3>
+
+<P>
+ When interacting with the authorization server, the client identifies itself using a client
+ identifier and authenticates using a set of client credentials. This specification provides
+ one mechanism for authenticating the client using password credentials.
+
+</P>
+<P>
+ The means through which the client obtains its credentials are beyond the scope of this
+ specification, but usually involve registration with the authorization server.
+ [[ OAuth Discovery provides one way of obtaining a client password ]]
+
+</P>
+<P>
+ Due to the nature of some clients, authorization servers SHOULD NOT make assumptions
+ about the confidentiality of client secrets without establishing trust with the
+ client operator. Authorization servers SHOULD NOT issue client secrets to clients
+ incapable of keeping their secrets confidential.
+
+</P>
+<P>
+ The authorization server MAY authenticate the client using any appropriate set of
+ credentials and authentication scheme. The client MUST NOT utilize more than one set of
+ credentials or authentication mechanism with each request.
+
+</P>
+<A name="anchor9"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.2.1"></A><H3>2.1.&nbsp;
+Client Password Credentials</H3>
+
+<P>
+ The client password credentials use a shared symmetric secret to authenticate the client.
+ The client identifier and password are included in the request using the
+ HTTP Basic authentication scheme as defined in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#RFC2617">[RFC2617]<SPAN> (</SPAN><SPAN class="info">Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P., Luotonen, A., and L. Stewart, “HTTP Authentication: Basic and Digest Access Authentication,” June&nbsp;1999.</SPAN><SPAN>)</SPAN></A> by including the
+ client identifier as the username and client password as the password.
+
+</P>
+<P>
+ For example (line breaks are for display purposes only):
+
+</P><DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ POST /token HTTP/1.1
+ Host: server.example.com
+ Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
+ Content-Type: application/x-www-form-urlencoded
+
+ grant_type=authorization_code&amp;client_id=s6BhdRkqt3&amp;code=i1WsRn1uB1&amp;
+ redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
+
+</PRE></DIV>
+<P>
+ Alternatively, the client MAY include the password in the request body using the
+ following parameter:
+
+ </P>
+<BLOCKQUOTE class="text"><DL>
+<DT>client_secret</DT>
+<DD>
+ REQUIRED. The client password.
+
+</DD>
+</DL></BLOCKQUOTE><P>
+
+</P>
+<P>
+ For example (line breaks are for display purposes only):
+
+</P><DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ POST /token HTTP/1.1
+ Host: server.example.com
+ Content-Type: application/x-www-form-urlencoded
+
+ grant_type=authorization_code&amp;client_id=s6BhdRkqt3&amp;
+ client_secret=gX1fBat3bV&amp;code=i1WsRn1uB1&amp;
+ redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
+
+</PRE></DIV>
+<P>
+ The authorization server MUST accept the client credentials using both the request
+ parameter, and the HTTP Basic authentication scheme. The authorization server MAY
+ support additional authentication schemes suitable for the transmission of a password.
+
+</P>
+<A name="user-authorization"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.3"></A><H3>3.&nbsp;
+Obtaining End-User Authorization</H3>
+
+<P>
+ When the client interacts with an end-user, the end-user MUST first grant the client
+ authorization to access its protected resources. Once obtained, the end-user access
+ grant is expressed as an authorization code which the client uses to obtain an access
+ token. To obtain an end-user authorization, the client sends the end-user to the
+ end-user authorization endpoint.
+
+</P>
+<P>
+ At the end-user authorization endpoint, the end-user first authenticates with the
+ authorization server, and then grants or denies the access request. 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, is beyond the scope
+ of this specification. However, the authorization server MUST first verify the identity of
+ the end-user.
+
+</P>
+<P>
+ The location of the end-user authorization endpoint can be found in the service
+ documentation, or can be obtained by using [[ OAuth Discovery ]]. The end-user
+ authorization endpoint URI MAY include a query component as defined by
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#RFC3986">[RFC3986]<SPAN> (</SPAN><SPAN class="info">Berners-Lee, T., Fielding, R., and L. Masinter, “Uniform Resource Identifier (URI): Generic Syntax,” January&nbsp;2005.</SPAN><SPAN>)</SPAN></A> section 3, which must be retained when adding additional
+ query parameters.
+
+</P>
+<P>
+ Since requests to the end-user authorization endpoint result in user authentication and
+ the transmission of sensitive information, the authorization server SHOULD require the
+ use of a transport-layer security mechanism such as TLS when sending requests to the
+ end-user authorization endpoint.
+
+</P>
+<P>
+ In order to direct the end-user's user-agent to the authorization server, the client
+ constructs the request URI by adding the following parameters to the end-user
+ authorization endpoint URI query component using the
+ <TT>application/x-www-form-urlencoded</TT> format as defined by
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#W3C.REC-html401-19991224">[W3C.REC‑html401‑19991224]<SPAN> (</SPAN><SPAN class="info">Raggett, D., Hors, A., and I. Jacobs, “HTML 4.01 Specification,” December&nbsp;1999.</SPAN><SPAN>)</SPAN></A>:
+
+ </P>
+<BLOCKQUOTE class="text"><DL>
+<DT>response_type</DT>
+<DD>
+
+ REQUIRED. The requested response: an access token, an authorization code, or both. The
+ parameter value MUST be set to <TT>token</TT> for requesting an
+ access token, <TT>code</TT> for requesting an authorization code, or
+ <TT>code_and_token</TT> to request both. The authorization server
+ MAY decline to provide one or more of these response types. [[ The 'code_and_token'
+ type is pending use cases and may be removed for the specification ]]
+
+</DD>
+<DT>client_id</DT>
+<DD>
+
+ REQUIRED. The client identifier as described in
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#client-authentication">Section&nbsp;2<SPAN> (</SPAN><SPAN class="info">Client Credentials</SPAN><SPAN>)</SPAN></A>.
+
+</DD>
+<DT>redirect_uri</DT>
+<DD>
+
+ 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 SHOULD require the client to pre-register
+ their redirection URI.
+
+</DD>
+<DT>scope</DT>
+<DD>
+
+ OPTIONAL. The scope of the access request expressed as a list of space-delimited
+ strings. The value of the <TT>scope</TT> 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.
+
+</DD>
+<DT>state</DT>
+<DD>
+
+ OPTIONAL. An opaque value used by the client to maintain state between the request
+ and callback. The authorization server includes this value when redirecting the
+ user-agent back to the client.
+
+</DD>
+</DL></BLOCKQUOTE><P>
+
+</P>
+<P>
+ The client directs the end-user to the constructed URI using an HTTP redirection
+ response, or by other means available to it via the end-user's user-agent. The
+ authorization server MUST support the use of the HTTP <TT>GET</TT>
+ method for the end-user authorization endpoint, and MAY support the use of the
+ <TT>POST</TT> method as well.
+
+</P>
+<P>
+ For example, the client directs the end-user's user-agent to make the following HTTP
+ request using transport-layer security (line breaks are for display purposes only):
+
+</P><DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ GET /authorize?response_type=code&amp;client_id=s6BhdRkqt3&amp;
+ redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1
+ Host: server.example.com
+
+</PRE></DIV>
+<P>
+ If the client has previously registered a redirection URI with the authorization server,
+ the authorization server MUST verify that the redirection URI received matches the
+ registered URI associated with the client identifier. [[ provide guidance on how to
+ perform matching ]]
+
+</P>
+<P>
+ Parameters sent without a value MUST be treated as if they were omitted from the request.
+ The authorization server SHOULD ignore unrecognized request parameters.
+
+</P>
+<P>
+ The authorization server validates the request to ensure all required parameters are
+ present and valid. If the request is invalid, the authorization server immediately
+ redirects the user-agent back to the client using the redirection URI provided with the
+ appropriate error code as described in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#auth-error">Section&nbsp;3.2<SPAN> (</SPAN><SPAN class="info">Error Response</SPAN><SPAN>)</SPAN></A>.
+
+</P>
+<P>
+ The authorization server authenticates the end-user and obtains an authorization
+ decision (by asking the end-user or by establishing approval via other means). When a
+ decision has been established, the authorization server directs the end-user's
+ user-agent to the provided client redirection URI using an HTTP redirection response,
+ or by other means available to it via the end-user's user-agent.
+
+</P>
+<A name="anchor10"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.3.1"></A><H3>3.1.&nbsp;
+Authorization Response</H3>
+
+<P>
+ If the end-user grants the access request, the authorization server issues an access
+ token, an authorization code, or both, and delivers them to the client by adding the
+ following parameters to the redirection URI (as described below):
+
+ </P>
+<BLOCKQUOTE class="text"><DL>
+<DT>code</DT>
+<DD>
+
+ REQUIRED if the response type is <TT>code</TT> or
+ <TT>code_and_token</TT>, otherwise MUST NOT be included. The
+ authorization code generated by the authorization server. The authorization code
+ SHOULD expire shortly after it is issued. The authorization server MUST invalidate
+ the authorization code after a single usage. The authorization code is bound to the
+ client identifier and redirection URI.
+
+</DD>
+<DT>access_token</DT>
+<DD>
+
+ REQUIRED if the response type is <TT>token</TT> or
+ <TT>code_and_token</TT>, otherwise MUST NOT be included. The
+ access token issued by the authorization server. The access token string MUST comply
+ with the access-token rule defined in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#authz-header">Section&nbsp;5.1.1<SPAN> (</SPAN><SPAN class="info">The Authorization Request Header Field</SPAN><SPAN>)</SPAN></A>.
+
+</DD>
+<DT>expires_in</DT>
+<DD>
+
+ OPTIONAL. The duration in seconds of the access token lifetime if an access token
+ is included. For example, the value <TT>3600</TT> denotes that the
+ access token will expire in one hour from the time the response was generated by the
+ authorization server.
+
+</DD>
+<DT>scope</DT>
+<DD>
+
+ OPTIONAL. The scope of the access token as a list of space-delimited strings if an
+ access token is included. The value of the <TT>scope</TT>
+ 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. The authorization server SHOULD
+ include the parameter if the requested scope is different from the one requested by
+ the client.
+
+</DD>
+<DT>state</DT>
+<DD>
+
+ REQUIRED if the <TT>state</TT> parameter was present in the
+ client authorization request. Set to the exact value received from the client.
+
+</DD>
+</DL></BLOCKQUOTE><P>
+
+</P>
+<P>
+ The method in which the authorization server adds the parameter to the redirection
+ URI is determined by the response type requested by the client in the authorization
+ request using the <TT>response_type</TT> parameter.
+
+</P>
+<P>
+ If the response type is <TT>code</TT>, the authorization
+ server adds the parameters to the redirection URI query component using the
+ <TT>application/x-www-form-urlencoded</TT> format as defined by
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#W3C.REC-html401-19991224">[W3C.REC‑html401‑19991224]<SPAN> (</SPAN><SPAN class="info">Raggett, D., Hors, A., and I. Jacobs, “HTML 4.01 Specification,” December&nbsp;1999.</SPAN><SPAN>)</SPAN></A>.
+
+</P>
+<P>
+ For example, the authorization server redirects the end-user's user-agent by
+ sending the following HTTP response:
+
+</P><DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ HTTP/1.1 302 Found
+ Location: https://client.example.com/cb?code=i1WsRn1uB1
+
+</PRE></DIV>
+<P>
+ If the response type is <TT>token</TT>, the authorization
+ server adds the parameters to the redirection URI fragment component using the
+ <TT>application/x-www-form-urlencoded</TT> format as defined by
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#W3C.REC-html401-19991224">[W3C.REC‑html401‑19991224]<SPAN> (</SPAN><SPAN class="info">Raggett, D., Hors, A., and I. Jacobs, “HTML 4.01 Specification,” December&nbsp;1999.</SPAN><SPAN>)</SPAN></A>.
+
+</P>
+<P>
+ For example, the authorization server redirects the end-user's user-agent by
+ sending the following HTTP response:
+
+</P><DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ HTTP/1.1 302 Found
+ Location: http://example.com/rd#access_token=FJQbwq9&amp;expires_in=3600
+
+</PRE></DIV>
+<P>
+ If the response type is <TT>code_and_token</TT>, the authorization
+ server adds the <TT>code</TT> and <TT>state</TT>
+ parameters to the redirection URI query component and the
+ <TT>access_token</TT>, <TT>scope</TT>, and
+ <TT>expires_in</TT> to the redirection URI fragment using the
+ <TT>application/x-www-form-urlencoded</TT> format as defined by
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#W3C.REC-html401-19991224">[W3C.REC‑html401‑19991224]<SPAN> (</SPAN><SPAN class="info">Raggett, D., Hors, A., and I. Jacobs, “HTML 4.01 Specification,” December&nbsp;1999.</SPAN><SPAN>)</SPAN></A>.
+
+</P>
+<P>
+ For example, the authorization server redirects the end-user's user-agent by
+ sending the following HTTP response (line breaks are for display purposes only):
+
+</P><DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ HTTP/1.1 302 Found
+ Location: http://example.com/rd?code=i1WsRn1uB1
+ #access_token=FJQbwq9&amp;expires_in=3600
+
+</PRE></DIV>
+<P>
+ Clients SHOULD ignore unrecognized response parameters. The sizes of tokens and other
+ values received from the authorization server, are left undefined by this specification.
+ Clients should avoid making assumptions about value sizes. Servers should document the
+ expected size of any value they issue.
+
+</P>
+<A name="auth-error"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.3.2"></A><H3>3.2.&nbsp;
+Error Response</H3>
+
+<P>
+ If the end-user denies the access request or if the request is invalid, the authorization
+ server informs the client by adding the following parameters to the redirection URI query
+ component using the <TT>application/x-www-form-urlencoded</TT> format
+ as defined by <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#W3C.REC-html401-19991224">[W3C.REC‑html401‑19991224]<SPAN> (</SPAN><SPAN class="info">Raggett, D., Hors, A., and I. Jacobs, “HTML 4.01 Specification,” December&nbsp;1999.</SPAN><SPAN>)</SPAN></A>:
+
+ </P>
+<BLOCKQUOTE class="text"><DL>
+<DT>error</DT>
+<DD>
+
+ REQUIRED. A single error code as described in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#auth-error-codes">Section&nbsp;3.2.1<SPAN> (</SPAN><SPAN class="info">Error Codes</SPAN><SPAN>)</SPAN></A>.
+
+</DD>
+<DT>error_description</DT>
+<DD>
+ OPTIONAL. A human-readable text providing additional information, used to assist in
+ the understanding and resolution of the error occurred.
+
+</DD>
+<DT>error_uri</DT>
+<DD>
+ OPTIONAL. 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.
+
+</DD>
+<DT>state</DT>
+<DD>
+
+ REQUIRED if the <TT>state</TT> parameter was present in the
+ client authorization request. Set to the exact value received from the client.
+
+</DD>
+</DL></BLOCKQUOTE><P>
+
+</P>
+<P>
+ For example, the authorization server redirects the end-user's user-agent by
+ sending the following HTTP response:
+
+</P><DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ HTTP/1.1 302 Found
+ Location: https://client.example.com/cb?error=access-denied
+
+</PRE></DIV>
+<A name="auth-error-codes"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.3.2.1"></A><H3>3.2.1.&nbsp;
+Error Codes</H3>
+
+<P>
+ The authorization server includes one of the following error codes with the error
+ response:
+
+ </P>
+<BLOCKQUOTE class="text"><DL>
+<DT>invalid_request</DT>
+<DD>
+
+ The request is missing a required parameter, includes an unsupported parameter or
+ parameter value, or is otherwise malformed.
+
+</DD>
+<DT>invalid_client</DT>
+<DD>
+
+ The client identifier provided is invalid.
+
+</DD>
+<DT>unauthorized_client</DT>
+<DD>
+
+ The client is not authorized to use the requested response type.
+
+</DD>
+<DT>redirect_uri_mismatch</DT>
+<DD>
+
+ The redirection URI provided does not match a pre-registered value.
+
+</DD>
+<DT>access_denied</DT>
+<DD>
+
+ The end-user or authorization server denied the request.
+
+</DD>
+<DT>unsupported_response_type</DT>
+<DD>
+
+ The requested response type is not supported by the authorization server.
+
+</DD>
+<DT>invalid_scope</DT>
+<DD>
+
+ The requested scope is invalid, unknown, or malformed.
+
+</DD>
+</DL></BLOCKQUOTE><P>
+
+</P>
+<P>
+ [[ Add mechanism for extending error codes ]]
+
+</P>
+<A name="obtaining-token"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.4"></A><H3>4.&nbsp;
+Obtaining an Access Token</H3>
+
+<P>
+ The client obtains an access token by authenticating with the authorization server and
+ presenting its access grant (in the form of an authorization code, resource owner
+ credentials, an assertion, or a refresh token).
+
+</P>
+<P>
+ 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 security mechanism when sending requests to the token endpoints.
+ Servers MUST support TLS 1.2 as defined in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#RFC5246">[RFC5246]<SPAN> (</SPAN><SPAN class="info">Dierks, T. and E. Rescorla, “The Transport Layer Security (TLS) Protocol Version 1.2,” August&nbsp;2008.</SPAN><SPAN>)</SPAN></A>, and MAY support
+ additional transport-layer security mechanisms.
+
+</P>
+<P>
+ The client requests an access token by making an HTTP <TT>POST</TT>
+ request to the token endpoint. The location of the token endpoint can be found in the
+ service documentation, or can be obtained by using [[ OAuth Discovery ]]. The token
+ endpoint URI MAY include a query component.
+
+</P>
+<P>
+ The client authenticates with the authorization server by adding its client credentials to
+ the request as described in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#client-authentication">Section&nbsp;2<SPAN> (</SPAN><SPAN class="info">Client Credentials</SPAN><SPAN>)</SPAN></A>. The authorization
+ server MAY allow unauthenticated access token requests when the client identity does not
+ matter (e.g. anonymous client) or when the client identity is established via other means
+ (e.g. using an assertion access grant).
+
+</P>
+<P>
+ The client constructs the request by including the following parameters using the
+ <TT>application/x-www-form-urlencoded</TT> format in the HTTP request
+ entity-body:
+
+ </P>
+<BLOCKQUOTE class="text"><DL>
+<DT>grant_type</DT>
+<DD>
+
+ REQUIRED. The access grant type included in the request. Value MUST be one of
+ <TT>authorization_code</TT>,
+ <TT>password</TT>,
+ <TT>assertion</TT>,
+ <TT>refresh_token</TT>, or <TT>none</TT>.
+
+</DD>
+<DT>client_id</DT>
+<DD>
+
+ REQUIRED, unless the client identity can be establish via other means (e.g. assertion).
+ The client identifier as described in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#client-authentication">Section&nbsp;2<SPAN> (</SPAN><SPAN class="info">Client Credentials</SPAN><SPAN>)</SPAN></A>.
+
+</DD>
+<DT>scope</DT>
+<DD>
+
+ OPTIONAL. The scope of the access request expressed as a list of space-delimited
+ strings. The value of the <TT>scope</TT> 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. If the access grant being used already represents an
+ approved scope (e.g. authorization code, assertion), the requested scope MUST be equal
+ or lesser than the scope previously granted.
+
+</DD>
+</DL></BLOCKQUOTE><P>
+
+</P>
+<P>
+ In addition, the client MUST include the appropriate parameters listed for the selected
+ access grant type as described in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#access-grant-types">Section&nbsp;4.1<SPAN> (</SPAN><SPAN class="info">Access Grant Types</SPAN><SPAN>)</SPAN></A>.
+
+</P>
+<P>
+ Parameters sent without a value MUST be treated as if they were omitted from the request.
+ The authorization server SHOULD ignore unrecognized request parameters.
+
+</P>
+<A name="access-grant-types"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.4.1"></A><H3>4.1.&nbsp;
+Access Grant Types</H3>
+
+<P>
+ The client requests an access token using one of the four types of access grants:
+ authorization code, password credentials, assertion, or refresh token.
+
+</P>
+<P>
+ When requesting an access token using the <TT>none</TT> 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).
+
+</P>
+<A name="anchor11"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.4.1.1"></A><H3>4.1.1.&nbsp;
+Authorization Code</H3>
+
+<P>
+ The client includes the authorization code using the
+ <TT>authorization_code</TT> access grant type and the following
+ parameters:
+
+ </P>
+<BLOCKQUOTE class="text"><DL>
+<DT>code</DT>
+<DD>
+
+ REQUIRED. The authorization code received from the authorization server.
+
+</DD>
+<DT>redirect_uri</DT>
+<DD>
+
+ REQUIRED. The redirection URI used in the initial request.
+
+</DD>
+</DL></BLOCKQUOTE><P>
+
+</P>
+<P>
+ For example, the client makes the following HTTP request by including its client
+ credentials via the <TT>client_secret</TT> parameter described in
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#client-authentication">Section&nbsp;2<SPAN> (</SPAN><SPAN class="info">Client Credentials</SPAN><SPAN>)</SPAN></A> and using transport-layer security (line
+ breaks are for display purposes only):
+
+</P><DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ POST /token HTTP/1.1
+ Host: server.example.com
+ Content-Type: application/x-www-form-urlencoded
+
+ grant_type=authorization_code&amp;client_id=s6BhdRkqt3&amp;
+ client_secret=gX1fBat3bV&amp;code=i1WsRn1uB1&amp;
+ redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
+
+</PRE></DIV>
+<P>
+ The authorization server MUST:
+
+ </P>
+<UL class="text">
+<LI>
+ Validate the client credentials (if present) and ensure they match the
+ authorization code.
+
+</LI>
+<LI>
+ Verify that the authorization code and redirection URI are all valid and match its
+ stored association.
+
+</LI>
+</UL><P>
+
+</P>
+<P>
+ If the request is valid, the authorization server issues a successful response as
+ described in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#access-token-response">Section&nbsp;4.2<SPAN> (</SPAN><SPAN class="info">Access Token Response</SPAN><SPAN>)</SPAN></A>.
+
+</P>
+<A name="anchor12"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.4.1.2"></A><H3>4.1.2.&nbsp;
+Resource Owner Password Credentials</H3>
+
+<P>
+ The client includes the resource owner credentials using the
+ <TT>password</TT> access grant type and the following
+ parameters: [[ add internationalization consideration for username and password ]]
+
+ </P>
+<BLOCKQUOTE class="text"><DL>
+<DT>username</DT>
+<DD>
+
+ REQUIRED. The resource owner's username.
+
+</DD>
+<DT>password</DT>
+<DD>
+
+ REQUIRED. The resource owner's password.
+
+</DD>
+</DL></BLOCKQUOTE><P>
+
+</P>
+<P>
+ For example, the client makes the following HTTP request by including its client
+ credentials via the <TT>client_secret</TT> parameter described in
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#client-authentication">Section&nbsp;2<SPAN> (</SPAN><SPAN class="info">Client Credentials</SPAN><SPAN>)</SPAN></A> and using transport-layer security (line
+ breaks are for display purposes only):
+
+</P><DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ POST /token HTTP/1.1
+ Host: server.example.com
+ Content-Type: application/x-www-form-urlencoded
+
+ grant_type=password&amp;client_id=s6BhdRkqt3&amp;
+ client_secret=47HDu8s&amp;username=johndoe&amp;password=A3ddj3w
+
+</PRE></DIV>
+<P>
+ The authorization server MUST validate the client credentials (if present) and end-user
+ credentials and if valid issue an access token response as described in
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#access-token-response">Section&nbsp;4.2<SPAN> (</SPAN><SPAN class="info">Access Token Response</SPAN><SPAN>)</SPAN></A>.
+
+</P>
+<A name="anchor13"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.4.1.3"></A><H3>4.1.3.&nbsp;
+Assertion</H3>
+
+<P>
+ The client includes the assertion using the <TT>assertion</TT> access
+ grant type and the following parameters:
+
+ </P>
+<BLOCKQUOTE class="text"><DL>
+<DT>assertion_type</DT>
+<DD>
+
+ REQUIRED. The format of the assertion as defined by the authorization server. The
+ value MUST be an absolute URI.
+
+</DD>
+<DT>assertion</DT>
+<DD>
+
+ REQUIRED. The assertion.
+
+</DD>
+</DL></BLOCKQUOTE><P>
+
+</P>
+<P>
+ For example, the client makes the following HTTP request using transport-layer
+ security, and client authentication is achieved via the assertion (line breaks are
+ for display purposes only):
+
+</P><DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ POST /token HTTP/1.1
+ Host: server.example.com
+ Content-Type: application/x-www-form-urlencoded
+
+ grant_type=assertion&amp;
+ assertion_type=urn%3Aoasis%3Anames%3Atc%3ASAML%3A2.0%3Aassertion&amp;
+ assertion=PHNhbWxwOl...[omitted for brevity]...ZT4%3D
+
+</PRE></DIV>
+<P>
+ The authorization server MUST validate the client credentials (if present) and the
+ assertion and if valid issues an access token response as described in
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#access-token-response">Section&nbsp;4.2<SPAN> (</SPAN><SPAN class="info">Access Token Response</SPAN><SPAN>)</SPAN></A>. The authorization server SHOULD NOT issue a
+ refresh token (instead, require the client to use the same or new assertion).
+
+</P>
+<P>
+ Authorization servers SHOULD issue access tokens with a limited lifetime and require
+ clients to refresh them by requesting a new access token using the same assertion if it
+ is still valid. Otherwise the client MUST obtain a new valid assertion.
+
+</P>
+<A name="token-refresh"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.4.1.4"></A><H3>4.1.4.&nbsp;
+Refresh Token</H3>
+
+<P>
+ The client includes the refresh token using the
+ <TT>refresh_token</TT> access grant type and the following
+ parameter:
+
+ </P>
+<BLOCKQUOTE class="text"><DL>
+<DT>refresh_token</DT>
+<DD>
+
+ REQUIRED. The refresh token associated with the access token to be refreshed.
+
+</DD>
+</DL></BLOCKQUOTE><P>
+
+</P>
+<P>
+ For example, the client makes the following HTTP request by including its client
+ credentials via the <TT>client_secret</TT> parameter described in
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#client-authentication">Section&nbsp;2<SPAN> (</SPAN><SPAN class="info">Client Credentials</SPAN><SPAN>)</SPAN></A> and using transport-layer security (line
+ breaks are for display purposes only):
+
+</P><DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ POST /token HTTP/1.1
+ Host: server.example.com
+ Content-Type: application/x-www-form-urlencoded
+
+ grant_type=refresh_token&amp;client_id=s6BhdRkqt3&amp;
+ client_secret=8eSEIpnqmM&amp;refresh_token=n4E9O119d
+
+</PRE></DIV>
+<P>
+ The authorization server MUST verify the client credentials (if present), the validity
+ of the refresh token, and that the resource owner's authorization is still valid. If
+ the request is valid, the authorization server issues an access token response as
+ described in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#access-token-response">Section&nbsp;4.2<SPAN> (</SPAN><SPAN class="info">Access Token Response</SPAN><SPAN>)</SPAN></A>. The authorization server MAY
+ issue a new refresh token.
+
+</P>
+<A name="access-token-response"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.4.2"></A><H3>4.2.&nbsp;
+Access Token Response</H3>
+
+<P>
+ After receiving and verifying a valid and authorized access token request from the
+ client, the authorization server issues the access token and optional refresh token,
+ and constructs the response by adding the following parameters to the entity body of
+ the HTTP response with a 200 (OK) status code:
+
+</P>
+<P>
+ The token response contains the following parameters:
+
+ </P>
+<BLOCKQUOTE class="text"><DL>
+<DT>access_token</DT>
+<DD>
+
+ REQUIRED. The access token issued by the authorization server. The access token
+ string MUST comply with the access-token rule defined in
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#authz-header">Section&nbsp;5.1.1<SPAN> (</SPAN><SPAN class="info">The Authorization Request Header Field</SPAN><SPAN>)</SPAN></A>.
+
+</DD>
+<DT>expires_in</DT>
+<DD>
+
+ OPTIONAL. The duration in seconds of the access token lifetime. For example, the
+ value <TT>3600</TT> denotes that the access token will expire in
+ one hour from the time the response was generated by the authorization server.
+
+</DD>
+<DT>refresh_token</DT>
+<DD>
+
+ OPTIONAL. The refresh token used to obtain new access tokens using the same
+ end-user access grant as described in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#token-refresh">Section&nbsp;4.1.4<SPAN> (</SPAN><SPAN class="info">Refresh Token</SPAN><SPAN>)</SPAN></A>. The
+ authorization server SHOULD NOT issue a refresh token when the access grant type is
+ set to <TT>none</TT>.
+
+</DD>
+<DT>scope</DT>
+<DD>
+
+ OPTIONAL. The scope of the access token as a list of space-delimited strings. The
+ value of the <TT>scope</TT> 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. The authorization server SHOULD include the parameter if the
+ requested scope is different from the one requested by the client.
+
+</DD>
+</DL></BLOCKQUOTE><P>
+
+</P>
+<P>
+ The parameters are including in the entity body of the HTTP response using the
+ <TT>application/json</TT> media type as defined by
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#RFC4627">[RFC4627]<SPAN> (</SPAN><SPAN class="info">Crockford, D., “The application/json Media Type for JavaScript Object Notation (JSON),” July&nbsp;2006.</SPAN><SPAN>)</SPAN></A>. The parameters are serialized into a JSON structure by
+ adding each parameter at the highest structure level. Parameter names and string values
+ are included as JSON strings. Numerical values are included as JSON numbers.
+
+</P>
+<P>
+ The authorization server MUST include the HTTP <TT>Cache-Control</TT>
+ response header field with a value of <TT>no-store</TT> in any
+ response containing tokens, secrets, or other sensitive information.
+
+</P>
+<P>
+ For example:
+
+</P><DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ HTTP/1.1 200 OK
+ Content-Type: application/json
+ Cache-Control: no-store
+
+ {
+ "access_token":"SlAV32hkKG",
+ "expires_in":3600,
+ "refresh_token":"8xLOxBtZp8"
+ }
+
+</PRE></DIV>
+<P>
+ Clients SHOULD ignore unrecognized response parameters. The sizes of tokens and other
+ values received from the authorization server, are left undefined by this specification.
+ Clients should avoid making assumptions about value sizes. Servers should document the
+ expected size of any value they issue.
+
+</P>
+<A name="token-error"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.4.3"></A><H3>4.3.&nbsp;
+Error Response</H3>
+
+<P>
+ If the token request is invalid or unauthorized, the authorization server constructs
+ the response by adding the following parameter to the entity body of the HTTP
+ response using the <TT>application/json</TT> media type:
+
+ </P>
+<BLOCKQUOTE class="text"><DL>
+<DT>error</DT>
+<DD>
+
+ REQUIRED. A single error code as described in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#token-error-codes">Section&nbsp;4.3.1<SPAN> (</SPAN><SPAN class="info">Error Codes</SPAN><SPAN>)</SPAN></A>.
+
+</DD>
+<DT>error_description</DT>
+<DD>
+ OPTIONAL. A human-readable text providing additional information, used to assist in
+ the understanding and resolution of the error occurred.
+
+</DD>
+<DT>error_uri</DT>
+<DD>
+ OPTIONAL. 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.
+
+</DD>
+</DL></BLOCKQUOTE><P>
+
+</P>
+<P>
+ For example:
+
+</P><DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ HTTP/1.1 400 Bad Request
+ Content-Type: application/json
+ Cache-Control: no-store
+
+ {
+ "error":"invalid_request"
+ }
+
+</PRE></DIV>
+<P>
+ If the client provided invalid credentials using an HTTP authentication scheme via the
+ <TT>Authorization</TT> request header field, the authorization server
+ MUST respond with the HTTP 401 (Unauthorized) status code. Otherwise, the authorization
+ server SHALL respond with the HTTP 400 (Bad Request) status code.
+
+</P>
+<A name="token-error-codes"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.4.3.1"></A><H3>4.3.1.&nbsp;
+Error Codes</H3>
+
+<P>
+ The authorization server includes one of the following error codes with the error
+ response:
+
+ </P>
+<BLOCKQUOTE class="text"><DL>
+<DT>invalid_request</DT>
+<DD>
+
+ The request is missing a required parameter, includes an unsupported parameter or
+ parameter value, repeats a parameter, includes multiple credentials, utilizes
+ more than one mechanism for authenticating the client, or is otherwise malformed.
+
+</DD>
+<DT>invalid_client</DT>
+<DD>
+
+ The client identifier provided is invalid, the client failed to authenticate, the
+ client did not include its credentials, provided multiple client credentials, or
+ used unsupported credentials type.
+
+</DD>
+<DT>unauthorized_client</DT>
+<DD>
+
+ The authenticated client is not authorized to use the access grant type provided.
+
+</DD>
+<DT>invalid_grant</DT>
+<DD>
+
+ The provided access grant is invalid, expired, or revoked (e.g. invalid assertion,
+ expired authorization token, bad end-user password credentials, or mismatching
+ authorization code and redirection URI).
+
+</DD>
+<DT>unsupported_grant_type</DT>
+<DD>
+
+ The access grant included - its type or another attribute - is not supported by the
+ authorization server.
+
+</DD>
+<DT>invalid_scope</DT>
+<DD>
+
+ The requested scope is invalid, unknown, malformed, or exceeds the previously
+ granted scope.
+
+</DD>
+</DL></BLOCKQUOTE><P>
+
+</P>
+<P>
+ [[ Add mechanism for extending error codes ]]
+
+</P>
+<A name="access-resource"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.5"></A><H3>5.&nbsp;
+Accessing a Protected Resource</H3>
+
+<P>
+ Clients access protected resources by presenting an access token to the resource server.
+ Access tokens act as bearer tokens, where the token string acts as a shared symmetric
+ secret. This requires treating the access token with the same care as other secrets (e.g.
+ end-user passwords). Access tokens SHOULD NOT be sent in the clear over an insecure
+ channel.
+
+</P>
+<P>
+ However, when it is necessary to transmit access tokens in the clear without a secure
+ channel, authorization servers SHOULD issue access tokens with limited scope and lifetime
+ to reduce the potential risk from a compromised access token.
+
+</P>
+<P>
+ Clients MUST NOT make authenticated requests with an access token to unfamiliar resource
+ servers, regardless of the presence of a secure channel.
+
+</P>
+<P>
+ The resource server MUST validate the access token and ensure it has not expired and
+ that its scope covers the requested resource. The methods used by the resource server
+ to validate the access token are beyond the scope of this specification, but generally
+ involve an interaction or coordination between the resource server and authorization
+ server.
+
+</P>
+<A name="anchor14"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.5.1"></A><H3>5.1.&nbsp;
+Authenticated Requests</H3>
+
+<P>
+ Clients make authenticated token requests using the
+ <TT>Authorization</TT> request header field. Resource servers MUST
+ accept authenticated requests using the <TT>OAuth</TT> HTTP
+ authentication scheme as described in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#authz-header">Section&nbsp;5.1.1<SPAN> (</SPAN><SPAN class="info">The Authorization Request Header Field</SPAN><SPAN>)</SPAN></A>, and MAY support
+ additional methods.
+
+</P>
+<P>
+ Alternatively, clients MAY attempt to include the access token using the HTTP request
+ URI in the query component as described in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#query-param">Section&nbsp;5.1.2<SPAN> (</SPAN><SPAN class="info">URI Query Parameter</SPAN><SPAN>)</SPAN></A>, or in the HTTP
+ body when using the <TT>application/x-www-form-urlencoded</TT> content
+ type as described in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#body-param">Section&nbsp;5.1.3<SPAN> (</SPAN><SPAN class="info">Form-Encoded Body Parameter</SPAN><SPAN>)</SPAN></A>. Resource server MAY support these
+ alternative methods.
+
+</P>
+<P>
+ Clients SHOULD only use the request URI or body when the
+ <TT>Authorization</TT> request header field is not available, and MUST
+ NOT use more than one method in each request.
+
+</P>
+<A name="authz-header"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.5.1.1"></A><H3>5.1.1.&nbsp;
+The Authorization Request Header Field</H3>
+
+<P>
+ The <TT>Authorization</TT> request header field is used by clients
+ to make authenticated token requests. The client uses the
+ <TT>OAuth</TT> authentication scheme to include the access token in
+ the request.
+
+</P>
+<P>
+ For example:
+
+</P><DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ GET /resource HTTP/1.1
+ Host: server.example.com
+ Authorization: OAuth vF9dft4qmT
+
+</PRE></DIV>
+<P>
+ The <TT>Authorization</TT> header field uses the framework defined by
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#RFC2617">[RFC2617]<SPAN> (</SPAN><SPAN class="info">Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P., Luotonen, A., and L. Stewart, “HTTP Authentication: Basic and Digest Access Authentication,” June&nbsp;1999.</SPAN><SPAN>)</SPAN></A> as follows:
+
+</P><DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ credentials = "OAuth" RWS access-token [ CS 1#auth-param ]
+ access-token = 1*( quoted-char / &lt;"&gt; )
+
+ CS = OWS "," OWS
+
+ quoted-char = "!" / "#" / "$" / "%" / "&amp;" / "'" / "("
+ / ")" / "*" / "+" / "-" / "." / "/" / DIGIT
+ / ":" / "&lt;" / "=" / "&gt;" / "?" / "@" / ALPHA
+ / "[" / "]" / "^" / "_" / "`" / "{" / "|"
+ / "}" / "~" / "\" / "," / ";"
+
+</PRE></DIV>
+<P>
+ </P>
+<BLOCKQUOTE class="text">
+<P>
+ NOTE: <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#RFC5849">[RFC5849]<SPAN> (</SPAN><SPAN class="info">Hammer-Lahav, E., “The OAuth 1.0 Protocol,” April&nbsp;2010.</SPAN><SPAN>)</SPAN></A> defines a different format for the
+ <TT>OAuth</TT> authentication scheme. Resource servers can
+ differentiate between the two protocol versions based on the presence of the
+ <TT>oauth_signature_method</TT> which is REQUIRED in the
+ previous version and is not supported by this specification.
+
+</P>
+</BLOCKQUOTE><P>
+
+</P>
+<A name="query-param"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.5.1.2"></A><H3>5.1.2.&nbsp;
+URI Query Parameter</H3>
+
+<P>
+ When including the access token in the HTTP request URI, the client adds the access
+ token to the request URI query component as defined by <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#RFC3986">[RFC3986]<SPAN> (</SPAN><SPAN class="info">Berners-Lee, T., Fielding, R., and L. Masinter, “Uniform Resource Identifier (URI): Generic Syntax,” January&nbsp;2005.</SPAN><SPAN>)</SPAN></A> using
+ the <TT>oauth_token</TT> parameter.
+
+</P>
+<P>
+ For example, the client makes the following HTTP request using transport-layer
+ security:
+
+</P><DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ GET /resource?oauth_token=vF9dft4qmT HTTP/1.1
+ Host: server.example.com
+
+</PRE></DIV>
+<P>
+ The HTTP request URI query can include other request-specific parameters, in which
+ case, the <TT>oauth_token</TT> parameters SHOULD be appended
+ following the request-specific parameters, properly separated by an
+ <TT>&amp;</TT> character (ASCII code 38).
+
+</P>
+<P>
+ For example:
+
+</P><DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ http://example.com/resource?x=y&amp;oauth_token=vF9dft4qmT
+
+</PRE></DIV>
+<P>
+ </P>
+<BLOCKQUOTE class="text">
+<P>
+ NOTE: The <TT>oauth_token</TT> parameter is used by the previous
+ version of the OAuth protocol as described in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#RFC5849">[RFC5849]<SPAN> (</SPAN><SPAN class="info">Hammer-Lahav, E., “The OAuth 1.0 Protocol,” April&nbsp;2010.</SPAN><SPAN>)</SPAN></A>. Resource
+ servers can differentiate between the two protocol versions based on the presence
+ of the <TT>oauth_signature_method</TT> which is REQUIRED in the
+ previous version and is not supported by this specification.
+
+</P>
+</BLOCKQUOTE><P>
+
+</P>
+<A name="body-param"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.5.1.3"></A><H3>5.1.3.&nbsp;
+Form-Encoded Body Parameter</H3>
+
+<P>
+ When including the access token in the HTTP request entity-body, the client adds the
+ access token to the request body using the <TT>oauth_token</TT>
+ parameter. The client can use this method only if the following REQUIRED conditions are
+ met:
+
+ </P>
+<UL class="text">
+<LI>
+ The entity-body is single-part.
+
+</LI>
+<LI>
+ The entity-body follows the encoding requirements of the
+ <TT>application/x-www-form-urlencoded</TT> content-type as
+ defined by <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#W3C.REC-html401-19991224">[W3C.REC‑html401‑19991224]<SPAN> (</SPAN><SPAN class="info">Raggett, D., Hors, A., and I. Jacobs, “HTML 4.01 Specification,” December&nbsp;1999.</SPAN><SPAN>)</SPAN></A>.
+
+</LI>
+<LI>
+ The HTTP request entity-header includes the <TT>Content-Type</TT>
+ header field set to <TT>application/x-www-form-urlencoded</TT>.
+
+</LI>
+<LI>
+ The HTTP request method is <TT>POST</TT>,
+ <TT>PUT</TT>, or <TT>DELETE</TT>.
+
+</LI>
+</UL><P>
+
+</P>
+<P>
+ The entity-body can include other request-specific parameters, in which case, the
+ <TT>oauth_token</TT> parameters SHOULD be appended following the
+ request-specific parameters, properly separated by an <TT>&amp;</TT>
+ character (ASCII code 38).
+
+</P>
+<P>
+ For example, the client makes the following HTTP request using transport-layer
+ security:
+
+</P><DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ POST /resource HTTP/1.1
+ Host: server.example.com
+ Content-Type: application/x-www-form-urlencoded
+
+ oauth_token=vF9dft4qmT
+
+</PRE></DIV>
+<P>
+ </P>
+<BLOCKQUOTE class="text">
+<P>
+ NOTE: The <TT>oauth_token</TT> parameter is used by the previous
+ version of the OAuth protocol as described in <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#RFC5849">[RFC5849]<SPAN> (</SPAN><SPAN class="info">Hammer-Lahav, E., “The OAuth 1.0 Protocol,” April&nbsp;2010.</SPAN><SPAN>)</SPAN></A>. Resource
+ servers can differentiate between the two protocol versions based on the presence
+ of the <TT>oauth_signature_method</TT> which is REQUIRED in the
+ previous version and is not supported by this specification.
+
+</P>
+</BLOCKQUOTE><P>
+
+</P>
+<A name="authn-header"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.5.2"></A><H3>5.2.&nbsp;
+The WWW-Authenticate Response Header Field</H3>
+
+<P>
+ If the protected resource request contains an invalid access token or is malformed, the
+ resource server MUST include the HTTP <TT>WWW-Authenticate</TT>
+ response header field. The <TT>WWW-Authenticate</TT> header field
+ uses the framework defined by <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#RFC2617">[RFC2617]<SPAN> (</SPAN><SPAN class="info">Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P., Luotonen, A., and L. Stewart, “HTTP Authentication: Basic and Digest Access Authentication,” June&nbsp;1999.</SPAN><SPAN>)</SPAN></A> as follows:
+
+</P><DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ challenge = "OAuth" RWS token-challenge
+
+ token-challenge = realm
+ [ CS error ]
+ [ CS error-desc ]
+ [ CS error-uri ]
+ [ CS scope ]
+ [ CS 1#auth-param ]
+
+ error = "error" "=" &lt;"&gt; token &lt;"&gt;
+ error-desc = "error_description" "=" quoted-string
+ error-uri = "error_uri" = &lt;"&gt; URI-Reference &lt;"&gt;
+ scope = quoted-value /
+ &lt;"&gt; quoted-value *( 1*SP quoted-value ) &lt;"&gt;
+ quoted-value = 1*quoted-char
+
+</PRE></DIV>
+<P>
+ For example:
+
+</P><DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ HTTP/1.1 401 Unauthorized
+ WWW-Authenticate: OAuth realm='Example Service', error='expired-token'
+
+</PRE></DIV>
+<P>
+ The <TT>realm</TT> attribute is used to provide the protected
+ resources partition as defined by <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#RFC2617">[RFC2617]<SPAN> (</SPAN><SPAN class="info">Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P., Luotonen, A., and L. Stewart, “HTTP Authentication: Basic and Digest Access Authentication,” June&nbsp;1999.</SPAN><SPAN>)</SPAN></A>. [[ add explanation ]]
+
+</P>
+<P>
+ The <TT>error</TT> attribute is used to provide the client with the
+ reason why the access request was declined. The parameter values are described in
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#resource-error-codes">Section&nbsp;5.2.1<SPAN> (</SPAN><SPAN class="info">Error Codes</SPAN><SPAN>)</SPAN></A>.
+
+</P>
+<P>
+ The <TT>error_description</TT> attribute provides a human-readable
+ text containing additional information, used to assist in the understanding and
+ resolution of the error occurred.
+
+</P>
+<P>
+ The <TT>error_uri</TT> attribute provides a URI identifying a
+ human-readable web page with information about the error, used to offer the end-user
+ with additional information about the error. If the value is not an absolute URI, it is
+ relative to the URI of the requested protected resource.
+
+</P>
+<P>
+ The <TT>scope</TT> attribute is a space-delimited list of scope values
+ indicating the required scope of the access token for accessing the requested resource.
+
+</P>
+<A name="resource-error-codes"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.5.2.1"></A><H3>5.2.1.&nbsp;
+Error Codes</H3>
+
+<P>
+ The authorization server includes one of the following error codes with the error
+ response:
+
+ </P>
+<BLOCKQUOTE class="text"><DL>
+<DT>invalid_request</DT>
+<DD>
+
+ The request is missing a required parameter, includes an unsupported parameter or
+ parameter value, repeats the same parameter, uses more than one method for
+ including an access token, or is otherwise malformed. The resource server MUST
+ respond with the HTTP 400 (Bad Request) status code.
+
+</DD>
+<DT>invalid_token</DT>
+<DD>
+
+ The access token provided is invalid. Resource servers SHOULD use this error code
+ when receiving an expired token which cannot be refreshed to indicate to the client
+ that a new authorization is necessary. The resource server MUST respond with the
+ HTTP 401 (Unauthorized) status code.
+
+</DD>
+<DT>expired_token</DT>
+<DD>
+
+ The access token provided has expired. Resource servers SHOULD only use this error
+ code when the client is expected to be able to handle the response and request a
+ new access token using the refresh token issued with the expired access token. The
+ resource server MUST respond with the HTTP 401 (Unauthorized) status code.
+
+</DD>
+<DT>insufficient_scope</DT>
+<DD>
+
+ The request requires higher privileges than provided by the access token. The
+ resource server SHOULD respond with the HTTP 403 (Forbidden) status code and MAY
+ include the <TT>scope</TT> attribute with the scope necessary to
+ access the protected resource.
+
+</DD>
+</DL></BLOCKQUOTE><P>
+
+</P>
+<P>
+ [[ Add mechanism for extending error codes ]]
+
+</P>
+<P>
+ If the request lacks any authentication information (i.e. the client was unaware
+ authentication is necessary or attempted using an unsupported authentication method),
+ the resource server SHOULD not include an error code or other error information.
+
+</P>
+<P>
+ For example:
+
+</P><DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ HTTP/1.1 401 Unauthorized
+ WWW-Authenticate: OAuth realm='Example Service'
+
+</PRE></DIV>
+<A name="anchor15"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.6"></A><H3>6.&nbsp;
+Extensibility</H3>
+
+<A name="anchor16"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.6.1"></A><H3>6.1.&nbsp;
+Defining New Client Credentials Types</H3>
+
+<P>
+ [[ TBD ]]
+
+</P>
+<A name="anchor17"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.6.2"></A><H3>6.2.&nbsp;
+Defining New Endpoint Parameters</H3>
+
+<P>
+ Applications that wish to define new request or response parameters for use with the
+ end-user authorization endpoint or the token endpoint SHALL do so in one of two ways:
+ register them in the parameters registry (following the procedures in
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#parameters-registry">Section&nbsp;8.1<SPAN> (</SPAN><SPAN class="info">The OAuth Parameters Registry</SPAN><SPAN>)</SPAN></A>), or use the <TT>x_</TT>
+ parameter name prefix.
+
+</P>
+<P>
+ Parameters utilizing the <TT>x_</TT> parameter name prefix MUST be
+ limited to vendor-specific extensions that are not commonly applicable, and are specific
+ to the implementation details of the authorization server where they are used. All other
+ new parameters MUST be registered, and MUST NOT use the <TT>x_</TT>
+ parameter name prefix.
+
+</P>
+<P>
+ Parameter names MUST conform to the param-name ABNF, and parameter values syntax MUST be
+ well-defined (e.g., using ABNF, or a reference to the syntax of an existing parameter).
+
+</P><DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ param-name = 1*name-char
+ name-char = "-" / "." / "_" / DIGIT / ALPHA
+
+</PRE></DIV>
+<A name="anchor18"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.6.3"></A><H3>6.3.&nbsp;
+Defining New Header Field Parameters</H3>
+
+<P>
+ Applications that wish to define new parameters for use in the OAuth
+ <TT>Authorization</TT> or <TT>WWW-Authenticate</TT>
+ header fields MUST register them in the parameters registry, following the procedures in
+ <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#parameters-registry">Section&nbsp;8.1<SPAN> (</SPAN><SPAN class="info">The OAuth Parameters Registry</SPAN><SPAN>)</SPAN></A>.
+
+</P>
+<P>
+ Parameter names MUST conform to the param-name ABNF and MUST NOT begin with
+ <TT>x_</TT>. Parameter values MUST conform to the param-value ABNF and
+ their syntax MUST be well-defined (e.g., using ABNF, or a reference to the syntax of an
+ existing parameter).
+
+</P><DIV style="display: table; width: 0; margin-left: 3em; margin-right: auto"><PRE>
+ param-value = quoted-value | quoted-string
+
+</PRE></DIV>
+<A name="anchor19"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.6.4"></A><H3>6.4.&nbsp;
+Defining New Access Grant Types</H3>
+
+<P>
+ The assertion access grant type was designed to allow the authorization server to
+ accept additional access grants not specified. Applications that wish to define
+ additional access grant types can do so by utilizing a new or existing assertion type
+ and format.
+
+</P>
+<A name="anchor20"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.7"></A><H3>7.&nbsp;
+Security Considerations</H3>
+
+<P>
+ [[ TBD ]]
+
+</P>
+<A name="anchor21"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.8"></A><H3>8.&nbsp;
+IANA Considerations</H3>
+
+<A name="parameters-registry"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.8.1"></A><H3>8.1.&nbsp;
+The OAuth Parameters Registry</H3>
+
+<P>
+ This document establishes the OAuth parameters registry.
+
+</P>
+<P>
+ Additional parameters to be use in the end-user authorization endpoint request, the
+ end-user authorization endpoint response, the token endpoint request, the token endpoint
+ response, the <TT>Authorization</TT> header field, or the
+ <TT>WWW-Authenticate</TT> header field, are registered on the advice
+ of one or more Designated Experts (appointed by the IESG or their delegate), with a
+ Specification Required (using terminology from <A class="info" href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#RFC5226">[RFC5226]<SPAN> (</SPAN><SPAN class="info">Narten, T. and H. Alvestrand, “Guidelines for Writing an IANA Considerations Section in RFCs,” May&nbsp;2008.</SPAN><SPAN>)</SPAN></A>). However, to
+ allow for the allocation of values prior to publication, the Designated Expert(s) may
+ approve registration once they are satisfied that such a specification will be published.
+
+</P>
+<P>
+ Registration requests should be sent to the [TBD]@ietf.org mailing list for review and
+ comment, with an appropriate subject (e.g., "Request for parameter: example").
+ [[ Note to RFC-EDITOR: The name of the mailing list should be determined in consultation
+ with the IESG and IANA. Suggested name: oauth-ext-review. ]]
+
+</P>
+<P>
+ Before a period of 14 days has passed, the Designated Expert(s) will either approve or
+ deny the registration request, communicating this decision both to the review list and to
+ IANA. Denials should include an explanation and, if applicable, suggestions as to how to
+ make the request successful. Registration requests that are undetermined for a period
+ longer than 21 days can be brought to the IESG's attention (using the iesg@iesg.org
+ mailing list) for resolution.
+
+</P>
+<A name="anchor22"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.8.1.1"></A><H3>8.1.1.&nbsp;
+Registration Template</H3>
+
+<P>
+ </P>
+<BLOCKQUOTE class="text"><DL>
+<DT>Parameter name:</DT>
+<DD>
+ The name requested (e.g., "example").
+
+</DD>
+<DT>Parameter usage location:</DT>
+<DD>
+ The location(s) where parameter can be used. The possible locations are: the
+ end-user authorization endpoint request, the end-user authorization endpoint
+ response, the token endpoint request, the token endpoint response, the
+ <TT>Authorization</TT> header field, or the
+ <TT>WWW-Authenticate</TT> header field.
+
+</DD>
+<DT>Change controller:</DT>
+<DD>
+ For standards-track RFCs, state "IETF". For others, give the name of the
+ responsible party. Other details (e.g., postal address, e-mail address, home page
+ URI) may also be included.
+
+</DD>
+<DT>Specification document(s):</DT>
+<DD>
+ Reference to document that specifies the parameter, preferably including a URI that
+ can be used to retrieve a copy of the document. An indication of the relevant
+ sections may also be included, but is not required.
+
+</DD>
+<DT>Related information:</DT>
+<DD>
+ Optionally, citations to additional documents containing further relevant
+ information.
+
+</DD>
+</DL></BLOCKQUOTE><P>
+
+</P>
+<A name="anchor23"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.8.1.2"></A><H3>8.1.2.&nbsp;
+Example</H3>
+
+<P>
+ The following is the parameter registration request for the
+ <TT>scope</TT> parameter as defined in this specification:
+
+ </P>
+<BLOCKQUOTE class="text"><DL>
+<DT>Parameter name:</DT>
+<DD>
+ scope
+
+</DD>
+<DT>Parameter usage location:</DT>
+<DD>
+ The end-user authorization endpoint request, the end-user authorization endpoint
+ response, the token endpoint request, the token endpoint response, and the
+ <TT>WWW-Authenticate</TT> header field.
+
+</DD>
+<DT>Change controller:</DT>
+<DD>
+ IETF
+
+</DD>
+<DT>Specification document(s):</DT>
+<DD>
+ [[ this document ]]
+
+</DD>
+<DT>Related information:</DT>
+<DD>
+ None
+
+</DD>
+</DL></BLOCKQUOTE><P>
+
+</P>
+<A name="anchor24"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.A"></A><H3>Appendix A.&nbsp;
+Examples</H3>
+
+<P>
+ [[ TBD ]]
+
+</P>
+<A name="anchor25"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.B"></A><H3>Appendix B.&nbsp;
+Contributors</H3>
+
+<P>
+ The following people contributed to preliminary versions of this document:
+ Blaine Cook (BT), Brian Eaton (Google), Yaron Goland (Microsoft), Brent Goldman (Facebook),
+ Raffi Krikorian (Twitter), Luke Shepard (Facebook), and Allen Tom (Yahoo!). The content and
+ concepts within are a product of the OAuth community, WRAP community, and the OAuth Working
+ Group.
+
+</P>
+<P>
+ The OAuth Working Group has dozens of very active contributors who proposed ideas and
+ wording for this document, including: [[ If your name is missing or you think someone
+ should be added here, please send Eran a note - don't be shy ]]
+
+</P>
+<P>
+ Michael Adams, Andrew Arnott, Dirk Balfanz, Brian Campbell, Leah Culver, Brian Ellin,
+ Igor Faynberg, George Fletcher, Evan Gilbert, Justin Hart, John Kemp, Chasen Le Hara,
+ Torsten Lodderstedt, Eve Maler, James Manger, Laurence Miao, Chuck Mortimore,
+ Justin Richer, Peter Saint-Andre, Nat Sakimura, Rob Sayre, Marius Scurtescu, Justin Smith,
+ Jeremy Suriel, and Franklin Tse.
+
+</P>
+<A name="anchor26"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.C"></A><H3>Appendix C.&nbsp;
+Acknowledgements</H3>
+
+<P>
+ [[ Add OAuth 1.0a authors + WG contributors ]]
+
+</P>
+<A name="anchor27"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.D"></A><H3>Appendix D.&nbsp;
+Document History</H3>
+
+<P>
+ [[ to be removed by RFC editor before publication as an RFC ]]
+
+</P>
+<P>
+ -10
+
+ </P>
+<UL class="text">
+<LI>
+ Fixed typos. Many editorial changes. Rewrote introduction. removed terminology
+ grouping.
+
+</LI>
+<LI>
+ Allowed POST for end-user authorization endpoint.
+
+</LI>
+<LI>
+ Fixed token endpoint to not require client authentication.
+
+</LI>
+<LI>
+ Made URI query and POST body 'oauth_token' parameter optional.
+
+</LI>
+<LI>
+ Moved all parameter names and values to use underscores.
+
+</LI>
+<LI>
+ Changed 'basic_credentials' to 'password', 'invalid_client_credentials' and
+ 'invalid_client_id' to 'invalid_client'.
+
+</LI>
+<LI>
+ Added note that access token requests without an access grant should not include
+ a refresh token.
+
+</LI>
+<LI>
+ Changed scheme name from 'Token' to 'OAuth', simplified request format to simple
+ string for token instead of key=value pair (still supported for extensions).
+
+</LI>
+<LI>
+ Defined permitted access token string characters (suitable for inclusion in an HTTP
+ header).
+
+</LI>
+<LI>
+ Added a note about conflicts with previous versions.
+
+</LI>
+<LI>
+ Moved 'client_id' definition from client authentication to access token endpoint.
+
+</LI>
+</UL><P>
+
+</P>
+<P>
+ -09
+
+ </P>
+<UL class="text">
+<LI>
+ Fixed typos, editorial changes.
+
+</LI>
+<LI>
+ Added token expiration example.
+
+</LI>
+<LI>
+ Added scope parameter to end-user authorization endpoint response.
+
+</LI>
+<LI>
+ Added note about parameters with empty values (same as omitted).
+
+</LI>
+<LI>
+ Changed parameter values to use '-' instead of '_'. Parameter names still use '_'.
+
+</LI>
+<LI>
+ Changed authorization endpoint client type to response type with values: code, token,
+ and both.
+
+</LI>
+<LI>
+ Complete cleanup of error codes. Added support for error description and URI.
+
+</LI>
+<LI>
+ Add initial extensibility support.
+
+</LI>
+</UL><P>
+
+</P>
+<P>
+ -08
+
+ </P>
+<UL class="text">
+<LI>
+ Renamed verification code to authorization code.
+
+</LI>
+<LI>
+ Revised terminology, structured section, added new terms.
+
+</LI>
+<LI>
+ Changed flows to profiles and moved to introduction.
+
+</LI>
+<LI>
+ Added support for access token rescoping.
+
+</LI>
+<LI>
+ Cleaned up client credentials section.
+
+</LI>
+<LI>
+ New introduction overview.
+
+</LI>
+<LI>
+ Added error code for invalid username and password, and renamed error code to be more
+ consistent.
+
+</LI>
+<LI>
+ Added access grant type parameter to token endpoint.
+
+</LI>
+</UL><P>
+
+</P>
+<P>
+ -07
+
+ </P>
+<UL class="text">
+<LI>
+ Major rewrite of entire document structure.
+
+</LI>
+<LI>
+ Removed device profile.
+
+</LI>
+<LI>
+ Added verification code support to user-agent flow.
+
+</LI>
+<LI>
+ Removed multiple formats support, leaving JSON as the only format.
+
+</LI>
+<LI>
+ Changed assertion <TT>assertion_format</TT> parameter to
+ <TT>assertion_type</TT>.
+
+</LI>
+<LI>
+ Removed <TT>type</TT> parameter from token endpoint.
+
+</LI>
+</UL><P>
+
+</P>
+<P>
+ -06
+
+ </P>
+<UL class="text">
+<LI>
+ Editorial changes, corrections, clarifications, etc.
+
+</LI>
+<LI>
+ Removed conformance section.
+
+</LI>
+<LI>
+ Moved authors section to contributors appendix.
+
+</LI>
+<LI>
+ Added section on native applications.
+
+</LI>
+<LI>
+ Changed error response to use the requested format. Added support for HTTP
+ <TT>Accept</TT> header.
+
+</LI>
+<LI>
+ Flipped the order of the web server and user-agent flows.
+
+</LI>
+<LI>
+ Renamed assertion flow <TT>format</TT> parameter name to
+ <TT>assertion_format</TT> to resolve conflict.
+
+</LI>
+<LI>
+ Removed the term identifier from token definitions. Added a cryptographic token
+ definition.
+
+</LI>
+<LI>
+ Added figure titles.
+
+</LI>
+<LI>
+ Added server response 401 when client tried to authenticate using multiple credentials.
+
+</LI>
+<LI>
+ Clarified support for TLS alternatives, and added requirement for TLS 1.2 support for
+ token endpoint.
+
+</LI>
+<LI>
+ Removed all signature and cryptography.
+
+</LI>
+<LI>
+ Removed all discovery.
+
+</LI>
+<LI>
+ Updated HTML4 reference.
+
+</LI>
+</UL><P>
+
+</P>
+<P>
+ -05
+
+ </P>
+<UL class="text">
+<LI>
+ Corrected device example.
+
+</LI>
+<LI>
+ Added client credentials parameters to the assertion flow as OPTIONAL.
+
+</LI>
+<LI>
+ Added the ability to send client credentials using an HTTP authentication scheme.
+
+</LI>
+<LI>
+ Initial text for the <TT>WWW-Authenticate</TT> header (also added
+ scope support).
+
+</LI>
+<LI>
+ Change authorization endpoint to end-user endpoint.
+
+</LI>
+<LI>
+ In the device flow, change the <TT>user_uri</TT> parameter to
+ <TT>verification_uri</TT> to avoid confusion with the end-user
+ endpoint.
+
+</LI>
+<LI>
+ Add <TT>format</TT> request parameter and support for XML and
+ form-encoded responses.
+
+</LI>
+</UL><P>
+
+</P>
+<P>
+ -04
+
+ </P>
+<UL class="text">
+<LI>
+ Changed all token endpoints to use <TT>POST</TT>
+
+</LI>
+<LI>
+ Clarified the authorization server's ability to issue a new refresh token when
+ refreshing a token.
+
+</LI>
+<LI>
+ Changed the flow categories to clarify the autonomous group.
+
+</LI>
+<LI>
+ Changed client credentials language not to always be server-issued.
+
+</LI>
+<LI>
+ Added a <TT>scope</TT> response parameter.
+
+</LI>
+<LI>
+ Fixed typos.
+
+</LI>
+<LI>
+ Fixed broken document structure.
+
+</LI>
+</UL><P>
+
+</P>
+<P>
+ -03
+
+ </P>
+<UL class="text">
+<LI>
+ Fixed typo in JSON error examples.
+
+</LI>
+<LI>
+ Fixed general typos.
+
+</LI>
+<LI>
+ Moved all flows sections up one level.
+
+</LI>
+</UL><P>
+
+</P>
+<P>
+ -02
+
+ </P>
+<UL class="text">
+<LI>
+ Removed restriction on <TT>redirect_uri</TT> including a query.
+
+</LI>
+<LI>
+ Added <TT>scope</TT> parameter.
+
+</LI>
+<LI>
+ Initial proposal for a JSON-based token response format.
+
+</LI>
+</UL><P>
+
+</P>
+<P>
+ -01
+
+ </P>
+<UL class="text">
+<LI>
+ Editorial changes based on feedback from Brian Eaton, Bill Keenan, and Chuck Mortimore.
+
+</LI>
+<LI>
+ Changed device flow <TT>type</TT> parameter values and switch to use
+ only the token endpoint.
+
+</LI>
+</UL><P>
+
+</P>
+<P>
+ -00
+
+ </P>
+<UL class="text">
+<LI>
+ Initial draft based on a combination of WRAP and OAuth 1.0a.
+
+</LI>
+</UL><P>
+
+</P>
+<A name="rfc.references"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<A name="rfc.section.9"></A><H3>9.&nbsp;
+References</H3>
+
+<A name="rfc.references1"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<H3>9.1.&nbsp;Normative References</H3>
+<TABLE width="99%" border="0">
+<TBODY><TR><TD class="author-text" valign="top"><A name="I-D.ietf-httpbis-p1-messaging">[I-D.ietf-httpbis-p1-messaging]</A></TD>
+<TD class="author-text">Fielding, R., Gettys, J., Mogul, J., Nielsen, H., Masinter, L., Leach, P., Berners-Lee, T., and J. Reschke, “<A href="http://www.ietf.org/internet-drafts/draft-ietf-httpbis-p1-messaging-09.txt">HTTP/1.1, part 1: URIs, Connections, and Message Parsing</A>,” draft-ietf-httpbis-p1-messaging-09 (work in progress), March&nbsp;2010 (<A href="http://www.ietf.org/internet-drafts/draft-ietf-httpbis-p1-messaging-09.txt">TXT</A>).</TD></TR>
+<TR><TD class="author-text" valign="top"><A name="NIST FIPS-180-3">[NIST FIPS-180-3]</A></TD>
+<TD class="author-text">National Institute of Standards and Technology, “<A href="http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf">Secure Hash Standard (SHS). FIPS PUB 180-3, October 2008</A>.”</TD></TR>
+<TR><TD class="author-text" valign="top"><A name="RFC2045">[RFC2045]</A></TD>
+<TD class="author-text"><A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=ned@innosoft.com&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">Freed, N.</A> and <A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=nsb@nsb.fv.com&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">N. Borenstein</A>, “<A href="http://tools.ietf.org/html/rfc2045">Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies</A>,” RFC&nbsp;2045, November&nbsp;1996 (<A href="http://www.rfc-editor.org/rfc/rfc2045.txt">TXT</A>).</TD></TR>
+<TR><TD class="author-text" valign="top"><A name="RFC2104">[RFC2104]</A></TD>
+<TD class="author-text"><A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=hugo@watson.ibm.com&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">Krawczyk, H.</A>, <A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=mihir@cs.ucsd.edu&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">Bellare, M.</A>, and <A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=canetti@watson.ibm.com&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">R. Canetti</A>, “<A href="http://tools.ietf.org/html/rfc2104">HMAC: Keyed-Hashing for Message Authentication</A>,” RFC&nbsp;2104, February&nbsp;1997 (<A href="http://www.rfc-editor.org/rfc/rfc2104.txt">TXT</A>).</TD></TR>
+<TR><TD class="author-text" valign="top"><A name="RFC2119">[RFC2119]</A></TD>
+<TD class="author-text"><A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=sob@harvard.edu&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">Bradner, S.</A>, “<A href="http://tools.ietf.org/html/rfc2119">Key words for use in RFCs to Indicate Requirement Levels</A>,” BCP&nbsp;14, RFC&nbsp;2119, March&nbsp;1997 (<A href="http://www.rfc-editor.org/rfc/rfc2119.txt">TXT</A>, <A href="http://xml.resource.org/public/rfc/html/rfc2119.html">HTML</A>, <A href="http://xml.resource.org/public/rfc/xml/rfc2119.xml">XML</A>).</TD></TR>
+<TR><TD class="author-text" valign="top"><A name="RFC2616">[RFC2616]</A></TD>
+<TD class="author-text"><A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=fielding@ics.uci.edu&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">Fielding, R.</A>, <A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=jg@w3.org&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">Gettys, J.</A>, <A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=mogul@wrl.dec.com&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">Mogul, J.</A>, <A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=frystyk@w3.org&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">Frystyk, H.</A>, <A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=masinter@parc.xerox.com&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">Masinter, L.</A>, <A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=paulle@microsoft.com&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">Leach, P.</A>, and <A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=timbl@w3.org&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">T. Berners-Lee</A>, “<A href="http://tools.ietf.org/html/rfc2616">Hypertext Transfer Protocol -- HTTP/1.1</A>,” RFC&nbsp;2616, June&nbsp;1999 (<A href="http://www.rfc-editor.org/rfc/rfc2616.txt">TXT</A>, <A href="http://www.rfc-editor.org/rfc/rfc2616.ps">PS</A>, <A href="http://www.rfc-editor.org/rfc/rfc2616.pdf">PDF</A>, <A href="http://xml.resource.org/public/rfc/html/rfc2616.html">HTML</A>, <A href="http://xml.resource.org/public/rfc/xml/rfc2616.xml">XML</A>).</TD></TR>
+<TR><TD class="author-text" valign="top"><A name="RFC2617">[RFC2617]</A></TD>
+<TD class="author-text"><A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=john@math.nwu.edu&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">Franks, J.</A>, <A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=pbaker@verisign.com&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">Hallam-Baker, P.</A>, <A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=jeff@AbiSource.com&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">Hostetler, J.</A>, <A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=lawrence@agranat.com&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">Lawrence, S.</A>, <A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=paulle@microsoft.com&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">Leach, P.</A>, Luotonen, A., and <A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=stewart@OpenMarket.com&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">L. Stewart</A>, “<A href="http://tools.ietf.org/html/rfc2617">HTTP Authentication: Basic and Digest Access Authentication</A>,” RFC&nbsp;2617, June&nbsp;1999 (<A href="http://www.rfc-editor.org/rfc/rfc2617.txt">TXT</A>, <A href="http://xml.resource.org/public/rfc/html/rfc2617.html">HTML</A>, <A href="http://xml.resource.org/public/rfc/xml/rfc2617.xml">XML</A>).</TD></TR>
+<TR><TD class="author-text" valign="top"><A name="RFC2818">[RFC2818]</A></TD>
+<TD class="author-text">Rescorla, E., “<A href="http://tools.ietf.org/html/rfc2818">HTTP Over TLS</A>,” RFC&nbsp;2818, May&nbsp;2000 (<A href="http://www.rfc-editor.org/rfc/rfc2818.txt">TXT</A>).</TD></TR>
+<TR><TD class="author-text" valign="top"><A name="RFC3023">[RFC3023]</A></TD>
+<TD class="author-text">Murata, M., St. Laurent, S., and D. Kohn, “<A href="http://tools.ietf.org/html/rfc3023">XML Media Types</A>,” RFC&nbsp;3023, January&nbsp;2001 (<A href="http://www.rfc-editor.org/rfc/rfc3023.txt">TXT</A>).</TD></TR>
+<TR><TD class="author-text" valign="top"><A name="RFC3447">[RFC3447]</A></TD>
+<TD class="author-text">Jonsson, J. and B. Kaliski, “<A href="http://tools.ietf.org/html/rfc3447">Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1</A>,” RFC&nbsp;3447, February&nbsp;2003 (<A href="http://www.rfc-editor.org/rfc/rfc3447.txt">TXT</A>).</TD></TR>
+<TR><TD class="author-text" valign="top"><A name="RFC3629">[RFC3629]</A></TD>
+<TD class="author-text">Yergeau, F., “<A href="http://tools.ietf.org/html/rfc3629">UTF-8, a transformation format of ISO 10646</A>,” STD&nbsp;63, RFC&nbsp;3629, November&nbsp;2003 (<A href="http://www.rfc-editor.org/rfc/rfc3629.txt">TXT</A>).</TD></TR>
+<TR><TD class="author-text" valign="top"><A name="RFC3986">[RFC3986]</A></TD>
+<TD class="author-text"><A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=timbl@w3.org&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">Berners-Lee, T.</A>, <A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=fielding@gbiv.com&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">Fielding, R.</A>, and <A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=LMM@acm.org&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">L. Masinter</A>, “<A href="http://tools.ietf.org/html/rfc3986">Uniform Resource Identifier (URI): Generic Syntax</A>,” STD&nbsp;66, RFC&nbsp;3986, January&nbsp;2005 (<A href="http://www.rfc-editor.org/rfc/rfc3986.txt">TXT</A>, <A href="http://xml.resource.org/public/rfc/html/rfc3986.html">HTML</A>, <A href="http://xml.resource.org/public/rfc/xml/rfc3986.xml">XML</A>).</TD></TR>
+<TR><TD class="author-text" valign="top"><A name="RFC4627">[RFC4627]</A></TD>
+<TD class="author-text">Crockford, D., “<A href="http://tools.ietf.org/html/rfc4627">The application/json Media Type for JavaScript Object Notation (JSON)</A>,” RFC&nbsp;4627, July&nbsp;2006 (<A href="http://www.rfc-editor.org/rfc/rfc4627.txt">TXT</A>).</TD></TR>
+<TR><TD class="author-text" valign="top"><A name="RFC5226">[RFC5226]</A></TD>
+<TD class="author-text">Narten, T. and H. Alvestrand, “<A href="http://tools.ietf.org/html/rfc5226">Guidelines for Writing an IANA Considerations Section in RFCs</A>,” BCP&nbsp;26, RFC&nbsp;5226, May&nbsp;2008 (<A href="http://www.rfc-editor.org/rfc/rfc5226.txt">TXT</A>).</TD></TR>
+<TR><TD class="author-text" valign="top"><A name="RFC5246">[RFC5246]</A></TD>
+<TD class="author-text">Dierks, T. and E. Rescorla, “<A href="http://tools.ietf.org/html/rfc5246">The Transport Layer Security (TLS) Protocol Version 1.2</A>,” RFC&nbsp;5246, August&nbsp;2008 (<A href="http://www.rfc-editor.org/rfc/rfc5246.txt">TXT</A>).</TD></TR>
+<TR><TD class="author-text" valign="top"><A name="RFC5849">[RFC5849]</A></TD>
+<TD class="author-text">Hammer-Lahav, E., “<A href="http://tools.ietf.org/html/rfc5849">The OAuth 1.0 Protocol</A>,” RFC&nbsp;5849, April&nbsp;2010 (<A href="http://www.rfc-editor.org/rfc/rfc5849.txt">TXT</A>).</TD></TR>
+<TR><TD class="author-text" valign="top"><A name="W3C.REC-html401-19991224">[W3C.REC-html401-19991224]</A></TD>
+<TD class="author-text">Raggett, D., Hors, A., and I. Jacobs, “<A href="http://www.w3.org/TR/1999/REC-html401-19991224">HTML 4.01 Specification</A>,” World Wide Web Consortium Recommendation&nbsp;REC-html401-19991224, December&nbsp;1999 (<A href="http://www.w3.org/TR/1999/REC-html401-19991224">HTML</A>).</TD></TR>
+</TBODY></TABLE>
+
+<A name="rfc.references2"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<H3>9.2.&nbsp;Informative References</H3>
+<TABLE width="99%" border="0">
+<TBODY><TR><TD class="author-text" valign="top"><A name="I-D.hammer-oauth">[I-D.hammer-oauth]</A></TD>
+<TD class="author-text">Hammer-Lahav, E., “<A href="http://www.ietf.org/internet-drafts/draft-hammer-oauth-10.txt">The OAuth 1.0 Protocol</A>,” draft-hammer-oauth-10 (work in progress), February&nbsp;2010 (<A href="http://www.ietf.org/internet-drafts/draft-hammer-oauth-10.txt">TXT</A>).</TD></TR>
+<TR><TD class="author-text" valign="top"><A name="I-D.hardt-oauth">[I-D.hardt-oauth]</A></TD>
+<TD class="author-text">Hardt, D., Tom, A., Eaton, B., and Y. Goland, “<A href="http://www.ietf.org/internet-drafts/draft-hardt-oauth-01.txt">OAuth Web Resource Authorization Profiles</A>,” draft-hardt-oauth-01 (work in progress), January&nbsp;2010 (<A href="http://www.ietf.org/internet-drafts/draft-hardt-oauth-01.txt">TXT</A>).</TD></TR>
+<TR><TD class="author-text" valign="top"><A name="OASIS.saml-core-2.0-os">[OASIS.saml-core-2.0-os]</A></TD>
+<TD class="author-text"><A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=cantor.2@osu.edu&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">Cantor, S.</A>, <A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=John.Kemp@nokia.com&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">Kemp, J.</A>, <A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=rphilpott@rsasecurity.com&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">Philpott, R.</A>, and <A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=eve.maler@sun.com&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">E. Maler</A>, “<A href="http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf">Assertions and Protocol for the OASIS Security Assertion Markup Language
+ (SAML) V2.0</A>,” OASIS Standard&nbsp;saml-core-2.0-os, March&nbsp;2005.</TD></TR>
+</TBODY></TABLE>
+
+<A name="rfc.authors"></A><BR><HR>
+<TABLE summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><TBODY><TR><TD class="TOCbug"><A href="http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#toc">&nbsp;TOC&nbsp;</A></TD></TR></TBODY></TABLE>
+<H3>Authors' Addresses</H3>
+<TABLE width="99%" border="0" cellpadding="0" cellspacing="0">
+<TBODY><TR><TD class="author-text">&nbsp;</TD>
+<TD class="author-text">Eran Hammer-Lahav (editor)</TD></TR>
+<TR><TD class="author-text">&nbsp;</TD>
+<TD class="author-text">Yahoo!</TD></TR>
+<TR><TD class="author" align="right">Email:&nbsp;</TD>
+<TD class="author-text"><A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=eran@hueniverse.com&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">eran@hueniverse.com</A></TD></TR>
+<TR><TD class="author" align="right">URI:&nbsp;</TD>
+<TD class="author-text"><A href="http://hueniverse.com/">http://hueniverse.com</A></TD></TR>
+<TR cellpadding="3"><TD>&nbsp;</TD><TD>&nbsp;</TD></TR>
+<TR><TD class="author-text">&nbsp;</TD>
+<TD class="author-text">David Recordon</TD></TR>
+<TR><TD class="author-text">&nbsp;</TD>
+<TD class="author-text">Facebook</TD></TR>
+<TR><TD class="author" align="right">Email:&nbsp;</TD>
+<TD class="author-text"><A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=davidrecordon@facebook.com&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">davidrecordon@facebook.com</A></TD></TR>
+<TR><TD class="author" align="right">URI:&nbsp;</TD>
+<TD class="author-text"><A href="http://www.davidrecordon.com/">http://www.davidrecordon.com/</A></TD></TR>
+<TR cellpadding="3"><TD>&nbsp;</TD><TD>&nbsp;</TD></TR>
+<TR><TD class="author-text">&nbsp;</TD>
+<TD class="author-text">Dick Hardt</TD></TR>
+<TR><TD class="author-text">&nbsp;</TD>
+<TD class="author-text">Microsoft</TD></TR>
+<TR><TD class="author" align="right">Email:&nbsp;</TD>
+<TD class="author-text"><A href="javascript:void(0)" onclick="window.open(&#39;http://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;to=dick.hardt@gmail.com&#39;,&#39;Compose new message&#39;,&#39;width=640,height=480&#39;)" rel="noreferrer">dick.hardt@gmail.com</A></TD></TR>
+<TR><TD class="author" align="right">URI:&nbsp;</TD>
+<TD class="author-text"><A href="http://dickhardt.org/">http://dickhardt.org/</A></TD></TR>
+</TBODY></TABLE>
+
+</BODY><STYLE type="text/css">#AdContainer,#RadAd_Skyscraper,#ad-frame,#bbccom_leaderboard,#bbccom_mpu,#center_banner,#footer_adcode,#hbBHeaderSpon,#header_adcode,#hiddenHeaderSpon,#navbar_adcode,#pagelet_adbox,#rightAds,#rightcolumn_adcode,#top-advertising,#topMPU,#tracker_advertorial,.ad-now,.adbox,.adspot,.dfpad,.prWrap,.sponsored,[id^="ad_block"],[id^="adbrite"],[id^="dclkAds"],[id^="konaLayer"],[id^="ew"][id$="_bannerDiv"],a.kLink span[id^="preLoadWrap"][class="preLoadWrap"],A[href^="http://adserver.adpredictive.com"],A[href^="http://ad."][href*=".doubleclick.net/"],div[class^="dms_ad_IDS"],DIV[id="adxLeaderboard"],DIV[id="rm_container"],div[id^="sponsorads"],div[id^="y5_direct"],DIV[id="FFN_Banner_Holder"],DIV[id="FFN_imBox_Container"],DIV[id="p360-format-box"],div[id="tooltipbox"][class^="itxt"],div[id^="adKontekst_"],div[id^="google_ads_div"],div[id^="kona_"][id$="_wrapper"],div[class="wnDVUtilityBlock"],embed[flashvars*="AdID"],embed[id="Advertisement"][name="Advertisement"],iframe[class="chitikaAdBlock"],iframe[id^="dapIfM"],iframe[name^="AdBrite"],iframe[name^="google_ads_"],iframe[src*="clicksor.com"],img[src*="clicksor.com"],IMG[src^="http://cdn.adnxs.com"],ispan#ab_pointer,object[id="flashad"],object[id="ve_threesixty_swf"][name="ve_threesixty_swf"],[src*="sixsigmatraffic.com"],div#dir_ads_site,div#tads table[align="center"][width="100%"],div#rhs div#rhs_block table#mbEnd,#A9AdsMiddleBoxTop,#A9AdsOutOfStockWidgetTop,#A9AdsServicesWidgetTop,#AD_CONTROL_22,#ADsmallWrapper,#Ad1,#Ad2,#Ad3Left,#Ad3Right,#AdBanner_F1,#AdBar1,#AdContainerTop,#AdHeader,#AdMiddle,#AdRectangle,#AdSenseDiv,#AdShowcase_F1,#AdSky23,#AdSkyscraper,#AdSponsor_SF,#AdTargetControl1_iframe,#AdText,#Ad_Block,#Ad_Center1,#Ad_Top,#Adbanner,#Adrectangle,#AdsContent,#AdsWrap,#AdvertMPU23b,#AdvertiseFrame,#Advertisement,#Advertorial,#BannerAdvert,#BigBoxAd,#CompanyDetailsNarrowGoogleAdsPresentationControl,#CompanyDetailsWideGoogleAdsPresentationControl,#ContentAd,#ContentAd1,#ContentAd2,#ContentAdPlaceHolder1,#ContentAdPlaceHolder2,#ContentAdXXL,#ContentPolepositionAds_Result,#FooterAd,#FooterAdContainer,#GoogleAdsense,#HEADERAD,#HOME_TOP_RIGHT_BOXAD,#HeaderAdsBlock,#HeaderAdsBlockFront,#HeaderBannerAdSpacer,#HeaderTextAd,#HeroAd,#HomeAd1,#HouseAd,#ID_Ad_Sky,#Journal_Ad_125,#Journal_Ad_300,#LeftAd,#LeftAdF1,#LeftAdF2,#LowerContentAd,#PREFOOTER_LEFT_BOXAD,#PREFOOTER_RIGHT_BOXAD,#PageLeaderAd,#RightAd,#RightSponsoredAd,#SectionAd300-250,#SidebarAdContainer,#SkyAd,#SpecialAds,#SponsoredAd,#TOP_ADROW,#TOP_RIGHT_BOXAD,#TopAdPos,#VM-MPU-adspace,#VM-footer-adspace,#VM-header-adspace,#VM-header-adwrap,#XEadLeaderboard,#XEadSkyscraper,#_ads,#ad-120x600-sidebar,#ad-160x600,#ad-160x600-sidebar,#ad-250x300,#ad-300,#ad-300x250,#ad-300x250-sidebar,#ad-300x250Div,#ad-728,#ad-article,#ad-banner,#ad-bottom,#ad-bottom-wrapper,#ad-colB-1,#ad-column,#ad-container,#ad-footer,#ad-footprint-160x600,#ad-front-footer,#ad-front-sponsoredlinks,#ad-halfpage,#ad-label,#ad-leaderboard,#ad-leaderboard-bottom,#ad-leaderboard-spot,#ad-leaderboard-top,#ad-left,#ad-list-row,#ad-lrec,#ad-medium-rectangle,#ad-middlethree,#ad-middletwo,#ad-module,#ad-mpu,#ad-mpu1-spot,#ad-mpu2-spot,#ad-placard,#ad-rectangle,#ad-righttop,#ad-side-text,#ad-skyscraper,#ad-slug-wrapper,#ad-space,#ad-splash,#ad-spot,#ad-target,#ad-target-Leaderbord,#ad-teaser,#ad-top,#ad-top-text-low,#ad-tower,#ad-trailerboard-spot,#ad-typ1,#ad-west,#ad-wrap,#ad-wrap-right,#ad-wrapper,#ad-wrapper1,#ad-yahoo-simple,#ad1,#ad125BL,#ad125BR,#ad125TL,#ad125TR,#ad125x125,#ad160x600,#ad160x600right,#ad1Sp,#ad2,#ad2Sp,#ad3,#ad300,#ad300-250,#ad300X250,#ad300_x_250,#ad300x150,#ad300x250,#ad300x250Module,#ad300x60,#ad300x600,#ad300x600_callout,#ad336,#ad336x280,#ad375x85,#ad468,#ad468x60,#ad526x250,#ad600,#ad7,#ad728,#ad728Wrapper,#ad728x90,#adB,#adBadges,#adBanner,#adBanner120x600,#adBannerTable,#adBannerTop,#adBar,#adBlock125,#adBlocks,#adBox,#adContainer,#adDiv,#adFps,#adFtofrs,#adGallery,#adGroup1,#adHeader,#adL,#adLB,#adLeaderboard,#adMPU,#adMiddle0Frontpage,#adMiniPremiere,#adP,#adPlaceHolderRight,#adRight,#adSenseModule,#adServer_marginal,#adSidebar,#adSidebarSq,#adSky,#adSkyscraper,#adSlider,#adSpace3,#adSpace300_ifrMain,#adSpace4,#adSpace5,#adSpace6,#adSpace7,#adSpace_footer,#adSpace_top,#adSpecial,#adSpot-Leader,#adSpot-banner,#adSpot-mrec1,#adSpot-sponsoredlinks,#adSpot-textbox1,#adSpot-widestrip,#adSpotAdvertorial,#adSpotIsland,#adSpotSponsoredLinks,#adSquare,#adStaticA,#adStrip,#adSuperPremiere,#adTableCell,#adTag1,#adTag2,#adText,#adText_container,#adTop,#adTopboxright,#adUnit,#adWrapper,#adZoneTop,#ad_160x160,#ad_160x600,#ad_190x90,#ad_300,#ad_300_250,#ad_300x250,#ad_468_60,#ad_5,#ad_728_foot,#ad_728x90,#ad_A,#ad_B,#ad_Banner,#ad_C,#ad_C2,#ad_D,#ad_E,#ad_F,#ad_G,#ad_H,#ad_I,#ad_J,#ad_K,#ad_L,#ad_M,#ad_N,#ad_O,#ad_P,#ad_YieldManager-300x250,#ad_anchor,#ad_banner,#ad_banner_top,#ad_bar,#ad_block_1,#ad_block_2,#ad_bottom,#ad_box_colspan,#ad_branding,#ad_bs_area,#ad_center_monster,#ad_container,#ad_content_wrap,#ad_feature,#ad_footer,#ad_haha_1,#ad_haha_4,#ad_halfpage,#ad_head,#ad_header,#ad_horseshoe_left,#ad_horseshoe_right,#ad_horseshoe_spacer,#ad_horseshoe_top,#ad_hotpots,#ad_island,#ad_label,#ad_layer2,#ad_leader,#ad_leaderBoard,#ad_leaderboard,#ad_lwr_square,#ad_medium_rectangle,#ad_medium_rectangular,#ad_middle,#ad_mpu,#ad_mrcontent,#ad_overlay,#ad_play_300,#ad_rect,#ad_rect_body,#ad_rect_bottom,#ad_rectangle,#ad_related_links_div,#ad_related_links_div_program,#ad_replace_div_1,#ad_report_leaderboard,#ad_report_rectangle,#ad_right,#ad_right_main,#ad_ros_tower,#ad_rr_1,#ad_sidebar1,#ad_sidebar2,#ad_sidebar3,#ad_skyscraper,#ad_slot_livesky,#ad_space,#ad_square,#ad_ss,#ad_term_bottom_place,#ad_top,#ad_top_holder,#ad_tp_banner_1,#ad_tp_banner_2,#ad_vertical,#ad_window,#ad_wrapper,#adbanner,#adbnr,#adboard,#adbottom,#adbox,#adbox2,#adclear,#adcode1,#adcode2,#adcode3,#adcode4,#adcolumnwrapper,#adcontainer,#adcontainsm,#adcontrolPushSite,#addiv-bottom,#addiv-top,#adfooter_728x90,#adframe:not(frameset),#adhead,#adhead_g,#adheader,#adhome,#adiframe1_iframe,#adiframe2_iframe,#adiframe3_iframe,#adimg,#adition_content_ad,#adlabel,#adlabelFooter,#adleaderboard,#adlinks,#adlinkws,#admid,#admiddle3center,#admiddle3left,#adposition,#adposition-C,#adposition-FPMM,#adposition2,#adposition3,#adposition4,#adrectanglea,#adrectangleb,#adright,#adright2,#ads,#ads-468,#ads-area,#ads-block,#ads-bot,#ads-bottom,#ads-dell,#ads-horizontal,#ads-indextext,#ads-leaderboard1,#ads-lrec,#ads-prices,#ads-rhs,#ads-top,#ads160left,#ads2,#ads300,#ads336x280,#ads7,#ads728bottom,#ads728top,#ads790,#adsDisplay,#adsID,#ads_160,#ads_300,#ads_728,#ads_belowforumlist,#ads_belownav,#ads_bottom_outer,#ads_catDiv,#ads_footer,#ads_right,#ads_sidebar_roadblock,#ads_top,#adsbottom,#adscolumn,#adsense,#adsense-text,#adsenseWrap,#adsense_inline,#adsense_leaderboard,#adsense_placeholder_2,#adsensetopplay,#adskyscraper,#adslot,#adsonar,#adspace,#adspace-300x250,#adspace300x250,#adspaceBox,#adspaceBox300,#adspace_header,#adspot-a,#adsright,#adstop,#adt,#adtech_googleslot_03c,#adtech_takeover,#adtop,#adv-masthead,#adv_google_300,#adv_google_728,#adv_top_banner_wrapper,#adv_wide_banner,#adver1,#adver2,#adver3,#adver4,#advert,#advert-1,#advert-boomer,#advert-display,#advert-header,#advert-leaderboard,#advert-top,#advert1,#advertBanner,#advert_250x250,#advert_box,#advert_leaderboard,#advert_lrec_format,#advert_mpu,#advertbox,#advertbox2,#advertbox3,#advertbox4,#adverthome,#advertise,#advertise-now,#advertise1,#advertisement,#advertisement160x600,#advertisement728x90,#advertisementLigatus,#advertisementPrio2,#advertiser-container,#advertiserLinks,#advertising,#advertising-skyscraper,#advertisingModule160x600,#advertisingModule728x90,#advertorial,#adwhitepaperwidget,#adwin_rec,#adwith,#adwords-4-container,#adwrapper,#adxtop,#adzerk,#adzoneBANNER,#agi-ad300x250,#agi-ad300x250overlay,#agi-sponsored,#anchorAd,#annoying_ad,#ap_adframe,#araHealthSponsorAd,#article-ad-container,#article-box-ad,#articleAdReplacement,#articleSideAd,#article_ad,#article_box_ad,#asinglead,#atlasAdDivGame,#banner-ad,#banner-ad-container,#banner-ads,#banner468x60,#banner728x90,#bannerAd,#bannerAdTop,#bannerAd_ctr,#banner_ad,#banner_ads,#banner_topad,#bannerad,#bannerad2,#bbccom_mpu,#bbo_ad1,#bg_YieldManager-300x250,#bigAd,#bigBoxAd,#bigadbox,#bigadspot,#billboard_ad,#block-ad_cube-1,#block-thewrap_ads_250x300-0,#block_advert,#blox-big-ad,#blox-halfpage-ad,#blox-tile-ad,#botad,#bott_ad2,#bott_ad2_300,#bottom-ad-container,#bottom-ads,#bottomAd,#bottomAdCCBucket,#bottomAdContainer,#bottomAdSense,#bottomAdSenseDiv,#bottomAds,#bottomRightAd,#bottomRightAdSpace,#bottom_ad,#bottom_ad_area,#bottom_ads,#bottom_banner_ad,#bottom_overture,#bottom_sponsor_ads,#bottom_sponsored_links,#bottom_text_ad,#bottomad,#bottomadsense,#box-googleadsense-1,#box-googleadsense-r,#box1ad,#boxAd300,#boxAdContainer,#box_ad,#box_mod_googleadsense,#boxad1,#boxad2,#boxad3,#boxad4,#boxad5,#bps-header-ad-container,#btr_horiz_ad,#burn_header_ad,#button-ads-horizontal,#button-ads-vertical,#button_ad_container,#button_ad_wrap,#cellAd,#channel_ad,#channel_ads,#ciHomeRHSAdslot,#circ_ad,#cnnRR336ad,#cnnTopAd,#colRightAd,#column4-google-ads,#commercial_ads,#common_right_lower_player_adspace,#common_right_player_adspace,#common_top_adspace,#containerLocalAds,#containerMrecAd,#content-ad-header,#contentAd,#content_ad,#content_ad_square,#content_ad_top,#content_ads_content,#content_box_300body_sponsoredoffers,#content_box_adright300_google,#contentad,#contentad_imtext,#contentad_right,#contentads,#contentinlineAd,#contextual-ads-block,#contextualad,#coverads,#ctl00_BottomAd,#ctl00_LHTowerAd,#ctl00_LeftHandAd,#ctl00_MasterHolder_IBanner_adHolder,#ctl00_TopAd,#ctl00_TowerAd,#ctl00_VBanner_adHolder,#ctl00_adFooter,#ctl00_atop_bt,#ctl00_cphMain_hlAd1,#ctl00_cphMain_hlAd2,#ctl00_cphMain_hlAd3,#ctl00_ctl00_MainPlaceHolder_itvAdSkyscraper,#ctl00_ctl00_ctl00_Main_Main_PlaceHolderGoogleTopBanner_MPTopBannerAd,#ctl00_ctl00_ctl00_Main_Main_SideBar_MPSideAd,#ctl00_ctl00_ctl00_tableAdsTop,#ctl00_m_skinTracker_m_adLBL,#ctl00_phCrackerMain_ucAffiliateAdvertDisplayMiddle_pnlAffiliateAdvert,#ctl00_phCrackerMain_ucAffiliateAdvertDisplayRight_pnlAffiliateAdvert,#ctrlsponsored,#cubeAd,#cube_ads,#cube_ads_inner,#cubead,#cubead-2,#dc-display-right-ad-1,#dcol-sponsored,#defer-adright,#detail_page_vid_topads,#divAd,#divAdBox,#divWrapper_Ad,#div_video_ads,#dlads,#dni-header-ad,#download_ads,#ds-mpu,#editorsmpu,#evotopTen_advert,#exads,#featuread,#featuredAdContainer2,#featuredAds,#feed_links_ad_container,#first_ad_unit,#firstad,#fl_hdrAd,#footer-ad,#footer-sponsored,#footerAd,#footerAdDiv,#footerAds,#footerAdverts,#footer_ad,#footer_ad_block,#footer_ads,#footer_adspace,#footer_text_ad,#footerad,#fr_ad_center,#frnContentAd,#from_our_sponsors,#front_advert,#front_mpu,#ft-ad,#ft-ad-1,#ft-ad-container,#ft_mpu,#fusionad,#fw-advertisement,#g_ad,#g_adsense,#ga_300x250,#gad,#gallery-ad-m0,#gallery_ads,#game-info-ad,#global_header_ad_area,#gmi-ResourcePageAd,#gmi-ResourcePageLowerAd,#google-ad,#google-ad-art,#google-ad-tower,#google-ads,#google-ads-bottom,#google-ads-left-side,#google-adsense-mpusize,#googleAd,#googleAds,#googleAdsense,#googleAdsenseBanner,#googleAdsenseBannerBlog,#googleAdwordsModule,#googleAfcContainer,#googleShoppingAdsRight,#googleShoppingAdsTop,#google_ad,#google_ad_test,#google_ads,#google_ads_frame1,#google_ads_test,#googlead,#googleads,#googlesponsor,#grid_ad,#gsyadrectangleload,#gsyadrightload,#gsyadtop,#gsyadtopload,#gtopadvts,#halfPageAd,#halfe-page-ad-box,#hdtv_ad_ss,#head-ad,#head_advert,#header-ad,#header-ads,#header-advert,#headerAd,#headerAdBackground,#headerAdContainer,#headerAdWrap,#headerAdsWrapper,#headerTopAd,#header_ad,#header_adcode,#header_ads,#header_advertisement_top,#header_leaderboard_ad_container,#headerad,#headeradbox,#headline_ad,#hiddenadAC,#homeTopRightAd,#home_ad,#home_contentad,#home_spensoredlinks,#homepage-ad,#homepage_right_ad,#homepage_right_ad_container,#hometop_234x60ad,#hor_ad,#horizontal-banner-ad,#horizontal_ad,#horizontal_ad_top,#horizontalads,#houseAd,#hp-store-ad,#hpV2_300x250Ad,#hpV2_googAds,#icePage_SearchLinks_AdRightDiv,#icePage_SearchLinks_DownloadToolbarAdRightDiv,#indexad,#inlinead,#inlinegoogleads,#inner-advert-row,#insider_ad_wrapper,#instoryad,#int-ad,#interstitial_ad_wrapper,#islandAd,#j_ad,#jmp-ad-buttons,#joead,#joead2,#ka_adRightSkyscraperWide,#landing-adserver,#largead,#lateAd,#lb-sponsor-left,#lb-sponsor-right,#leader-board-ad,#leader-sponsor,#leaderAdContainer,#leaderad,#leaderad_section,#leaderboard-ad,#leaderboard-bottom-ad,#leaderboard_ad,#left-ad-skin,#leftAdContainer,#leftAd_rdr,#leftAdvert,#leftSectionAd300-100,#left_ad,#left_adspace,#leftad,#leftads,#lg-banner-ad,#linkAds,#live-ad,#longAdSpace,#lowerthirdad,#mBannerAd,#main-ad,#main-ad160x600,#main-ad160x600-img,#main-ad728x90,#mainAd,#mainAdUnit,#mainAdvert,#main_ad,#main_rec_ad,#mastAdvert,#mastad,#masthead_ad,#masthead_topad,#medRecAd,#media_ad,#menuAds,#mi_story_assets_ad,#mid-ad300x250,#mid-table-ad,#mid_ad_title,#mid_mpu,#middlead,#middleads,#midrect_ad,#midstrip_ad,#mini-ad,#module-google_ads,#module_ad,#module_box_ad,#moogleAd,#most_popular_ad,#mpu,#mpu-advert,#mpuAd,#mpuDiv,#mpuWrapper,#mpuWrapperAd,#mpu_banner,#mpu_holder,#mpu_text_ad,#mpuad,#mrecAdContainer,#ms_ad,#msad,#multiLinkAdContainer,#n_sponsor_ads,#namecom_ad_hosting_main,#narrow_ad_unit,#natadad300x250,#national_microlink_ads,#navi_banner_ad_780,#nba300Ad,#nbaMidAds,#nbaVid300Ad,#new_topad,#ng_rtcol_ad,#noresultsads,#northad,#oanda_ads,#onespot-ads,#p-googleadsense,#page-header-ad,#pageAds,#pageAdsDiv,#page_content_top_ad,#pcworldAdBottom,#pcworldAdTop,#pinball_ad,#player_ad,#player_ads,#portlet-advertisement-left,#portlet-advertisement-right,#post5_adbox,#post_ad,#priceGrabberAd,#print_ads,#printads,#product-adsense,#promo-ad,#promoAds,#ps-vertical-ads,#pub468x60,#publicidad,#pushdown_ad,#r1SoftAd,#rail_ad1,#rail_ad2,#realEstateAds,#rect_ad,#rectangle-ad,#rectangle_ad,#refine-300-ad,#region-top-ad,#rh-ad-container,#rh_tower_ad,#rhsadvert,#right-ad,#right-ad-skin,#right-box-ad,#rightAd,#rightAd300x250,#rightAdColumn,#rightAd_rdr,#rightColAd,#rightColumnMpuAd,#rightColumnSkyAd,#right_ad_wrapper,#right_ads,#right_advertisement,#right_advertising,#right_column_ads,#rightad,#rightadvertbar-doubleclickads,#rightbar-ad,#rightside_ad,#rm_ad_text,#ros_ad,#rotatingads,#row2AdContainer,#rtMod_ad,#sAdsBox,#sb-ad-sq,#sb_advert,#search-google-ads,#search_ads,#secondBoxAdContainer,#section-container-ddc_ads,#section_advertorial_feature,#servfail-ads,#sew-ad1,#shoppingads,#show-ad,#side-ad,#side-ad-container,#sideAd,#sideBarAd,#side_ad_wrapper,#side_ads_by_google,#sidead,#sidebar-125x125-ads,#sidebar-125x125-ads-below-index,#sidebar-ad,#sidebar-ad-boxes,#sidebar-ad-space,#sidebar-ad-wrap,#sidebar-ads,#sidebar2ads,#sidebar_ad_widget,#sidebar_ads,#sidebar_sponsoredresult_body,#sidebarad,#sideline-ad,#single-mpu,#singlead,#site-leaderboard-ads,#site_top_ad,#sky-ad,#skyAd,#skyScrapperAd,#sky_ad,#sky_advert,#skyscraper-ad,#skyscraperAd,#skyscraper_ad,#skyscraper_advert,#sliderAdHolder,#slideshow_ad_300x250,#sm-banner-ad,#small_ad,#smallerAd,#speeds_ads,#speeds_ads_fstitem,#sphereAd,#splinks,#sponLinkDiv_1,#sponlink,#sponsAds,#sponsLinks,#spons_left,#sponseredlinks,#sponsor-search,#sponsorAd1,#sponsorAd2,#sponsorAdDiv,#sponsorLinks,#sponsorTextLink,#sponsor_banderole,#sponsor_box,#sponsor_deals,#sponsor_panSponsor,#sponsored,#sponsored-ads,#sponsored-features,#sponsored-links,#sponsored-resources,#sponsored1,#sponsoredBox1,#sponsoredBox2,#sponsoredLinks,#sponsoredList,#sponsoredResults,#sponsoredSiteMainline,#sponsoredSiteSidebar,#sponsored_ads_v4,#sponsored_content,#sponsored_game_row_listing,#sponsored_links,#sponsoredlinks,#sponsoredlinks_cntr,#sponsoredresults_top,#sponsorlink,#spotlightAds,#spotlightad,#squareAd,#squareAdSpace,#square_ad,#start_middle_container_advertisment,#sticky-ad,#stickyBottomAd,#story-ad-a,#story-ad-b,#story-sponsoredlinks,#storyAd,#storyAdWrap,#subpage-ad-right,#subpage-ad-top,#swads,#synch-ad,#tabAdvertising,#tblAd,#tbl_googlead,#template_ad_leaderboard,#tertiary_advertising,#text-ad,#textAd,#textAds,#text_ad,#text_advert,#the-last-ad-standing,#thefooterad,#themis-ads,#tile-ad,#tmglBannerAd,#top-ad,#top-ad-container,#top-ad-menu,#top-ads,#top-ads-tabs,#top-advertisement,#top-banner-ad,#top-search-ad-wrapper,#topAd,#topAd728x90,#topAdBanner,#topAdContainer,#topAdSenseDiv,#topAds,#topAdsContainer,#topAdvert,#topBannerAd,#topNavLeaderboardAdHolder,#top_ad,#top_ad_area,#top_ad_game,#top_ad_wrapper,#top_ads,#top_advertise,#top_advertising,#top_right_ad,#top_wide_ad,#topad,#topad_left,#topad_right,#topadblock,#topads,#topadzone,#topcustomad,#toprightAdvert,#toptextad,#towerad,#ttp_ad_slot1,#ttp_ad_slot2,#twogamesAd,#txt_link_ads,#undergameAd,#upperMpu,#upperad,#urban_contentad_article,#v_ad,#vert_ad,#vertical_ad,#vertical_ads,#video_cnv_ad,#video_overlay_ad,#walltopad,#welcomeAdsContainer,#welcome_ad_mrec,#welcome_advertisement,#wgtAd,#whatsnews_top_ad,#whitepaper-ad,#whoisRightAdContainer,#wide_ad_unit_top,#widget_advertisement,#wrapAdRight,#wrapAdTop,#y708-ad-expedia,#y708-ad-lrec,#y708-ad-partners,#y708-ad-ysm,#y708-advertorial-marketplace,#yahoo-ads,#yahoo-sponsors,#yahoo_ads,#yahoo_ads_2010,#yahooad-tbl,#yan-sponsored,#ybf-ads,#yfi_fp_ad_mort,#yfi_fp_ad_nns,#yfi_pf_ad_mort,#ygrp-sponsored-links,#ymap_adbanner,#yn-gmy-ad-lrec,#yreSponsoredLinks,#ysm_ad_iframe,#zoneAdserverMrec,#zoneAdserverSuper,.ADBAR,.ADPod,.AD_MOVIE_ITEM,.AD_MOVIE_ITEMLIST,.AD_MOVIE_ITEMROW,.Ad120x600,.Ad160x600,.Ad247x90,.Ad300x250,.Ad300x250L,.Ad728x90,.AdBox,.AdBox7,.AdContainerBox308,.AdHere,.AdInfo,.AdPlaceHolder,.AdRingtone,.AdSense,.AdSpace,.AdTitle,.AdUnit,.AdUnit300,.Ad_C,.Ad_D_Wrapper,.Ad_E_Wrapper,.Ad_Right,.Ads,.AdsBoxSection,.AdsLinks1,.AdsLinks2,.AdvertMidPage,.AdvertiseWithUs,.AdvertisementTextTag,.ArticleInlineAd,.BannerAd,.BlockAd,.BottomAffiliate,.CG_adkit_leaderboard,.CommentAd,.DeptAd,.FT_Ad,.FlatAds,.HPNewAdsBannerDiv,.HomeContentAd,.LeftTowerAd,.M2Advertisement,.MD_adZone,.MPU,.MPUHolder,.MiddleAdContainer,.OpenXad,.PU_DoubleClickAdsContent,.Post5ad,.RBboxAd,.RelatedAds,.RightRailTop300x250Ad,.RightSponsoredAdTitle,.RightTowerAd,.SidebarAd,.SponsoredAdTitle,.SponsoredContent,.SponsoredLinks,.SponsoredLinksGrayBox,.SquareAd,.StandardAdLeft,.StandardAdRight,.TextAd,.TheEagleGoogleAdSense300x250,.TopAd,.TopAdL,.TopAdR,.UIStandardFrame_SidebarAds,.UIWashFrame_SidebarAds,.UnderAd,.VerticalAd,.WidgetAdvertiser,.ad-160x600,.ad-250,.ad-300,.ad-300-block,.ad-300-blog,.ad-300x100,.ad-300x250,.ad-600,.ad-728,.ad-adlink-bottom,.ad-adlink-side,.ad-background,.ad-banner,.ad-bigsize,.ad-block,.ad-blog2biz,.ad-bottom,.ad-box,.ad-break,.ad-btn,.ad-btn-heading,.ad-button,.ad-cell,.ad-container,.ad-div,.ad-feedback,.ad-filler,.ad-footer,.ad-footer-leaderboard,.ad-google,.ad-gray,.ad-hdr,.ad-head,.ad-holder,.ad-homeleaderboard,.ad-img,.ad-island,.ad-leaderboard,.ad-links,.ad-medium,.ad-medium-two,.ad-mpu,.ad-other,.ad-permalink,.ad-placeholder,.ad-postText,.ad-poster,.ad-rect,.ad-rectangle,.ad-rectangle-text,.ad-related,.ad-rh,.ad-ri,.ad-right,.ad-right-header,.ad-right-txt,.ad-section,.ad-sidebar300,.ad-slot,.ad-slot-234-60,.ad-slot-300-250,.ad-slot-728-90,.ad-space,.ad-space-mpu-box,.ad-spot,.ad-statement,.ad-text,.ad-tile,.ad-top,.ad-top-left,.ad-unit,.ad-unit-300,.ad-unit-300-wrapper,.ad-unit-anchor,.ad-vtu,.ad-wrap,.ad-wrapper,.ad-zone-s-q-l,.ad0,.ad1,.ad10,.ad120,.ad160,.ad160x600,.ad18,.ad19,.ad2,.ad21,.ad250c,.ad3,.ad300,.ad300_250,.ad300x100,.ad300x250,.ad300x250Top,.ad300x250_container,.ad300x250box,.ad300x600,.ad310,.ad336x280,.ad343x290,.ad450,.ad468,.ad468_60,.ad468x60,.ad6,.ad620x70,.ad626X35,.ad7,.ad728,.ad728_90,.ad728x90,.ad728x90_container,.ad8,.adAgate,.adBanner,.adBannerTyp1,.adBannerTypSortableList,.adBannerTypW300,.adBgBottom,.adBgMId,.adBgTop,.adBox,.adBoxContent,.adBoxSidebar,.adBoxSingle,.adCMRight,.adColumn,.adContainer,.adContour,.adCreative,.adDiv,.adElement,.adFrame,.adFtr,.adFullWidthMiddle,.adGoogle,.adHeader,.adHeadline,.adHolder,.adHome300x250,.adInNews,.adLabel,.adLeader,.adLeaderForum,.adLeaderboard,.adLeft,.adMastheadLeft,.adMastheadRight,.adMkt2Colw,.adModule,.adNewsChannel,.adNoOutline,.adNoticeOut,.adObj,.adPageBorderL,.adPageBorderR,.adPanel,.adRect,.adRight,.adSelfServiceAdvertiseLink,.adServer,.adSlot,.adSpBelow,.adSpace,.adSpacer,.adSpot,.adSpot-searchAd,.adSpot-textBox,.adSpot-twin,.adSpotIsland,.adSquare,.adSummary,.adSuperboard,.adTag,.adText,.adTileWrap,.adTiler,.adTitle,.adTout,.adTxt,.adWithTab,.adWrap,.adWrapper,.ad_1,.ad_125,.ad_130x90,.ad_160,.ad_160x600,.ad_2,.ad_3,.ad_300,.ad_300_250,.ad_300x250,.ad_336,.ad_336x280,.ad_350x250,.ad_468,.ad_600,.ad_728,.ad_728x90,.ad_amazon,.ad_biz,.ad_block_338,.ad_bottom_leaderboard,.ad_box,.ad_box2,.ad_callout,.ad_caption,.ad_contain,.ad_container,.ad_content,.ad_content_wide,.ad_contents,.ad_descriptor,.ad_footer,.ad_framed,.ad_front_promo,.ad_header,.ad_hpm,.ad_info_block,.ad_label,.ad_launchpad,.ad_leader,.ad_leaderboard,.ad_left,.ad_linkunit,.ad_loc,.ad_lrec,.ad_medrect,.ad_mpu,.ad_mr,.ad_mrec,.ad_mrec_title_article,.ad_notice,.ad_p360,.ad_partner,.ad_partners,.ad_plus,.ad_post,.ad_power,.ad_rectangle,.ad_right,.ad_sidebar,.ad_skyscraper,.ad_slug_table,.ad_space,.ad_space_300_250,.ad_sponsor,.ad_sponsoredsection,.ad_spot_b,.ad_spot_c,.ad_square_r,.ad_square_top,.ad_text,.ad_title,.ad_top,.ad_top_leaderboard,.ad_tower,.ad_unit,.ad_unit_rail,.ad_warning,.ad_wide,.ad_wrap,.ad_wrapper,.ad_wrapper_fixed,.ad_wrapper_top,.ad_zone,.adarea,.adbanner,.adbannerright,.adbar,.adborder,.adbot,.adbottom,.adbottomright,.adbox,.adbox-outer,.adbox_366x280,.adbox_468X60,.adbox_bottom,.adboxclass,.adcode,.adcolumn_wrapper,.adcontainer,.adcopy,.addiv,.adfoot,.adfootbox,.adframe,.adhead,.adheader,.adheader100,.adhere,.adhoriz,.adi,.adinfo,.adinside,.adjlink,.adkit,.adkit-advert,.adkit-lb-footer,.adlabel-horz,.adlabel-vert,.adleft,.adline,.adlink,.adlinks,.adlist,.adlnklst,.admarker,.admedrec,.admessage,.admodule,.admpu,.adnotice,.adops,.adpadding,.adpic,.adright,.adrotate_widget,.adrow,.adrow-post,.adrule,.ads-banner,.ads-categories-bsa,.ads-favicon,.ads-links-general,.ads-mpu,.ads-profile,.ads-right,.ads-sidebar,.ads-sky,.ads-text,.ads2,.ads3,.ads:not(body),.adsArea,.adsBelowHeadingNormal,.adsBox,.adsImages,.adsTextHouse,.adsTower2,.adsTowerWrap,.adsWithUs,.ads_300,.ads_728x90,.ads_big,.ads_big-half,.ads_brace,.ads_catDiv,.ads_container,.ads_disc_anchor,.ads_disc_leader,.ads_disc_lwr_square,.ads_disc_skyscraper,.ads_disc_square,.ads_div,.ads_header,.ads_leaderboard,.ads_mpu,.ads_outer,.ads_right,.ads_sc_bl_i,.ads_sc_tl_i,.ads_side,.ads_takeover,.ads_tr,.adsborder,.adsbyyahoo,.adsc,.adscontainer,.adscreen,.adsection_a2,.adsection_c2,.adsense,.adsense-heading,.adsense-right,.adsense-title,.adsenseBlock,.adsenseContainer,.adsenseblock,.adsenselr,.adsensesq,.adsidebox,.adsingle,.adslogan,.adspace,.adspace-MR,.adspace_buysell,.adspace_rotate,.adspacer,.adspot,.adstrip,.adtag,.adtext,.adtext_gray,.adtext_onwhite,.adtop,.adtravel,.adv-mpu,.adverTag,.adver_cont_below,.advert,.advert-box,.advert-head,.advert-horizontal,.advert-mpu,.advert-skyscraper,.advert-text,.advertCont,.advertContainer,.advertHeadline,.advertRight,.advertText,.advert_468x60,.advert_box,.advert_cont,.advert_leaderboard,.advert_note,.advertise,.advertise-here,.advertise-homestrip,.advertise-horz,.advertise-leaderboard,.advertise-vert,.advertiseContainer,.advertiseText,.advertisement,.advertisement-728x90,.advertisement-block,.advertisement-top,.advertisement468,.advertisementColumnGroup,.advertisementContainer,.advertisementLabel,.advertisementPanel,.advertisement_caption,.advertisement_g,.advertisement_header,.advertisement_horizontal,.advertiser,.advertising,.advertising-header,.advertising2,.advertisingTable,.advertising_block,.advertisment,.advertisment_two,.advertize,.advertorial,.advertorial-promo-box,.adverts,.advt,.advt-banner-3,.advt300,.advt720,.adwordListings,.adwrapper,.adwrapper-lrec,.adwrapper948,.affiliate,.affiliate-link,.affiliate-sidebar,.affiliateAdvertText,.agi-adsaleslinks,.alt_ad,.anchorAd,.answer_ad_content,.aolSponsoredLinks,.aopsadvert,.article-ads,.articleAd,.articleAds,.articleAdsL,.articleEmbeddedAdBox,.article_ad,.article_adbox,.article_mpu_box,.articleads,.aseadn,.aux-ad-widget-2,.b-astro-sponsored-links_horizontal,.b-astro-sponsored-links_vertical,.banner-ad,.banner-ads,.banner-adverts,.banner300x100,.banner300x250,.banner468,.bannerAd,.bannerAdWrapper300x250,.bannerAdWrapper730x86,.banner_300x250,.banner_728x90,.banner_ad,.banner_ad_footer,.banner_ad_leaderboard,.bannerad,.barkerAd,.base-ad-mpu,.base_ad,.bgnavad,.big-ads,.bigAd,.big_ad,.big_ads,.bigad,.bigad2,.billboard_ad,.block-ad,.block-adsense,.block_ad,.block_ad_sb_text,.block_ad_sponsored_links,.block_ad_sponsored_links-wrapper,.blocked-ads,.blog-ads-container,.blogAd,.blogAdvertisement,.blogBigAd,.blog_ad,.blogads,.body_ad,.body_sponsoredresults_bottom,.body_sponsoredresults_middle,.body_sponsoredresults_top,.bookseller-header-advt,.bottomAd,.bottomAds,.bottom_ad_block,.bottom_sponsor,.bottomad,.bottomrightrailAd,.bottomvidad,.box-ad,.box-ads,.boxAd,.box_ad,.box_advertisment_62_border,.box_content_ad,.box_content_ads,.boxad,.bps-ad-wrapper,.bps-advertisement,.bps-advertisement-inline-ads,.bullet-sponsored-links,.bullet-sponsored-links-gray,.burstContentAdIndex,.buttonAd,.buttonAds,.buttonadbox,.bx_ad,.bx_ad_right,.cA-adStrap,.cColumn-TextAdsBox,.care2_adspace,.cb-ad-container,.cb_footer_sponsor,.cb_navigation_ad,.cbstv_ad_label,.cbzadvert,.cdAdTitle,.cdmainlineSearchAdParent,.cdsidebarSearchAdParent,.centerAd,.center_ad,.centerad,.clearerad,.cm_ads,.cms-Advert,.cnn160AdFooter,.cnnAd,.cnnMosaic160Container,.cnnStoreAd,.cnnStoryElementBoxAd,.cnnWCAdBox,.cnnWireAdLtgBox,.cnn_728adbin,.cnn_adcntr300x100,.cnn_adspc336cntr,.cnn_adtitle,.column2-ad,.conductor_ad,.confirm_ad_left,.confirm_ad_right,.confirm_leader_ad,.consoleAd,.container-adwords,.containerSqAd,.container_serendipity_plugin_google_adsense,.contentAd,.content_ad,.content_adsq,.contentad,.contenttextad,.contest_ad,.cp_ad,.cpmstarHeadline,.cpmstarText,.cs-mpu,.cspAd,.ct_ad,.cubeAd,.cube_ads,.currency_ad,.darla_ad,.dartAdImage,.dart_ad,.dart_tag,.dartadvert,.dartiframe,.dc-ad,.dcAdvertHeader,.deckAd,.deckads,.detail-ads,.detailMpu,.divAd,.divads,.divider_ad,.dmco_advert_iabrighttitle,.download_ad,.downloadad,.dynamic_ad,.e-ad,.ec-ads,.entryad,.ez-clientAd,.f_Ads,.featuredAds,.featuredadvertising,.flagads,.flash_advert,.flashad,.flexiad,.flipbook_v2_sponsor_ad,.footerAd,.footerAdModule,.footerTextAd,.footer_ad,.footer_ads,.footer_block_ad,.footer_line_ad,.footerad,.ft-ad,.ftdContentAd,.full_ad_box,.fullbannerad,.g3rtn-ad-site,.g_ggl_ad,.ga-textads-bottom,.ga-textads-top,.gads_cb,.gglAds,.googads,.google-ad-container,.google-ads,.google-ads-boxout,.google-ads-slim,.google-right-ad,.google-sponsored-ads,.google468_60,.googleAd,.googleAd-content,.googleAd-list,.googleAdBox,.googleAdSense,.googleAd_body,.googleAds,.googleAds_article_page_above_comments,.googleAdsense,.googleProfileAd,.google_ads_bom_title,.googlead,.googleaddiv,.googleaddiv2,.googleads,.googleads_300x250,.googleads_title,.gpAds,.gradientAd,.gsfAd,.gt_ad,.gt_ad_300x250,.gt_ad_728x90,.gt_adlabel,.gutter-ad-left,.gutter-ad-right,.h_Ads,.h_ad,.hd_advert,.header-ad,.header-advert,.headerAd,.headerAds,.headerAdvert,.header_ad,.header_ad_center,.header_advertisment,.hi5-ad,.highlightsAd,.hm_advertisment,.home-ad-links,.homeAd,.homeMediumAdGroup,.home_ad_bottom,.homead,.homepage-ad,.homepageFlexAdOuter,.homepageMPU,.hor_ad,.horiz_adspace,.horizontalAd,.horizontal_ad,.hortad,.houseAdsStyle,.hp2-adtag,.hp_ad_cont,.hp_ad_text,.hp_t_ad,.hp_w_ad,.ic-ads,.ico-adv,.idMultiAd,.image-advertisement,.imageads,.in-page-ad,.in-story-text-ad,.indy_googleads,.inline-mpu-left,.inlineSideAd,.inline_ad_title,.inlinead,.inlist-ad,.inner-advt-banner-3,.innerAds,.innerad,.inpostad,.is24-adplace,.islandAd,.islandAdvert,.islandad,.jp-advertisment-promotional,.js-advert,.kw_advert,.kw_advert_pair,.l_ad_sub,.l_banner.ads_show_if,.largeRectangleAd,.leader_ad,.leaderboardAd,.leaderboardad,.left-ad,.leftAd,.left_ads,.leftad,.leftbar_ad_160_600,.leftnavad,.lgRecAd,.lg_ad,.linead,.link_advertise,.live-search-list-ad-container,.log_ads,.lowerAds,.m4-adsbygoogle,.m_banner_ads,.macAd,.macad,.main-ad,.main-tabs-ad-block,.main_ad,.main_adbox,.map_media_banner_ad,.marginadsthin,.marketing-ad,.mdl-ad,.media-advert,.mediaAd,.mediaAdContainer,.medium-rectangle-ad,.menuItemBannerAd,.messageBoardAd,.micro_ad,.mid_ad,.midad,.min_navi_ad,.miniad,.mobile-sponsoring,.mod-ad-lrec,.mod-ad-n,.mod-adopenx,.mod_admodule,.module-ad-small,.module-ads,.moduleAdvertContent,.modulegad,.moduletable-advert,.moduletablesquaread,.mpu,.mpu-ad,.mpu-footer,.mpu-fp,.mpu-title,.mpu-top-left,.mpu-top-right,.mpuAd,.mpuBox,.mpuContainer,.mpuTextAd,.mpu_ad,.mpu_gold,.mpu_holder,.mpu_platinum,.mpu_text_ad,.mpuad,.mpuholderportalpage,.mrec_advert,.ms-ads-link,.msfg-shopping-mpu,.mwaads,.nSponsoredLcContent,.nSponsoredLcTopic,.nadvt300,.narrow_ad_unit,.narrow_ads,.naviad,.nba300Ad,.nbaT3Ad160,.nbaTVPodAd,.nbaTwo130Ads,.nbc_ad_carousel_wrp,.newTopAdContainer,.newad,.nf-adbox,.nn-mpu,.noAdForLead,.normalAds,.nrAds,.oas-bottom-ads,.oio-banner-zone,.oio-link-sidebar,.oio-zone-position,.onethirdadholder,.openx,.openx-ad,.other_adv2,.ov_spns,.pageGoogleAd,.pageGoogleAdFlat,.pageLeaderAd,.pagead,.partnersTextLinks,.pencil_ad,.player_ad_box,.player_page_ad_box,.pnp_ad,.podSponsoredLink,.post-ad,.post_ad,.post_sponsor_unit,.postbit_adbit_register,.postbit_adcode,.prebodyads,.premium_ad_container,.promoAd,.promoAds,.promo_ad,.publication-ad,.publicidad,.puff-advertorials,.qa_ad_left,.quigo-ad,.qzvAdDiv,.r_ad_box,.rad_container,.rectad,.rectangleAd,.rectanglead,.redads_cont,.regularad,.relatedAds,.remads,.result_ad,.results_sponsor,.results_sponsor_right,.reviewMidAdvertAlign,.rght300x250,.rhads,.rhs-ad,.rhs-ads-panel,.right-ad,.right-ad-holder,.right-ad2,.right-ads2,.rightAd,.right_ad,.right_ad_text,.right_ads,.right_col_ad,.right_hand_advert_column,.rightad,.rightad_1,.rightad_2,.rightads,.rightadunit,.rightcol_boxad,.rightcoladvert,.rnav_ad,.rt_ad1_300x90,.rt_ad_300x250,.rt_ad_call,.savvyad_unit,.sb-ad-sq-bg,.sbAdUnitContainer,.sb_adsN,.sb_adsNv2,.sb_adsW,.sb_adsWv2,.scanAd,.scc_advert,.sci-ad-main,.sci-ad-sub,.search-results-ad,.search-sponsor,.search-sponsored,.searchAd,.searchSponsoredResultsBox,.search_column_results_sponsored,.search_results_sponsored_top,.section-sponsor,.section_mpu_wrapper,.selfServeAds,.sidbaread,.side-ad,.side-ads,.side_ad,.side_ad2,.sidead,.sideadsbox,.sideadvert,.sidebar-ad,.sidebar-text-ad,.sidebarAd,.sidebarAdUnit,.sidebarAdvert,.sidebar_ad,.sidebar_ad_300_250,.sidebar_box_ad,.sidebarad,.sidebarad_bottom,.sideheadnarrowad,.sideheadsponsorsad,.singleAd,.singleAdsContainer,.singlead,.sitesponsor,.skinAd,.skin_ad_638,.sky-ad,.skyAd,.skyAdd,.sky_ad,.skyad,.skyscraper-ad,.slideshow-ad,.slinks,.slpBigSlimAdUnit,.slpSquareAdUnit,.sm_ad,.smallSkyAd1,.smallSkyAd2,.small_ad,.small_ads,.smallad-left,.smallsponsorad,.specialAd175x90,.speedyads,.sphereAdContainer,.spl_ad,.spl_ad2,.spl_ad_plus,.splitAd,.spons-link,.sponslink,.sponsor-ad,.sponsor-links,.sponsorArea,.sponsorPost,.sponsorPostWrap,.sponsor_ad_area,.sponsor_line,.sponsor_links,.sponsoradtitle,.sponsorbox,.sponsored,.sponsored-chunk,.sponsored-editorial,.sponsored-links,.sponsored-links-holder,.sponsored-post,.sponsored-results,.sponsored-text,.sponsoredLinks,.sponsoredLinksHeader,.sponsored_ads,.sponsored_box,.sponsored_box_search,.sponsored_by,.sponsored_links,.sponsored_links_title_container,.sponsored_links_title_container_top,.sponsored_links_top,.sponsored_results,.sponsoredibbox,.sponsoredlinks,.sponsoredtextlink_container,.sponsoredtextlink_container_ovt,.sponsorlink,.sponsorlink2,.spotlightAd,.squareAd,.square_ad,.squared_ad,.ss-ad-mpu,.staticAd,.store-ads,.story_AD,.subad,.subcontent-ad,.supercommentad_left,.supercommentad_right,.supportAdItem,.surveyad,.t10ad,.tab_ad,.tab_ad_area,.tablebordersponsor,.tadsanzeige,.tadsbanner,.tadselement,.tallad,.tblTopAds,.tbl_ad,.teaser-sponsor,.teaserAdContainer,.teaser_adtiles,.text-ad-links,.text-g-advertisement,.text-g-group-short-rec-ad,.text-g-net-grp-google-ads-article-page,.textAd,.textAds,.text_ad,.text_ads,.textad,.textad_headline,.textadbox,.textads,.textadsfoot,.textlink-ads,.thisIsAd,.thisIsAnAd,.ticket-ad,.tileAds,.title-ad,.title_adbig,.tncms-region-ads,.toolad,.toolbar-ad,.top-ad,.top-ad-space,.top-ads,.top-menu-ads,.topAdWrap,.topAds,.topAdvertisement,.topBannerAd,.top_Ad,.top_ad,.top_ad_728_90,.top_ad_disclaimer,.top_ad_wrapper,.top_ads,.top_advert,.top_advertising_lb,.top_container_ad,.top_sponsor,.topad,.topadbox,.topads,.topadspot,.topcontentadvertisement,.topic_inad,.topstoriesad,.towerAd,.towerAdLeft,.towerAds,.tower_ad_disclaimer,.ts-ad_unit_bigbox,.ts-banner_ad,.ttlAdsensel,.tto-sponsored-element,.twoColumnAd,.twoadcoll,.twoadcolr,.tx_smartadserver_pi1,.txt-ads,.txtadvertise,.type_miniad,.type_promoads,.undertimyads,.usenext,.vertad,.videoAd,.videoBoxAd,.video_ad,.view-promo-mpu-right,.wide-ad,.wide-skyscraper-ad,.wideAdTable,.wide_ad_unit_top,.wide_ads,.wide_google_ads,.widget-ad,.widget-entry-ads-160,.wikia_ad_placeholder,.withAds,.wnMultiAd,.wp125ad,.wpn_ad_content,.wsSponsoredLinksRight,.wsTopSposoredLinks,.x03-adunit,.x04-adunit,.y-ads,.y-ads-wide,.y7-advertisement,.yahoo-sponsored,.yahoo_ads,.yan-sponsored,.ygrp-ad,.yrail_ad_wrap,.yrail_ads,.ysmsponsor,.ysponsor,a[href^="http://adserving.liveuniversenetwork.com/"],a[href^="http://latestdownloads.net/download.php?"],a[href^="http://secure.signup-page.com/"],a[href^="http://secure.signup-way.com/"],a[href^="http://www.FriendlyDuck.com/AF_"],a[href^="http://www.adbrite.com/mb/commerce/purchase_form.php?"],a[href^="http://www.friendlyduck.com/AF_"],a[href^="http://www.google.com/aclk?"],a[href^="http://www.liutilities.com/aff"],a[href^="http://www.my-dirty-hobby.com/?sub="],a[href^="http://www.ringtonematcher.com/"],#mbEnd[cellspacing="0"][style="padding: 0pt; white-space: nowrap;"],div#mclip_container:first-child:last-child,div#tads.c,table.ra[align="left"][width="30%"],table.ra[align="right"][width="30%"] { visibility:hidden !important; display:none !important; }</STYLE></HTML> \ No newline at end of file
diff --git a/projecttemplates/MvcRelyingParty/Controllers/AccountController.cs b/projecttemplates/MvcRelyingParty/Controllers/AccountController.cs
index a322f7d..864a38e 100644
--- a/projecttemplates/MvcRelyingParty/Controllers/AccountController.cs
+++ b/projecttemplates/MvcRelyingParty/Controllers/AccountController.cs
@@ -50,13 +50,21 @@
[Authorize]
public ActionResult Authorize() {
- if (OAuthServiceProvider.PendingAuthorizationRequest == null) {
+ var pendingRequest = OAuthServiceProvider.AuthorizationServer.ReadAuthorizationRequest();
+ if (pendingRequest == null) {
return RedirectToAction("Edit");
}
+ var requestingClient = Database.DataContext.Clients.First(c => c.ClientIdentifier == pendingRequest.ClientIdentifier);
+
+ // Consider auto-approving if safe to do so.
+ if (((OAuthAuthorizationServer)OAuthServiceProvider.AuthorizationServer.AuthorizationServer).CanBeAutoApproved(pendingRequest)) {
+ OAuthServiceProvider.AuthorizationServer.ApproveAuthorizationRequest(pendingRequest, HttpContext.User.Identity.Name);
+ }
+
var model = new AccountAuthorizeModel {
- ConsumerApp = OAuthServiceProvider.PendingAuthorizationConsumer.Name,
- IsUnsafeRequest = OAuthServiceProvider.PendingAuthorizationRequest.IsUnsafeRequest,
+ ClientApp = requestingClient.Name,
+ Scope = pendingRequest.Scope,
};
return View(model);
@@ -64,43 +72,30 @@
[Authorize, AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken]
public ActionResult Authorize(bool isApproved) {
+ var getRequest = new HttpRequestInfo("GET", this.Request.Url, this.Request.RawUrl, new WebHeaderCollection(), null);
+ var pendingRequest = OAuthServiceProvider.AuthorizationServer.ReadAuthorizationRequest(getRequest);
+ var requestingClient = Database.DataContext.Clients.First(c => c.ClientIdentifier == pendingRequest.ClientIdentifier);
+
+ IDirectedProtocolMessage response;
if (isApproved) {
- var consumer = OAuthServiceProvider.PendingAuthorizationConsumer;
- var tokenManager = OAuthServiceProvider.ServiceProvider.TokenManager;
- var pendingRequest = OAuthServiceProvider.PendingAuthorizationRequest;
- ITokenContainingMessage requestTokenMessage = pendingRequest;
- var requestToken = tokenManager.GetRequestToken(requestTokenMessage.Token);
-
- var response = OAuthServiceProvider.AuthorizePendingRequestTokenAsWebResponse();
- if (response != null) {
- // The consumer provided a callback URL that can take care of everything else.
- return response.AsActionResult();
- }
-
- var model = new AccountAuthorizeModel {
- ConsumerApp = consumer.Name,
- };
-
- if (!pendingRequest.IsUnsafeRequest) {
- model.VerificationCode = ServiceProvider.CreateVerificationCode(consumer.VerificationCodeFormat, consumer.VerificationCodeLength);
- requestToken.VerificationCode = model.VerificationCode;
- tokenManager.UpdateToken(requestToken);
- }
-
- return View("AuthorizeApproved", model);
+ Database.LoggedInUser.ClientAuthorizations.Add(
+ new ClientAuthorization() {
+ Client = requestingClient,
+ Scope = string.Join(" ", pendingRequest.Scope.ToArray()),
+ User = Database.LoggedInUser,
+ CreatedOnUtc = DateTime.UtcNow.CutToSecond(),
+ });
+ response = OAuthServiceProvider.AuthorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, HttpContext.User.Identity.Name);
} else {
- OAuthServiceProvider.PendingAuthorizationRequest = null;
- return View("AuthorizeDenied");
+ response = OAuthServiceProvider.AuthorizationServer.PrepareRejectAuthorizationRequest(pendingRequest);
}
+
+ return OAuthServiceProvider.AuthorizationServer.Channel.PrepareResponse(response).AsActionResult();
}
[Authorize, AcceptVerbs(HttpVerbs.Delete)] // ValidateAntiForgeryToken would be GREAT here, but it's not a FORM POST operation so that doesn't work.
- public ActionResult RevokeToken(string token) {
- if (String.IsNullOrEmpty(token)) {
- throw new ArgumentNullException("token");
- }
-
- var tokenEntity = Database.DataContext.IssuedTokens.OfType<IssuedAccessToken>().Where(t => t.User.UserId == Database.LoggedInUser.UserId && t.Token == token).FirstOrDefault();
+ public ActionResult RevokeAuthorization(int authorizationId) {
+ var tokenEntity = Database.DataContext.ClientAuthorizations.Where(auth => auth.User.UserId == Database.LoggedInUser.UserId && auth.AuthorizationId == authorizationId).FirstOrDefault();
if (tokenEntity == null) {
throw new ArgumentOutOfRangeException("id", "The logged in user does not have a token with this name to revoke.");
}
@@ -112,9 +107,9 @@
}
private static AccountInfoModel GetAccountInfoModel() {
- var authorizedApps = from token in Database.DataContext.IssuedTokens.OfType<IssuedAccessToken>()
- where token.User.UserId == Database.LoggedInUser.UserId
- select new AccountInfoModel.AuthorizedApp { AppName = token.Consumer.Name, Token = token.Token };
+ var authorizedApps = from auth in Database.DataContext.ClientAuthorizations
+ where auth.User.UserId == Database.LoggedInUser.UserId
+ select new AccountInfoModel.AuthorizedApp { AppName = auth.Client.Name, AuthorizationId = auth.AuthorizationId, Scope = auth.Scope };
Database.LoggedInUser.AuthenticationTokens.Load();
var model = new AccountInfoModel {
FirstName = Database.LoggedInUser.FirstName,
diff --git a/projecttemplates/MvcRelyingParty/Models/AccountAuthorizeModel.cs b/projecttemplates/MvcRelyingParty/Models/AccountAuthorizeModel.cs
index 0fbd9f4..97c96f0 100644
--- a/projecttemplates/MvcRelyingParty/Models/AccountAuthorizeModel.cs
+++ b/projecttemplates/MvcRelyingParty/Models/AccountAuthorizeModel.cs
@@ -5,10 +5,8 @@
using System.Web;
public class AccountAuthorizeModel {
- public string ConsumerApp { get; set; }
+ public string ClientApp { get; set; }
- public bool IsUnsafeRequest { get; set; }
-
- public string VerificationCode { get; set; }
+ public HashSet<string> Scope { get; set; }
}
}
diff --git a/projecttemplates/MvcRelyingParty/Models/AccountInfoModel.cs b/projecttemplates/MvcRelyingParty/Models/AccountInfoModel.cs
index 787b8df..6e005c4 100644
--- a/projecttemplates/MvcRelyingParty/Models/AccountInfoModel.cs
+++ b/projecttemplates/MvcRelyingParty/Models/AccountInfoModel.cs
@@ -17,9 +17,11 @@
public IList<AuthenticationToken> AuthenticationTokens { get; set; }
public class AuthorizedApp {
- public string Token { get; set; }
+ public int AuthorizationId { get; set; }
public string AppName { get; set; }
+
+ public string Scope { get; set; }
}
}
}
diff --git a/projecttemplates/MvcRelyingParty/MvcRelyingParty.csproj b/projecttemplates/MvcRelyingParty/MvcRelyingParty.csproj
index 0a1b11f..e08465f 100644
--- a/projecttemplates/MvcRelyingParty/MvcRelyingParty.csproj
+++ b/projecttemplates/MvcRelyingParty/MvcRelyingParty.csproj
@@ -84,8 +84,8 @@
</Compile>
<Compile Include="Models\AccountAuthorizeModel.cs" />
<Compile Include="Models\AccountInfoModel.cs" />
- <Compile Include="OAuth.ashx.cs">
- <DependentUpon>OAuth.ashx</DependentUpon>
+ <Compile Include="OAuthTokenEndpoint.ashx.cs">
+ <DependentUpon>OAuthTokenEndpoint.ashx</DependentUpon>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Setup.aspx.cs">
@@ -176,16 +176,16 @@
</ItemGroup>
<ItemGroup>
<Content Include="Content\images\infocard_23x16.png" />
- <Content Include="OAuth.ashx" />
<Content Include="Views\Account\AuthenticationTokens.ascx" />
<Content Include="Views\Account\Authorize.aspx" />
- <Content Include="Views\Account\AuthorizeApproved.aspx" />
<Content Include="Views\Account\AuthorizedApps.ascx" />
- <Content Include="Views\Account\AuthorizeDenied.aspx" />
</ItemGroup>
<ItemGroup>
<Folder Include="App_Data\" />
</ItemGroup>
+ <ItemGroup>
+ <Content Include="OAuthTokenEndpoint.ashx" />
+ </ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
diff --git a/projecttemplates/MvcRelyingParty/OAuth.ashx b/projecttemplates/MvcRelyingParty/OAuth.ashx
deleted file mode 100644
index 81b3d52..0000000
--- a/projecttemplates/MvcRelyingParty/OAuth.ashx
+++ /dev/null
@@ -1 +0,0 @@
-<%@ WebHandler Language="C#" CodeBehind="OAuth.ashx.cs" Class="MvcRelyingParty.OAuth" %>
diff --git a/projecttemplates/MvcRelyingParty/OAuth.ashx.cs b/projecttemplates/MvcRelyingParty/OAuth.ashx.cs
deleted file mode 100644
index b9051c1..0000000
--- a/projecttemplates/MvcRelyingParty/OAuth.ashx.cs
+++ /dev/null
@@ -1,66 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="OAuth.ashx.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace MvcRelyingParty {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.SessionState;
- using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.OAuth;
- using DotNetOpenAuth.OAuth.Messages;
- using RelyingPartyLogic;
-
- /// <summary>
- /// Responds to incoming OAuth Service Provider messages.
- /// </summary>
- public class OAuth : IHttpHandler, IRequiresSessionState {
- /// <summary>
- /// Initializes a new instance of the <see cref="OAuth"/> class.
- /// </summary>
- public OAuth() {
- }
-
- /// <summary>
- /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"/> instance.
- /// </summary>
- /// <returns>
- /// true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false.
- /// </returns>
- public bool IsReusable {
- get { return true; }
- }
-
- /// <summary>
- /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
- /// </summary>
- /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
- public void ProcessRequest(HttpContext context) {
- var serviceProvider = OAuthServiceProvider.ServiceProvider;
- var requestMessage = serviceProvider.ReadRequest(new HttpRequestInfo(context.Request));
-
- UnauthorizedTokenRequest unauthorizedTokenRequestMessage;
- AuthorizedTokenRequest authorizedTokenRequestMessage;
- UserAuthorizationRequest userAuthorizationRequest;
- if ((unauthorizedTokenRequestMessage = requestMessage as UnauthorizedTokenRequest) != null) {
- var response = serviceProvider.PrepareUnauthorizedTokenMessage(unauthorizedTokenRequestMessage);
- serviceProvider.Channel.Send(response);
- } else if ((authorizedTokenRequestMessage = requestMessage as AuthorizedTokenRequest) != null) {
- var response = serviceProvider.PrepareAccessTokenMessage(authorizedTokenRequestMessage);
- serviceProvider.Channel.Send(response);
- } else if ((userAuthorizationRequest = requestMessage as UserAuthorizationRequest) != null) {
- // This is a browser opening to allow the user to authorize a request token,
- // so redirect to the authorization page, which will automatically redirect
- // to have the user log in if necessary.
- OAuthServiceProvider.PendingAuthorizationRequest = userAuthorizationRequest;
- HttpContext.Current.Response.Redirect("~/Account/Authorize");
- } else {
- throw new InvalidOperationException();
- }
- }
- }
-}
diff --git a/projecttemplates/MvcRelyingParty/OAuthTokenEndpoint.ashx b/projecttemplates/MvcRelyingParty/OAuthTokenEndpoint.ashx
new file mode 100644
index 0000000..dc12aeb
--- /dev/null
+++ b/projecttemplates/MvcRelyingParty/OAuthTokenEndpoint.ashx
@@ -0,0 +1 @@
+<%@ WebHandler Language="C#" CodeBehind="OAuthTokenEndpoint.ashx.cs" Class="MvcRelyingParty.OAuthTokenEndpoint" %>
diff --git a/projecttemplates/MvcRelyingParty/OAuthTokenEndpoint.ashx.cs b/projecttemplates/MvcRelyingParty/OAuthTokenEndpoint.ashx.cs
new file mode 100644
index 0000000..89e55d5
--- /dev/null
+++ b/projecttemplates/MvcRelyingParty/OAuthTokenEndpoint.ashx.cs
@@ -0,0 +1,51 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuthTokenEndpoint.ashx.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace MvcRelyingParty {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Web;
+ using System.Web.SessionState;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2;
+ using RelyingPartyLogic;
+
+ /// <summary>
+ /// An OAuth 2.0 token endpoint.
+ /// </summary>
+ public class OAuthTokenEndpoint : IHttpHandler, IRequiresSessionState {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="OAuthTokenEndpoint"/> class.
+ /// </summary>
+ public OAuthTokenEndpoint() {
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"/> instance.
+ /// </summary>
+ /// <returns>
+ /// true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false.
+ /// </returns>
+ public bool IsReusable {
+ get { return true; }
+ }
+
+ /// <summary>
+ /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
+ /// </summary>
+ /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
+ public void ProcessRequest(HttpContext context) {
+ var serviceProvider = OAuthServiceProvider.AuthorizationServer;
+ IDirectResponseProtocolMessage response;
+ if (serviceProvider.TryPrepareAccessTokenResponse(new HttpRequestInfo(context.Request), out response)) {
+ serviceProvider.Channel.Send(response);
+ } else {
+ throw new InvalidOperationException();
+ }
+ }
+ }
+}
diff --git a/projecttemplates/MvcRelyingParty/Views/Account/Authorize.aspx b/projecttemplates/MvcRelyingParty/Views/Account/Authorize.aspx
index e8eaaaa..da2676e 100644
--- a/projecttemplates/MvcRelyingParty/Views/Account/Authorize.aspx
+++ b/projecttemplates/MvcRelyingParty/Views/Account/Authorize.aspx
@@ -12,11 +12,15 @@
</div>
<p>
The
- <%= Html.Encode(Model.ConsumerApp) %>
+ <%= Html.Encode(Model.ClientApp) %>
application is requesting to access the private data in your account here. Is that
alright with you?
</p>
<p>
+ <b>Requested access: </b>
+ <%= Html.Encode(String.Join(" ", Model.Scope.ToArray())) %>
+ </p>
+ <p>
If you grant access now, you can revoke it at any time by returning to
<%= Html.ActionLink("your account page", "Edit") %>.
</p>
@@ -31,18 +35,6 @@
<b>Javascript appears to be disabled in your browser. </b>This page requires Javascript
to be enabled to better protect your security.
</div>
- <% if (Model.IsUnsafeRequest) { %>
- <div style="background-color: red; color: white; font-weight: bold">
- This website is registered with
- <asp:Label runat="server" ID="serviceProviderDomainNameLabel" />
- to make authorization requests, but has not been configured to send requests securely.
- If you grant access but you did not initiate this request at
- <%= Html.Encode(Model.ConsumerApp) %>, it may be possible for other users of
- <%= Html.Encode(Model.ConsumerApp) %>
- to access your data. We recommend you deny access unless you are certain that you
- initiated this request directly with
- <%= Html.Encode(Model.ConsumerApp) %>.
- <% } %>
<script language="javascript" type="text/javascript">
//<![CDATA[
diff --git a/projecttemplates/MvcRelyingParty/Views/Account/AuthorizeApproved.aspx b/projecttemplates/MvcRelyingParty/Views/Account/AuthorizeApproved.aspx
deleted file mode 100644
index a2d91b0..0000000
--- a/projecttemplates/MvcRelyingParty/Views/Account/AuthorizeApproved.aspx
+++ /dev/null
@@ -1,24 +0,0 @@
-<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcRelyingParty.Models.AccountAuthorizeModel>" %>
-
-<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
- Authorized
-</asp:Content>
-<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
- <h2>
- Authorized
- </h2>
- <p>
- Authorization has been granted.
- </p>
- <% if (!string.IsNullOrEmpty(Model.VerificationCode)) { %>
- <p>
- You must enter this verification code at the Consumer: <b>
- <%= Html.Encode(Model.VerificationCode)%>
- </b>
- </p>
- <% } else { %>
- <p>
- You may now close this window and return to the Consumer.
- </p>
- <% } %>
-</asp:Content>
diff --git a/projecttemplates/MvcRelyingParty/Views/Account/AuthorizeDenied.aspx b/projecttemplates/MvcRelyingParty/Views/Account/AuthorizeDenied.aspx
deleted file mode 100644
index 99bfb2a..0000000
--- a/projecttemplates/MvcRelyingParty/Views/Account/AuthorizeDenied.aspx
+++ /dev/null
@@ -1,13 +0,0 @@
-<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcRelyingParty.Models.AccountAuthorizeModel>" %>
-
-<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
- AuthorizeDenied
-</asp:Content>
-<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
- <h2>
- AuthorizeDenied
- </h2>
- <p>
- Authorization has been denied. You're free to do whatever now.
- </p>
-</asp:Content>
diff --git a/projecttemplates/MvcRelyingParty/Views/Account/AuthorizedApps.ascx b/projecttemplates/MvcRelyingParty/Views/Account/AuthorizedApps.ascx
index 57c2b1a..4fadad9 100644
--- a/projecttemplates/MvcRelyingParty/Views/Account/AuthorizedApps.ascx
+++ b/projecttemplates/MvcRelyingParty/Views/Account/AuthorizedApps.ascx
@@ -9,7 +9,7 @@
<% } else { %>
<ul>
<% foreach (var app in Model.AuthorizedApps) { %>
- <li><%= Html.Encode(app.AppName) %> - <%= Ajax.ActionLink("revoke", "RevokeToken", new { token = app.Token }, new AjaxOptions { HttpMethod = "DELETE", UpdateTargetId = "authorizedApps", OnFailure = "function(e) { alert('Revoking authorization for this application failed.'); }" }) %></li>
+ <li><%= Html.Encode(app.AppName) %> - <%= Html.Encode(app.Scope) %> - <%= Ajax.ActionLink("revoke", "RevokeAuthorization", new { authorizationId = app.AuthorizationId }, new AjaxOptions { HttpMethod = "DELETE", UpdateTargetId = "authorizedApps", OnFailure = "function(e) { alert('Revoking authorization for this application failed.'); }" })%></li>
<% } %>
</ul>
<% } %> \ No newline at end of file
diff --git a/projecttemplates/RelyingPartyDatabase/Properties/Database.sqlcmdvars b/projecttemplates/RelyingPartyDatabase/Properties/Database.sqlcmdvars
index a396dc9..f2c472d 100644
--- a/projecttemplates/RelyingPartyDatabase/Properties/Database.sqlcmdvars
+++ b/projecttemplates/RelyingPartyDatabase/Properties/Database.sqlcmdvars
@@ -4,7 +4,7 @@
<Properties>
<Property>
<PropertyName>Path1</PropertyName>
- <PropertyValue>WEBROOT\App_Data\</PropertyValue>
+ <PropertyValue>WEBROOT</PropertyValue>
</Property>
</Properties>
</SqlCommandVariables> \ No newline at end of file
diff --git a/projecttemplates/RelyingPartyDatabase/RelyingPartyDatabase.dbproj b/projecttemplates/RelyingPartyDatabase/RelyingPartyDatabase.dbproj
index db3234b..3df061c 100644
--- a/projecttemplates/RelyingPartyDatabase/RelyingPartyDatabase.dbproj
+++ b/projecttemplates/RelyingPartyDatabase/RelyingPartyDatabase.dbproj
@@ -285,5 +285,40 @@
<ItemGroup>
<BuildContributorArgument Include="OutDir=$(OutDir)" />
</ItemGroup>
- <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
-</Project> \ No newline at end of file
+ <ItemGroup>
+ <NotInBuild Include="Schema Comparisons\SchemaComparison1.scmp">
+ <SubType>NotInBuild</SubType>
+ </NotInBuild>
+ </ItemGroup>
+ <ItemGroup>
+ <Build Include="Schema Objects\Schemas\dbo\Tables\Constraints\DF_IssuedToken_CreatedOn_1.defconst.sql">
+ <SubType>Code</SubType>
+ </Build>
+ <Build Include="Schema Objects\Schemas\dbo\Tables\Keys\FK_IssuedToken_Consumer_1.fkey.sql">
+ <SubType>Code</SubType>
+ </Build>
+ <Build Include="Schema Objects\Schemas\dbo\Tables\Keys\FK_IssuedToken_User_1.fkey.sql">
+ <SubType>Code</SubType>
+ </Build>
+ <Build Include="Schema Objects\Schemas\dbo\Tables\Indexes\IX_Consumer_1.index.sql">
+ <SubType>Code</SubType>
+ </Build>
+ <Build Include="Schema Objects\Schemas\dbo\Tables\Keys\PK_IssuedToken_1.pkey.sql">
+ <SubType>Code</SubType>
+ </Build>
+ <Build Include="Schema Objects\Schemas\dbo\Tables\Keys\PK_Consumer_1.pkey.sql">
+ <SubType>Code</SubType>
+ </Build>
+ <Build Include="Schema Objects\Schemas\dbo\Tables\ClientAuthorization.table.sql">
+ <SubType>Code</SubType>
+ <AnsiNulls>On</AnsiNulls>
+ <QuotedIdentifier>On</QuotedIdentifier>
+ </Build>
+ <Build Include="Schema Objects\Schemas\dbo\Tables\Client.table.sql">
+ <SubType>Code</SubType>
+ <AnsiNulls>On</AnsiNulls>
+ <QuotedIdentifier>On</QuotedIdentifier>
+ </Build>
+ </ItemGroup>
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
+</Project>
diff --git a/projecttemplates/RelyingPartyDatabase/Schema Comparisons/SchemaComparison1.scmp b/projecttemplates/RelyingPartyDatabase/Schema Comparisons/SchemaComparison1.scmp
new file mode 100644
index 0000000..b3160a4
--- /dev/null
+++ b/projecttemplates/RelyingPartyDatabase/Schema Comparisons/SchemaComparison1.scmp
@@ -0,0 +1,328 @@
+<?xml version="1.0" encoding="utf-8"?>
+<SchemaComparison>
+ <Version>1</Version>
+ <SourceModelProvider>
+ <ConnectionBasedModelProvider>
+ <ConnectionString>Data Source=.\sqlexpress;Initial Catalog=RelyingPartyDatabase;Integrated Security=True;Password=</ConnectionString>
+ <DatabaseName>RelyingPartyDatabase</DatabaseName>
+ <DspFamilyName>sql</DspFamilyName>
+ <Name>[THINKAGAIN\sqlexpress.RelyingPartyDatabase]</Name>
+ </ConnectionBasedModelProvider>
+ </SourceModelProvider>
+ <TargetModelProvider>
+ <ProjectBasedModelProvider>
+ <ProjectGuid>{2b4261ac-25ac-4b8d-b459-1c42b6b1401d}</ProjectGuid>
+ <Name>RelyingPartyDatabase</Name>
+ </ProjectBasedModelProvider>
+ </TargetModelProvider>
+ <SchemaCompareSettingsService>
+ <SchemaCompareSettingsService>
+ <PropertyElementName>
+ <Name>Version</Name>
+ <Value>1</Value>
+ </PropertyElementName>
+ </SchemaCompareSettingsService>
+ <ConfigurationOptionsElement>
+ <PropertyElementName>
+ <Name>PlanGenerationType</Name>
+ <Value>Sql90SchemaDeploymentOptions</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>DoNotUseAlterAssemblyStatementsToUpdateCLRTypes</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>DisableAndReenableDdlTriggers</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreDdlTriggerOrder</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreDdlTriggerState</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreObjectPlacementOnPartitionScheme</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreAuthorizer</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreDefaultSchema</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreRouteLifetime</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>OnlyCompareElementsInSource</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreStatisticsSample</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>CommentOutSetVarDeclarations</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>GenerateDeployStateChecks</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>DeployDatabaseProperties</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreComments</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreWhitespace</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreKeywordCasing</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreSemicolonBetweenStatements</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>BlockIncrementalDeploymentIfDataLoss</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>PerformDatabaseBackup</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>SingleUserMode</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IncludeTransactionalScripts</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>EnforceMinimalDependencies</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>DeploymentCollationPreference</Name>
+ <Value>UseSourceModelCollation</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnorePartitionSchemes</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreWithNocheckOnCheckConstraints</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreWithNocheckOnForeignKeys</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreIdentitySeed</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreIncrement</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreFillFactor</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreIndexPadding</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreColumnCollation</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreLockHintsOnIndexes</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreTableOptions</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreIndexOptions</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreDmlTriggerOrder</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>ScriptDatabaseCollation</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreDmlTriggerState</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreAnsiNulls</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreQuotedIdentifiers</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreUserSettingsObjects</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>AbortOnFirstError</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreFilegroupPlacement</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreFullTextCatalogFilePath</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreFileAndLogFilePath</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreLoginSids</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreNotForReplication</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreFileSize</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>OverrideSevenSetOptions</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>SetAnsiNulls</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>SetAnsiPadding</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>SetAnsiWarnings</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>SetArithAbort</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>SetConcatNullYieldsNull</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>SetQuotedIdentifier</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>SetNumericRoundAbort</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>UnmodifiableObjectWarnings</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>DropIndexesNotInSource</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>DropConstraintsNotInSource</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>CheckNewConstraints</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreColumnOrder</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnorePasswords</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>IgnoreBodyDependencies</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>SourceSqlCmdVariablesFile</Name>
+ <Value>C:\Users\andarno\git\dotnetopenid\projecttemplates\RelyingPartyDatabase\Properties\Database.sqlcmdvars</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>AlwaysCreateNewDatabase</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>GenerateDropsIfNotInProject</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>TargetDatabaseName</Name>
+ <Value>RelyingPartyDatabase</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>TargetConnectionString</Name>
+ <Value>Data Source=.\sqlexpress;Initial Catalog=RelyingPartyDatabase;Integrated Security=True;Pooling=False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>VerifyDeployment</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>TreatVerificationErrorsAsWarnings</Name>
+ <Value>False</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>BuildtimeContributorsMustExist</Name>
+ <Value>True</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>Microsoft.Data.Schema.Sql.SchemaModel.ISqlPermissionStatement</Name>
+ <Value>ExcludedType</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>Microsoft.Data.Schema.Sql.SchemaModel.ISqlFilegroup</Name>
+ <Value>ExcludedType</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>Microsoft.Data.Schema.Sql.SchemaModel.ISqlFile</Name>
+ <Value>ExcludedType</Value>
+ </PropertyElementName>
+ <PropertyElementName>
+ <Name>Microsoft.Data.Schema.Sql.SchemaModel.ISqlExtendedProperty</Name>
+ <Value>ExcludedType</Value>
+ </PropertyElementName>
+ </ConfigurationOptionsElement>
+ </SchemaCompareSettingsService>
+</SchemaComparison> \ No newline at end of file
diff --git a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Client.table.sql b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Client.table.sql
new file mode 100644
index 0000000..8dc2f64
--- /dev/null
+++ b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Client.table.sql
@@ -0,0 +1,12 @@
+CREATE TABLE [dbo].[Client] (
+ [ClientId] INT IDENTITY (1, 1) NOT NULL,
+ [ClientIdentifier] VARCHAR (255) COLLATE SQL_Latin1_General_CP1_CS_AS NOT NULL,
+ [ClientSecret] VARCHAR (255) COLLATE SQL_Latin1_General_CP1_CS_AS NULL,
+ [Callback] VARCHAR (2048) NULL,
+ [Name] NVARCHAR (50) NOT NULL
+);
+
+
+
+
+
diff --git a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/ClientAuthorization.table.sql b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/ClientAuthorization.table.sql
new file mode 100644
index 0000000..3a31062
--- /dev/null
+++ b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/ClientAuthorization.table.sql
@@ -0,0 +1,9 @@
+CREATE TABLE [dbo].[ClientAuthorization] (
+ [AuthorizationId] INT IDENTITY (1, 1) NOT NULL,
+ [ClientId] INT NOT NULL,
+ [UserId] INT NOT NULL,
+ [CreatedOn] DATETIME NOT NULL,
+ [ExpirationDate] DATETIME NULL,
+ [Scope] VARCHAR (2048) NULL
+);
+
diff --git a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Constraints/DF_IssuedToken_CreatedOn.defconst.sql b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Constraints/DF_IssuedToken_CreatedOn.defconst.sql
index c60323f..28f59be 100644
--- a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Constraints/DF_IssuedToken_CreatedOn.defconst.sql
+++ b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Constraints/DF_IssuedToken_CreatedOn.defconst.sql
@@ -1,3 +1,3 @@
-ALTER TABLE [dbo].[IssuedToken]
- ADD CONSTRAINT [DF_IssuedToken_CreatedOn] DEFAULT (getutcdate()) FOR [CreatedOn];
+/*ALTER TABLE [dbo].[IssuedToken]
+ ADD CONSTRAINT [DF_IssuedToken_CreatedOn] DEFAULT (getutcdate()) FOR [CreatedOn];*/
diff --git a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Constraints/DF_IssuedToken_CreatedOn_1.defconst.sql b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Constraints/DF_IssuedToken_CreatedOn_1.defconst.sql
new file mode 100644
index 0000000..3ba2b0b
--- /dev/null
+++ b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Constraints/DF_IssuedToken_CreatedOn_1.defconst.sql
@@ -0,0 +1,3 @@
+ALTER TABLE [dbo].[ClientAuthorization]
+ ADD CONSTRAINT [DF_IssuedToken_CreatedOn] DEFAULT (getutcdate()) FOR [CreatedOn];
+
diff --git a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Constraints/DF_IssuedToken_IsAccessToken.defconst.sql b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Constraints/DF_IssuedToken_IsAccessToken.defconst.sql
index 2e9e5fd..cf3ec08 100644
--- a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Constraints/DF_IssuedToken_IsAccessToken.defconst.sql
+++ b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Constraints/DF_IssuedToken_IsAccessToken.defconst.sql
@@ -1,3 +1,3 @@
-ALTER TABLE [dbo].[IssuedToken]
- ADD CONSTRAINT [DF_IssuedToken_IsAccessToken] DEFAULT ((0)) FOR [IsAccessToken];
+/*ALTER TABLE [dbo].[IssuedToken]
+ ADD CONSTRAINT [DF_IssuedToken_IsAccessToken] DEFAULT ((0)) FOR [IsAccessToken];*/
diff --git a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Consumer.table.sql b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Consumer.table.sql
index 8549a78..ab14759 100644
--- a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Consumer.table.sql
+++ b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Consumer.table.sql
@@ -1,4 +1,4 @@
-CREATE TABLE [dbo].[Consumer] (
+/*CREATE TABLE [dbo].[Consumer] (
[ConsumerId] INT IDENTITY (1, 1) NOT NULL,
[ConsumerKey] NVARCHAR (255) COLLATE SQL_Latin1_General_CP1_CS_AS NOT NULL,
[ConsumerSecret] NVARCHAR (255) COLLATE SQL_Latin1_General_CP1_CS_AS NULL,
@@ -7,5 +7,5 @@
[VerificationCodeFormat] INT NOT NULL,
[VerificationCodeLength] INT NOT NULL,
[Name] NVARCHAR (50) NULL
-);
+);*/
diff --git a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Indexes/IX_Consumer.index.sql b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Indexes/IX_Consumer.index.sql
index 149ae35..d469e71 100644
--- a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Indexes/IX_Consumer.index.sql
+++ b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Indexes/IX_Consumer.index.sql
@@ -1,3 +1,3 @@
-CREATE UNIQUE NONCLUSTERED INDEX [IX_Consumer]
- ON [dbo].[Consumer]([ConsumerKey] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF, ONLINE = OFF, MAXDOP = 0);
+/*CREATE UNIQUE NONCLUSTERED INDEX [IX_Consumer]
+ ON [dbo].[Consumer]([ConsumerKey] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF, ONLINE = OFF, MAXDOP = 0);*/
diff --git a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Indexes/IX_Consumer_1.index.sql b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Indexes/IX_Consumer_1.index.sql
new file mode 100644
index 0000000..e5ad21b
--- /dev/null
+++ b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Indexes/IX_Consumer_1.index.sql
@@ -0,0 +1,4 @@
+CREATE UNIQUE NONCLUSTERED INDEX [IX_Consumer]
+ ON [dbo].[Client]([ClientIdentifier] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF, ONLINE = OFF, MAXDOP = 0)
+ ON [PRIMARY];
+
diff --git a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Indexes/IX_IssuedToken.index.sql b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Indexes/IX_IssuedToken.index.sql
index 5bc3a53..f2f59e1 100644
--- a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Indexes/IX_IssuedToken.index.sql
+++ b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Indexes/IX_IssuedToken.index.sql
@@ -1,3 +1,3 @@
-CREATE UNIQUE NONCLUSTERED INDEX [IX_IssuedToken]
- ON [dbo].[IssuedToken]([Token] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF, ONLINE = OFF, MAXDOP = 0);
+/*CREATE UNIQUE NONCLUSTERED INDEX [IX_IssuedToken]
+ ON [dbo].[IssuedToken]([Token] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF, ONLINE = OFF, MAXDOP = 0);*/
diff --git a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/IssuedToken.table.sql b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/IssuedToken.table.sql
index 8882e93..ee0ffdf 100644
--- a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/IssuedToken.table.sql
+++ b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/IssuedToken.table.sql
@@ -1,4 +1,4 @@
-CREATE TABLE [dbo].[IssuedToken] (
+/*CREATE TABLE [dbo].[IssuedToken] (
[IssuedTokenId] INT IDENTITY (1, 1) NOT NULL,
[ConsumerId] INT NOT NULL,
[UserId] INT NULL,
@@ -11,5 +11,5 @@
[ExpirationDate] DATETIME NULL,
[IsAccessToken] BIT NOT NULL,
[Scope] NVARCHAR (255) NULL
-);
+);*/
diff --git a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/FK_IssuedToken_Consumer.fkey.sql b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/FK_IssuedToken_Consumer.fkey.sql
index a5b3dac..fe25092 100644
--- a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/FK_IssuedToken_Consumer.fkey.sql
+++ b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/FK_IssuedToken_Consumer.fkey.sql
@@ -1,3 +1,3 @@
-ALTER TABLE [dbo].[IssuedToken]
- ADD CONSTRAINT [FK_IssuedToken_Consumer] FOREIGN KEY ([ConsumerId]) REFERENCES [dbo].[Consumer] ([ConsumerId]) ON DELETE CASCADE ON UPDATE CASCADE;
+/*ALTER TABLE [dbo].[IssuedToken]
+ ADD CONSTRAINT [FK_IssuedToken_Consumer] FOREIGN KEY ([ConsumerId]) REFERENCES [dbo].[Consumer] ([ConsumerId]) ON DELETE CASCADE ON UPDATE CASCADE;*/
diff --git a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/FK_IssuedToken_Consumer_1.fkey.sql b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/FK_IssuedToken_Consumer_1.fkey.sql
new file mode 100644
index 0000000..062b9d7
--- /dev/null
+++ b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/FK_IssuedToken_Consumer_1.fkey.sql
@@ -0,0 +1,3 @@
+ALTER TABLE [dbo].[ClientAuthorization]
+ ADD CONSTRAINT [FK_IssuedToken_Consumer] FOREIGN KEY ([ClientId]) REFERENCES [dbo].[Client] ([ClientId]) ON DELETE CASCADE ON UPDATE CASCADE;
+
diff --git a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/FK_IssuedToken_User.fkey.sql b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/FK_IssuedToken_User.fkey.sql
index 045a694..3b9bbc1 100644
--- a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/FK_IssuedToken_User.fkey.sql
+++ b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/FK_IssuedToken_User.fkey.sql
@@ -1,3 +1,3 @@
-ALTER TABLE [dbo].[IssuedToken]
- ADD CONSTRAINT [FK_IssuedToken_User] FOREIGN KEY ([UserId]) REFERENCES [dbo].[User] ([UserId]) ON DELETE CASCADE ON UPDATE CASCADE;
+/*ALTER TABLE [dbo].[IssuedToken]
+ ADD CONSTRAINT [FK_IssuedToken_User] FOREIGN KEY ([UserId]) REFERENCES [dbo].[User] ([UserId]) ON DELETE CASCADE ON UPDATE CASCADE;*/
diff --git a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/FK_IssuedToken_User_1.fkey.sql b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/FK_IssuedToken_User_1.fkey.sql
new file mode 100644
index 0000000..e32b291
--- /dev/null
+++ b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/FK_IssuedToken_User_1.fkey.sql
@@ -0,0 +1,3 @@
+ALTER TABLE [dbo].[ClientAuthorization]
+ ADD CONSTRAINT [FK_IssuedToken_User] FOREIGN KEY ([UserId]) REFERENCES [dbo].[User] ([UserId]) ON DELETE CASCADE ON UPDATE CASCADE;
+
diff --git a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/PK_Consumer.pkey.sql b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/PK_Consumer.pkey.sql
index edde20f..181fdf5 100644
--- a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/PK_Consumer.pkey.sql
+++ b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/PK_Consumer.pkey.sql
@@ -1,3 +1,3 @@
-ALTER TABLE [dbo].[Consumer]
- ADD CONSTRAINT [PK_Consumer] PRIMARY KEY CLUSTERED ([ConsumerId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);
+/*ALTER TABLE [dbo].[Consumer]
+ ADD CONSTRAINT [PK_Consumer] PRIMARY KEY CLUSTERED ([ConsumerId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);*/
diff --git a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/PK_Consumer_1.pkey.sql b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/PK_Consumer_1.pkey.sql
new file mode 100644
index 0000000..04c039f
--- /dev/null
+++ b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/PK_Consumer_1.pkey.sql
@@ -0,0 +1,3 @@
+ALTER TABLE [dbo].[Client]
+ ADD CONSTRAINT [PK_Consumer] PRIMARY KEY CLUSTERED ([ClientId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);
+
diff --git a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/PK_IssuedToken.pkey.sql b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/PK_IssuedToken.pkey.sql
index e2f95ef..931fa54 100644
--- a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/PK_IssuedToken.pkey.sql
+++ b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/PK_IssuedToken.pkey.sql
@@ -1,3 +1,3 @@
-ALTER TABLE [dbo].[IssuedToken]
- ADD CONSTRAINT [PK_IssuedToken] PRIMARY KEY CLUSTERED ([IssuedTokenId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);
+/*ALTER TABLE [dbo].[IssuedToken]
+ ADD CONSTRAINT [PK_IssuedToken] PRIMARY KEY CLUSTERED ([IssuedTokenId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);*/
diff --git a/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/PK_IssuedToken_1.pkey.sql b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/PK_IssuedToken_1.pkey.sql
new file mode 100644
index 0000000..dcd7edc
--- /dev/null
+++ b/projecttemplates/RelyingPartyDatabase/Schema Objects/Schemas/dbo/Tables/Keys/PK_IssuedToken_1.pkey.sql
@@ -0,0 +1,3 @@
+ALTER TABLE [dbo].[ClientAuthorization]
+ ADD CONSTRAINT [PK_IssuedToken] PRIMARY KEY CLUSTERED ([AuthorizationId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);
+
diff --git a/projecttemplates/RelyingPartyLogic/Model.Client.cs b/projecttemplates/RelyingPartyLogic/Model.Client.cs
new file mode 100644
index 0000000..9426408
--- /dev/null
+++ b/projecttemplates/RelyingPartyLogic/Model.Client.cs
@@ -0,0 +1,29 @@
+//-----------------------------------------------------------------------
+// <copyright file="Model.Client.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace RelyingPartyLogic {
+ using System;
+
+ using DotNetOpenAuth.OAuth2;
+
+ public partial class Client : IConsumerDescription {
+ public Uri Callback {
+ get { return this.CallbackAsString != null ? new Uri(this.CallbackAsString) : null; }
+ set { this.CallbackAsString = value != null ? value.AbsoluteUri : null; }
+ }
+
+ #region IConsumerDescription Members
+
+ /// <summary>
+ /// Gets the client secret.
+ /// </summary>
+ string IConsumerDescription.Secret {
+ get { return this.ClientSecret; }
+ }
+
+ #endregion
+ }
+}
diff --git a/projecttemplates/RelyingPartyLogic/Model.IssuedToken.cs b/projecttemplates/RelyingPartyLogic/Model.ClientAuthorization.cs
index 5e10178..3d7646a 100644
--- a/projecttemplates/RelyingPartyLogic/Model.IssuedToken.cs
+++ b/projecttemplates/RelyingPartyLogic/Model.ClientAuthorization.cs
@@ -1,5 +1,5 @@
//-----------------------------------------------------------------------
-// <copyright file="Model.IssuedToken.cs" company="Andrew Arnott">
+// <copyright file="Model.ClientAuthorization.cs" company="Andrew Arnott">
// Copyright (c) Andrew Arnott. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
@@ -11,11 +11,11 @@ namespace RelyingPartyLogic {
using System.Web;
using DotNetOpenAuth.OAuth.ChannelElements;
- public partial class IssuedToken {
+ public partial class ClientAuthorization {
/// <summary>
/// Initializes a new instance of the <see cref="IssuedToken"/> class.
/// </summary>
- public IssuedToken() {
+ public ClientAuthorization() {
this.CreatedOnUtc = DateTime.UtcNow;
}
diff --git a/projecttemplates/RelyingPartyLogic/Model.Consumer.cs b/projecttemplates/RelyingPartyLogic/Model.Consumer.cs
deleted file mode 100644
index a09029a..0000000
--- a/projecttemplates/RelyingPartyLogic/Model.Consumer.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="Model.Consumer.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace RelyingPartyLogic {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Security.Cryptography.X509Certificates;
- using System.Web;
- using DotNetOpenAuth.OAuth;
- using DotNetOpenAuth.OAuth.ChannelElements;
-
- public partial class Consumer : IConsumerDescription {
- public VerificationCodeFormat VerificationCodeFormat {
- get { return (VerificationCodeFormat)this.VerificationCodeFormatAsInt; }
- set { this.VerificationCodeFormatAsInt = (int)value; }
- }
-
- public X509Certificate2 Certificate {
- get { return this.X509CertificateAsBinary != null ? new X509Certificate2(this.X509CertificateAsBinary) : null; }
- set { this.X509CertificateAsBinary = value != null ? value.RawData : null; }
- }
-
- public Uri Callback {
- get { return this.CallbackAsString != null ? new Uri(this.CallbackAsString) : null; }
- set { this.CallbackAsString = value != null ? value.AbsoluteUri : null; }
- }
-
- string IConsumerDescription.Secret {
- get { return this.ConsumerSecret; }
- }
-
- string IConsumerDescription.Key {
- get { return this.ConsumerKey; }
- }
- }
-}
diff --git a/projecttemplates/RelyingPartyLogic/Model.Designer.cs b/projecttemplates/RelyingPartyLogic/Model.Designer.cs
index a1a5348..8884760 100644
--- a/projecttemplates/RelyingPartyLogic/Model.Designer.cs
+++ b/projecttemplates/RelyingPartyLogic/Model.Designer.cs
@@ -1,7 +1,7 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
-// Runtime Version:4.0.30104.0
+// Runtime Version:4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
@@ -11,11 +11,11 @@
[assembly: global::System.Data.Objects.DataClasses.EdmSchemaAttribute()]
[assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("DatabaseModel", "UserRole", "Role", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(RelyingPartyLogic.Role), "User", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(RelyingPartyLogic.User))]
[assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("DatabaseModel", "FK_AuthenticationToken_User", "User", global::System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(RelyingPartyLogic.User), "AuthenticationToken", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(RelyingPartyLogic.AuthenticationToken))]
-[assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("DatabaseModel", "FK_IssuedToken_Consumer1", "Consumer", global::System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(RelyingPartyLogic.Consumer), "IssuedToken", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(RelyingPartyLogic.IssuedToken))]
-[assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("DatabaseModel", "FK_IssuedToken_User1", "User", global::System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(RelyingPartyLogic.User), "IssuedToken", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(RelyingPartyLogic.IssuedToken))]
+[assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("DatabaseModel", "FK_IssuedToken_Consumer", "Client", global::System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(RelyingPartyLogic.Client), "ClientAuthorization", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(RelyingPartyLogic.ClientAuthorization))]
+[assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("DatabaseModel", "FK_IssuedToken_User", "User", global::System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(RelyingPartyLogic.User), "ClientAuthorization", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(RelyingPartyLogic.ClientAuthorization))]
// Original file name:
-// Generation date: 1/7/2010 8:42:18 PM
+// Generation date: 7/14/2010 9:35:17 PM
namespace RelyingPartyLogic
{
@@ -101,73 +101,73 @@ namespace RelyingPartyLogic
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
private global::System.Data.Objects.ObjectQuery<AuthenticationToken> _AuthenticationTokens;
/// <summary>
- /// There are no comments for Consumers in the schema.
+ /// There are no comments for Nonces in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public global::System.Data.Objects.ObjectQuery<Consumer> Consumers
+ public global::System.Data.Objects.ObjectQuery<Nonce> Nonces
{
get
{
- if ((this._Consumers == null))
+ if ((this._Nonces == null))
{
- this._Consumers = base.CreateQuery<Consumer>("[Consumers]");
+ this._Nonces = base.CreateQuery<Nonce>("[Nonces]");
}
- return this._Consumers;
+ return this._Nonces;
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private global::System.Data.Objects.ObjectQuery<Consumer> _Consumers;
+ private global::System.Data.Objects.ObjectQuery<Nonce> _Nonces;
/// <summary>
- /// There are no comments for IssuedTokens in the schema.
+ /// There are no comments for OpenIdAssociations in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public global::System.Data.Objects.ObjectQuery<IssuedToken> IssuedTokens
+ public global::System.Data.Objects.ObjectQuery<OpenIdAssociation> OpenIdAssociations
{
get
{
- if ((this._IssuedTokens == null))
+ if ((this._OpenIdAssociations == null))
{
- this._IssuedTokens = base.CreateQuery<IssuedToken>("[IssuedTokens]");
+ this._OpenIdAssociations = base.CreateQuery<OpenIdAssociation>("[OpenIdAssociations]");
}
- return this._IssuedTokens;
+ return this._OpenIdAssociations;
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private global::System.Data.Objects.ObjectQuery<IssuedToken> _IssuedTokens;
+ private global::System.Data.Objects.ObjectQuery<OpenIdAssociation> _OpenIdAssociations;
/// <summary>
- /// There are no comments for Nonces in the schema.
+ /// There are no comments for Clients in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public global::System.Data.Objects.ObjectQuery<Nonce> Nonces
+ public global::System.Data.Objects.ObjectQuery<Client> Clients
{
get
{
- if ((this._Nonces == null))
+ if ((this._Clients == null))
{
- this._Nonces = base.CreateQuery<Nonce>("[Nonces]");
+ this._Clients = base.CreateQuery<Client>("[Clients]");
}
- return this._Nonces;
+ return this._Clients;
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private global::System.Data.Objects.ObjectQuery<Nonce> _Nonces;
+ private global::System.Data.Objects.ObjectQuery<Client> _Clients;
/// <summary>
- /// There are no comments for OpenIdAssociations in the schema.
+ /// There are no comments for ClientAuthorizations in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public global::System.Data.Objects.ObjectQuery<OpenIdAssociation> OpenIdAssociations
+ public global::System.Data.Objects.ObjectQuery<ClientAuthorization> ClientAuthorizations
{
get
{
- if ((this._OpenIdAssociations == null))
+ if ((this._ClientAuthorizations == null))
{
- this._OpenIdAssociations = base.CreateQuery<OpenIdAssociation>("[OpenIdAssociations]");
+ this._ClientAuthorizations = base.CreateQuery<ClientAuthorization>("[ClientAuthorizations]");
}
- return this._OpenIdAssociations;
+ return this._ClientAuthorizations;
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private global::System.Data.Objects.ObjectQuery<OpenIdAssociation> _OpenIdAssociations;
+ private global::System.Data.Objects.ObjectQuery<ClientAuthorization> _ClientAuthorizations;
/// <summary>
/// There are no comments for Roles in the schema.
/// </summary>
@@ -193,36 +193,36 @@ namespace RelyingPartyLogic
base.AddObject("AuthenticationTokens", authenticationToken);
}
/// <summary>
- /// There are no comments for Consumers in the schema.
+ /// There are no comments for Nonces in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public void AddToConsumers(Consumer consumer)
+ public void AddToNonces(Nonce nonce)
{
- base.AddObject("Consumers", consumer);
+ base.AddObject("Nonces", nonce);
}
/// <summary>
- /// There are no comments for IssuedTokens in the schema.
+ /// There are no comments for OpenIdAssociations in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public void AddToIssuedTokens(IssuedToken issuedToken)
+ public void AddToOpenIdAssociations(OpenIdAssociation openIdAssociation)
{
- base.AddObject("IssuedTokens", issuedToken);
+ base.AddObject("OpenIdAssociations", openIdAssociation);
}
/// <summary>
- /// There are no comments for Nonces in the schema.
+ /// There are no comments for Clients in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public void AddToNonces(Nonce nonce)
+ public void AddToClients(Client client)
{
- base.AddObject("Nonces", nonce);
+ base.AddObject("Clients", client);
}
/// <summary>
- /// There are no comments for OpenIdAssociations in the schema.
+ /// There are no comments for ClientAuthorizations in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public void AddToOpenIdAssociations(OpenIdAssociation openIdAssociation)
+ public void AddToClientAuthorizations(ClientAuthorization clientAuthorization)
{
- base.AddObject("OpenIdAssociations", openIdAssociation);
+ base.AddObject("ClientAuthorizations", clientAuthorization);
}
}
/// <summary>
@@ -791,609 +791,503 @@ namespace RelyingPartyLogic
}
}
/// <summary>
- /// There are no comments for IssuedTokens in the schema.
+ /// There are no comments for ClientAuthorizations in the schema.
/// </summary>
- [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("DatabaseModel", "FK_IssuedToken_User1", "IssuedToken")]
+ [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("DatabaseModel", "FK_IssuedToken_User", "ClientAuthorization")]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
[global::System.Xml.Serialization.XmlIgnoreAttribute()]
[global::System.Xml.Serialization.SoapIgnoreAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
- public global::System.Data.Objects.DataClasses.EntityCollection<IssuedToken> IssuedTokens
+ public global::System.Data.Objects.DataClasses.EntityCollection<ClientAuthorization> ClientAuthorizations
{
get
{
- return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedCollection<IssuedToken>("DatabaseModel.FK_IssuedToken_User1", "IssuedToken");
+ return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedCollection<ClientAuthorization>("DatabaseModel.FK_IssuedToken_User", "ClientAuthorization");
}
set
{
if ((value != null))
{
- ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedCollection<IssuedToken>("DatabaseModel.FK_IssuedToken_User1", "IssuedToken", value);
+ ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedCollection<ClientAuthorization>("DatabaseModel.FK_IssuedToken_User", "ClientAuthorization", value);
}
}
}
}
/// <summary>
- /// There are no comments for DatabaseModel.Consumer in the schema.
+ /// There are no comments for DatabaseModel.Nonce in the schema.
/// </summary>
/// <KeyProperties>
- /// ConsumerId
+ /// NonceId
/// </KeyProperties>
- [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="DatabaseModel", Name="Consumer")]
+ [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="DatabaseModel", Name="Nonce")]
[global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)]
[global::System.Serializable()]
- public partial class Consumer : global::System.Data.Objects.DataClasses.EntityObject
+ public partial class Nonce : global::System.Data.Objects.DataClasses.EntityObject
{
/// <summary>
- /// Create a new Consumer object.
+ /// Create a new Nonce object.
/// </summary>
- /// <param name="consumerKey">Initial value of ConsumerKey.</param>
- /// <param name="verificationCodeLength">Initial value of VerificationCodeLength.</param>
- /// <param name="consumerId">Initial value of ConsumerId.</param>
+ /// <param name="nonceId">Initial value of NonceId.</param>
+ /// <param name="context">Initial value of Context.</param>
+ /// <param name="code">Initial value of Code.</param>
+ /// <param name="issuedUtc">Initial value of IssuedUtc.</param>
+ /// <param name="expiresUtc">Initial value of ExpiresUtc.</param>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public static Consumer CreateConsumer(string consumerKey, int verificationCodeLength, int consumerId)
+ public static Nonce CreateNonce(int nonceId, string context, string code, global::System.DateTime issuedUtc, global::System.DateTime expiresUtc)
{
- Consumer consumer = new Consumer();
- consumer.ConsumerKey = consumerKey;
- consumer.VerificationCodeLength = verificationCodeLength;
- consumer.ConsumerId = consumerId;
- return consumer;
+ Nonce nonce = new Nonce();
+ nonce.NonceId = nonceId;
+ nonce.Context = context;
+ nonce.Code = code;
+ nonce.IssuedUtc = issuedUtc;
+ nonce.ExpiresUtc = expiresUtc;
+ return nonce;
}
/// <summary>
- /// There are no comments for property ConsumerKey in the schema.
+ /// There are no comments for property NonceId in the schema.
/// </summary>
- [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
+ [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public string ConsumerKey
+ public int NonceId
{
get
{
- return this._ConsumerKey;
+ return this._NonceId;
}
set
{
- this.OnConsumerKeyChanging(value);
- this.ReportPropertyChanging("ConsumerKey");
- this._ConsumerKey = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false);
- this.ReportPropertyChanged("ConsumerKey");
- this.OnConsumerKeyChanged();
+ this.OnNonceIdChanging(value);
+ this.ReportPropertyChanging("NonceId");
+ this._NonceId = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
+ this.ReportPropertyChanged("NonceId");
+ this.OnNonceIdChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private string _ConsumerKey;
+ private int _NonceId;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnConsumerKeyChanging(string value);
+ partial void OnNonceIdChanging(int value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnConsumerKeyChanged();
+ partial void OnNonceIdChanged();
/// <summary>
- /// There are no comments for property ConsumerSecret in the schema.
+ /// Gets or sets the Provider Endpoint URL the nonce came from.
/// </summary>
- [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()]
+ [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public string ConsumerSecret
+ public string Context
{
get
{
- return this._ConsumerSecret;
+ return this._Context;
}
set
{
- this.OnConsumerSecretChanging(value);
- this.ReportPropertyChanging("ConsumerSecret");
- this._ConsumerSecret = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true);
- this.ReportPropertyChanged("ConsumerSecret");
- this.OnConsumerSecretChanged();
+ this.OnContextChanging(value);
+ this.ReportPropertyChanging("Context");
+ this._Context = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false);
+ this.ReportPropertyChanged("Context");
+ this.OnContextChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private string _ConsumerSecret;
+ private string _Context;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnConsumerSecretChanging(string value);
+ partial void OnContextChanging(string value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnConsumerSecretChanged();
+ partial void OnContextChanged();
/// <summary>
- /// There are no comments for property X509CertificateAsBinary in the schema.
+ /// There are no comments for property Code in the schema.
/// </summary>
- [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()]
+ [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private byte[] X509CertificateAsBinary
+ public string Code
{
get
{
- return global::System.Data.Objects.DataClasses.StructuralObject.GetValidValue(this._X509CertificateAsBinary);
+ return this._Code;
}
set
{
- this.OnX509CertificateAsBinaryChanging(value);
- this.ReportPropertyChanging("X509CertificateAsBinary");
- this._X509CertificateAsBinary = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true);
- this.ReportPropertyChanged("X509CertificateAsBinary");
- this.OnX509CertificateAsBinaryChanged();
+ this.OnCodeChanging(value);
+ this.ReportPropertyChanging("Code");
+ this._Code = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false);
+ this.ReportPropertyChanged("Code");
+ this.OnCodeChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private byte[] _X509CertificateAsBinary;
+ private string _Code;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnX509CertificateAsBinaryChanging(byte[] value);
+ partial void OnCodeChanging(string value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnX509CertificateAsBinaryChanged();
+ partial void OnCodeChanged();
/// <summary>
- /// There are no comments for property CallbackAsString in the schema.
+ /// There are no comments for property IssuedUtc in the schema.
/// </summary>
- [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()]
+ [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public string CallbackAsString
+ public global::System.DateTime IssuedUtc
{
get
{
- return this._CallbackAsString;
+ return this._IssuedUtc;
}
set
{
- this.OnCallbackAsStringChanging(value);
- this.ReportPropertyChanging("CallbackAsString");
- this._CallbackAsString = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true);
- this.ReportPropertyChanged("CallbackAsString");
- this.OnCallbackAsStringChanged();
+ this.OnIssuedUtcChanging(value);
+ this.ReportPropertyChanging("IssuedUtc");
+ this._IssuedUtc = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
+ this.ReportPropertyChanged("IssuedUtc");
+ this.OnIssuedUtcChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private string _CallbackAsString;
+ private global::System.DateTime _IssuedUtc;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnCallbackAsStringChanging(string value);
+ partial void OnIssuedUtcChanging(global::System.DateTime value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnCallbackAsStringChanged();
+ partial void OnIssuedUtcChanged();
/// <summary>
- /// There are no comments for property VerificationCodeFormatAsInt in the schema.
+ /// There are no comments for property ExpiresUtc in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private int VerificationCodeFormatAsInt
+ public global::System.DateTime ExpiresUtc
{
get
{
- return this._VerificationCodeFormatAsInt;
+ return this._ExpiresUtc;
}
set
{
- this.OnVerificationCodeFormatAsIntChanging(value);
- this.ReportPropertyChanging("VerificationCodeFormatAsInt");
- this._VerificationCodeFormatAsInt = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
- this.ReportPropertyChanged("VerificationCodeFormatAsInt");
- this.OnVerificationCodeFormatAsIntChanged();
+ this.OnExpiresUtcChanging(value);
+ this.ReportPropertyChanging("ExpiresUtc");
+ this._ExpiresUtc = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
+ this.ReportPropertyChanged("ExpiresUtc");
+ this.OnExpiresUtcChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private int _VerificationCodeFormatAsInt;
+ private global::System.DateTime _ExpiresUtc;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnVerificationCodeFormatAsIntChanging(int value);
+ partial void OnExpiresUtcChanging(global::System.DateTime value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnVerificationCodeFormatAsIntChanged();
+ partial void OnExpiresUtcChanged();
+ }
+ /// <summary>
+ /// There are no comments for DatabaseModel.OpenIdAssociation in the schema.
+ /// </summary>
+ /// <KeyProperties>
+ /// AssociationId
+ /// </KeyProperties>
+ [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="DatabaseModel", Name="OpenIdAssociation")]
+ [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)]
+ [global::System.Serializable()]
+ public partial class OpenIdAssociation : global::System.Data.Objects.DataClasses.EntityObject
+ {
/// <summary>
- /// There are no comments for property VerificationCodeLength in the schema.
+ /// Create a new OpenIdAssociation object.
/// </summary>
- [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
- [global::System.Runtime.Serialization.DataMemberAttribute()]
+ /// <param name="associationId">Initial value of AssociationId.</param>
+ /// <param name="distinguishingFactor">Initial value of DistinguishingFactor.</param>
+ /// <param name="associationHandle">Initial value of AssociationHandle.</param>
+ /// <param name="expirationUtc">Initial value of ExpirationUtc.</param>
+ /// <param name="privateData">Initial value of PrivateData.</param>
+ /// <param name="privateDataLength">Initial value of PrivateDataLength.</param>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public int VerificationCodeLength
+ public static OpenIdAssociation CreateOpenIdAssociation(int associationId, string distinguishingFactor, string associationHandle, global::System.DateTime expirationUtc, byte[] privateData, int privateDataLength)
{
- get
- {
- return this._VerificationCodeLength;
- }
- set
- {
- this.OnVerificationCodeLengthChanging(value);
- this.ReportPropertyChanging("VerificationCodeLength");
- this._VerificationCodeLength = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
- this.ReportPropertyChanged("VerificationCodeLength");
- this.OnVerificationCodeLengthChanged();
- }
+ OpenIdAssociation openIdAssociation = new OpenIdAssociation();
+ openIdAssociation.AssociationId = associationId;
+ openIdAssociation.DistinguishingFactor = distinguishingFactor;
+ openIdAssociation.AssociationHandle = associationHandle;
+ openIdAssociation.ExpirationUtc = expirationUtc;
+ openIdAssociation.PrivateData = privateData;
+ openIdAssociation.PrivateDataLength = privateDataLength;
+ return openIdAssociation;
}
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private int _VerificationCodeLength;
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnVerificationCodeLengthChanging(int value);
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnVerificationCodeLengthChanged();
/// <summary>
- /// There are no comments for property ConsumerId in the schema.
+ /// There are no comments for property AssociationId in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public int ConsumerId
+ public int AssociationId
{
get
{
- return this._ConsumerId;
+ return this._AssociationId;
}
- private set
+ set
{
- this.OnConsumerIdChanging(value);
- this.ReportPropertyChanging("ConsumerId");
- this._ConsumerId = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
- this.ReportPropertyChanged("ConsumerId");
- this.OnConsumerIdChanged();
+ this.OnAssociationIdChanging(value);
+ this.ReportPropertyChanging("AssociationId");
+ this._AssociationId = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
+ this.ReportPropertyChanged("AssociationId");
+ this.OnAssociationIdChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private int _ConsumerId;
+ private int _AssociationId;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnConsumerIdChanging(int value);
+ partial void OnAssociationIdChanging(int value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnConsumerIdChanged();
+ partial void OnAssociationIdChanged();
/// <summary>
- /// There are no comments for property Name in the schema.
+ /// Gets or sets the Provider Endpoint URL the association is with.
/// </summary>
- [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()]
+ [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public string Name
+ public string DistinguishingFactor
{
get
{
- return this._Name;
+ return this._DistinguishingFactor;
}
set
{
- this.OnNameChanging(value);
- this.ReportPropertyChanging("Name");
- this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true);
- this.ReportPropertyChanged("Name");
- this.OnNameChanged();
+ this.OnDistinguishingFactorChanging(value);
+ this.ReportPropertyChanging("DistinguishingFactor");
+ this._DistinguishingFactor = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false);
+ this.ReportPropertyChanged("DistinguishingFactor");
+ this.OnDistinguishingFactorChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private string _Name;
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnNameChanging(string value);
+ private string _DistinguishingFactor;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnNameChanged();
- /// <summary>
- /// There are no comments for IssuedTokens in the schema.
- /// </summary>
- [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("DatabaseModel", "FK_IssuedToken_Consumer1", "IssuedToken")]
+ partial void OnDistinguishingFactorChanging(string value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- [global::System.Xml.Serialization.XmlIgnoreAttribute()]
- [global::System.Xml.Serialization.SoapIgnoreAttribute()]
- [global::System.Runtime.Serialization.DataMemberAttribute()]
- public global::System.Data.Objects.DataClasses.EntityCollection<IssuedToken> IssuedTokens
- {
- get
- {
- return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedCollection<IssuedToken>("DatabaseModel.FK_IssuedToken_Consumer1", "IssuedToken");
- }
- set
- {
- if ((value != null))
- {
- ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedCollection<IssuedToken>("DatabaseModel.FK_IssuedToken_Consumer1", "IssuedToken", value);
- }
- }
- }
- }
- /// <summary>
- /// There are no comments for DatabaseModel.IssuedToken in the schema.
- /// </summary>
- /// <KeyProperties>
- /// IssuedTokenId
- /// </KeyProperties>
- [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="DatabaseModel", Name="IssuedToken")]
- [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)]
- [global::System.Serializable()]
- [global::System.Runtime.Serialization.KnownTypeAttribute(typeof(global::RelyingPartyLogic.IssuedRequestToken))]
- [global::System.Runtime.Serialization.KnownTypeAttribute(typeof(global::RelyingPartyLogic.IssuedAccessToken))]
- public abstract partial class IssuedToken : global::System.Data.Objects.DataClasses.EntityObject
- {
+ partial void OnDistinguishingFactorChanged();
/// <summary>
- /// There are no comments for property Token in the schema.
+ /// There are no comments for property AssociationHandle in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public string Token
+ public string AssociationHandle
{
get
{
- return this._Token;
+ return this._AssociationHandle;
}
set
{
- this.OnTokenChanging(value);
- this.ReportPropertyChanging("Token");
- this._Token = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false);
- this.ReportPropertyChanged("Token");
- this.OnTokenChanged();
+ this.OnAssociationHandleChanging(value);
+ this.ReportPropertyChanging("AssociationHandle");
+ this._AssociationHandle = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false);
+ this.ReportPropertyChanged("AssociationHandle");
+ this.OnAssociationHandleChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private string _Token;
+ private string _AssociationHandle;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnTokenChanging(string value);
+ partial void OnAssociationHandleChanging(string value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnTokenChanged();
+ partial void OnAssociationHandleChanged();
/// <summary>
- /// There are no comments for property TokenSecret in the schema.
+ /// There are no comments for property ExpirationUtc in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public string TokenSecret
+ public global::System.DateTime ExpirationUtc
{
get
{
- return this._TokenSecret;
+ return this._ExpirationUtc;
}
set
{
- this.OnTokenSecretChanging(value);
- this.ReportPropertyChanging("TokenSecret");
- this._TokenSecret = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false);
- this.ReportPropertyChanged("TokenSecret");
- this.OnTokenSecretChanged();
+ this.OnExpirationUtcChanging(value);
+ this.ReportPropertyChanging("ExpirationUtc");
+ this._ExpirationUtc = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
+ this.ReportPropertyChanged("ExpirationUtc");
+ this.OnExpirationUtcChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private string _TokenSecret;
+ private global::System.DateTime _ExpirationUtc;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnTokenSecretChanging(string value);
+ partial void OnExpirationUtcChanging(global::System.DateTime value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnTokenSecretChanged();
+ partial void OnExpirationUtcChanged();
/// <summary>
- /// There are no comments for property CreatedOnUtc in the schema.
+ /// There are no comments for property PrivateData in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public global::System.DateTime CreatedOnUtc
+ public byte[] PrivateData
{
get
{
- return this._CreatedOnUtc;
+ return global::System.Data.Objects.DataClasses.StructuralObject.GetValidValue(this._PrivateData);
}
- internal set
+ set
{
- this.OnCreatedOnUtcChanging(value);
- this.ReportPropertyChanging("CreatedOnUtc");
- this._CreatedOnUtc = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
- this.ReportPropertyChanged("CreatedOnUtc");
- this.OnCreatedOnUtcChanged();
+ this.OnPrivateDataChanging(value);
+ this.ReportPropertyChanging("PrivateData");
+ this._PrivateData = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false);
+ this.ReportPropertyChanged("PrivateData");
+ this.OnPrivateDataChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private global::System.DateTime _CreatedOnUtc;
+ private byte[] _PrivateData;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnCreatedOnUtcChanging(global::System.DateTime value);
+ partial void OnPrivateDataChanging(byte[] value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnCreatedOnUtcChanged();
+ partial void OnPrivateDataChanged();
/// <summary>
- /// There are no comments for property Scope in the schema.
+ /// There are no comments for property PrivateDataLength in the schema.
/// </summary>
- [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()]
+ [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public string Scope
+ public int PrivateDataLength
{
get
{
- return this._Scope;
+ return this._PrivateDataLength;
}
set
{
- this.OnScopeChanging(value);
- this.ReportPropertyChanging("Scope");
- this._Scope = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true);
- this.ReportPropertyChanged("Scope");
- this.OnScopeChanged();
+ this.OnPrivateDataLengthChanging(value);
+ this.ReportPropertyChanging("PrivateDataLength");
+ this._PrivateDataLength = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
+ this.ReportPropertyChanged("PrivateDataLength");
+ this.OnPrivateDataLengthChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private string _Scope;
+ private int _PrivateDataLength;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnScopeChanging(string value);
+ partial void OnPrivateDataLengthChanging(int value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnScopeChanged();
+ partial void OnPrivateDataLengthChanged();
+ }
+ /// <summary>
+ /// There are no comments for DatabaseModel.Client in the schema.
+ /// </summary>
+ /// <KeyProperties>
+ /// ClientId
+ /// </KeyProperties>
+ [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="DatabaseModel", Name="Client")]
+ [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)]
+ [global::System.Serializable()]
+ public partial class Client : global::System.Data.Objects.DataClasses.EntityObject
+ {
/// <summary>
- /// There are no comments for property IssuedTokenId in the schema.
+ /// Create a new Client object.
/// </summary>
- [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
- [global::System.Runtime.Serialization.DataMemberAttribute()]
+ /// <param name="clientId">Initial value of ClientId.</param>
+ /// <param name="clientIdentifier">Initial value of ClientIdentifier.</param>
+ /// <param name="name">Initial value of Name.</param>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public int IssuedTokenId
+ public static Client CreateClient(int clientId, string clientIdentifier, string name)
{
- get
- {
- return this._IssuedTokenId;
- }
- internal set
- {
- this.OnIssuedTokenIdChanging(value);
- this.ReportPropertyChanging("IssuedTokenId");
- this._IssuedTokenId = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
- this.ReportPropertyChanged("IssuedTokenId");
- this.OnIssuedTokenIdChanged();
- }
+ Client client = new Client();
+ client.ClientId = clientId;
+ client.ClientIdentifier = clientIdentifier;
+ client.Name = name;
+ return client;
}
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private int _IssuedTokenId;
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnIssuedTokenIdChanging(int value);
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnIssuedTokenIdChanged();
/// <summary>
- /// There are no comments for Consumer in the schema.
+ /// There are no comments for property ClientId in the schema.
/// </summary>
- [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("DatabaseModel", "FK_IssuedToken_Consumer1", "Consumer")]
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- [global::System.Xml.Serialization.XmlIgnoreAttribute()]
- [global::System.Xml.Serialization.SoapIgnoreAttribute()]
+ [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
- public Consumer Consumer
- {
- get
- {
- return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<Consumer>("DatabaseModel.FK_IssuedToken_Consumer1", "Consumer").Value;
- }
- set
- {
- ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<Consumer>("DatabaseModel.FK_IssuedToken_Consumer1", "Consumer").Value = value;
- }
- }
- /// <summary>
- /// There are no comments for Consumer in the schema.
- /// </summary>
- [global::System.ComponentModel.BrowsableAttribute(false)]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- [global::System.Runtime.Serialization.DataMemberAttribute()]
- public global::System.Data.Objects.DataClasses.EntityReference<Consumer> ConsumerReference
+ public int ClientId
{
get
{
- return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<Consumer>("DatabaseModel.FK_IssuedToken_Consumer1", "Consumer");
+ return this._ClientId;
}
set
{
- if ((value != null))
- {
- ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedReference<Consumer>("DatabaseModel.FK_IssuedToken_Consumer1", "Consumer", value);
- }
+ this.OnClientIdChanging(value);
+ this.ReportPropertyChanging("ClientId");
+ this._ClientId = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
+ this.ReportPropertyChanged("ClientId");
+ this.OnClientIdChanged();
}
}
- /// <summary>
- /// There are no comments for User in the schema.
- /// </summary>
- [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("DatabaseModel", "FK_IssuedToken_User1", "User")]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- [global::System.Xml.Serialization.XmlIgnoreAttribute()]
- [global::System.Xml.Serialization.SoapIgnoreAttribute()]
- [global::System.Runtime.Serialization.DataMemberAttribute()]
- public User User
- {
- get
- {
- return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<User>("DatabaseModel.FK_IssuedToken_User1", "User").Value;
- }
- set
- {
- ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<User>("DatabaseModel.FK_IssuedToken_User1", "User").Value = value;
- }
- }
- /// <summary>
- /// There are no comments for User in the schema.
- /// </summary>
- [global::System.ComponentModel.BrowsableAttribute(false)]
+ private int _ClientId;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- [global::System.Runtime.Serialization.DataMemberAttribute()]
- public global::System.Data.Objects.DataClasses.EntityReference<User> UserReference
- {
- get
- {
- return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<User>("DatabaseModel.FK_IssuedToken_User1", "User");
- }
- set
- {
- if ((value != null))
- {
- ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedReference<User>("DatabaseModel.FK_IssuedToken_User1", "User", value);
- }
- }
- }
- }
- /// <summary>
- /// There are no comments for DatabaseModel.IssuedRequestToken in the schema.
- /// </summary>
- /// <KeyProperties>
- /// IssuedTokenId
- /// </KeyProperties>
- [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="DatabaseModel", Name="IssuedRequestToken")]
- [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)]
- [global::System.Serializable()]
- public partial class IssuedRequestToken : IssuedToken
- {
- /// <summary>
- /// Create a new IssuedRequestToken object.
- /// </summary>
- /// <param name="token">Initial value of Token.</param>
- /// <param name="tokenSecret">Initial value of TokenSecret.</param>
- /// <param name="createdOnUtc">Initial value of CreatedOnUtc.</param>
- /// <param name="issuedTokenId">Initial value of IssuedTokenId.</param>
+ partial void OnClientIdChanging(int value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public static IssuedRequestToken CreateIssuedRequestToken(string token, string tokenSecret, global::System.DateTime createdOnUtc, int issuedTokenId)
- {
- IssuedRequestToken issuedRequestToken = new IssuedRequestToken();
- issuedRequestToken.Token = token;
- issuedRequestToken.TokenSecret = tokenSecret;
- issuedRequestToken.CreatedOnUtc = createdOnUtc;
- issuedRequestToken.IssuedTokenId = issuedTokenId;
- return issuedRequestToken;
- }
+ partial void OnClientIdChanged();
/// <summary>
- /// There are no comments for property ConsumerVersionAsString in the schema.
+ /// There are no comments for property ClientIdentifier in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private string ConsumerVersionAsString
+ public string ClientIdentifier
{
get
{
- return this._ConsumerVersionAsString;
+ return this._ClientIdentifier;
}
set
{
- this.OnConsumerVersionAsStringChanging(value);
- this.ReportPropertyChanging("ConsumerVersionAsString");
- this._ConsumerVersionAsString = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false);
- this.ReportPropertyChanged("ConsumerVersionAsString");
- this.OnConsumerVersionAsStringChanged();
+ this.OnClientIdentifierChanging(value);
+ this.ReportPropertyChanging("ClientIdentifier");
+ this._ClientIdentifier = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false);
+ this.ReportPropertyChanged("ClientIdentifier");
+ this.OnClientIdentifierChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private string _ConsumerVersionAsString;
+ private string _ClientIdentifier;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnConsumerVersionAsStringChanging(string value);
+ partial void OnClientIdentifierChanging(string value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnConsumerVersionAsStringChanged();
+ partial void OnClientIdentifierChanged();
/// <summary>
- /// There are no comments for property VerificationCode in the schema.
+ /// There are no comments for property ClientSecret in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public string VerificationCode
+ public string ClientSecret
{
get
{
- return this._VerificationCode;
+ return this._ClientSecret;
}
set
{
- this.OnVerificationCodeChanging(value);
- this.ReportPropertyChanging("VerificationCode");
- this._VerificationCode = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true);
- this.ReportPropertyChanged("VerificationCode");
- this.OnVerificationCodeChanged();
+ this.OnClientSecretChanging(value);
+ this.ReportPropertyChanging("ClientSecret");
+ this._ClientSecret = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true);
+ this.ReportPropertyChanged("ClientSecret");
+ this.OnClientSecretChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private string _VerificationCode;
+ private string _ClientSecret;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnVerificationCodeChanging(string value);
+ partial void OnClientSecretChanging(string value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnVerificationCodeChanged();
+ partial void OnClientSecretChanged();
/// <summary>
/// There are no comments for property CallbackAsString in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private string CallbackAsString
+ public string CallbackAsString
{
get
{
@@ -1414,422 +1308,265 @@ namespace RelyingPartyLogic
partial void OnCallbackAsStringChanging(string value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
partial void OnCallbackAsStringChanged();
- }
- /// <summary>
- /// There are no comments for DatabaseModel.IssuedAccessToken in the schema.
- /// </summary>
- /// <KeyProperties>
- /// IssuedTokenId
- /// </KeyProperties>
- [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="DatabaseModel", Name="IssuedAccessToken")]
- [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)]
- [global::System.Serializable()]
- public partial class IssuedAccessToken : IssuedToken
- {
/// <summary>
- /// Create a new IssuedAccessToken object.
- /// </summary>
- /// <param name="token">Initial value of Token.</param>
- /// <param name="tokenSecret">Initial value of TokenSecret.</param>
- /// <param name="createdOnUtc">Initial value of CreatedOnUtc.</param>
- /// <param name="issuedTokenId">Initial value of IssuedTokenId.</param>
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public static IssuedAccessToken CreateIssuedAccessToken(string token, string tokenSecret, global::System.DateTime createdOnUtc, int issuedTokenId)
- {
- IssuedAccessToken issuedAccessToken = new IssuedAccessToken();
- issuedAccessToken.Token = token;
- issuedAccessToken.TokenSecret = tokenSecret;
- issuedAccessToken.CreatedOnUtc = createdOnUtc;
- issuedAccessToken.IssuedTokenId = issuedTokenId;
- return issuedAccessToken;
- }
- /// <summary>
- /// There are no comments for property ExpirationDateUtc in the schema.
+ /// There are no comments for property Name in the schema.
/// </summary>
- [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()]
+ [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public global::System.Nullable<global::System.DateTime> ExpirationDateUtc
+ public string Name
{
get
{
- return this._ExpirationDateUtc;
+ return this._Name;
}
set
{
- this.OnExpirationDateUtcChanging(value);
- this.ReportPropertyChanging("ExpirationDateUtc");
- this._ExpirationDateUtc = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
- this.ReportPropertyChanged("ExpirationDateUtc");
- this.OnExpirationDateUtcChanged();
+ this.OnNameChanging(value);
+ this.ReportPropertyChanging("Name");
+ this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false);
+ this.ReportPropertyChanged("Name");
+ this.OnNameChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private global::System.Nullable<global::System.DateTime> _ExpirationDateUtc;
+ private string _Name;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnExpirationDateUtcChanging(global::System.Nullable<global::System.DateTime> value);
+ partial void OnNameChanging(string value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnExpirationDateUtcChanged();
- }
- /// <summary>
- /// There are no comments for DatabaseModel.Nonce in the schema.
- /// </summary>
- /// <KeyProperties>
- /// NonceId
- /// </KeyProperties>
- [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="DatabaseModel", Name="Nonce")]
- [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)]
- [global::System.Serializable()]
- public partial class Nonce : global::System.Data.Objects.DataClasses.EntityObject
- {
+ partial void OnNameChanged();
/// <summary>
- /// Create a new Nonce object.
+ /// There are no comments for ClientAuthorizations in the schema.
/// </summary>
- /// <param name="nonceId">Initial value of NonceId.</param>
- /// <param name="context">Initial value of Context.</param>
- /// <param name="code">Initial value of Code.</param>
- /// <param name="issuedUtc">Initial value of IssuedUtc.</param>
- /// <param name="expiresUtc">Initial value of ExpiresUtc.</param>
+ [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("DatabaseModel", "FK_IssuedToken_Consumer", "ClientAuthorization")]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public static Nonce CreateNonce(int nonceId, string context, string code, global::System.DateTime issuedUtc, global::System.DateTime expiresUtc)
- {
- Nonce nonce = new Nonce();
- nonce.NonceId = nonceId;
- nonce.Context = context;
- nonce.Code = code;
- nonce.IssuedUtc = issuedUtc;
- nonce.ExpiresUtc = expiresUtc;
- return nonce;
- }
- /// <summary>
- /// There are no comments for property NonceId in the schema.
- /// </summary>
- [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
+ [global::System.Xml.Serialization.XmlIgnoreAttribute()]
+ [global::System.Xml.Serialization.SoapIgnoreAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public int NonceId
+ public global::System.Data.Objects.DataClasses.EntityCollection<ClientAuthorization> ClientAuthorizations
{
get
{
- return this._NonceId;
+ return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedCollection<ClientAuthorization>("DatabaseModel.FK_IssuedToken_Consumer", "ClientAuthorization");
}
set
{
- this.OnNonceIdChanging(value);
- this.ReportPropertyChanging("NonceId");
- this._NonceId = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
- this.ReportPropertyChanged("NonceId");
- this.OnNonceIdChanged();
+ if ((value != null))
+ {
+ ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedCollection<ClientAuthorization>("DatabaseModel.FK_IssuedToken_Consumer", "ClientAuthorization", value);
+ }
}
}
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private int _NonceId;
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnNonceIdChanging(int value);
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnNonceIdChanged();
+ }
+ /// <summary>
+ /// There are no comments for DatabaseModel.ClientAuthorization in the schema.
+ /// </summary>
+ /// <KeyProperties>
+ /// AuthorizationId
+ /// </KeyProperties>
+ [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="DatabaseModel", Name="ClientAuthorization")]
+ [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)]
+ [global::System.Serializable()]
+ public partial class ClientAuthorization : global::System.Data.Objects.DataClasses.EntityObject
+ {
/// <summary>
- /// Gets or sets the Provider Endpoint URL the nonce came from.
+ /// Create a new ClientAuthorization object.
/// </summary>
- [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
- [global::System.Runtime.Serialization.DataMemberAttribute()]
+ /// <param name="authorizationId">Initial value of AuthorizationId.</param>
+ /// <param name="createdOnUtc">Initial value of CreatedOnUtc.</param>
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public string Context
+ public static ClientAuthorization CreateClientAuthorization(int authorizationId, global::System.DateTime createdOnUtc)
{
- get
- {
- return this._Context;
- }
- set
- {
- this.OnContextChanging(value);
- this.ReportPropertyChanging("Context");
- this._Context = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false);
- this.ReportPropertyChanged("Context");
- this.OnContextChanged();
- }
+ ClientAuthorization clientAuthorization = new ClientAuthorization();
+ clientAuthorization.AuthorizationId = authorizationId;
+ clientAuthorization.CreatedOnUtc = createdOnUtc;
+ return clientAuthorization;
}
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private string _Context;
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnContextChanging(string value);
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnContextChanged();
/// <summary>
- /// There are no comments for property Code in the schema.
+ /// There are no comments for property AuthorizationId in the schema.
/// </summary>
- [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
+ [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public string Code
+ public int AuthorizationId
{
get
{
- return this._Code;
+ return this._AuthorizationId;
}
set
{
- this.OnCodeChanging(value);
- this.ReportPropertyChanging("Code");
- this._Code = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false);
- this.ReportPropertyChanged("Code");
- this.OnCodeChanged();
+ this.OnAuthorizationIdChanging(value);
+ this.ReportPropertyChanging("AuthorizationId");
+ this._AuthorizationId = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
+ this.ReportPropertyChanged("AuthorizationId");
+ this.OnAuthorizationIdChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private string _Code;
+ private int _AuthorizationId;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnCodeChanging(string value);
+ partial void OnAuthorizationIdChanging(int value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnCodeChanged();
+ partial void OnAuthorizationIdChanged();
/// <summary>
- /// There are no comments for property IssuedUtc in the schema.
+ /// There are no comments for property CreatedOnUtc in the schema.
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public global::System.DateTime IssuedUtc
+ public global::System.DateTime CreatedOnUtc
{
get
{
- return this._IssuedUtc;
+ return this._CreatedOnUtc;
}
set
{
- this.OnIssuedUtcChanging(value);
- this.ReportPropertyChanging("IssuedUtc");
- this._IssuedUtc = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
- this.ReportPropertyChanged("IssuedUtc");
- this.OnIssuedUtcChanged();
+ this.OnCreatedOnUtcChanging(value);
+ this.ReportPropertyChanging("CreatedOnUtc");
+ this._CreatedOnUtc = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
+ this.ReportPropertyChanged("CreatedOnUtc");
+ this.OnCreatedOnUtcChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private global::System.DateTime _IssuedUtc;
+ private global::System.DateTime _CreatedOnUtc;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnIssuedUtcChanging(global::System.DateTime value);
+ partial void OnCreatedOnUtcChanging(global::System.DateTime value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnIssuedUtcChanged();
+ partial void OnCreatedOnUtcChanged();
/// <summary>
- /// There are no comments for property ExpiresUtc in the schema.
+ /// There are no comments for property ExpirationDate in the schema.
/// </summary>
- [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
+ [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public global::System.DateTime ExpiresUtc
+ public global::System.Nullable<global::System.DateTime> ExpirationDate
{
get
{
- return this._ExpiresUtc;
+ return this._ExpirationDate;
}
set
{
- this.OnExpiresUtcChanging(value);
- this.ReportPropertyChanging("ExpiresUtc");
- this._ExpiresUtc = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
- this.ReportPropertyChanged("ExpiresUtc");
- this.OnExpiresUtcChanged();
+ this.OnExpirationDateChanging(value);
+ this.ReportPropertyChanging("ExpirationDate");
+ this._ExpirationDate = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
+ this.ReportPropertyChanged("ExpirationDate");
+ this.OnExpirationDateChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private global::System.DateTime _ExpiresUtc;
+ private global::System.Nullable<global::System.DateTime> _ExpirationDate;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnExpiresUtcChanging(global::System.DateTime value);
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnExpiresUtcChanged();
- }
- /// <summary>
- /// There are no comments for DatabaseModel.OpenIdAssociation in the schema.
- /// </summary>
- /// <KeyProperties>
- /// AssociationId
- /// </KeyProperties>
- [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="DatabaseModel", Name="OpenIdAssociation")]
- [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)]
- [global::System.Serializable()]
- public partial class OpenIdAssociation : global::System.Data.Objects.DataClasses.EntityObject
- {
- /// <summary>
- /// Create a new OpenIdAssociation object.
- /// </summary>
- /// <param name="associationId">Initial value of AssociationId.</param>
- /// <param name="distinguishingFactor">Initial value of DistinguishingFactor.</param>
- /// <param name="associationHandle">Initial value of AssociationHandle.</param>
- /// <param name="expirationUtc">Initial value of ExpirationUtc.</param>
- /// <param name="privateData">Initial value of PrivateData.</param>
- /// <param name="privateDataLength">Initial value of PrivateDataLength.</param>
+ partial void OnExpirationDateChanging(global::System.Nullable<global::System.DateTime> value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public static OpenIdAssociation CreateOpenIdAssociation(int associationId, string distinguishingFactor, string associationHandle, global::System.DateTime expirationUtc, byte[] privateData, int privateDataLength)
- {
- OpenIdAssociation openIdAssociation = new OpenIdAssociation();
- openIdAssociation.AssociationId = associationId;
- openIdAssociation.DistinguishingFactor = distinguishingFactor;
- openIdAssociation.AssociationHandle = associationHandle;
- openIdAssociation.ExpirationUtc = expirationUtc;
- openIdAssociation.PrivateData = privateData;
- openIdAssociation.PrivateDataLength = privateDataLength;
- return openIdAssociation;
- }
+ partial void OnExpirationDateChanged();
/// <summary>
- /// There are no comments for property AssociationId in the schema.
+ /// There are no comments for property Scope in the schema.
/// </summary>
- [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
+ [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public int AssociationId
+ public string Scope
{
get
{
- return this._AssociationId;
+ return this._Scope;
}
set
{
- this.OnAssociationIdChanging(value);
- this.ReportPropertyChanging("AssociationId");
- this._AssociationId = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
- this.ReportPropertyChanged("AssociationId");
- this.OnAssociationIdChanged();
+ this.OnScopeChanging(value);
+ this.ReportPropertyChanging("Scope");
+ this._Scope = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true);
+ this.ReportPropertyChanged("Scope");
+ this.OnScopeChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private int _AssociationId;
+ private string _Scope;
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnAssociationIdChanging(int value);
+ partial void OnScopeChanging(string value);
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnAssociationIdChanged();
+ partial void OnScopeChanged();
/// <summary>
- /// Gets or sets the Provider Endpoint URL the association is with.
+ /// There are no comments for Client in the schema.
/// </summary>
- [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
- [global::System.Runtime.Serialization.DataMemberAttribute()]
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public string DistinguishingFactor
- {
- get
- {
- return this._DistinguishingFactor;
- }
- set
- {
- this.OnDistinguishingFactorChanging(value);
- this.ReportPropertyChanging("DistinguishingFactor");
- this._DistinguishingFactor = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false);
- this.ReportPropertyChanged("DistinguishingFactor");
- this.OnDistinguishingFactorChanged();
- }
- }
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private string _DistinguishingFactor;
+ [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("DatabaseModel", "FK_IssuedToken_Consumer", "Client")]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnDistinguishingFactorChanging(string value);
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnDistinguishingFactorChanged();
- /// <summary>
- /// There are no comments for property AssociationHandle in the schema.
- /// </summary>
- [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
+ [global::System.Xml.Serialization.XmlIgnoreAttribute()]
+ [global::System.Xml.Serialization.SoapIgnoreAttribute()]
[global::System.Runtime.Serialization.DataMemberAttribute()]
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public string AssociationHandle
+ public Client Client
{
get
{
- return this._AssociationHandle;
+ return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<Client>("DatabaseModel.FK_IssuedToken_Consumer", "Client").Value;
}
set
{
- this.OnAssociationHandleChanging(value);
- this.ReportPropertyChanging("AssociationHandle");
- this._AssociationHandle = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false);
- this.ReportPropertyChanged("AssociationHandle");
- this.OnAssociationHandleChanged();
+ ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<Client>("DatabaseModel.FK_IssuedToken_Consumer", "Client").Value = value;
}
}
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private string _AssociationHandle;
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnAssociationHandleChanging(string value);
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnAssociationHandleChanged();
/// <summary>
- /// There are no comments for property ExpirationUtc in the schema.
+ /// There are no comments for Client in the schema.
/// </summary>
- [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
- [global::System.Runtime.Serialization.DataMemberAttribute()]
+ [global::System.ComponentModel.BrowsableAttribute(false)]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public global::System.DateTime ExpirationUtc
+ [global::System.Runtime.Serialization.DataMemberAttribute()]
+ public global::System.Data.Objects.DataClasses.EntityReference<Client> ClientReference
{
get
{
- return this._ExpirationUtc;
+ return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<Client>("DatabaseModel.FK_IssuedToken_Consumer", "Client");
}
set
{
- this.OnExpirationUtcChanging(value);
- this.ReportPropertyChanging("ExpirationUtc");
- this._ExpirationUtc = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
- this.ReportPropertyChanged("ExpirationUtc");
- this.OnExpirationUtcChanged();
+ if ((value != null))
+ {
+ ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedReference<Client>("DatabaseModel.FK_IssuedToken_Consumer", "Client", value);
+ }
}
}
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private global::System.DateTime _ExpirationUtc;
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnExpirationUtcChanging(global::System.DateTime value);
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnExpirationUtcChanged();
/// <summary>
- /// There are no comments for property PrivateData in the schema.
+ /// There are no comments for User in the schema.
/// </summary>
- [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
- [global::System.Runtime.Serialization.DataMemberAttribute()]
+ [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("DatabaseModel", "FK_IssuedToken_User", "User")]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public byte[] PrivateData
+ [global::System.Xml.Serialization.XmlIgnoreAttribute()]
+ [global::System.Xml.Serialization.SoapIgnoreAttribute()]
+ [global::System.Runtime.Serialization.DataMemberAttribute()]
+ public User User
{
get
{
- return global::System.Data.Objects.DataClasses.StructuralObject.GetValidValue(this._PrivateData);
+ return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<User>("DatabaseModel.FK_IssuedToken_User", "User").Value;
}
set
{
- this.OnPrivateDataChanging(value);
- this.ReportPropertyChanging("PrivateData");
- this._PrivateData = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false);
- this.ReportPropertyChanged("PrivateData");
- this.OnPrivateDataChanged();
+ ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<User>("DatabaseModel.FK_IssuedToken_User", "User").Value = value;
}
}
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private byte[] _PrivateData;
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnPrivateDataChanging(byte[] value);
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnPrivateDataChanged();
/// <summary>
- /// There are no comments for property PrivateDataLength in the schema.
+ /// There are no comments for User in the schema.
/// </summary>
- [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)]
- [global::System.Runtime.Serialization.DataMemberAttribute()]
+ [global::System.ComponentModel.BrowsableAttribute(false)]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- public int PrivateDataLength
+ [global::System.Runtime.Serialization.DataMemberAttribute()]
+ public global::System.Data.Objects.DataClasses.EntityReference<User> UserReference
{
get
{
- return this._PrivateDataLength;
+ return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference<User>("DatabaseModel.FK_IssuedToken_User", "User");
}
set
{
- this.OnPrivateDataLengthChanging(value);
- this.ReportPropertyChanging("PrivateDataLength");
- this._PrivateDataLength = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value);
- this.ReportPropertyChanged("PrivateDataLength");
- this.OnPrivateDataLengthChanged();
+ if ((value != null))
+ {
+ ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedReference<User>("DatabaseModel.FK_IssuedToken_User", "User", value);
+ }
}
}
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- private int _PrivateDataLength;
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnPrivateDataLengthChanging(int value);
- [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
- partial void OnPrivateDataLengthChanged();
}
}
diff --git a/projecttemplates/RelyingPartyLogic/Model.IssuedAccessToken.cs b/projecttemplates/RelyingPartyLogic/Model.IssuedAccessToken.cs
deleted file mode 100644
index 25d983b..0000000
--- a/projecttemplates/RelyingPartyLogic/Model.IssuedAccessToken.cs
+++ /dev/null
@@ -1,74 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="Model.IssuedAccessToken.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace RelyingPartyLogic {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using DotNetOpenAuth.OAuth.ChannelElements;
-
- public partial class IssuedAccessToken : IServiceProviderAccessToken {
- /// <summary>
- /// Gets the roles that the OAuth principal should belong to.
- /// </summary>
- /// <value>
- /// The roles that the user belongs to, or a subset of these according to the rights
- /// granted when the user authorized the request token.
- /// </value>
- string[] IServiceProviderAccessToken.Roles {
- get {
- List<string> roles = new List<string>();
-
- // Include the roles the user who authorized this OAuth token has.
- roles.AddRange(this.User.Roles.Select(r => r.Name));
-
- // Always add an extra role to indicate this is an OAuth-authorized request.
- // This allows us to deny access to account management pages to OAuth requests.
- roles.Add("delegated");
-
- return roles.ToArray();
- }
- }
-
- /// <summary>
- /// Gets the username of the principal that will be impersonated by this access token.
- /// </summary>
- /// <value>
- /// The name of the user who authorized the OAuth request token originally.
- /// </value>
- string IServiceProviderAccessToken.Username {
- get {
- // We don't really have the concept of a single username, but we
- // can use any of the authentication tokens instead since that
- // is what the rest of the web site expects.
- if (!this.UserReference.IsLoaded) {
- this.UserReference.Load();
- }
- if (!this.User.AuthenticationTokens.IsLoaded) {
- this.User.AuthenticationTokens.Load();
- }
- return this.User.AuthenticationTokens.First().ClaimedIdentifier;
- }
- }
-
- /// <summary>
- /// Gets the expiration date (local time) for the access token.
- /// </summary>
- /// <value>
- /// The expiration date, or <c>null</c> if there is no expiration date.
- /// </value>
- DateTime? IServiceProviderAccessToken.ExpirationDate {
- get { return this.ExpirationDateUtc.HasValue ? (DateTime?)this.ExpirationDateUtc.Value.ToLocalTime() : null; }
- }
-
- partial void OnExpirationDateUtcChanging(DateTime? value) {
- if (value.HasValue) {
- Utilities.VerifyThrowNotLocalTime(value.Value);
- }
- }
- }
-}
diff --git a/projecttemplates/RelyingPartyLogic/Model.IssuedRequestToken.cs b/projecttemplates/RelyingPartyLogic/Model.IssuedRequestToken.cs
deleted file mode 100644
index 1e96eb7..0000000
--- a/projecttemplates/RelyingPartyLogic/Model.IssuedRequestToken.cs
+++ /dev/null
@@ -1,63 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="Model.IssuedRequestToken.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace RelyingPartyLogic {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using DotNetOpenAuth.OAuth.ChannelElements;
-
- public partial class IssuedRequestToken : IServiceProviderRequestToken {
- /// <summary>
- /// Gets or sets the callback associated specifically with this token, if any.
- /// </summary>
- /// <value>
- /// The callback URI; or <c>null</c> if no callback was specifically assigned to this token.
- /// </value>
- public Uri Callback {
- get { return this.CallbackAsString != null ? new Uri(this.CallbackAsString) : null; }
- set { this.CallbackAsString = value != null ? value.AbsoluteUri : null; }
- }
-
- /// <summary>
- /// Gets or sets the version of the Consumer that requested this token.
- /// </summary>
- /// <remarks>
- /// This property is used to determine whether a <see cref="VerificationCode"/> must be
- /// generated when the user authorizes the Consumer or not.
- /// </remarks>
- Version IServiceProviderRequestToken.ConsumerVersion {
- get { return this.ConsumerVersionAsString != null ? new Version(this.ConsumerVersionAsString) : null; }
- set { this.ConsumerVersionAsString = value != null ? value.ToString() : null; }
- }
-
- /// <summary>
- /// Gets the consumer key that requested this token.
- /// </summary>
- string IServiceProviderRequestToken.ConsumerKey {
- get { return this.Consumer.ConsumerKey; }
- }
-
- /// <summary>
- /// Gets the (local) date that this request token was first created on.
- /// </summary>
- DateTime IServiceProviderRequestToken.CreatedOn {
- get { return this.CreatedOnUtc.ToLocalTime(); }
- }
-
- /// <summary>
- /// Authorizes this request token to allow exchange for an access token.
- /// </summary>
- /// <remarks>
- /// Call this method when the user has completed web-based authorization.
- /// </remarks>
- public void Authorize() {
- this.User = Database.LoggedInUser;
- Database.DataContext.SaveChanges();
- }
- }
-}
diff --git a/projecttemplates/RelyingPartyLogic/Model.edmx b/projecttemplates/RelyingPartyLogic/Model.edmx
index 9d7ec7b..a003493 100644
--- a/projecttemplates/RelyingPartyLogic/Model.edmx
+++ b/projecttemplates/RelyingPartyLogic/Model.edmx
@@ -4,27 +4,27 @@
<edmx:Runtime>
<!-- SSDL content -->
<edmx:StorageModels>
- <Schema Namespace="DatabaseModel.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2005" xmlns="http://schemas.microsoft.com/ado/2006/04/edm/ssdl">
+ <Schema Namespace="DatabaseModel.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2005" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2006/04/edm/ssdl">
<EntityContainer Name="DatabaseModelStoreContainer">
- <EntitySet Name="AuthenticationToken" EntityType="DatabaseModel.Store.AuthenticationToken" store:Type="Tables" Schema="dbo" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" />
- <EntitySet Name="Consumer" EntityType="DatabaseModel.Store.Consumer" store:Type="Tables" Schema="dbo" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" />
- <EntitySet Name="IssuedToken" EntityType="DatabaseModel.Store.IssuedToken" store:Type="Tables" Schema="dbo" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" />
- <EntitySet Name="Nonce" EntityType="DatabaseModel.Store.Nonce" store:Type="Tables" Schema="dbo" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" />
- <EntitySet Name="OpenIDAssociation" EntityType="DatabaseModel.Store.OpenIDAssociation" store:Type="Tables" Schema="dbo" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" />
- <EntitySet Name="Role" EntityType="DatabaseModel.Store.Role" store:Type="Tables" Schema="dbo" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" />
- <EntitySet Name="User" EntityType="DatabaseModel.Store.User" store:Type="Tables" Schema="dbo" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" />
- <EntitySet Name="UserRole" EntityType="DatabaseModel.Store.UserRole" store:Type="Tables" Schema="dbo" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" />
+ <EntitySet Name="AuthenticationToken" EntityType="DatabaseModel.Store.AuthenticationToken" store:Type="Tables" Schema="dbo" />
+ <EntitySet Name="Client" EntityType="DatabaseModel.Store.Client" store:Type="Tables" Schema="dbo" />
+ <EntitySet Name="ClientAuthorization" EntityType="DatabaseModel.Store.ClientAuthorization" store:Type="Tables" Schema="dbo" />
+ <EntitySet Name="Nonce" EntityType="DatabaseModel.Store.Nonce" store:Type="Tables" Schema="dbo" />
+ <EntitySet Name="OpenIDAssociation" EntityType="DatabaseModel.Store.OpenIDAssociation" store:Type="Tables" Schema="dbo" />
+ <EntitySet Name="Role" EntityType="DatabaseModel.Store.Role" store:Type="Tables" Schema="dbo" />
+ <EntitySet Name="User" EntityType="DatabaseModel.Store.User" store:Type="Tables" Schema="dbo" />
+ <EntitySet Name="UserRole" EntityType="DatabaseModel.Store.UserRole" store:Type="Tables" Schema="dbo" />
<AssociationSet Name="FK_AuthenticationToken_User" Association="DatabaseModel.Store.FK_AuthenticationToken_User">
<End Role="User" EntitySet="User" />
<End Role="AuthenticationToken" EntitySet="AuthenticationToken" />
</AssociationSet>
<AssociationSet Name="FK_IssuedToken_Consumer" Association="DatabaseModel.Store.FK_IssuedToken_Consumer">
- <End Role="Consumer" EntitySet="Consumer" />
- <End Role="IssuedToken" EntitySet="IssuedToken" />
+ <End Role="Client" EntitySet="Client" />
+ <End Role="ClientAuthorization" EntitySet="ClientAuthorization" />
</AssociationSet>
<AssociationSet Name="FK_IssuedToken_User" Association="DatabaseModel.Store.FK_IssuedToken_User">
<End Role="User" EntitySet="User" />
- <End Role="IssuedToken" EntitySet="IssuedToken" />
+ <End Role="ClientAuthorization" EntitySet="ClientAuthorization" />
</AssociationSet>
<AssociationSet Name="FK_UserRole_Role" Association="DatabaseModel.Store.FK_UserRole_Role">
<End Role="Role" EntitySet="Role" />
@@ -47,35 +47,26 @@
<Property Name="LastUsed" Type="datetime" Nullable="false" />
<Property Name="UsageCount" Type="int" Nullable="false" />
</EntityType>
- <EntityType Name="Consumer">
+ <EntityType Name="Client">
<Key>
- <PropertyRef Name="ConsumerId" />
+ <PropertyRef Name="ClientId" />
</Key>
- <Property Name="ConsumerId" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />
- <Property Name="ConsumerKey" Type="nvarchar" Nullable="false" MaxLength="255" />
- <Property Name="ConsumerSecret" Type="nvarchar" MaxLength="255" />
- <Property Name="X509Certificate" Type="image" />
- <Property Name="Callback" Type="nvarchar" MaxLength="2048" />
- <Property Name="VerificationCodeFormat" Type="int" Nullable="false" />
- <Property Name="VerificationCodeLength" Type="int" Nullable="false" />
- <Property Name="Name" Type="nvarchar" MaxLength="50" />
+ <Property Name="ClientId" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />
+ <Property Name="ClientIdentifier" Type="varchar" Nullable="false" MaxLength="255" />
+ <Property Name="ClientSecret" Type="varchar" MaxLength="255" />
+ <Property Name="Callback" Type="varchar" MaxLength="2048" />
+ <Property Name="Name" Type="nvarchar" Nullable="false" MaxLength="50" />
</EntityType>
- <EntityType Name="IssuedToken">
+ <EntityType Name="ClientAuthorization">
<Key>
- <PropertyRef Name="IssuedTokenId" />
+ <PropertyRef Name="AuthorizationId" />
</Key>
- <Property Name="IssuedTokenId" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />
- <Property Name="ConsumerId" Type="int" Nullable="false" />
- <Property Name="UserId" Type="int" />
- <Property Name="Token" Type="nvarchar" Nullable="false" MaxLength="255" />
- <Property Name="TokenSecret" Type="nvarchar" Nullable="false" MaxLength="255" />
+ <Property Name="AuthorizationId" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />
+ <Property Name="ClientId" Type="int" Nullable="false" />
+ <Property Name="UserId" Type="int" Nullable="false" />
<Property Name="CreatedOn" Type="datetime" Nullable="false" />
- <Property Name="Callback" Type="nvarchar" MaxLength="2048" />
- <Property Name="VerificationCode" Type="nvarchar" MaxLength="255" />
- <Property Name="ConsumerVersion" Type="varchar" MaxLength="10" />
<Property Name="ExpirationDate" Type="datetime" />
- <Property Name="IsAccessToken" Type="bit" Nullable="false" />
- <Property Name="Scope" Type="nvarchar" MaxLength="255" />
+ <Property Name="Scope" Type="varchar" MaxLength="2048" />
</EntityType>
<EntityType Name="Nonce">
<Key>
@@ -95,7 +86,7 @@
<Property Name="DistinguishingFactor" Type="varchar" Nullable="false" MaxLength="255" />
<Property Name="AssociationHandle" Type="varchar" Nullable="false" MaxLength="255" />
<Property Name="Expiration" Type="datetime" Nullable="false" />
- <Property Name="PrivateData" Type="binary" Nullable="false" MaxLength="32" />
+ <Property Name="PrivateData" Type="binary" Nullable="false" MaxLength="64" />
<Property Name="PrivateDataLength" Type="int" Nullable="false" />
</EntityType>
<EntityType Name="Role">
@@ -139,29 +130,29 @@
</ReferentialConstraint>
</Association>
<Association Name="FK_IssuedToken_Consumer">
- <End Role="Consumer" Type="DatabaseModel.Store.Consumer" Multiplicity="1">
+ <End Role="Client" Type="DatabaseModel.Store.Client" Multiplicity="1">
<OnDelete Action="Cascade" />
</End>
- <End Role="IssuedToken" Type="DatabaseModel.Store.IssuedToken" Multiplicity="*" />
+ <End Role="ClientAuthorization" Type="DatabaseModel.Store.ClientAuthorization" Multiplicity="*" />
<ReferentialConstraint>
- <Principal Role="Consumer">
- <PropertyRef Name="ConsumerId" />
+ <Principal Role="Client">
+ <PropertyRef Name="ClientId" />
</Principal>
- <Dependent Role="IssuedToken">
- <PropertyRef Name="ConsumerId" />
+ <Dependent Role="ClientAuthorization">
+ <PropertyRef Name="ClientId" />
</Dependent>
</ReferentialConstraint>
</Association>
<Association Name="FK_IssuedToken_User">
- <End Role="User" Type="DatabaseModel.Store.User" Multiplicity="0..1">
+ <End Role="User" Type="DatabaseModel.Store.User" Multiplicity="1">
<OnDelete Action="Cascade" />
</End>
- <End Role="IssuedToken" Type="DatabaseModel.Store.IssuedToken" Multiplicity="*" />
+ <End Role="ClientAuthorization" Type="DatabaseModel.Store.ClientAuthorization" Multiplicity="*" />
<ReferentialConstraint>
<Principal Role="User">
<PropertyRef Name="UserId" />
</Principal>
- <Dependent Role="IssuedToken">
+ <Dependent Role="ClientAuthorization">
<PropertyRef Name="UserId" />
</Dependent>
</ReferentialConstraint>
@@ -208,20 +199,23 @@
<End Role="User" EntitySet="Users" />
</AssociationSet>
<EntitySet Name="AuthenticationTokens" EntityType="DatabaseModel.AuthenticationToken" />
- <EntitySet Name="Consumers" EntityType="DatabaseModel.Consumer" />
- <EntitySet Name="IssuedTokens" EntityType="DatabaseModel.IssuedToken" />
<AssociationSet Name="FK_AuthenticationToken_User" Association="DatabaseModel.FK_AuthenticationToken_User">
<End Role="User" EntitySet="Users" />
<End Role="AuthenticationToken" EntitySet="AuthenticationTokens" /></AssociationSet>
- <AssociationSet Name="FK_IssuedToken_Consumer1" Association="DatabaseModel.FK_IssuedToken_Consumer1">
- <End Role="Consumer" EntitySet="Consumers" />
- <End Role="IssuedToken" EntitySet="IssuedTokens" /></AssociationSet>
- <AssociationSet Name="FK_IssuedToken_User1" Association="DatabaseModel.FK_IssuedToken_User1">
- <End Role="User" EntitySet="Users" />
- <End Role="IssuedToken" EntitySet="IssuedTokens" /></AssociationSet>
<EntitySet Name="Nonces" EntityType="DatabaseModel.Nonce" />
<EntitySet Name="OpenIdAssociations" EntityType="DatabaseModel.OpenIdAssociation" />
- <FunctionImport Name="ClearExpiredNonces" /></EntityContainer>
+ <FunctionImport Name="ClearExpiredNonces" />
+ <EntitySet Name="Clients" EntityType="DatabaseModel.Client" />
+ <EntitySet Name="ClientAuthorizations" EntityType="DatabaseModel.ClientAuthorization" />
+ <AssociationSet Name="FK_IssuedToken_Consumer" Association="DatabaseModel.FK_IssuedToken_Consumer">
+ <End Role="Client" EntitySet="Clients" />
+ <End Role="ClientAuthorization" EntitySet="ClientAuthorizations" />
+ </AssociationSet>
+ <AssociationSet Name="FK_IssuedToken_User" Association="DatabaseModel.FK_IssuedToken_User">
+ <End Role="User" EntitySet="Users" />
+ <End Role="ClientAuthorization" EntitySet="ClientAuthorizations" />
+ </AssociationSet>
+ </EntityContainer>
<EntityType Name="AuthenticationToken" Abstract="false">
<Key>
<PropertyRef Name="AuthenticationTokenId" /></Key>
@@ -253,48 +247,14 @@
<Property Name="CreatedOnUtc" Type="DateTime" Nullable="false" a:SetterAccess="Private" xmlns:a="http://schemas.microsoft.com/ado/2006/04/codegeneration" />
<Property Name="UserId" Type="Int32" Nullable="false" a:SetterAccess="Private" xmlns:a="http://schemas.microsoft.com/ado/2006/04/codegeneration" />
<NavigationProperty Name="AuthenticationTokens" Relationship="DatabaseModel.FK_AuthenticationToken_User" FromRole="User" ToRole="AuthenticationToken" />
- <NavigationProperty Name="IssuedTokens" Relationship="DatabaseModel.FK_IssuedToken_User1" FromRole="User" ToRole="IssuedToken" /></EntityType>
+ <NavigationProperty Name="ClientAuthorizations" Relationship="DatabaseModel.FK_IssuedToken_User" FromRole="User" ToRole="ClientAuthorization" /></EntityType>
<Association Name="UserRole">
<End Role="Role" Type="DatabaseModel.Role" Multiplicity="*" />
<End Role="User" Type="DatabaseModel.User" Multiplicity="*" />
</Association>
- <EntityType Name="Consumer">
- <Key>
- <PropertyRef Name="ConsumerId" /></Key>
- <Property Name="ConsumerKey" Type="String" Nullable="false" />
- <Property Name="ConsumerSecret" Type="String" Nullable="true" />
- <Property Name="X509CertificateAsBinary" Type="Binary" Nullable="true" a:SetterAccess="Private" a:GetterAccess="Private" xmlns:a="http://schemas.microsoft.com/ado/2006/04/codegeneration" />
- <Property Name="CallbackAsString" Type="String" Nullable="true" />
- <Property Name="VerificationCodeFormatAsInt" Type="Int32" Nullable="false" a:GetterAccess="Private" a:SetterAccess="Private" xmlns:a="http://schemas.microsoft.com/ado/2006/04/codegeneration" />
- <Property Name="VerificationCodeLength" Type="Int32" Nullable="false" />
- <Property Name="ConsumerId" Type="Int32" Nullable="false" a:SetterAccess="Private" xmlns:a="http://schemas.microsoft.com/ado/2006/04/codegeneration" />
- <Property Name="Name" Type="String" Nullable="true" />
- <NavigationProperty Name="IssuedTokens" Relationship="DatabaseModel.FK_IssuedToken_Consumer1" FromRole="Consumer" ToRole="IssuedToken" /></EntityType>
- <EntityType Name="IssuedToken" Abstract="true">
- <Key>
- <PropertyRef Name="IssuedTokenId" /></Key>
- <Property Name="Token" Type="String" Nullable="false" />
- <Property Name="TokenSecret" Type="String" Nullable="false" />
- <Property Name="CreatedOnUtc" Type="DateTime" Nullable="false" a:SetterAccess="Internal" xmlns:a="http://schemas.microsoft.com/ado/2006/04/codegeneration" />
- <Property Name="Scope" Type="String" Nullable="true" />
- <Property Name="IssuedTokenId" Type="Int32" Nullable="false" a:SetterAccess="Internal" xmlns:a="http://schemas.microsoft.com/ado/2006/04/codegeneration" />
- <NavigationProperty Name="Consumer" Relationship="DatabaseModel.FK_IssuedToken_Consumer1" FromRole="IssuedToken" ToRole="Consumer" />
- <NavigationProperty Name="User" Relationship="DatabaseModel.FK_IssuedToken_User1" FromRole="IssuedToken" ToRole="User" /></EntityType>
- <EntityType Name="IssuedRequestToken" BaseType="DatabaseModel.IssuedToken">
- <Property Name="ConsumerVersionAsString" Type="String" Nullable="false" a:GetterAccess="Private" a:SetterAccess="Private" xmlns:a="http://schemas.microsoft.com/ado/2006/04/codegeneration" />
- <Property Name="VerificationCode" Type="String" Nullable="true" />
- <Property Name="CallbackAsString" Type="String" Nullable="true" a:GetterAccess="Private" a:SetterAccess="Private" xmlns:a="http://schemas.microsoft.com/ado/2006/04/codegeneration" /></EntityType>
- <EntityType Name="IssuedAccessToken" BaseType="DatabaseModel.IssuedToken">
- <Property Name="ExpirationDateUtc" Type="DateTime" Nullable="true" /></EntityType>
<Association Name="FK_AuthenticationToken_User">
<End Type="DatabaseModel.User" Role="User" Multiplicity="1" />
<End Type="DatabaseModel.AuthenticationToken" Role="AuthenticationToken" Multiplicity="*" /></Association>
- <Association Name="FK_IssuedToken_Consumer1">
- <End Type="DatabaseModel.Consumer" Role="Consumer" Multiplicity="1" />
- <End Type="DatabaseModel.IssuedToken" Role="IssuedToken" Multiplicity="*" /></Association>
- <Association Name="FK_IssuedToken_User1">
- <End Type="DatabaseModel.User" Role="User" Multiplicity="0..1" />
- <End Type="DatabaseModel.IssuedToken" Role="IssuedToken" Multiplicity="*" /></Association>
<EntityType Name="Nonce" a:TypeAccess="Public" xmlns:a="http://schemas.microsoft.com/ado/2006/04/codegeneration">
<Key>
<PropertyRef Name="NonceId" /></Key>
@@ -315,7 +275,37 @@
<Property Name="AssociationHandle" Type="String" Nullable="false" />
<Property Name="ExpirationUtc" Type="DateTime" Nullable="false" />
<Property Name="PrivateData" Type="Binary" Nullable="false" />
- <Property Name="PrivateDataLength" Type="Int32" Nullable="false" /></EntityType></Schema>
+ <Property Name="PrivateDataLength" Type="Int32" Nullable="false" /></EntityType>
+ <EntityType Name="Client">
+ <Key>
+ <PropertyRef Name="ClientId" />
+ </Key>
+ <Property Type="Int32" Name="ClientId" Nullable="false" a:StoreGeneratedPattern="Identity" xmlns:a="http://schemas.microsoft.com/ado/2009/02/edm/annotation" />
+ <Property Type="String" Name="ClientIdentifier" Nullable="false" MaxLength="255" FixedLength="false" Unicode="true" />
+ <Property Type="String" Name="ClientSecret" MaxLength="255" FixedLength="false" Unicode="true" />
+ <Property Type="String" Name="CallbackAsString" MaxLength="2048" FixedLength="false" Unicode="true" />
+ <Property Type="String" Name="Name" MaxLength="50" FixedLength="false" Unicode="true" Nullable="false" />
+ <NavigationProperty Name="ClientAuthorizations" Relationship="DatabaseModel.FK_IssuedToken_Consumer" FromRole="Client" ToRole="ClientAuthorization" />
+ </EntityType>
+ <EntityType Name="ClientAuthorization">
+ <Key>
+ <PropertyRef Name="AuthorizationId" />
+ </Key>
+ <Property Type="Int32" Name="AuthorizationId" Nullable="false" a:StoreGeneratedPattern="Identity" xmlns:a="http://schemas.microsoft.com/ado/2009/02/edm/annotation" />
+ <Property Type="DateTime" Name="CreatedOnUtc" Nullable="false" />
+ <Property Type="DateTime" Name="ExpirationDate" />
+ <Property Type="String" Name="Scope" MaxLength="2048" FixedLength="false" Unicode="false" />
+ <NavigationProperty Name="Client" Relationship="DatabaseModel.FK_IssuedToken_Consumer" FromRole="ClientAuthorization" ToRole="Client" />
+ <NavigationProperty Name="User" Relationship="DatabaseModel.FK_IssuedToken_User" FromRole="ClientAuthorization" ToRole="User" />
+ </EntityType>
+ <Association Name="FK_IssuedToken_Consumer">
+ <End Type="DatabaseModel.Client" Role="Client" Multiplicity="1" />
+ <End Type="DatabaseModel.ClientAuthorization" Role="ClientAuthorization" Multiplicity="*" />
+ </Association>
+ <Association Name="FK_IssuedToken_User">
+ <End Type="DatabaseModel.User" Role="User" Multiplicity="1" />
+ <End Type="DatabaseModel.ClientAuthorization" Role="ClientAuthorization" Multiplicity="*" />
+ </Association></Schema>
</edmx:ConceptualModels>
<!-- C-S mapping content -->
<edmx:Mappings>
@@ -358,54 +348,11 @@
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
- <EntitySetMapping Name="Consumers">
- <EntityTypeMapping TypeName="IsTypeOf(DatabaseModel.Consumer)">
- <MappingFragment StoreEntitySet="Consumer">
- <ScalarProperty Name="Name" ColumnName="Name" />
- <ScalarProperty Name="ConsumerId" ColumnName="ConsumerId" />
- <ScalarProperty Name="VerificationCodeLength" ColumnName="VerificationCodeLength" />
- <ScalarProperty Name="VerificationCodeFormatAsInt" ColumnName="VerificationCodeFormat" />
- <ScalarProperty Name="CallbackAsString" ColumnName="Callback" />
- <ScalarProperty Name="X509CertificateAsBinary" ColumnName="X509Certificate" />
- <ScalarProperty Name="ConsumerSecret" ColumnName="ConsumerSecret" />
- <ScalarProperty Name="ConsumerKey" ColumnName="ConsumerKey" /></MappingFragment></EntityTypeMapping></EntitySetMapping>
- <EntitySetMapping Name="IssuedTokens">
- <EntityTypeMapping TypeName="IsTypeOf(DatabaseModel.IssuedToken)">
- <MappingFragment StoreEntitySet="IssuedToken">
- <ScalarProperty Name="IssuedTokenId" ColumnName="IssuedTokenId" />
- <ScalarProperty Name="Scope" ColumnName="Scope" />
- <ScalarProperty Name="CreatedOnUtc" ColumnName="CreatedOn" />
- <ScalarProperty Name="TokenSecret" ColumnName="TokenSecret" />
- <ScalarProperty Name="Token" ColumnName="Token" />
- </MappingFragment></EntityTypeMapping>
- <EntityTypeMapping TypeName="IsTypeOf(DatabaseModel.IssuedRequestToken)">
- <MappingFragment StoreEntitySet="IssuedToken">
- <ScalarProperty Name="IssuedTokenId" ColumnName="IssuedTokenId" />
- <ScalarProperty Name="CallbackAsString" ColumnName="Callback" />
- <ScalarProperty Name="ConsumerVersionAsString" ColumnName="ConsumerVersion" />
- <ScalarProperty Name="VerificationCode" ColumnName="VerificationCode" />
- <Condition ColumnName="IsAccessToken" Value="0" /></MappingFragment></EntityTypeMapping>
- <EntityTypeMapping TypeName="IsTypeOf(DatabaseModel.IssuedAccessToken)">
- <MappingFragment StoreEntitySet="IssuedToken">
- <ScalarProperty Name="IssuedTokenId" ColumnName="IssuedTokenId" />
- <ScalarProperty Name="ExpirationDateUtc" ColumnName="ExpirationDate" />
- <Condition ColumnName="IsAccessToken" Value="1" /></MappingFragment></EntityTypeMapping></EntitySetMapping>
<AssociationSetMapping Name="FK_AuthenticationToken_User" TypeName="DatabaseModel.FK_AuthenticationToken_User" StoreEntitySet="AuthenticationToken">
<EndProperty Name="AuthenticationToken">
<ScalarProperty Name="AuthenticationTokenId" ColumnName="AuthenticationTokenId" /></EndProperty>
<EndProperty Name="User">
<ScalarProperty Name="UserId" ColumnName="UserId" /></EndProperty></AssociationSetMapping>
- <AssociationSetMapping Name="FK_IssuedToken_Consumer1" TypeName="DatabaseModel.FK_IssuedToken_Consumer1" StoreEntitySet="IssuedToken">
- <EndProperty Name="IssuedToken">
- <ScalarProperty Name="IssuedTokenId" ColumnName="IssuedTokenId" /></EndProperty>
- <EndProperty Name="Consumer">
- <ScalarProperty Name="ConsumerId" ColumnName="ConsumerId" /></EndProperty></AssociationSetMapping>
- <AssociationSetMapping Name="FK_IssuedToken_User1" TypeName="DatabaseModel.FK_IssuedToken_User1" StoreEntitySet="IssuedToken">
- <EndProperty Name="IssuedToken">
- <ScalarProperty Name="IssuedTokenId" ColumnName="IssuedTokenId" /></EndProperty>
- <EndProperty Name="User">
- <ScalarProperty Name="UserId" ColumnName="UserId" /></EndProperty>
- <Condition ColumnName="UserId" IsNull="false" /></AssociationSetMapping>
<EntitySetMapping Name="Nonces">
<EntityTypeMapping TypeName="IsTypeOf(DatabaseModel.Nonce)">
<MappingFragment StoreEntitySet="Nonce">
@@ -423,7 +370,44 @@
<ScalarProperty Name="AssociationHandle" ColumnName="AssociationHandle" />
<ScalarProperty Name="DistinguishingFactor" ColumnName="DistinguishingFactor" />
<ScalarProperty Name="AssociationId" ColumnName="AssociationId" /></MappingFragment></EntityTypeMapping></EntitySetMapping>
- <FunctionImportMapping FunctionImportName="ClearExpiredNonces" FunctionName="DatabaseModel.Store.ClearExpiredNonces" /></EntityContainerMapping>
+ <FunctionImportMapping FunctionImportName="ClearExpiredNonces" FunctionName="DatabaseModel.Store.ClearExpiredNonces" />
+ <EntitySetMapping Name="Clients">
+ <EntityTypeMapping TypeName="DatabaseModel.Client">
+ <MappingFragment StoreEntitySet="Client">
+ <ScalarProperty Name="Name" ColumnName="Name" />
+ <ScalarProperty Name="CallbackAsString" ColumnName="Callback" />
+ <ScalarProperty Name="ClientSecret" ColumnName="ClientSecret" />
+ <ScalarProperty Name="ClientIdentifier" ColumnName="ClientIdentifier" />
+ <ScalarProperty Name="ClientId" ColumnName="ClientId" />
+ </MappingFragment>
+ </EntityTypeMapping>
+ </EntitySetMapping>
+ <EntitySetMapping Name="ClientAuthorizations">
+ <EntityTypeMapping TypeName="DatabaseModel.ClientAuthorization">
+ <MappingFragment StoreEntitySet="ClientAuthorization">
+ <ScalarProperty Name="Scope" ColumnName="Scope" />
+ <ScalarProperty Name="ExpirationDate" ColumnName="ExpirationDate" />
+ <ScalarProperty Name="CreatedOnUtc" ColumnName="CreatedOn" />
+ <ScalarProperty Name="AuthorizationId" ColumnName="AuthorizationId" />
+ </MappingFragment>
+ </EntityTypeMapping>
+ </EntitySetMapping>
+ <AssociationSetMapping Name="FK_IssuedToken_Consumer" TypeName="DatabaseModel.FK_IssuedToken_Consumer" StoreEntitySet="ClientAuthorization">
+ <EndProperty Name="ClientAuthorization">
+ <ScalarProperty Name="AuthorizationId" ColumnName="AuthorizationId" />
+ </EndProperty>
+ <EndProperty Name="Client">
+ <ScalarProperty Name="ClientId" ColumnName="ClientId" />
+ </EndProperty>
+ </AssociationSetMapping>
+ <AssociationSetMapping Name="FK_IssuedToken_User" TypeName="DatabaseModel.FK_IssuedToken_User" StoreEntitySet="ClientAuthorization">
+ <EndProperty Name="ClientAuthorization">
+ <ScalarProperty Name="AuthorizationId" ColumnName="AuthorizationId" />
+ </EndProperty>
+ <EndProperty Name="User">
+ <ScalarProperty Name="UserId" ColumnName="UserId" />
+ </EndProperty>
+ </AssociationSetMapping></EntityContainerMapping>
</Mapping>
</edmx:Mappings>
</edmx:Runtime>
@@ -437,11 +421,13 @@
<edmx:Options>
<DesignerInfoPropertySet xmlns="http://schemas.microsoft.com/ado/2007/06/edmx">
<DesignerProperty Name="ValidateOnBuild" Value="true" />
+ <DesignerProperty Name="EnablePluralization" Value="True" />
+ <DesignerProperty Name="IncludeForeignKeysInModel" Value="False" />
</DesignerInfoPropertySet>
</edmx:Options>
<!-- Diagram content (shape and connector positions) -->
<edmx:Diagrams>
- <Diagram Name="Model" ZoomLevel="56" xmlns="http://schemas.microsoft.com/ado/2007/06/edmx">
+ <Diagram Name="Model" ZoomLevel="101" xmlns="http://schemas.microsoft.com/ado/2007/06/edmx">
<EntityTypeShape EntityType="DatabaseModel.AuthenticationToken" Width="1.875" PointX="5.25" PointY="0.75" Height="2.5571907552083339" IsExpanded="true" />
<EntityTypeShape EntityType="DatabaseModel.Role" Width="1.5" PointX="0.75" PointY="1.25" Height="1.59568359375" IsExpanded="true" />
<EntityTypeShape EntityType="DatabaseModel.User" Width="1.75" PointX="2.875" PointY="0.5" Height="3.1340950520833339" IsExpanded="true" />
@@ -451,30 +437,20 @@
<InheritanceConnector EntityType="DatabaseModel.AuthenticationToken">
<ConnectorPoint PointX="6.5625" PointY="3.375" />
<ConnectorPoint PointX="6.5625" PointY="2.9129850260416665" /></InheritanceConnector>
- <EntityTypeShape EntityType="DatabaseModel.Consumer" Width="2.125" PointX="0.5" PointY="3.625" Height="2.1725878906249996" />
- <EntityTypeShape EntityType="DatabaseModel.IssuedToken" Width="2" PointX="5.25" PointY="3.875" Height="2.7494921874999996" />
- <EntityTypeShape EntityType="DatabaseModel.IssuedRequestToken" Width="2" PointX="4.25" PointY="7" Height="1.5956835937499996" />
- <EntityTypeShape EntityType="DatabaseModel.IssuedAccessToken" Width="1.625" PointX="6.5" PointY="7" Height="1.2110807291666657" />
- <InheritanceConnector EntityType="DatabaseModel.IssuedRequestToken" ManuallyRouted="false">
- <ConnectorPoint PointX="5.75" PointY="6.6244921875" />
- <ConnectorPoint PointX="5.75" PointY="7" />
- </InheritanceConnector>
- <InheritanceConnector EntityType="DatabaseModel.IssuedAccessToken" ManuallyRouted="false">
- <ConnectorPoint PointX="6.875" PointY="6.6244921875" />
- <ConnectorPoint PointX="6.875" PointY="7" />
- </InheritanceConnector>
<AssociationConnector Association="DatabaseModel.FK_AuthenticationToken_User">
- <ConnectorPoint PointX="4.625" PointY="1.4776205358072916" />
- <ConnectorPoint PointX="5.25" PointY="1.4776205358072916" /></AssociationConnector>
- <AssociationConnector Association="DatabaseModel.FK_IssuedToken_Consumer1">
- <ConnectorPoint PointX="2.625" PointY="4.8322661624685885" />
- <ConnectorPoint PointX="5.25" PointY="4.8322661624685885" />
- </AssociationConnector>
- <AssociationConnector Association="DatabaseModel.FK_IssuedToken_User1">
- <ConnectorPoint PointX="3.75" PointY="3.6340950520833339" />
- <ConnectorPoint PointX="3.75" PointY="4.0627779870647478" />
- <ConnectorPoint PointX="5.25" PointY="4.0627779870647478" /></AssociationConnector>
- <EntityTypeShape EntityType="DatabaseModel.Nonce" Width="1.5" PointX="0.5" PointY="7.75" Height="1.9802864583333326" />
- <EntityTypeShape EntityType="DatabaseModel.OpenIdAssociation" Width="1.75" PointX="2.25" PointY="7.75" Height="1.9802864583333333" /></Diagram></edmx:Diagrams>
+ <ConnectorPoint PointX="4.625" PointY="1.9324446614583337" />
+ <ConnectorPoint PointX="5.25" PointY="1.9324446614583337" /></AssociationConnector>
+ <EntityTypeShape EntityType="DatabaseModel.Nonce" Width="1.5" PointX="9.375" PointY="0.75" Height="1.9802864583333326" />
+ <EntityTypeShape EntityType="DatabaseModel.OpenIdAssociation" Width="1.75" PointX="7.375" PointY="0.75" Height="2.1725878906249996" />
+ <EntityTypeShape EntityType="DatabaseModel.Client" Width="1.625" PointX="5.25" PointY="3.75" Height="2.1725878906249996" />
+ <EntityTypeShape EntityType="DatabaseModel.ClientAuthorization" Width="1.75" PointX="2.875" PointY="3.75" Height="2.1725878906250031" />
+ <AssociationConnector Association="DatabaseModel.FK_IssuedToken_Consumer" >
+ <ConnectorPoint PointX="5.25" PointY="4.8362939453125" />
+ <ConnectorPoint PointX="4.625" PointY="4.8362939453125" />
+ </AssociationConnector>
+ <AssociationConnector Association="DatabaseModel.FK_IssuedToken_User" >
+ <ConnectorPoint PointX="3.75" PointY="3.2494921875" />
+ <ConnectorPoint PointX="3.75" PointY="3.75" />
+ </AssociationConnector></Diagram></edmx:Diagrams>
</edmx:Designer>
</edmx:Edmx> \ No newline at end of file
diff --git a/projecttemplates/RelyingPartyLogic/OAuthAuthenticationModule.cs b/projecttemplates/RelyingPartyLogic/OAuthAuthenticationModule.cs
index e47e4ee..c0685bc 100644
--- a/projecttemplates/RelyingPartyLogic/OAuthAuthenticationModule.cs
+++ b/projecttemplates/RelyingPartyLogic/OAuthAuthenticationModule.cs
@@ -12,9 +12,7 @@ namespace RelyingPartyLogic {
using System.Web;
using System.Web.Security;
using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.OAuth;
- using DotNetOpenAuth.OAuth.ChannelElements;
- using DotNetOpenAuth.OAuth.Messages;
+ using DotNetOpenAuth.OAuth2;
public class OAuthAuthenticationModule : IHttpModule {
private HttpApplication application;
@@ -51,10 +49,13 @@ namespace RelyingPartyLogic {
return;
}
- IDirectedProtocolMessage incomingMessage = OAuthServiceProvider.ServiceProvider.ReadRequest(new HttpRequestInfo(this.application.Context.Request));
- var authorization = incomingMessage as AccessProtectedResourceRequest;
- if (authorization != null) {
- this.application.Context.User = OAuthServiceProvider.ServiceProvider.CreatePrincipal(authorization);
+ var tokenAnalyzer = new SpecialAccessTokenAnalyzer(OAuthAuthorizationServer.AsymmetricKey, OAuthAuthorizationServer.AsymmetricKey);
+ var resourceServer = new ResourceServer(tokenAnalyzer);
+
+ IPrincipal principal;
+ var errorMessage = resourceServer.VerifyAccess(new HttpRequestInfo(this.application.Context.Request), out principal);
+ if (errorMessage == null) {
+ this.application.Context.User = principal;
}
}
@@ -70,7 +71,7 @@ namespace RelyingPartyLogic {
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Web.Security.RoleManagerEventArgs"/> instance containing the event data.</param>
private void roleManager_GetRoles(object sender, RoleManagerEventArgs e) {
- if (this.application.User is OAuthPrincipal) {
+ if (this.application.User is DotNetOpenAuth.OAuth.ChannelElements.OAuthPrincipal) {
e.RolesPopulated = true;
}
}
diff --git a/projecttemplates/RelyingPartyLogic/OAuthAuthorizationManager.cs b/projecttemplates/RelyingPartyLogic/OAuthAuthorizationManager.cs
index 35af472..6ac2977 100644
--- a/projecttemplates/RelyingPartyLogic/OAuthAuthorizationManager.cs
+++ b/projecttemplates/RelyingPartyLogic/OAuthAuthorizationManager.cs
@@ -15,6 +15,7 @@ namespace RelyingPartyLogic {
using System.ServiceModel.Security;
using DotNetOpenAuth;
using DotNetOpenAuth.OAuth;
+ using DotNetOpenAuth.OAuth2;
/// <summary>
/// A WCF extension to authenticate incoming messages using OAuth.
@@ -28,15 +29,16 @@ namespace RelyingPartyLogic {
return false;
}
- HttpRequestMessageProperty httpDetails = operationContext.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
- Uri requestUri = operationContext.RequestContext.RequestMessage.Properties["OriginalHttpRequestUri"] as Uri;
- ServiceProvider sp = OAuthServiceProvider.ServiceProvider;
- try {
- var auth = sp.ReadProtectedResourceAuthorization(httpDetails, requestUri);
- if (auth != null) {
- var accessToken = Database.DataContext.IssuedTokens.OfType<IssuedAccessToken>().First(token => token.Token == auth.AccessToken);
+ var httpDetails = operationContext.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
+ var requestUri = operationContext.RequestContext.RequestMessage.Properties["OriginalHttpRequestUri"] as Uri;
- var principal = sp.CreatePrincipal(auth);
+ var tokenAnalyzer = new SpecialAccessTokenAnalyzer(OAuthAuthorizationServer.AsymmetricKey, OAuthAuthorizationServer.AsymmetricKey);
+ var resourceServer = new ResourceServer(tokenAnalyzer);
+
+ try {
+ IPrincipal principal;
+ var errorResponse = resourceServer.VerifyAccess(httpDetails, requestUri, out principal);
+ if (errorResponse == null) {
var policy = new OAuthPrincipalAuthorizationPolicy(principal);
var policies = new List<IAuthorizationPolicy> {
policy,
@@ -56,8 +58,7 @@ namespace RelyingPartyLogic {
};
// Only allow this method call if the access token scope permits it.
- string[] scopes = accessToken.Scope.Split('|');
- if (scopes.Contains(operationContext.IncomingMessageHeaders.Action)) {
+ if (principal.IsInRole(operationContext.IncomingMessageHeaders.Action)) {
return true;
}
}
diff --git a/projecttemplates/RelyingPartyLogic/OAuthAuthorizationServer.cs b/projecttemplates/RelyingPartyLogic/OAuthAuthorizationServer.cs
new file mode 100644
index 0000000..3dafa0a
--- /dev/null
+++ b/projecttemplates/RelyingPartyLogic/OAuthAuthorizationServer.cs
@@ -0,0 +1,173 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuthAuthorizationServer.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace RelyingPartyLogic {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Security.Cryptography;
+ using System.Text;
+ using System.Web;
+
+ using DotNetOpenAuth.Messaging.Bindings;
+ using DotNetOpenAuth.OAuth2;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+ using DotNetOpenAuth.OAuth2.Messages;
+
+ /// <summary>
+ /// Provides OAuth 2.0 authorization server information to DotNetOpenAuth.
+ /// </summary>
+ public class OAuthAuthorizationServer : IAuthorizationServer {
+ internal static readonly RSAParameters AsymmetricKey;
+
+ private static readonly byte[] secret;
+
+ private readonly INonceStore nonceStore = new NonceDbStore();
+
+ static OAuthAuthorizationServer() {
+ // TODO: Replace this sample code with real code.
+ // For this sample, we just generate random secrets.
+ RandomNumberGenerator crypto = new RNGCryptoServiceProvider();
+ secret = new byte[16];
+ crypto.GetBytes(secret);
+
+ AsymmetricKey = new RSACryptoServiceProvider().ExportParameters(true);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="OAuthAuthorizationServer"/> class.
+ /// </summary>
+ public OAuthAuthorizationServer() {
+ }
+
+ #region IAuthorizationServer Members
+
+ /// <summary>
+ /// Gets the secret used to symmetrically encrypt and sign authorization codes and refresh tokens.
+ /// </summary>
+ /// <value></value>
+ /// <remarks>
+ /// This secret should be kept strictly confidential in the authorization server(s)
+ /// and NOT shared with the resource server. Anyone with this secret can mint
+ /// tokens to essentially grant themselves access to anything they want.
+ /// </remarks>
+ public byte[] Secret {
+ get { return secret; }
+ }
+
+ /// <summary>
+ /// Gets the asymmetric private key to use for signing access tokens.
+ /// </summary>
+ /// <value></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>
+ public RSAParameters AccessTokenSigningPrivateKey {
+ get { return AsymmetricKey; }
+ }
+
+ /// <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>
+ public INonceStore VerificationCodeNonceStore {
+ get { return this.nonceStore; }
+ }
+
+ /// <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>
+ public IConsumerDescription GetClient(string clientIdentifier) {
+ try {
+ return Database.DataContext.Clients.First(c => c.ClientIdentifier == clientIdentifier);
+ } catch (InvalidOperationException ex) {
+ throw new ArgumentOutOfRangeException("No client by that identifier.", ex);
+ }
+ }
+
+ /// <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>
+ public bool IsAuthorizationValid(IAuthorizationDescription authorization) {
+ return this.IsAuthorizationValid(authorization.Scope, authorization.ClientIdentifier, authorization.UtcIssued, authorization.User);
+ }
+
+ #endregion
+
+ public bool CanBeAutoApproved(EndUserAuthorizationRequest authorizationRequest) {
+ if (authorizationRequest == null) {
+ throw new ArgumentNullException("authorizationRequest");
+ }
+
+ // NEVER issue an auto-approval to a client that would end up getting an access token immediately
+ // (without a client secret), as that would allow ANY client to spoof an approved client's identity
+ // and obtain unauthorized access to user data.
+ if (authorizationRequest.ResponseType == EndUserAuthorizationResponseType.AuthorizationCode) {
+ // Never issue auto-approval if the client secret is blank, since that too makes it easy to spoof
+ // a client's identity and obtain unauthorized access.
+ var requestingClient = Database.DataContext.Clients.First(c => c.ClientIdentifier == authorizationRequest.ClientIdentifier);
+ if (!string.IsNullOrEmpty(requestingClient.ClientSecret)) {
+ return this.IsAuthorizationValid(
+ authorizationRequest.Scope,
+ authorizationRequest.ClientIdentifier,
+ DateTime.UtcNow,
+ HttpContext.Current.User.Identity.Name);
+ }
+ }
+
+ // Default to not auto-approving.
+ return false;
+ }
+
+ private bool IsAuthorizationValid(HashSet<string> requestedScopes, string clientIdentifier, DateTime issuedUtc, string username)
+ {
+ var grantedScopeStrings = from auth in Database.DataContext.ClientAuthorizations
+ where
+ auth.Client.ClientIdentifier == clientIdentifier &&
+ auth.CreatedOnUtc <= issuedUtc &&
+ auth.User.AuthenticationTokens.Any(token => token.ClaimedIdentifier == username)
+ select auth.Scope;
+
+ if (!grantedScopeStrings.Any()) {
+ // No granted authorizations prior to the issuance of this token, so it must have been revoked.
+ // Even if later authorizations restore this client's ability to call in, we can't allow
+ // access tokens issued before the re-authorization because the revoked authorization should
+ // effectively and permanently revoke all access and refresh tokens.
+ return false;
+ }
+
+ var grantedScopes = new HashSet<string>(OAuthUtilities.ScopeStringComparer);
+ foreach (string scope in grantedScopeStrings) {
+ grantedScopes.UnionWith(OAuthUtilities.SplitScopes(scope));
+ }
+
+ return requestedScopes.IsSubsetOf(grantedScopes);
+ }
+ }
+}
diff --git a/projecttemplates/RelyingPartyLogic/OAuthConsumerTokenManager.cs b/projecttemplates/RelyingPartyLogic/OAuthConsumerTokenManager.cs
deleted file mode 100644
index 64e6be8..0000000
--- a/projecttemplates/RelyingPartyLogic/OAuthConsumerTokenManager.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="OAuthConsumerTokenManager.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace RelyingPartyLogic {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using DotNetOpenAuth.OAuth.ChannelElements;
-
- public class OAuthConsumerTokenManager : OAuthTokenManager, IConsumerTokenManager {
- /// <summary>
- /// Initializes a new instance of the <see cref="OAuthConsumerTokenManager"/> class.
- /// </summary>
- /// <param name="consumerKey">The consumer key.</param>
- /// <param name="consumerSecret">The consumer secret.</param>
- public OAuthConsumerTokenManager(string consumerKey, string consumerSecret) {
- if (String.IsNullOrEmpty(consumerKey)) {
- throw new ArgumentNullException("consumerKey");
- }
- if (consumerSecret == null) {
- throw new ArgumentNullException("consumerSecret");
- }
-
- this.ConsumerKey = consumerKey;
- this.ConsumerSecret = consumerSecret;
- }
-
- #region IConsumerTokenManager Members
-
- /// <summary>
- /// Gets the consumer key.
- /// </summary>
- /// <value>The consumer key.</value>
- public string ConsumerKey { get; private set; }
-
- /// <summary>
- /// Gets the consumer secret.
- /// </summary>
- /// <value>The consumer secret.</value>
- public string ConsumerSecret { get; private set; }
-
- #endregion
- }
-}
diff --git a/projecttemplates/RelyingPartyLogic/OAuthPrincipalAuthorizationPolicy.cs b/projecttemplates/RelyingPartyLogic/OAuthPrincipalAuthorizationPolicy.cs
index ddd0b3f..482f44b 100644
--- a/projecttemplates/RelyingPartyLogic/OAuthPrincipalAuthorizationPolicy.cs
+++ b/projecttemplates/RelyingPartyLogic/OAuthPrincipalAuthorizationPolicy.cs
@@ -10,18 +10,19 @@ namespace RelyingPartyLogic {
using System.IdentityModel.Claims;
using System.IdentityModel.Policy;
using System.Linq;
+ using System.Security.Principal;
using System.Web;
using DotNetOpenAuth.OAuth.ChannelElements;
public class OAuthPrincipalAuthorizationPolicy : IAuthorizationPolicy {
private readonly Guid uniqueId = Guid.NewGuid();
- private readonly OAuthPrincipal principal;
+ private readonly IPrincipal principal;
/// <summary>
/// Initializes a new instance of the <see cref="OAuthPrincipalAuthorizationPolicy"/> class.
/// </summary>
/// <param name="principal">The principal.</param>
- public OAuthPrincipalAuthorizationPolicy(OAuthPrincipal principal) {
+ public OAuthPrincipalAuthorizationPolicy(IPrincipal principal) {
this.principal = principal;
}
diff --git a/projecttemplates/RelyingPartyLogic/OAuthServiceProvider.cs b/projecttemplates/RelyingPartyLogic/OAuthServiceProvider.cs
index 807da2d..69181f5 100644
--- a/projecttemplates/RelyingPartyLogic/OAuthServiceProvider.cs
+++ b/projecttemplates/RelyingPartyLogic/OAuthServiceProvider.cs
@@ -10,9 +10,9 @@ namespace RelyingPartyLogic {
using System.Linq;
using System.Web;
using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.OAuth;
- using DotNetOpenAuth.OAuth.ChannelElements;
- using DotNetOpenAuth.OAuth.Messages;
+ using DotNetOpenAuth.OAuth2;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+ using DotNetOpenAuth.OAuth2.Messages;
public class OAuthServiceProvider {
private const string PendingAuthorizationRequestSessionKey = "PendingAuthorizationRequest";
@@ -20,28 +20,26 @@ namespace RelyingPartyLogic {
/// <summary>
/// The shared service description for this web site.
/// </summary>
- private static ServiceProviderDescription serviceDescription;
-
- private static OAuthServiceProviderTokenManager tokenManager;
+ private static AuthorizationServerDescription authorizationServerDescription;
/// <summary>
- /// The shared service provider object.
+ /// The shared authorization server.
/// </summary>
- private static ServiceProvider serviceProvider;
+ private static AuthorizationServer authorizationServer;
/// <summary>
- /// The lock to synchronize initialization of the <see cref="serviceProvider"/> field.
+ /// The lock to synchronize initialization of the <see cref="authorizationServer"/> field.
/// </summary>
- private static object initializerLock = new object();
+ private static readonly object InitializerLock = new object();
/// <summary>
/// Gets the service provider.
/// </summary>
/// <value>The service provider.</value>
- public static ServiceProvider ServiceProvider {
+ public static AuthorizationServer AuthorizationServer {
get {
EnsureInitialized();
- return serviceProvider;
+ return authorizationServer;
}
}
@@ -49,83 +47,28 @@ namespace RelyingPartyLogic {
/// Gets the service description.
/// </summary>
/// <value>The service description.</value>
- public static ServiceProviderDescription ServiceDescription {
+ public static AuthorizationServerDescription AuthorizationServerDescription {
get {
EnsureInitialized();
- return serviceDescription;
- }
- }
-
- public static UserAuthorizationRequest PendingAuthorizationRequest {
- get { return HttpContext.Current.Session[PendingAuthorizationRequestSessionKey] as UserAuthorizationRequest; }
- set { HttpContext.Current.Session[PendingAuthorizationRequestSessionKey] = value; }
- }
-
- public static Consumer PendingAuthorizationConsumer {
- get {
- ITokenContainingMessage message = PendingAuthorizationRequest;
- if (message == null) {
- throw new InvalidOperationException();
- }
-
- return Database.DataContext.IssuedTokens.OfType<IssuedRequestToken>().Include("Consumer").First(t => t.Token == message.Token).Consumer;
- }
- }
-
- public static void AuthorizePendingRequestToken() {
- var response = AuthorizePendingRequestTokenAndGetResponse();
- if (response != null) {
- serviceProvider.Channel.Send(response);
- }
- }
-
- public static OutgoingWebResponse AuthorizePendingRequestTokenAsWebResponse() {
- var response = AuthorizePendingRequestTokenAndGetResponse();
- if (response != null) {
- return serviceProvider.Channel.PrepareResponse(response);
- } else {
- return null;
+ return authorizationServerDescription;
}
}
- private static UserAuthorizationResponse AuthorizePendingRequestTokenAndGetResponse() {
- var pendingRequest = PendingAuthorizationRequest;
- if (pendingRequest == null) {
- throw new InvalidOperationException("No pending authorization request to authorize.");
- }
-
- ITokenContainingMessage msg = pendingRequest;
- var token = Database.DataContext.IssuedTokens.OfType<IssuedRequestToken>().First(t => t.Token == msg.Token);
- token.Authorize();
-
- PendingAuthorizationRequest = null;
- var response = serviceProvider.PrepareAuthorizationResponse(pendingRequest);
- return response;
- }
-
/// <summary>
- /// Initializes the <see cref="serviceProvider"/> field if it has not yet been initialized.
+ /// Initializes the <see cref="authorizationServer"/> field if it has not yet been initialized.
/// </summary>
private static void EnsureInitialized() {
- if (serviceProvider == null) {
- lock (initializerLock) {
- if (serviceDescription == null) {
- var postEndpoint = new MessageReceivingEndpoint(new Uri(Utilities.ApplicationRoot, "OAuth.ashx"), HttpDeliveryMethods.PostRequest);
- var getEndpoint = new MessageReceivingEndpoint(postEndpoint.Location, HttpDeliveryMethods.GetRequest);
- serviceDescription = new ServiceProviderDescription {
- TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() },
- RequestTokenEndpoint = postEndpoint,
- AccessTokenEndpoint = postEndpoint,
- UserAuthorizationEndpoint = getEndpoint,
+ if (authorizationServer == null) {
+ lock (InitializerLock) {
+ if (authorizationServerDescription == null) {
+ authorizationServerDescription = new AuthorizationServerDescription {
+ AuthorizationEndpoint = new Uri(Utilities.ApplicationRoot, "OAuth.ashx"),
+ TokenEndpoint = new Uri(Utilities.ApplicationRoot, "OAuth.ashx"),
};
}
- if (tokenManager == null) {
- tokenManager = new OAuthServiceProviderTokenManager();
- }
-
- if (serviceProvider == null) {
- serviceProvider = new ServiceProvider(serviceDescription, tokenManager);
+ if (authorizationServer == null) {
+ authorizationServer = new AuthorizationServer(new OAuthAuthorizationServer());
}
}
}
diff --git a/projecttemplates/RelyingPartyLogic/OAuthServiceProviderTokenManager.cs b/projecttemplates/RelyingPartyLogic/OAuthServiceProviderTokenManager.cs
deleted file mode 100644
index 4ae50ce..0000000
--- a/projecttemplates/RelyingPartyLogic/OAuthServiceProviderTokenManager.cs
+++ /dev/null
@@ -1,112 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="OAuthServiceProviderTokenManager.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace RelyingPartyLogic {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using DotNetOpenAuth.OAuth.ChannelElements;
-
- public class OAuthServiceProviderTokenManager : OAuthTokenManager, IServiceProviderTokenManager {
- /// <summary>
- /// Initializes a new instance of the <see cref="OAuthServiceProviderTokenManager"/> class.
- /// </summary>
- public OAuthServiceProviderTokenManager() {
- }
-
- #region IServiceProviderTokenManager Members
-
- /// <summary>
- /// Gets the Consumer description for a given a Consumer Key.
- /// </summary>
- /// <param name="consumerKey">The Consumer Key.</param>
- /// <returns>
- /// A description of the consumer. Never null.
- /// </returns>
- /// <exception cref="KeyNotFoundException">Thrown if the consumer key cannot be found.</exception>
- public IConsumerDescription GetConsumer(string consumerKey) {
- try {
- return Database.DataContext.Consumers.First(c => c.ConsumerKey == consumerKey);
- } catch (InvalidOperationException) {
- throw new KeyNotFoundException();
- }
- }
-
- /// <summary>
- /// Checks whether a given request token has already been authorized
- /// by some user for use by the Consumer that requested it.
- /// </summary>
- /// <param name="requestToken">The Consumer's request token.</param>
- /// <returns>
- /// True if the request token has already been fully authorized by the user
- /// who owns the relevant protected resources. False if the token has not yet
- /// been authorized, has expired or does not exist.
- /// </returns>
- public bool IsRequestTokenAuthorized(string requestToken) {
- return Database.DataContext.IssuedTokens.OfType<IssuedRequestToken>().Any(
- t => t.Token == requestToken && t.User != null);
- }
-
- /// <summary>
- /// Gets details on the named request token.
- /// </summary>
- /// <param name="token">The request token.</param>
- /// <returns>A description of the token. Never null.</returns>
- /// <exception cref="KeyNotFoundException">Thrown if the token cannot be found.</exception>
- /// <remarks>
- /// It is acceptable for implementations to find the token, see that it has expired,
- /// delete it from the database and then throw <see cref="KeyNotFoundException"/>,
- /// or alternatively it can return the expired token anyway and the OAuth channel will
- /// log and throw the appropriate error.
- /// </remarks>
- public IServiceProviderRequestToken GetRequestToken(string token) {
- try {
- return Database.DataContext.IssuedTokens.OfType<IssuedRequestToken>().First(tok => tok.Token == token);
- } catch (InvalidOperationException) {
- throw new KeyNotFoundException();
- }
- }
-
- /// <summary>
- /// Gets details on the named access token.
- /// </summary>
- /// <param name="token">The access token.</param>
- /// <returns>A description of the token. Never null.</returns>
- /// <exception cref="KeyNotFoundException">Thrown if the token cannot be found.</exception>
- /// <remarks>
- /// It is acceptable for implementations to find the token, see that it has expired,
- /// delete it from the database and then throw <see cref="KeyNotFoundException"/>,
- /// or alternatively it can return the expired token anyway and the OAuth channel will
- /// log and throw the appropriate error.
- /// </remarks>
- public IServiceProviderAccessToken GetAccessToken(string token) {
- try {
- return Database.DataContext.IssuedTokens.OfType<IssuedAccessToken>().First(tok => tok.Token == token);
- } catch (InvalidOperationException) {
- throw new KeyNotFoundException();
- }
- }
-
- /// <summary>
- /// Persists any changes made to the token.
- /// </summary>
- /// <param name="token">The token whose properties have been changed.</param>
- /// <remarks>
- /// This library will invoke this method after making a set
- /// of changes to the token as part of a web request to give the host
- /// the opportunity to persist those changes to a database.
- /// Depending on the object persistence framework the host site uses,
- /// this method MAY not need to do anything (if changes made to the token
- /// will automatically be saved without any extra handling).
- /// </remarks>
- public void UpdateToken(IServiceProviderRequestToken token) {
- Database.DataContext.SaveChanges();
- }
-
- #endregion
- }
-}
diff --git a/projecttemplates/RelyingPartyLogic/OAuthTokenManager.cs b/projecttemplates/RelyingPartyLogic/OAuthTokenManager.cs
deleted file mode 100644
index fbf808c..0000000
--- a/projecttemplates/RelyingPartyLogic/OAuthTokenManager.cs
+++ /dev/null
@@ -1,141 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="OAuthTokenManager.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace RelyingPartyLogic {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Security.Cryptography.X509Certificates;
- using System.Web;
- using DotNetOpenAuth.OAuth;
- using DotNetOpenAuth.OAuth.ChannelElements;
- using DotNetOpenAuth.OAuth.Messages;
-
- /// <summary>
- /// The token manager this web site uses in its roles both as
- /// a consumer and as a service provider.
- /// </summary>
- public class OAuthTokenManager : ITokenManager {
- /// <summary>
- /// Initializes a new instance of the <see cref="OAuthTokenManager"/> class.
- /// </summary>
- protected OAuthTokenManager() {
- }
-
- #region ITokenManager Members
-
- /// <summary>
- /// Gets the Token Secret given a request or access token.
- /// </summary>
- /// <param name="token">The request or access token.</param>
- /// <returns>
- /// The secret associated with the given token.
- /// </returns>
- /// <exception cref="ArgumentException">Thrown if the secret cannot be found for the given token.</exception>
- public string GetTokenSecret(string token) {
- try {
- return Database.DataContext.IssuedTokens.First(t => t.Token == token).TokenSecret;
- } catch (InvalidOperationException) {
- throw new ArgumentOutOfRangeException();
- }
- }
-
- /// <summary>
- /// Stores a newly generated unauthorized request token, secret, and optional
- /// application-specific parameters for later recall.
- /// </summary>
- /// <param name="request">The request message that resulted in the generation of a new unauthorized request token.</param>
- /// <param name="response">The response message that includes the unauthorized request token.</param>
- /// <exception cref="ArgumentException">Thrown if the consumer key is not registered, or a required parameter was not found in the parameters collection.</exception>
- /// <remarks>
- /// Request tokens stored by this method SHOULD NOT associate any user account with this token.
- /// It usually opens up security holes in your application to do so. Instead, you associate a user
- /// account with access tokens (not request tokens) in the <see cref="ExpireRequestTokenAndStoreNewAccessToken"/>
- /// method.
- /// </remarks>
- public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response) {
- Consumer consumer;
- try {
- consumer = Database.DataContext.Consumers.First(c => c.ConsumerKey == request.ConsumerKey);
- } catch (InvalidOperationException) {
- throw new ArgumentOutOfRangeException();
- }
-
- var token = new IssuedRequestToken {
- Callback = request.Callback,
- Consumer = consumer,
- Token = response.Token,
- TokenSecret = response.TokenSecret,
- };
- string scope;
- if (request.ExtraData.TryGetValue("scope", out scope)) {
- token.Scope = scope;
- }
- Database.DataContext.AddToIssuedTokens(token);
- Database.DataContext.SaveChanges();
- }
-
- /// <summary>
- /// Deletes a request token and its associated secret and stores a new access token and secret.
- /// </summary>
- /// <param name="consumerKey">The Consumer that is exchanging its request token for an access token.</param>
- /// <param name="requestToken">The Consumer's request token that should be deleted/expired.</param>
- /// <param name="accessToken">The new access token that is being issued to the Consumer.</param>
- /// <param name="accessTokenSecret">The secret associated with the newly issued access token.</param>
- /// <remarks>
- /// <para>
- /// Any scope of granted privileges associated with the request token from the
- /// original call to <see cref="StoreNewRequestToken"/> should be carried over
- /// to the new Access Token.
- /// </para>
- /// <para>
- /// To associate a user account with the new access token,
- /// <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
- /// token to associate the access token with a user account at that point.
- /// </para>
- /// </remarks>
- public void ExpireRequestTokenAndStoreNewAccessToken(string consumerKey, string requestToken, string accessToken, string accessTokenSecret) {
- var requestTokenEntity = Database.DataContext.IssuedTokens.OfType<IssuedRequestToken>()
- .Include("User")
- .First(t => t.Consumer.ConsumerKey == consumerKey && t.Token == requestToken);
-
- var accessTokenEntity = new IssuedAccessToken {
- Token = accessToken,
- TokenSecret = accessTokenSecret,
- ExpirationDateUtc = null, // currently, our access tokens don't expire
- User = requestTokenEntity.User,
- Scope = requestTokenEntity.Scope,
- Consumer = requestTokenEntity.Consumer,
- };
-
- Database.DataContext.DeleteObject(requestTokenEntity);
- Database.DataContext.AddToIssuedTokens(accessTokenEntity);
- Database.DataContext.SaveChanges();
- }
-
- /// <summary>
- /// Classifies a token as a request token or an access token.
- /// </summary>
- /// <param name="token">The token to classify.</param>
- /// <returns>
- /// Request or Access token, or invalid if the token is not recognized.
- /// </returns>
- public TokenType GetTokenType(string token) {
- IssuedToken tok = Database.DataContext.IssuedTokens.FirstOrDefault(t => t.Token == token);
- if (tok == null) {
- return TokenType.InvalidToken;
- } else {
- return tok is IssuedAccessToken ? TokenType.AccessToken : TokenType.RequestToken;
- }
- }
-
- #endregion
- }
-}
diff --git a/projecttemplates/RelyingPartyLogic/RelyingPartyLogic.csproj b/projecttemplates/RelyingPartyLogic/RelyingPartyLogic.csproj
index c371d5a..942fa3b 100644
--- a/projecttemplates/RelyingPartyLogic/RelyingPartyLogic.csproj
+++ b/projecttemplates/RelyingPartyLogic/RelyingPartyLogic.csproj
@@ -107,31 +107,28 @@
</ItemGroup>
<ItemGroup>
<Compile Include="Model.cs" />
- <Compile Include="Model.IssuedToken.cs" />
+ <Compile Include="Model.ClientAuthorization.cs" />
<Compile Include="Database.cs" />
<Compile Include="DataRoleProvider.cs" />
<Compile Include="Model.AuthenticationToken.cs" />
- <Compile Include="Model.Consumer.cs" />
+ <Compile Include="Model.Client.cs" />
<Compile Include="Model.Designer.cs">
<DependentUpon>Model.edmx</DependentUpon>
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
</Compile>
- <Compile Include="Model.IssuedAccessToken.cs" />
- <Compile Include="Model.IssuedRequestToken.cs" />
<Compile Include="Model.OpenIdAssociation.cs" />
<Compile Include="Model.User.cs" />
<Compile Include="NonceDbStore.cs" />
+ <Compile Include="OAuthAuthorizationServer.cs" />
<Compile Include="OAuthAuthenticationModule.cs" />
<Compile Include="OAuthAuthorizationManager.cs" />
- <Compile Include="OAuthConsumerTokenManager.cs" />
<Compile Include="OAuthPrincipalAuthorizationPolicy.cs" />
<Compile Include="OAuthServiceProvider.cs" />
- <Compile Include="OAuthServiceProviderTokenManager.cs" />
- <Compile Include="OAuthTokenManager.cs" />
<Compile Include="Policies.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="RelyingPartyApplicationDbStore.cs" />
+ <Compile Include="SpecialAccessTokenAnalyzer.cs" />
<Compile Include="Utilities.cs" />
</ItemGroup>
<ItemGroup>
@@ -145,12 +142,12 @@
<Project>{3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}</Project>
<Name>DotNetOpenAuth</Name>
</ProjectReference>
- <ProjectReference Include="..\RelyingPartyDatabase\RelyingPartyDatabase.dbproj">
- <Name>RelyingPartyDatabase</Name>
- <!-- Deploy the latest SQL script first, so that this project can embed the latest version. -->
- <Targets>Build;Deploy</Targets>
- <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
- </ProjectReference>
+ <ProjectReference Include="..\RelyingPartyDatabase\RelyingPartyDatabase.dbproj">
+ <Name>RelyingPartyDatabase</Name>
+ <!-- Deploy the latest SQL script first, so that this project can embed the latest version. -->
+ <Targets>Build;Deploy</Targets>
+ <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
+ </ProjectReference>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="CreateDatabase.sql" />
diff --git a/projecttemplates/RelyingPartyLogic/SpecialAccessTokenAnalyzer.cs b/projecttemplates/RelyingPartyLogic/SpecialAccessTokenAnalyzer.cs
new file mode 100644
index 0000000..d4a7e49
--- /dev/null
+++ b/projecttemplates/RelyingPartyLogic/SpecialAccessTokenAnalyzer.cs
@@ -0,0 +1,36 @@
+//-----------------------------------------------------------------------
+// <copyright file="SpecialAccessTokenAnalyzer.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace RelyingPartyLogic {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Security.Cryptography;
+ using System.Text;
+
+ using DotNetOpenAuth.OAuth2;
+
+ internal class SpecialAccessTokenAnalyzer : StandardAccessTokenAnalyzer {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SpecialAccessTokenAnalyzer"/> class.
+ /// </summary>
+ /// <param name="authorizationServerPublicSigningKey">The authorization server public signing key.</param>
+ /// <param name="resourceServerPrivateEncryptionKey">The resource server private encryption key.</param>
+ internal SpecialAccessTokenAnalyzer(RSAParameters authorizationServerPublicSigningKey, RSAParameters resourceServerPrivateEncryptionKey)
+ : base(authorizationServerPublicSigningKey, resourceServerPrivateEncryptionKey) {
+ }
+
+ public override bool TryValidateAccessToken(DotNetOpenAuth.Messaging.IDirectedProtocolMessage message, string accessToken, out string user, out HashSet<string> scope) {
+ bool result = base.TryValidateAccessToken(message, accessToken, out user, out scope);
+ if (result) {
+ // Ensure that clients coming in this way always belong to the oauth_client role.
+ scope.Add("oauth_client");
+ }
+
+ return result;
+ }
+ }
+}
diff --git a/projecttemplates/WebFormsRelyingParty/Members/AccountInfo.aspx b/projecttemplates/WebFormsRelyingParty/Members/AccountInfo.aspx
index fd438d0..458d624 100644
--- a/projecttemplates/WebFormsRelyingParty/Members/AccountInfo.aspx
+++ b/projecttemplates/WebFormsRelyingParty/Members/AccountInfo.aspx
@@ -89,12 +89,14 @@
</HeaderTemplate>
<ItemTemplate>
<li>
- <asp:Label runat="server" Text='<%# HttpUtility.HtmlEncode(Eval("Consumer.Name").ToString()) %>' />
+ <asp:Label runat="server" Text='<%# HttpUtility.HtmlEncode(Eval("Client.Name").ToString()) %>' />
-
- <asp:Label ID="Label1" runat="server" Text='<%# HttpUtility.HtmlEncode(Eval("CreatedOn").ToString()) %>' ForeColor="Gray" />
+ <asp:Label ID="Label2" runat="server" Text='<%# HttpUtility.HtmlEncode((string)Eval("Scope")) %>' ForeColor="Gray" />
+ -
+ <asp:Label ID="Label1" runat="server" Text='<%# HttpUtility.HtmlEncode(Eval("CreatedOnUtc").ToString()) %>' ForeColor="Gray" />
-
<asp:LinkButton ID="revokeLink" runat="server" Text="revoke" OnCommand="revokeToken_Command"
- CommandName="revokeToken" CommandArgument='<%# Eval("Token") %>' />
+ CommandName="revokeToken" CommandArgument='<%# Eval("AuthorizationId") %>' />
</li>
</ItemTemplate>
<FooterTemplate>
diff --git a/projecttemplates/WebFormsRelyingParty/Members/AccountInfo.aspx.cs b/projecttemplates/WebFormsRelyingParty/Members/AccountInfo.aspx.cs
index 68b4398..95feb8c 100644
--- a/projecttemplates/WebFormsRelyingParty/Members/AccountInfo.aspx.cs
+++ b/projecttemplates/WebFormsRelyingParty/Members/AccountInfo.aspx.cs
@@ -20,16 +20,16 @@ namespace WebFormsRelyingParty.Members {
Database.LoggedInUser.AuthenticationTokens.Load();
this.Repeater1.DataSource = Database.LoggedInUser.AuthenticationTokens;
- if (!Database.LoggedInUser.IssuedTokens.IsLoaded) {
- Database.LoggedInUser.IssuedTokens.Load();
+ if (!Database.LoggedInUser.ClientAuthorizations.IsLoaded) {
+ Database.LoggedInUser.ClientAuthorizations.Load();
}
- this.tokenListRepeater.DataSource = Database.LoggedInUser.IssuedTokens;
- foreach (var token in Database.LoggedInUser.IssuedTokens) {
- if (!token.ConsumerReference.IsLoaded) {
- token.ConsumerReference.Load();
+ this.tokenListRepeater.DataSource = Database.LoggedInUser.ClientAuthorizations;
+ foreach (var token in Database.LoggedInUser.ClientAuthorizations) {
+ if (!token.ClientReference.IsLoaded) {
+ token.ClientReference.Load();
}
}
- this.authorizedClientsPanel.Visible = Database.LoggedInUser.IssuedTokens.Count > 0;
+ this.authorizedClientsPanel.Visible = Database.LoggedInUser.ClientAuthorizations.Count > 0;
if (!IsPostBack) {
this.Repeater1.DataBind();
@@ -71,14 +71,14 @@ namespace WebFormsRelyingParty.Members {
}
protected void revokeToken_Command(object sender, CommandEventArgs e) {
- string token = (string)e.CommandArgument;
- var tokenToRevoke = Database.DataContext.IssuedTokens.FirstOrDefault(t => t.Token == token && t.User.UserId == Database.LoggedInUser.UserId);
+ int authorizationId = Convert.ToInt32(e.CommandArgument);
+ var tokenToRevoke = Database.DataContext.ClientAuthorizations.FirstOrDefault(a => a.AuthorizationId == authorizationId && a.User.UserId == Database.LoggedInUser.UserId);
if (tokenToRevoke != null) {
Database.DataContext.DeleteObject(tokenToRevoke);
}
this.tokenListRepeater.DataBind();
- this.noAuthorizedClientsPanel.Visible = Database.LoggedInUser.IssuedTokens.Count == 0;
+ this.noAuthorizedClientsPanel.Visible = Database.LoggedInUser.ClientAuthorizations.Count == 0;
}
private void AddIdentifier(string claimedId, string friendlyId) {
diff --git a/projecttemplates/WebFormsRelyingParty/Members/AccountInfo.aspx.designer.cs b/projecttemplates/WebFormsRelyingParty/Members/AccountInfo.aspx.designer.cs
index 359794b..100b794 100644
--- a/projecttemplates/WebFormsRelyingParty/Members/AccountInfo.aspx.designer.cs
+++ b/projecttemplates/WebFormsRelyingParty/Members/AccountInfo.aspx.designer.cs
@@ -1,10 +1,9 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
-// Runtime Version:2.0.50727.4927
//
// Changes to this file may cause incorrect behavior and will be lost if
-// the code is regenerated.
+// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
diff --git a/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx b/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx
index 7886157..9ec00a8 100644
--- a/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx
+++ b/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx
@@ -5,81 +5,45 @@
<h2>
Client authorization
</h2>
- <asp:MultiView runat="server" ID="outerMultiView" ActiveViewIndex="0">
- <asp:View runat="server" ID="getPermissionView">
- <div style="background-color: Yellow">
- <b>Warning</b>: Never give your login credentials to another web site or application.
- </div>
- <p>
- The
- <asp:Label ID="consumerNameLabel" runat="server" Text="(app name)" />
- application is requesting to access the private data in your account here. Is that
- alright with you?
- </p>
- <p>
- If you grant access now, you can revoke it at any time by returning to <a href="AccountInfo.aspx"
- target="_blank">your account page</a>.
- </p>
- <div style="display: none" id="responseButtonsDiv">
- <asp:Button ID="yesButton" runat="server" Text="Yes" OnClick="yesButton_Click" />
- <asp:Button ID="noButton" runat="server" Text="No" OnClick="noButton_Click" />
- <asp:HiddenField runat="server" ID="csrfCheck" EnableViewState="false" />
- </div>
- <div id="javascriptDisabled">
- <b>Javascript appears to be disabled in your browser. </b>This page requires Javascript
- to be enabled to better protect your security.
- </div>
- <asp:Panel runat="server" BackColor="Red" ForeColor="White" Font-Bold="true" Visible="false"
- ID="OAuth10ConsumerWarning">
- This website is registered with
- <asp:Label runat="server" ID="serviceProviderDomainNameLabel" />
- to make authorization requests, but has not been configured to send requests securely.
- If you grant access but you did not initiate this request at
- <asp:Label runat="server" ID="consumerDomainNameLabel1" />, it may be possible for
- other users of
- <asp:Label runat="server" ID="consumerDomainNameLabel2" />
- to access your data. We recommend you deny access unless you are certain that you
- initiated this request directly with
- <asp:Label runat="server" ID="consumerDomainNameLabel3" />.
- </asp:Panel>
+ <div style="background-color: Yellow">
+ <b>Warning</b>: Never give your login credentials to another web site or application.
+ </div>
+ <p>
+ The
+ <asp:Label ID="consumerNameLabel" runat="server" Text="(app name)" />
+ application is requesting to access the private data in your account here. Is that
+ alright with you?
+ </p>
+ <p>
+ <b>Requested access: </b>
+ <asp:Label runat="server" ID="scopeLabel" />
+ </p>
+ <p>
+ If you grant access now, you can revoke it at any time by returning to <a href="AccountInfo.aspx"
+ target="_blank">your account page</a>.
+ </p>
+ <div style="display: none" id="responseButtonsDiv">
+ <asp:Button ID="yesButton" runat="server" Text="Yes" OnClick="yesButton_Click" />
+ <asp:Button ID="noButton" runat="server" Text="No" OnClick="noButton_Click" />
+ <asp:HiddenField runat="server" ID="csrfCheck" EnableViewState="false" />
+ </div>
+ <div id="javascriptDisabled">
+ <b>Javascript appears to be disabled in your browser. </b>This page requires Javascript
+ to be enabled to better protect your security.
+ </div>
- <script language="javascript" type="text/javascript">
- //<![CDATA[
- // we use HTML to hide the action buttons and Javascript to show them
- // to protect against click-jacking in an iframe whose javascript is disabled.
- document.getElementById('responseButtonsDiv').style.display = 'block';
- document.getElementById('javascriptDisabled').style.display = 'none';
+ <script language="javascript" type="text/javascript">
+ //<![CDATA[
+ // we use HTML to hide the action buttons and Javascript to show them
+ // to protect against click-jacking in an iframe whose javascript is disabled.
+ document.getElementById('responseButtonsDiv').style.display = 'block';
+ document.getElementById('javascriptDisabled').style.display = 'none';
- // Frame busting code (to protect us from being hosted in an iframe).
- // This protects us from click-jacking.
- if (document.location !== window.top.location) {
- window.top.location = document.location;
- }
- //]]>
- </script>
-
- </asp:View>
- <asp:View ID="authorizationGrantedView" runat="server">
- <p>
- Authorization has been granted.</p>
- <asp:MultiView runat="server" ID="verifierMultiView" ActiveViewIndex="0">
- <asp:View ID="verificationCodeView" runat="server">
- <p>
- You must enter this verification code at the Consumer:
- <asp:Label runat="server" ID="verificationCodeLabel" />
- </p>
- </asp:View>
- <asp:View ID="noCallbackView" runat="server">
- <p>
- You may now close this window and return to the Consumer.
- </p>
- </asp:View>
- </asp:MultiView>
- </asp:View>
- <asp:View ID="authorizationDeniedView" runat="server">
- <p>
- Authorization has been denied. You're free to do whatever now.
- </p>
- </asp:View>
- </asp:MultiView>
+ // Frame busting code (to protect us from being hosted in an iframe).
+ // This protects us from click-jacking.
+ if (document.location !== window.top.location) {
+ window.top.location = document.location;
+ }
+ //]]>
+ </script>
</asp:Content>
diff --git a/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx.cs b/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx.cs
index 16e48f0..05a5f52 100644
--- a/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx.cs
+++ b/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx.cs
@@ -7,60 +7,62 @@
namespace WebFormsRelyingParty.Members {
using System;
using System.Collections.Generic;
+ using System.Globalization;
using System.Linq;
+ using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
+ using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OAuth;
using DotNetOpenAuth.OAuth.Messages;
+ using DotNetOpenAuth.OAuth2;
+ using DotNetOpenAuth.OAuth2.Messages;
using RelyingPartyLogic;
public partial class OAuthAuthorize : System.Web.UI.Page {
+ private EndUserAuthorizationRequest pendingRequest;
+
protected void Page_Load(object sender, EventArgs e) {
- if (!IsPostBack) {
- var pendingRequest = OAuthServiceProvider.PendingAuthorizationRequest;
- if (pendingRequest == null) {
- Response.Redirect("AccountInfo.aspx");
- }
+ // We'll mask that on postback it's a POST when looking up the authorization details so that the GET-only
+ // message can be picked up.
+ var requestInfo = this.IsPostBack
+ ? new HttpRequestInfo("GET", this.Request.Url, this.Request.RawUrl, new WebHeaderCollection(), null)
+ : null;
+ this.pendingRequest = OAuthServiceProvider.AuthorizationServer.ReadAuthorizationRequest(requestInfo);
+ if (this.pendingRequest == null) {
+ Response.Redirect("AccountInfo.aspx");
+ }
+ if (!IsPostBack) {
this.csrfCheck.Value = Code.SiteUtilities.SetCsrfCookie();
- this.consumerNameLabel.Text = HttpUtility.HtmlEncode(OAuthServiceProvider.PendingAuthorizationConsumer.Name);
- this.OAuth10ConsumerWarning.Visible = pendingRequest.IsUnsafeRequest;
+ var requestingClient = Database.DataContext.Clients.First(c => c.ClientIdentifier == this.pendingRequest.ClientIdentifier);
+ this.consumerNameLabel.Text = HttpUtility.HtmlEncode(requestingClient.Name);
+ this.scopeLabel.Text = HttpUtility.HtmlEncode(OAuthUtilities.JoinScopes(this.pendingRequest.Scope));
- this.serviceProviderDomainNameLabel.Text = HttpUtility.HtmlEncode(this.Request.Url.Host);
- this.consumerDomainNameLabel3.Text = this.consumerDomainNameLabel2.Text = this.consumerDomainNameLabel1.Text = HttpUtility.HtmlEncode(OAuthServiceProvider.PendingAuthorizationConsumer.Name);
+ // Consider auto-approving if safe to do so.
+ if (((OAuthAuthorizationServer)OAuthServiceProvider.AuthorizationServer.AuthorizationServer).CanBeAutoApproved(this.pendingRequest)) {
+ OAuthServiceProvider.AuthorizationServer.ApproveAuthorizationRequest(this.pendingRequest, HttpContext.Current.User.Identity.Name);
+ }
} else {
Code.SiteUtilities.VerifyCsrfCookie(this.csrfCheck.Value);
}
}
protected void yesButton_Click(object sender, EventArgs e) {
- this.outerMultiView.SetActiveView(this.authorizationGrantedView);
-
- var consumer = OAuthServiceProvider.PendingAuthorizationConsumer;
- var tokenManager = OAuthServiceProvider.ServiceProvider.TokenManager;
- var pendingRequest = OAuthServiceProvider.PendingAuthorizationRequest;
- ITokenContainingMessage requestTokenMessage = pendingRequest;
- var requestToken = tokenManager.GetRequestToken(requestTokenMessage.Token);
-
- OAuthServiceProvider.AuthorizePendingRequestToken();
-
- // The rest of this method only executes if we couldn't automatically
- // redirect to the consumer.
- if (pendingRequest.IsUnsafeRequest) {
- this.verifierMultiView.SetActiveView(this.noCallbackView);
- } else {
- this.verifierMultiView.SetActiveView(this.verificationCodeView);
- string verifier = ServiceProvider.CreateVerificationCode(consumer.VerificationCodeFormat, consumer.VerificationCodeLength);
- this.verificationCodeLabel.Text = HttpUtility.HtmlEncode(verifier);
- requestToken.VerificationCode = verifier;
- tokenManager.UpdateToken(requestToken);
- }
+ var requestingClient = Database.DataContext.Clients.First(c => c.ClientIdentifier == this.pendingRequest.ClientIdentifier);
+ Database.LoggedInUser.ClientAuthorizations.Add(
+ new ClientAuthorization {
+ Client = requestingClient,
+ Scope = OAuthUtilities.JoinScopes(this.pendingRequest.Scope),
+ User = Database.LoggedInUser,
+ CreatedOnUtc = DateTime.UtcNow.CutToSecond(),
+ });
+ OAuthServiceProvider.AuthorizationServer.ApproveAuthorizationRequest(this.pendingRequest, HttpContext.Current.User.Identity.Name);
}
protected void noButton_Click(object sender, EventArgs e) {
- this.outerMultiView.SetActiveView(this.authorizationDeniedView);
- OAuthServiceProvider.PendingAuthorizationRequest = null;
+ OAuthServiceProvider.AuthorizationServer.RejectAuthorizationRequest(this.pendingRequest);
}
}
}
diff --git a/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx.designer.cs b/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx.designer.cs
index 20d5ea9..d243c81 100644
--- a/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx.designer.cs
+++ b/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx.designer.cs
@@ -1,10 +1,9 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
-// Runtime Version:2.0.50727.4927
//
// Changes to this file may cause incorrect behavior and will be lost if
-// the code is regenerated.
+// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
@@ -14,31 +13,22 @@ namespace WebFormsRelyingParty.Members {
public partial class OAuthAuthorize {
/// <summary>
- /// outerMultiView control.
- /// </summary>
- /// <remarks>
- /// Auto-generated field.
- /// To modify move field declaration from designer file to code-behind file.
- /// </remarks>
- protected global::System.Web.UI.WebControls.MultiView outerMultiView;
-
- /// <summary>
- /// getPermissionView control.
+ /// consumerNameLabel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
- protected global::System.Web.UI.WebControls.View getPermissionView;
+ protected global::System.Web.UI.WebControls.Label consumerNameLabel;
/// <summary>
- /// consumerNameLabel control.
+ /// scopeLabel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
- protected global::System.Web.UI.WebControls.Label consumerNameLabel;
+ protected global::System.Web.UI.WebControls.Label scopeLabel;
/// <summary>
/// yesButton control.
@@ -66,104 +56,5 @@ namespace WebFormsRelyingParty.Members {
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.HiddenField csrfCheck;
-
- /// <summary>
- /// OAuth10ConsumerWarning control.
- /// </summary>
- /// <remarks>
- /// Auto-generated field.
- /// To modify move field declaration from designer file to code-behind file.
- /// </remarks>
- protected global::System.Web.UI.WebControls.Panel OAuth10ConsumerWarning;
-
- /// <summary>
- /// serviceProviderDomainNameLabel control.
- /// </summary>
- /// <remarks>
- /// Auto-generated field.
- /// To modify move field declaration from designer file to code-behind file.
- /// </remarks>
- protected global::System.Web.UI.WebControls.Label serviceProviderDomainNameLabel;
-
- /// <summary>
- /// consumerDomainNameLabel1 control.
- /// </summary>
- /// <remarks>
- /// Auto-generated field.
- /// To modify move field declaration from designer file to code-behind file.
- /// </remarks>
- protected global::System.Web.UI.WebControls.Label consumerDomainNameLabel1;
-
- /// <summary>
- /// consumerDomainNameLabel2 control.
- /// </summary>
- /// <remarks>
- /// Auto-generated field.
- /// To modify move field declaration from designer file to code-behind file.
- /// </remarks>
- protected global::System.Web.UI.WebControls.Label consumerDomainNameLabel2;
-
- /// <summary>
- /// consumerDomainNameLabel3 control.
- /// </summary>
- /// <remarks>
- /// Auto-generated field.
- /// To modify move field declaration from designer file to code-behind file.
- /// </remarks>
- protected global::System.Web.UI.WebControls.Label consumerDomainNameLabel3;
-
- /// <summary>
- /// authorizationGrantedView control.
- /// </summary>
- /// <remarks>
- /// Auto-generated field.
- /// To modify move field declaration from designer file to code-behind file.
- /// </remarks>
- protected global::System.Web.UI.WebControls.View authorizationGrantedView;
-
- /// <summary>
- /// verifierMultiView control.
- /// </summary>
- /// <remarks>
- /// Auto-generated field.
- /// To modify move field declaration from designer file to code-behind file.
- /// </remarks>
- protected global::System.Web.UI.WebControls.MultiView verifierMultiView;
-
- /// <summary>
- /// verificationCodeView control.
- /// </summary>
- /// <remarks>
- /// Auto-generated field.
- /// To modify move field declaration from designer file to code-behind file.
- /// </remarks>
- protected global::System.Web.UI.WebControls.View verificationCodeView;
-
- /// <summary>
- /// verificationCodeLabel control.
- /// </summary>
- /// <remarks>
- /// Auto-generated field.
- /// To modify move field declaration from designer file to code-behind file.
- /// </remarks>
- protected global::System.Web.UI.WebControls.Label verificationCodeLabel;
-
- /// <summary>
- /// noCallbackView control.
- /// </summary>
- /// <remarks>
- /// Auto-generated field.
- /// To modify move field declaration from designer file to code-behind file.
- /// </remarks>
- protected global::System.Web.UI.WebControls.View noCallbackView;
-
- /// <summary>
- /// authorizationDeniedView control.
- /// </summary>
- /// <remarks>
- /// Auto-generated field.
- /// To modify move field declaration from designer file to code-behind file.
- /// </remarks>
- protected global::System.Web.UI.WebControls.View authorizationDeniedView;
}
}
diff --git a/projecttemplates/WebFormsRelyingParty/Members/Web.config b/projecttemplates/WebFormsRelyingParty/Members/Web.config
index f95a16d..4ab44bc 100644
--- a/projecttemplates/WebFormsRelyingParty/Members/Web.config
+++ b/projecttemplates/WebFormsRelyingParty/Members/Web.config
@@ -20,7 +20,7 @@
<location path="AccountInfo.aspx">
<system.web>
<authorization>
- <deny roles="delegated" />
+ <deny roles="oauth_client" />
</authorization>
</system.web>
</location>
diff --git a/projecttemplates/WebFormsRelyingParty/OAuth.ashx b/projecttemplates/WebFormsRelyingParty/OAuth.ashx
deleted file mode 100644
index 6176757..0000000
--- a/projecttemplates/WebFormsRelyingParty/OAuth.ashx
+++ /dev/null
@@ -1 +0,0 @@
-<%@ WebHandler Language="C#" CodeBehind="OAuth.ashx.cs" Class="WebFormsRelyingParty.OAuth" %>
diff --git a/projecttemplates/WebFormsRelyingParty/OAuth.ashx.cs b/projecttemplates/WebFormsRelyingParty/OAuth.ashx.cs
deleted file mode 100644
index cb7c819..0000000
--- a/projecttemplates/WebFormsRelyingParty/OAuth.ashx.cs
+++ /dev/null
@@ -1,66 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="OAuth.ashx.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace WebFormsRelyingParty {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.SessionState;
- using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.OAuth;
- using DotNetOpenAuth.OAuth.Messages;
- using RelyingPartyLogic;
-
- /// <summary>
- /// Responds to incoming OAuth Service Provider messages.
- /// </summary>
- public class OAuth : IHttpHandler, IRequiresSessionState {
- /// <summary>
- /// Initializes a new instance of the <see cref="OAuth"/> class.
- /// </summary>
- public OAuth() {
- }
-
- /// <summary>
- /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"/> instance.
- /// </summary>
- /// <returns>
- /// true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false.
- /// </returns>
- public bool IsReusable {
- get { return true; }
- }
-
- /// <summary>
- /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
- /// </summary>
- /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
- public void ProcessRequest(HttpContext context) {
- var serviceProvider = OAuthServiceProvider.ServiceProvider;
- var requestMessage = serviceProvider.ReadRequest(new HttpRequestInfo(context.Request));
-
- UnauthorizedTokenRequest unauthorizedTokenRequestMessage;
- AuthorizedTokenRequest authorizedTokenRequestMessage;
- UserAuthorizationRequest userAuthorizationRequest;
- if ((unauthorizedTokenRequestMessage = requestMessage as UnauthorizedTokenRequest) != null) {
- var response = serviceProvider.PrepareUnauthorizedTokenMessage(unauthorizedTokenRequestMessage);
- serviceProvider.Channel.Send(response);
- } else if ((authorizedTokenRequestMessage = requestMessage as AuthorizedTokenRequest) != null) {
- var response = serviceProvider.PrepareAccessTokenMessage(authorizedTokenRequestMessage);
- serviceProvider.Channel.Send(response);
- } else if ((userAuthorizationRequest = requestMessage as UserAuthorizationRequest) != null) {
- // This is a browser opening to allow the user to authorize a request token,
- // so redirect to the authorization page, which will automatically redirect
- // to have the user log in if necessary.
- OAuthServiceProvider.PendingAuthorizationRequest = userAuthorizationRequest;
- HttpContext.Current.Response.Redirect("~/Members/OAuthAuthorize.aspx");
- } else {
- throw new InvalidOperationException();
- }
- }
- }
-}
diff --git a/projecttemplates/WebFormsRelyingParty/OAuthTokenEndpoint.ashx b/projecttemplates/WebFormsRelyingParty/OAuthTokenEndpoint.ashx
new file mode 100644
index 0000000..3d1cd86
--- /dev/null
+++ b/projecttemplates/WebFormsRelyingParty/OAuthTokenEndpoint.ashx
@@ -0,0 +1 @@
+<%@ WebHandler Language="C#" CodeBehind="OAuthTokenEndpoint.ashx.cs" Class="WebFormsRelyingParty.OAuthTokenEndpoint" %>
diff --git a/projecttemplates/WebFormsRelyingParty/OAuthTokenEndpoint.ashx.cs b/projecttemplates/WebFormsRelyingParty/OAuthTokenEndpoint.ashx.cs
new file mode 100644
index 0000000..ca9b399
--- /dev/null
+++ b/projecttemplates/WebFormsRelyingParty/OAuthTokenEndpoint.ashx.cs
@@ -0,0 +1,51 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuthTokenEndpoint.ashx.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace WebFormsRelyingParty {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Web;
+ using System.Web.SessionState;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2;
+ using RelyingPartyLogic;
+
+ /// <summary>
+ /// An OAuth 2.0 token endpoint.
+ /// </summary>
+ public class OAuthTokenEndpoint : IHttpHandler, IRequiresSessionState {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="OAuthTokenEndpoint"/> class.
+ /// </summary>
+ public OAuthTokenEndpoint() {
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"/> instance.
+ /// </summary>
+ /// <returns>
+ /// true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false.
+ /// </returns>
+ public bool IsReusable {
+ get { return true; }
+ }
+
+ /// <summary>
+ /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
+ /// </summary>
+ /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
+ public void ProcessRequest(HttpContext context) {
+ var serviceProvider = OAuthServiceProvider.AuthorizationServer;
+ IDirectResponseProtocolMessage response;
+ if (serviceProvider.TryPrepareAccessTokenResponse(new HttpRequestInfo(context.Request), out response)) {
+ serviceProvider.Channel.Send(response);
+ } else {
+ throw new InvalidOperationException();
+ }
+ }
+ }
+}
diff --git a/projecttemplates/WebFormsRelyingParty/WebFormsRelyingParty.csproj b/projecttemplates/WebFormsRelyingParty/WebFormsRelyingParty.csproj
index 9fcf9ca..04c85b7 100644
--- a/projecttemplates/WebFormsRelyingParty/WebFormsRelyingParty.csproj
+++ b/projecttemplates/WebFormsRelyingParty/WebFormsRelyingParty.csproj
@@ -154,8 +154,8 @@
<Compile Include="Members\Default.aspx.designer.cs">
<DependentUpon>Default.aspx</DependentUpon>
</Compile>
- <Compile Include="OAuth.ashx.cs">
- <DependentUpon>OAuth.ashx</DependentUpon>
+ <Compile Include="OAuthTokenEndpoint.ashx.cs">
+ <DependentUpon>OAuthTokenEndpoint.ashx</DependentUpon>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Setup.aspx.cs">
@@ -236,7 +236,7 @@
<ItemGroup>
<Content Include="images\verisign.gif" />
<Content Include="Members\OAuthAuthorize.aspx" />
- <Content Include="OAuth.ashx" />
+ <Content Include="OAuthTokenEndpoint.ashx" />
<Content Include="PrivacyPolicy.aspx" />
</ItemGroup>
<ItemGroup>
diff --git a/samples/DotNetOpenAuth.ApplicationBlock/DotNetOpenAuth.ApplicationBlock.csproj b/samples/DotNetOpenAuth.ApplicationBlock/DotNetOpenAuth.ApplicationBlock.csproj
index adb1998..be80671 100644
--- a/samples/DotNetOpenAuth.ApplicationBlock/DotNetOpenAuth.ApplicationBlock.csproj
+++ b/samples/DotNetOpenAuth.ApplicationBlock/DotNetOpenAuth.ApplicationBlock.csproj
@@ -73,6 +73,8 @@
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
+ <Reference Include="System.Runtime.Serialization" />
+ <Reference Include="System.ServiceModel.Web" />
<Reference Include="System.Web" />
<Reference Include="System.Xml.Linq">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
@@ -87,11 +89,15 @@
<Compile Include="CustomExtensions\Acme.cs" />
<Compile Include="CustomExtensions\AcmeRequest.cs" />
<Compile Include="CustomExtensions\AcmeResponse.cs" />
+ <Compile Include="Facebook\FacebookClient.cs" />
+ <Compile Include="Facebook\FacebookGraph.cs" />
<Compile Include="GoogleConsumer.cs" />
+ <Compile Include="InMemoryClientAuthorizationTracker.cs" />
<Compile Include="InMemoryTokenManager.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs" />
+ <Compile Include="TokenManager.cs" />
<Compile Include="TwitterConsumer.cs" />
<Compile Include="Util.cs" />
<Compile Include="YammerConsumer.cs" />
diff --git a/samples/DotNetOpenAuth.ApplicationBlock/Facebook/FacebookClient.cs b/samples/DotNetOpenAuth.ApplicationBlock/Facebook/FacebookClient.cs
new file mode 100644
index 0000000..f838962
--- /dev/null
+++ b/samples/DotNetOpenAuth.ApplicationBlock/Facebook/FacebookClient.cs
@@ -0,0 +1,29 @@
+//-----------------------------------------------------------------------
+// <copyright file="FacebookClient.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.ApplicationBlock {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using System.Web;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2;
+
+ public class FacebookClient : WebServerClient {
+ private static readonly AuthorizationServerDescription FacebookDescription = new AuthorizationServerDescription {
+ TokenEndpoint = new Uri("https://graph.facebook.com/oauth/access_token"),
+ AuthorizationEndpoint = new Uri("https://graph.facebook.com/oauth/authorize"),
+ };
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="FacebookClient"/> class.
+ /// </summary>
+ public FacebookClient() : base(FacebookDescription) {
+ this.AuthorizationTracker = new TokenManager();
+ }
+ }
+}
diff --git a/samples/DotNetOpenAuth.ApplicationBlock/Facebook/FacebookGraph.cs b/samples/DotNetOpenAuth.ApplicationBlock/Facebook/FacebookGraph.cs
new file mode 100644
index 0000000..0e878c1
--- /dev/null
+++ b/samples/DotNetOpenAuth.ApplicationBlock/Facebook/FacebookGraph.cs
@@ -0,0 +1,54 @@
+//-----------------------------------------------------------------------
+// <copyright file="FacebookGraph.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.ApplicationBlock.Facebook {
+ using System;
+ using System.Collections.Generic;
+ using System.IO;
+ using System.Linq;
+ using System.Runtime.Serialization;
+ using System.Runtime.Serialization.Json;
+ using System.Text;
+
+ [DataContract]
+ public class FacebookGraph {
+ private static DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(FacebookGraph));
+
+ [DataMember(Name = "id")]
+ public int Id { get; set; }
+
+ [DataMember(Name = "name")]
+ public string Name { get; set; }
+
+ [DataMember(Name = "first_name")]
+ public string FirstName { get; set; }
+
+ [DataMember(Name = "last_name")]
+ public string LastName { get; set; }
+
+ [DataMember(Name = "link")]
+ public Uri Link { get; set; }
+
+ [DataMember(Name = "birthday")]
+ public string Birthday { get; set; }
+
+ public static FacebookGraph Deserialize(string json) {
+ if (String.IsNullOrEmpty(json)) {
+ throw new ArgumentNullException("json");
+ }
+
+ return Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(json)));
+ }
+
+ public static FacebookGraph Deserialize(Stream jsonStream) {
+ if (jsonStream == null) {
+ throw new ArgumentNullException("jsonStream");
+ }
+
+ return (FacebookGraph)jsonSerializer.ReadObject(jsonStream);
+ }
+ }
+}
diff --git a/samples/DotNetOpenAuth.ApplicationBlock/InMemoryClientAuthorizationTracker.cs b/samples/DotNetOpenAuth.ApplicationBlock/InMemoryClientAuthorizationTracker.cs
new file mode 100644
index 0000000..ef3b686
--- /dev/null
+++ b/samples/DotNetOpenAuth.ApplicationBlock/InMemoryClientAuthorizationTracker.cs
@@ -0,0 +1,51 @@
+//-----------------------------------------------------------------------
+// <copyright file="InMemoryClientAuthorizationTracker.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.ApplicationBlock {
+ using System;
+ using System.Collections.Generic;
+ using System.Globalization;
+ using System.Linq;
+ using System.ServiceModel;
+ using System.Text;
+ using System.Threading;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2;
+
+#if SAMPLESONLY
+ internal class InMemoryClientAuthorizationTracker : IClientAuthorizationTracker {
+ private readonly Dictionary<int, IAuthorizationState> savedStates = new Dictionary<int, IAuthorizationState>();
+ private int stateCounter;
+
+ #region Implementation of IClientTokenManager
+
+ /// <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>
+ public IAuthorizationState GetAuthorizationState(Uri callbackUrl, string clientState) {
+ IAuthorizationState state;
+ if (this.savedStates.TryGetValue(int.Parse(clientState), out state)) {
+ if (state.Callback != callbackUrl) {
+ throw new DotNetOpenAuth.Messaging.ProtocolException("Client state and callback URL do not match.");
+ }
+ }
+
+ return state;
+ }
+
+ #endregion
+
+ internal IAuthorizationState NewAuthorization(HashSet<string> scope, out string clientState) {
+ int counter = Interlocked.Increment(ref this.stateCounter);
+ clientState = counter.ToString(CultureInfo.InvariantCulture);
+ return this.savedStates[counter] = new AuthorizationState(scope);
+ }
+ }
+#endif
+}
diff --git a/samples/DotNetOpenAuth.ApplicationBlock/TokenManager.cs b/samples/DotNetOpenAuth.ApplicationBlock/TokenManager.cs
new file mode 100644
index 0000000..50ff85b
--- /dev/null
+++ b/samples/DotNetOpenAuth.ApplicationBlock/TokenManager.cs
@@ -0,0 +1,18 @@
+//-----------------------------------------------------------------------
+// <copyright file="TokenManager.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.ApplicationBlock {
+ using System;
+ using DotNetOpenAuth.OAuth2;
+
+ public class TokenManager : IClientAuthorizationTracker {
+ public IAuthorizationState GetAuthorizationState(Uri callbackUrl, string clientState) {
+ return new AuthorizationState {
+ Callback = callbackUrl,
+ };
+ }
+ }
+}
diff --git a/samples/OAuthConsumer/Default.aspx b/samples/OAuthConsumer/Default.aspx
index c952877..f3bceb6 100644
--- a/samples/OAuthConsumer/Default.aspx
+++ b/samples/OAuthConsumer/Default.aspx
@@ -9,6 +9,7 @@
<li><a href="GoogleAddressBook.aspx">Download your Gmail address book</a></li>
<li><a href="Twitter.aspx">Get your Twitter updates</a></li>
<li><a href="SignInWithTwitter.aspx">Sign In With Twitter</a></li>
+ <li><a href="Facebook.aspx">Sign in with Facebook</a></li>
<li><a href="SampleWcf.aspx">Interop with Service Provider sample using WCF w/ OAuth</a></li>
</ul>
</asp:Content>
diff --git a/samples/OAuthConsumer/Facebook.aspx b/samples/OAuthConsumer/Facebook.aspx
new file mode 100644
index 0000000..44fc46e
--- /dev/null
+++ b/samples/OAuthConsumer/Facebook.aspx
@@ -0,0 +1,16 @@
+<%@ Page Language="C#" AutoEventWireup="true" Inherits="OAuthConsumer.Facebook" Codebehind="Facebook.aspx.cs" %>
+
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head runat="server">
+ <title></title>
+</head>
+<body>
+ <form id="form1" runat="server">
+ <div>
+ Welcome,
+ <asp:Label Text="[name]" ID="nameLabel" runat="server" />
+ </div>
+ </form>
+</body>
+</html>
diff --git a/samples/OAuthConsumer/Facebook.aspx.cs b/samples/OAuthConsumer/Facebook.aspx.cs
new file mode 100644
index 0000000..95e209a
--- /dev/null
+++ b/samples/OAuthConsumer/Facebook.aspx.cs
@@ -0,0 +1,32 @@
+namespace OAuthConsumer {
+ using System;
+ using System.Configuration;
+ using System.Net;
+ using System.Web;
+ using DotNetOpenAuth.ApplicationBlock;
+ using DotNetOpenAuth.ApplicationBlock.Facebook;
+ using DotNetOpenAuth.OAuth2;
+
+ public partial class Facebook : System.Web.UI.Page {
+ private static readonly FacebookClient client = new FacebookClient {
+ ClientIdentifier = ConfigurationManager.AppSettings["facebookAppID"],
+ ClientSecret = ConfigurationManager.AppSettings["facebookAppSecret"],
+ };
+
+ protected void Page_Load(object sender, EventArgs e) {
+ IAuthorizationState authorization = client.ProcessUserAuthorization();
+ if (authorization == null) {
+ // Kick off authorization request
+ client.Channel.Send(client.PrepareRequestUserAuthorization());
+ } else {
+ var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken));
+ using (var response = request.GetResponse()) {
+ using (var responseStream = response.GetResponseStream()) {
+ var graph = FacebookGraph.Deserialize(responseStream);
+ this.nameLabel.Text = HttpUtility.HtmlEncode(graph.Name);
+ }
+ }
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/samples/OAuthConsumer/Facebook.aspx.designer.cs b/samples/OAuthConsumer/Facebook.aspx.designer.cs
new file mode 100644
index 0000000..a3f8195
--- /dev/null
+++ b/samples/OAuthConsumer/Facebook.aspx.designer.cs
@@ -0,0 +1,33 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+// This code was generated by a tool.
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace OAuthConsumer {
+
+
+ public partial class Facebook {
+
+ /// <summary>
+ /// form1 control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.HtmlControls.HtmlForm form1;
+
+ /// <summary>
+ /// nameLabel control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.WebControls.Label nameLabel;
+ }
+}
diff --git a/samples/OAuthConsumer/OAuthConsumer.csproj b/samples/OAuthConsumer/OAuthConsumer.csproj
index 284b8e9..698de7a 100644
--- a/samples/OAuthConsumer/OAuthConsumer.csproj
+++ b/samples/OAuthConsumer/OAuthConsumer.csproj
@@ -58,6 +58,7 @@
</ItemGroup>
<ItemGroup>
<Content Include="Default.aspx" />
+ <Content Include="Facebook.aspx" />
<Content Include="favicon.ico" />
<Content Include="Global.asax" />
<Content Include="GoogleAddressBook.aspx" />
@@ -71,6 +72,7 @@
<Generator>WCF Proxy Generator</Generator>
<LastGenOutput>Reference.cs</LastGenOutput>
</None>
+ <Content Include="SampleWcf2.aspx" />
<Content Include="SignInWithTwitter.aspx" />
<Content Include="TracePage.aspx" />
<Content Include="Twitter.aspx" />
@@ -86,6 +88,13 @@
<Compile Include="..\DotNetOpenAuth.ApplicationBlock\InMemoryTokenManager.cs">
<Link>Code\InMemoryTokenManager.cs</Link>
</Compile>
+ <Compile Include="Facebook.aspx.cs">
+ <DependentUpon>Facebook.aspx</DependentUpon>
+ <SubType>ASPXCodeBehind</SubType>
+ </Compile>
+ <Compile Include="Facebook.aspx.designer.cs">
+ <DependentUpon>Facebook.aspx</DependentUpon>
+ </Compile>
<Compile Include="Global.asax.cs">
<DependentUpon>Global.asax</DependentUpon>
</Compile>
@@ -99,6 +108,13 @@
<Compile Include="SampleWcf.aspx.designer.cs">
<DependentUpon>SampleWcf.aspx</DependentUpon>
</Compile>
+ <Compile Include="SampleWcf2.aspx.cs">
+ <DependentUpon>SampleWcf2.aspx</DependentUpon>
+ <SubType>ASPXCodeBehind</SubType>
+ </Compile>
+ <Compile Include="SampleWcf2.aspx.designer.cs">
+ <DependentUpon>SampleWcf2.aspx</DependentUpon>
+ </Compile>
<Compile Include="Service References\SampleServiceProvider\Reference.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
diff --git a/samples/OAuthConsumer/SampleWcf.aspx b/samples/OAuthConsumer/SampleWcf.aspx
index fb318ce..fcec089 100644
--- a/samples/OAuthConsumer/SampleWcf.aspx
+++ b/samples/OAuthConsumer/SampleWcf.aspx
@@ -1,4 +1,4 @@
-<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" Inherits="OAuthConsumer.SampleWcf" Codebehind="SampleWcf.aspx.cs" %>
+<%@ Page Title="OAuth 1.0a consumer" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" Inherits="OAuthConsumer.SampleWcf" Codebehind="SampleWcf.aspx.cs" %>
<asp:Content ID="Content2" ContentPlaceHolderID="Body" runat="Server">
<fieldset title="Authorization">
diff --git a/samples/OAuthConsumer/SampleWcf.aspx.cs b/samples/OAuthConsumer/SampleWcf.aspx.cs
index 489e294..74c6e6a 100644
--- a/samples/OAuthConsumer/SampleWcf.aspx.cs
+++ b/samples/OAuthConsumer/SampleWcf.aspx.cs
@@ -39,10 +39,10 @@
string[] scopes = (from item in this.scopeList.Items.OfType<ListItem>()
where item.Selected
select item.Value).ToArray();
- string scope = string.Join("|", scopes);
+ string scope = string.Join(" ", scopes);
var requestParams = new Dictionary<string, string> {
- { "scope", scope },
- };
+ { "scope", scope },
+ };
var response = consumer.PrepareRequestUserAuthorization(callback.Uri, requestParams, null);
consumer.Channel.Send(response);
}
@@ -83,7 +83,7 @@
WebConsumer consumer = this.CreateConsumer();
WebRequest httpRequest = consumer.PrepareAuthorizedRequest(serviceEndpoint, accessToken);
- HttpRequestMessageProperty httpDetails = new HttpRequestMessageProperty();
+ var httpDetails = new HttpRequestMessageProperty();
httpDetails.Headers[HttpRequestHeader.Authorization] = httpRequest.Headers[HttpRequestHeader.Authorization];
using (OperationContextScope scope = new OperationContextScope(client.InnerChannel)) {
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpDetails;
diff --git a/samples/OAuthConsumer/SampleWcf2.aspx b/samples/OAuthConsumer/SampleWcf2.aspx
new file mode 100644
index 0000000..797a2fc
--- /dev/null
+++ b/samples/OAuthConsumer/SampleWcf2.aspx
@@ -0,0 +1,23 @@
+<%@ Page Title="OAuth 2.0 client (web server flow)" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" Inherits="OAuthConsumer.SampleWcf2" Codebehind="SampleWcf2.aspx.cs" %>
+
+<asp:Content ID="Content2" ContentPlaceHolderID="Body" runat="Server">
+ <fieldset title="Authorization">
+ <asp:CheckBoxList runat="server" ID="scopeList">
+ <asp:ListItem Value="http://tempuri.org/IDataApi/GetName">GetName</asp:ListItem>
+ <asp:ListItem Value="http://tempuri.org/IDataApi/GetAge">GetAge</asp:ListItem>
+ <asp:ListItem Value="http://tempuri.org/IDataApi/GetFavoriteSites">GetFavoriteSites</asp:ListItem>
+ </asp:CheckBoxList>
+ <asp:Button ID="getAuthorizationButton" runat="server" Text="Get Authorization" OnClick="getAuthorizationButton_Click" />
+ <asp:Label ID="authorizationLabel" runat="server" />
+ </fieldset>
+ <br />
+ <asp:Button ID="getNameButton" runat="server" Text="Get Name" OnClick="getNameButton_Click" />
+ <asp:Label ID="nameLabel" runat="server" />
+ <br />
+ <asp:Button ID="getAgeButton" runat="server" Text="Get Age" OnClick="getAgeButton_Click" />
+ <asp:Label ID="ageLabel" runat="server" />
+ <br />
+ <asp:Button ID="getFavoriteSites" runat="server" Text="Get Favorite Sites"
+ onclick="getFavoriteSites_Click" />
+ <asp:Label ID="favoriteSitesLabel" runat="server" />
+</asp:Content> \ No newline at end of file
diff --git a/samples/OAuthConsumer/SampleWcf2.aspx.cs b/samples/OAuthConsumer/SampleWcf2.aspx.cs
new file mode 100644
index 0000000..deef073
--- /dev/null
+++ b/samples/OAuthConsumer/SampleWcf2.aspx.cs
@@ -0,0 +1,119 @@
+namespace OAuthConsumer {
+ using System;
+ using System.Collections.Generic;
+ using System.Globalization;
+ using System.Linq;
+ using System.Net;
+ using System.ServiceModel;
+ using System.ServiceModel.Channels;
+ using System.ServiceModel.Security;
+ using System.Web;
+ using System.Web.UI;
+ using System.Web.UI.WebControls;
+ using DotNetOpenAuth.OAuth2;
+
+ using OAuthConsumer.SampleServiceProvider;
+
+ public partial class SampleWcf2 : System.Web.UI.Page {
+ /// <summary>
+ /// The details about the sample OAuth-enabled WCF service that this sample client calls into.
+ /// </summary>
+ private static AuthorizationServerDescription AuthServerDescription = new AuthorizationServerDescription {
+ TokenEndpoint = new Uri("http://localhost:65169/OAuth2.ashx/token"),
+ AuthorizationEndpoint = new Uri("http://localhost:65169/OAuth2.ashx/auth"),
+ };
+
+ /// <summary>
+ /// Gets or sets the authorization details for the logged in user.
+ /// </summary>
+ /// <value>The authorization details.</value>
+ /// <remarks>
+ /// Because this is a sample, we simply store the authorization information in memory with the user session.
+ /// A real web app should store at least the access and refresh tokens in this object in a database associated with the user.
+ /// </remarks>
+ private static IAuthorizationState Authorization {
+ get { return (AuthorizationState)HttpContext.Current.Session["Authorization"]; }
+ set { HttpContext.Current.Session["Authorization"] = value; }
+ }
+
+ /// <summary>
+ /// The OAuth 2.0 client object to use to obtain authorization and authorize outgoing HTTP requests.
+ /// </summary>
+ private static readonly WebServerClient Client;
+
+ /// <summary>
+ /// Initializes the <see cref="SampleWcf2"/> class.
+ /// </summary>
+ static SampleWcf2() {
+ Client = new WebServerClient(AuthServerDescription, "sampleconsumer", "samplesecret");
+ }
+
+ protected void Page_Load(object sender, EventArgs e) {
+ if (!IsPostBack) {
+ // Check to see if we're receiving a end user authorization response.
+ var authorization = Client.ProcessUserAuthorization();
+ if (authorization != null) {
+ // We are receiving an authorization response. Store it and associate it with this user.
+ Authorization = authorization;
+ }
+ }
+ }
+
+ protected void getAuthorizationButton_Click(object sender, EventArgs e) {
+ string[] scopes = (from item in this.scopeList.Items.OfType<ListItem>()
+ where item.Selected
+ select item.Value).ToArray();
+
+ Client.RequestUserAuthorization(scopes).Send();
+ }
+
+ protected void getNameButton_Click(object sender, EventArgs e) {
+ try {
+ this.nameLabel.Text = CallService(client => client.GetName());
+ } catch (SecurityAccessDeniedException) {
+ this.nameLabel.Text = "Access denied!";
+ }
+ }
+
+ protected void getAgeButton_Click(object sender, EventArgs e) {
+ try {
+ int? age = CallService(client => client.GetAge());
+ this.ageLabel.Text = age.HasValue ? age.Value.ToString(CultureInfo.CurrentCulture) : "not available";
+ } catch (SecurityAccessDeniedException) {
+ this.ageLabel.Text = "Access denied!";
+ }
+ }
+
+ protected void getFavoriteSites_Click(object sender, EventArgs e) {
+ try {
+ string[] favoriteSites = CallService(client => client.GetFavoriteSites());
+ this.favoriteSitesLabel.Text = string.Join(", ", favoriteSites);
+ } catch (SecurityAccessDeniedException) {
+ this.favoriteSitesLabel.Text = "Access denied!";
+ }
+ }
+
+ private T CallService<T>(Func<DataApiClient, T> predicate) {
+ if (Authorization == null) {
+ throw new InvalidOperationException("No access token!");
+ }
+
+ var wcfClient = new DataApiClient();
+
+ // Refresh the access token if it expires and if its lifetime is too short to be of use.
+ if (Authorization.AccessTokenExpirationUtc.HasValue) {
+ Client.RefreshToken(Authorization, TimeSpan.FromMinutes(1));
+ }
+
+ var httpRequest = (HttpWebRequest)WebRequest.Create(wcfClient.Endpoint.Address.Uri);
+ Client.AuthorizeRequest(httpRequest, Authorization.AccessToken);
+
+ var httpDetails = new HttpRequestMessageProperty();
+ httpDetails.Headers[HttpRequestHeader.Authorization] = httpRequest.Headers[HttpRequestHeader.Authorization];
+ using (var scope = new OperationContextScope(wcfClient.InnerChannel)) {
+ OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpDetails;
+ return predicate(wcfClient);
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/samples/OAuthConsumer/SampleWcf2.aspx.designer.cs b/samples/OAuthConsumer/SampleWcf2.aspx.designer.cs
new file mode 100644
index 0000000..f42efff
--- /dev/null
+++ b/samples/OAuthConsumer/SampleWcf2.aspx.designer.cs
@@ -0,0 +1,96 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+// This code was generated by a tool.
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace OAuthConsumer {
+
+
+ public partial class SampleWcf2 {
+
+ /// <summary>
+ /// scopeList control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.WebControls.CheckBoxList scopeList;
+
+ /// <summary>
+ /// getAuthorizationButton control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.WebControls.Button getAuthorizationButton;
+
+ /// <summary>
+ /// authorizationLabel control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.WebControls.Label authorizationLabel;
+
+ /// <summary>
+ /// getNameButton control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.WebControls.Button getNameButton;
+
+ /// <summary>
+ /// nameLabel control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.WebControls.Label nameLabel;
+
+ /// <summary>
+ /// getAgeButton control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.WebControls.Button getAgeButton;
+
+ /// <summary>
+ /// ageLabel control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.WebControls.Label ageLabel;
+
+ /// <summary>
+ /// getFavoriteSites control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.WebControls.Button getFavoriteSites;
+
+ /// <summary>
+ /// favoriteSitesLabel control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.WebControls.Label favoriteSitesLabel;
+ }
+}
diff --git a/samples/OAuthConsumer/Web.config b/samples/OAuthConsumer/Web.config
index 2d8d817..0241480 100644
--- a/samples/OAuthConsumer/Web.config
+++ b/samples/OAuthConsumer/Web.config
@@ -39,6 +39,9 @@
<dotNetOpenAuth>
<!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. -->
<reporting enabled="true" />
+
+ <!-- FOR TESTING ONLY, we relax the SSL requirements. -->
+ <messaging relaxSslRequirements="true" />
</dotNetOpenAuth>
<appSettings>
@@ -48,11 +51,16 @@
<add key="twitterConsumerKey" value="" />
<add key="twitterConsumerSecret" value="" />
<!-- Google sign-up: https://www.google.com/accounts/ManageDomains -->
+ <add key="googleConsumerKey" value=""/>
+ <add key="googleConsumerSecret" value=""/>
<add key="googleConsumerKey" value="anonymous"/>
<add key="googleConsumerSecret" value="anonymous"/>
<!-- Yammer sign-up: https://www.yammer.com/client_applications/new -->
<add key="yammerConsumerKey" value=""/>
<add key="yammerConsumerSecret" value=""/>
+ <!-- Facebook sign-up: http://developers.facebook.com/setup/ -->
+ <add key="facebookAppID" value="367207604173"/>
+ <add key="facebookAppSecret" value="1df77e64055c4d7d3583cefdf2bc62d7"/>
</appSettings>
<connectionStrings/>
diff --git a/samples/OAuthConsumerWpf/Authorize2.xaml b/samples/OAuthConsumerWpf/Authorize2.xaml
new file mode 100644
index 0000000..eb59060
--- /dev/null
+++ b/samples/OAuthConsumerWpf/Authorize2.xaml
@@ -0,0 +1,11 @@
+<Window x:Class="DotNetOpenAuth.Samples.OAuthConsumerWpf.Authorize2"
+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+ xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ Title="Authorize" Height="500" Width="500">
+ <DockPanel LastChildFill="True">
+ <WindowsFormsHost Name="windowsFormsHost1">
+ <wf:WebBrowser x:Name="webBrowser" Dock="Fill" Navigating="webBrowser_Navigating" Navigated="webBrowser_Navigated" LocationChanged="webBrowser_LocationChanged" IsWebBrowserContextMenuEnabled="False" />
+ </WindowsFormsHost>
+ </DockPanel>
+</Window>
diff --git a/samples/OAuthConsumerWpf/Authorize2.xaml.cs b/samples/OAuthConsumerWpf/Authorize2.xaml.cs
new file mode 100644
index 0000000..8cf9f6f
--- /dev/null
+++ b/samples/OAuthConsumerWpf/Authorize2.xaml.cs
@@ -0,0 +1,76 @@
+namespace DotNetOpenAuth.Samples.OAuthConsumerWpf {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using System.Windows;
+ using System.Windows.Controls;
+ using System.Windows.Data;
+ using System.Windows.Documents;
+ using System.Windows.Input;
+ using System.Windows.Media;
+ using System.Windows.Media.Imaging;
+ using System.Windows.Navigation;
+ using System.Windows.Shapes;
+ using DotNetOpenAuth.OAuth2;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// Interaction logic for Authorize2.xaml
+ /// </summary>
+ public partial class Authorize2 : Window {
+ private UserAgentClient client;
+
+ internal Authorize2(UserAgentClient client, IAuthorizationState authorizationState) {
+ Contract.Requires(client != null, "client");
+ Contract.Requires(authorizationState != null, "authorizationState");
+
+ InitializeComponent();
+
+ this.client = client;
+ this.Authorization = authorizationState;
+ Uri authorizationUrl = this.client.RequestUserAuthorization(this.Authorization);
+ this.webBrowser.Navigate(authorizationUrl.AbsoluteUri); // use AbsoluteUri to workaround bug in WebBrowser that calls Uri.ToString instead of Uri.AbsoluteUri leading to escaping errors.
+ }
+
+ public IAuthorizationState Authorization { get; set; }
+
+ private void webBrowser_Navigating(object sender, System.Windows.Forms.WebBrowserNavigatingEventArgs e) {
+ this.locationChanged(e.Url);
+ }
+
+ private void locationChanged(Uri location) {
+ if (location.Scheme == "res") {
+ this.DialogResult = false;
+ this.Close();
+ MessageBox.Show("An error occurred during authorization.");
+ }
+
+ 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.DialogResult = !string.IsNullOrEmpty(this.Authorization.AccessToken);
+ this.Close();
+ }
+ }
+ }
+
+ private void webBrowser_Navigated(object sender, System.Windows.Forms.WebBrowserNavigatedEventArgs e) {
+ this.locationChanged(e.Url);
+ }
+
+ private void webBrowser_LocationChanged(object sender, EventArgs e) {
+ this.locationChanged(webBrowser.Url);
+ }
+
+ 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);
+ }
+ }
+} \ No newline at end of file
diff --git a/samples/OAuthConsumerWpf/MainWindow.xaml b/samples/OAuthConsumerWpf/MainWindow.xaml
index c59175c..6ba0c69 100644
--- a/samples/OAuthConsumerWpf/MainWindow.xaml
+++ b/samples/OAuthConsumerWpf/MainWindow.xaml
@@ -2,136 +2,194 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="DotNetOpenAuth Consumer (sample)" Height="400" Width="442">
- <TabControl Name="outerTabControl" Margin="0,10,0,0">
- <TabItem Header="Google" Name="googleTab">
- <Grid Margin="5">
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="Auto" />
- <ColumnDefinition />
- </Grid.ColumnDefinitions>
- <Grid.RowDefinitions>
- <RowDefinition Height="Auto" />
- <RowDefinition Height="Auto" />
- <RowDefinition Height="Auto" />
- <RowDefinition Height="Auto" />
- <RowDefinition />
- </Grid.RowDefinitions>
- <Button Grid.Column="1" Grid.Row="3" Name="beginAuthorizationButton" Click="beginAuthorizationButton_Click">Authorize</Button>
- <TabControl Grid.ColumnSpan="2" Grid.Row="4" Name="tabControl1" Margin="0,10,0,0">
- <TabItem Header="Gmail Contacts" Name="gmailContactsTab">
- <Grid Name="contactsGrid">
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="Auto" />
- <ColumnDefinition Width="Auto" />
- </Grid.ColumnDefinitions>
- </Grid>
- </TabItem>
- <TabItem Header="Blogger" Name="bloggerTab">
- <Grid>
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="Auto" />
- <ColumnDefinition Width="*" />
- </Grid.ColumnDefinitions>
- <Grid.RowDefinitions>
- <RowDefinition Height="Auto" />
- <RowDefinition Height="Auto" />
- <RowDefinition Height="Auto" />
- <RowDefinition Height="Auto" />
- </Grid.RowDefinitions>
- <Label>Blog URL</Label>
- <TextBox Grid.Column="1" x:Name="blogUrlBox"/>
- <Label Grid.Row="1">Title</Label>
- <TextBox Grid.Row="1" Grid.Column="1" x:Name="postTitleBox">OAuth Rocks!</TextBox>
- <Label Grid.Row="2">Body</Label>
- <TextBox Grid.Row="2" Grid.Column="1" x:Name="postBodyBox" AcceptsReturn="True" AcceptsTab="True" AutoWordSelection="True" TextWrapping="WrapWithOverflow">&lt;p xmlns="http://www.w3.org/1999/xhtml"&gt;Oauth is cool&lt;/p&gt;</TextBox>
- <Button x:Name="postButton" Grid.Row="3" Grid.Column="1" Click="postButton_Click" IsEnabled="False">Post</Button>
- </Grid>
- </TabItem>
- </TabControl>
- </Grid>
- </TabItem>
- <TabItem Header="WCF sample">
- <Grid Margin="5">
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="Auto" />
- <ColumnDefinition />
- </Grid.ColumnDefinitions>
- <Grid.RowDefinitions>
- <RowDefinition Height="Auto" />
- <RowDefinition Height="Auto" />
- <RowDefinition Height="Auto" />
- <RowDefinition Height="Auto" />
- <RowDefinition />
- </Grid.RowDefinitions>
- <Button Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0" Name="beginWcfAuthorizationButton" Click="beginWcfAuthorizationButton_Click">Authorize</Button>
- <Label Content="Name" Grid.Row="1" />
- <Label Grid.Row="1" Grid.Column="1" Name="wcfName" />
- <Label Content="Age" Grid.Row="2" />
- <Label Grid.Row="2" Grid.Column="1" Name="wcfAge" />
- <Label Content="Favorite sites" Grid.Row="3" />
- <Label Grid.Row="3" Grid.Column="1" Name="wcfFavoriteSites" />
- </Grid>
- </TabItem>
- <TabItem Header="Generic">
- <Grid>
- <Grid.RowDefinitions>
- <RowDefinition Height="auto" />
- <RowDefinition Height="auto" />
- <RowDefinition Height="auto" />
- <RowDefinition Height="auto" />
- <RowDefinition Height="auto" />
- <RowDefinition Height="auto" />
- <RowDefinition Height="auto" />
- <RowDefinition Height="auto" />
- <RowDefinition Height="*" />
- </Grid.RowDefinitions>
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="auto" />
- <ColumnDefinition Width="*" />
- <ColumnDefinition Width="auto" />
- </Grid.ColumnDefinitions>
- <Label Grid.Row="0">Request Token URL</Label>
- <TextBox Grid.Column="1" x:Name="requestTokenUrlBox" />
- <ComboBox Grid.Column="2" x:Name="requestTokenHttpMethod" SelectedIndex="1">
- <ComboBox.Items>
- <ComboBoxItem>GET</ComboBoxItem>
- <ComboBoxItem>POST</ComboBoxItem>
- </ComboBox.Items>
- </ComboBox>
- <Label Grid.Row="1">Authorize URL</Label>
- <TextBox Grid.Row="1" Grid.Column="1" x:Name="authorizeUrlBox" />
- <Label Grid.Row="1" Grid.Column="2">GET</Label>
- <Label Grid.Row="2">Access Token URL</Label>
- <TextBox Grid.Row="2" Grid.Column="1" x:Name="accessTokenUrlBox" />
- <ComboBox Grid.Row="2" Grid.Column="2" x:Name="accessTokenHttpMethod" SelectedIndex="1">
- <ComboBox.Items>
- <ComboBoxItem>GET</ComboBoxItem>
- <ComboBoxItem>POST</ComboBoxItem>
- </ComboBox.Items>
- </ComboBox>
- <Label Grid.Row="3">Resource URL</Label>
- <TextBox Grid.Row="3" Grid.Column="1" x:Name="resourceUrlBox" />
- <ComboBox Grid.Row="3" Grid.Column="2" x:Name="resourceHttpMethodList" SelectedIndex="0">
- <ComboBox.Items>
- <ComboBoxItem>GET w/ header</ComboBoxItem>
- <ComboBoxItem>GET w/ querystring</ComboBoxItem>
- <ComboBoxItem>POST</ComboBoxItem>
- </ComboBox.Items>
- </ComboBox>
- <Label Grid.Row="4">Consumer key</Label>
- <TextBox Grid.Row="4" Grid.Column="1" x:Name="consumerKeyBox" Grid.ColumnSpan="2"/>
- <Label Grid.Row="5">Consumer secret</Label>
- <TextBox Grid.Row="5" Grid.Column="1" x:Name="consumerSecretBox" Grid.ColumnSpan="2"/>
- <Label Grid.Row="6">OAuth version</Label>
- <ComboBox Grid.Row="6" Grid.Column="1" SelectedIndex="1" x:Name="oauthVersion">
- <ComboBox.Items>
- <ComboBoxItem>1.0</ComboBoxItem>
- <ComboBoxItem>1.0a</ComboBoxItem>
- </ComboBox.Items>
- </ComboBox>
- <Button Grid.Row="7" Grid.Column="1" x:Name="beginButton" Click="beginButton_Click">Begin</Button>
- <TextBox Grid.Column="0" Grid.Row="8" Grid.ColumnSpan="3" Name="resultsBox" IsReadOnly="True" />
- </Grid>
- </TabItem>
- </TabControl>
+ <TabControl Name="outerTabControl" Margin="0,10,0,0">
+ <TabItem Header="Google" Name="googleTab">
+ <Grid Margin="5">
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="Auto" />
+ <ColumnDefinition />
+ </Grid.ColumnDefinitions>
+ <Grid.RowDefinitions>
+ <RowDefinition Height="Auto" />
+ <RowDefinition Height="Auto" />
+ <RowDefinition Height="Auto" />
+ <RowDefinition Height="Auto" />
+ <RowDefinition />
+ </Grid.RowDefinitions>
+ <Button Grid.Column="1" Grid.Row="3" Name="beginAuthorizationButton" Click="beginAuthorizationButton_Click">Authorize</Button>
+ <TabControl Grid.ColumnSpan="2" Grid.Row="4" Name="tabControl1" Margin="0,10,0,0">
+ <TabItem Header="Gmail Contacts" Name="gmailContactsTab">
+ <Grid Name="contactsGrid">
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="Auto" />
+ <ColumnDefinition Width="Auto" />
+ </Grid.ColumnDefinitions>
+ </Grid>
+ </TabItem>
+ <TabItem Header="Blogger" Name="bloggerTab">
+ <Grid>
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="Auto" />
+ <ColumnDefinition Width="*" />
+ </Grid.ColumnDefinitions>
+ <Grid.RowDefinitions>
+ <RowDefinition Height="Auto" />
+ <RowDefinition Height="Auto" />
+ <RowDefinition Height="Auto" />
+ <RowDefinition Height="Auto" />
+ </Grid.RowDefinitions>
+ <Label>Blog URL</Label>
+ <TextBox Grid.Column="1" x:Name="blogUrlBox"/>
+ <Label Grid.Row="1">Title</Label>
+ <TextBox Grid.Row="1" Grid.Column="1" x:Name="postTitleBox">OAuth Rocks!</TextBox>
+ <Label Grid.Row="2">Body</Label>
+ <TextBox Grid.Row="2" Grid.Column="1" x:Name="postBodyBox" AcceptsReturn="True" AcceptsTab="True" AutoWordSelection="True" TextWrapping="WrapWithOverflow">&lt;p xmlns="http://www.w3.org/1999/xhtml"&gt;Oauth is cool&lt;/p&gt;</TextBox>
+ <Button x:Name="postButton" Grid.Row="3" Grid.Column="1" Click="postButton_Click" IsEnabled="False">Post</Button>
+ </Grid>
+ </TabItem>
+ </TabControl>
+ </Grid>
+ </TabItem>
+ <TabItem Header="WCF sample">
+ <Grid Margin="5">
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="Auto" />
+ <ColumnDefinition />
+ </Grid.ColumnDefinitions>
+ <Grid.RowDefinitions>
+ <RowDefinition Height="Auto" />
+ <RowDefinition Height="Auto" />
+ <RowDefinition Height="Auto" />
+ <RowDefinition Height="Auto" />
+ <RowDefinition />
+ </Grid.RowDefinitions>
+ <Button Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0" Name="beginWcfAuthorizationButton" Click="beginWcfAuthorizationButton_Click">Authorize</Button>
+ <Label Content="Name" Grid.Row="1" />
+ <Label Grid.Row="1" Grid.Column="1" Name="wcfName" />
+ <Label Content="Age" Grid.Row="2" />
+ <Label Grid.Row="2" Grid.Column="1" Name="wcfAge" />
+ <Label Content="Favorite sites" Grid.Row="3" />
+ <Label Grid.Row="3" Grid.Column="1" Name="wcfFavoriteSites" />
+ </Grid>
+ </TabItem>
+ <TabItem Header="Generic 1.0(a)">
+ <Grid>
+ <Grid.RowDefinitions>
+ <RowDefinition Height="auto" />
+ <RowDefinition Height="auto" />
+ <RowDefinition Height="auto" />
+ <RowDefinition Height="auto" />
+ <RowDefinition Height="auto" />
+ <RowDefinition Height="auto" />
+ <RowDefinition Height="auto" />
+ <RowDefinition Height="auto" />
+ <RowDefinition Height="*" />
+ </Grid.RowDefinitions>
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="auto" />
+ <ColumnDefinition Width="*" />
+ <ColumnDefinition Width="auto" />
+ </Grid.ColumnDefinitions>
+ <Label Grid.Row="0">Request Token URL</Label>
+ <TextBox Grid.Column="1" x:Name="requestTokenUrlBox" />
+ <ComboBox Grid.Column="2" x:Name="requestTokenHttpMethod" SelectedIndex="1">
+ <ComboBox.Items>
+ <ComboBoxItem>GET</ComboBoxItem>
+ <ComboBoxItem>POST</ComboBoxItem>
+ </ComboBox.Items>
+ </ComboBox>
+ <Label Grid.Row="1">Authorize URL</Label>
+ <TextBox Grid.Row="1" Grid.Column="1" x:Name="authorizeUrlBox" />
+ <Label Grid.Row="1" Grid.Column="2">GET</Label>
+ <Label Grid.Row="2">Access Token URL</Label>
+ <TextBox Grid.Row="2" Grid.Column="1" x:Name="accessTokenUrlBox" />
+ <ComboBox Grid.Row="2" Grid.Column="2" x:Name="accessTokenHttpMethod" SelectedIndex="1">
+ <ComboBox.Items>
+ <ComboBoxItem>GET</ComboBoxItem>
+ <ComboBoxItem>POST</ComboBoxItem>
+ </ComboBox.Items>
+ </ComboBox>
+ <Label Grid.Row="3">Resource URL</Label>
+ <TextBox Grid.Row="3" Grid.Column="1" x:Name="resourceUrlBox" />
+ <ComboBox Grid.Row="3" Grid.Column="2" x:Name="resourceHttpMethodList" SelectedIndex="0">
+ <ComboBox.Items>
+ <ComboBoxItem>GET w/ header</ComboBoxItem>
+ <ComboBoxItem>GET w/ querystring</ComboBoxItem>
+ <ComboBoxItem>POST</ComboBoxItem>
+ </ComboBox.Items>
+ </ComboBox>
+ <Label Grid.Row="4">Consumer key</Label>
+ <TextBox Grid.Row="4" Grid.Column="1" x:Name="consumerKeyBox" Grid.ColumnSpan="2"/>
+ <Label Grid.Row="5">Consumer secret</Label>
+ <TextBox Grid.Row="5" Grid.Column="1" x:Name="consumerSecretBox" Grid.ColumnSpan="2"/>
+ <Label Grid.Row="6">OAuth version</Label>
+ <ComboBox Grid.Row="6" Grid.Column="1" SelectedIndex="1" x:Name="oauthVersion">
+ <ComboBox.Items>
+ <ComboBoxItem>1.0</ComboBoxItem>
+ <ComboBoxItem>1.0a</ComboBoxItem>
+ </ComboBox.Items>
+ </ComboBox>
+ <Button Grid.Row="7" Grid.Column="1" x:Name="beginButton" Click="beginButton_Click">Begin</Button>
+ <TextBox Grid.Column="0" Grid.Row="8" Grid.ColumnSpan="3" Name="resultsBox" IsReadOnly="True" />
+ </Grid>
+ </TabItem>
+ <TabItem Header="Generic 2.0">
+ <Grid>
+ <Grid.RowDefinitions>
+ <RowDefinition Height="auto" />
+ <RowDefinition Height="auto" />
+ <RowDefinition Height="auto" />
+ <RowDefinition Height="auto" />
+ <RowDefinition Height="auto" />
+ <RowDefinition Height="auto" />
+ <RowDefinition Height="auto" />
+ <RowDefinition Height="auto" />
+ <RowDefinition Height="auto" />
+ <RowDefinition Height="*" />
+ </Grid.RowDefinitions>
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="auto" />
+ <ColumnDefinition Width="*" />
+ <ColumnDefinition Width="auto" />
+ </Grid.ColumnDefinitions>
+ <Label Grid.Row="1" TabIndex="202">Token Endpoint URL</Label>
+ <TextBox Grid.Row="1" Grid.Column="1" x:Name="oauth2TokenEndpointBox" Text="http://localhost:18916/OAuthTokenEndpoint.ashx" TabIndex="203" />
+ <Label Grid.Row="1" Grid.Column="2" TabIndex="204">POST</Label>
+ <Label Grid.Row="2" TabIndex="205">User Authorization URL</Label>
+ <TextBox Grid.Row="2" Grid.Column="1" x:Name="oauth2AuthorizationUrlBox" Text="http://localhost:18916/Account/Authorize" TabIndex="206" />
+ <Label Grid.Row="2" Grid.Column="2" TabIndex="207">GET</Label>
+ <Label Grid.Row="0" TabIndex="200">Grant Type</Label>
+ <ComboBox Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="2" x:Name="flowBox" SelectedIndex="0" TabIndex="201">
+ <ComboBox.Items>
+ <ComboBoxItem>Authorization Code</ComboBoxItem>
+ <ComboBoxItem>Resource Owner Basic Credentials</ComboBoxItem>
+ <ComboBoxItem>Access Code (direct)</ComboBoxItem>
+ </ComboBox.Items>
+ </ComboBox>
+ <Label Grid.Row="3" TabIndex="207">Resource URL</Label>
+ <TextBox Grid.Row="3" Grid.Column="1" x:Name="oauth2ResourceUrlBox" Text="http://localhost:18916/" TabIndex="208" />
+ <ComboBox Grid.Row="3" Grid.Column="2" x:Name="oauth2ResourceHttpMethodList" SelectedIndex="0" TabIndex="209">
+ <ComboBox.Items>
+ <ComboBoxItem>GET w/ header</ComboBoxItem>
+ <ComboBoxItem>GET w/ querystring</ComboBoxItem>
+ <ComboBoxItem>POST</ComboBoxItem>
+ </ComboBox.Items>
+ </ComboBox>
+ <Label Grid.Row="4" TabIndex="210">Client Identifier</Label>
+ <TextBox Grid.Row="4" Grid.Column="1" x:Name="oauth2ClientIdentifierBox" Grid.ColumnSpan="2" Text="a" TabIndex="211" />
+ <Label Grid.Row="5" TabIndex="212">Client Secret</Label>
+ <TextBox Grid.Row="5" Grid.Column="1" x:Name="oauth2ClientSecretBox" Grid.ColumnSpan="2" Text="b" TabIndex="213" />
+ <Label Grid.Row="6" TabIndex="214">Scope</Label>
+ <TextBox Grid.Row="6" Grid.Column="1" x:Name="oauth2ScopeBox" TabIndex="215" Text="some scope" />
+ <Label Grid.Row="7" TabIndex="216">OAuth 2.0 version</Label>
+ <ComboBox Grid.Row="7" Grid.Column="1" SelectedIndex="0" x:Name="oauth2Version" TabIndex="217">
+ <ComboBox.Items>
+ <ComboBoxItem>2.0 DRAFT 9</ComboBoxItem>
+ </ComboBox.Items>
+ </ComboBox>
+ <Button Grid.Row="8" Grid.Column="1" x:Name="oauth2BeginButton" Click="oauth2BeginButton_Click" TabIndex="218">Begin</Button>
+ <TextBox Grid.Column="0" Grid.Row="9" Grid.ColumnSpan="3" Name="oauth2ResultsBox" IsReadOnly="True" TabIndex="219"/>
+ </Grid>
+ </TabItem>
+ </TabControl>
</Window>
diff --git a/samples/OAuthConsumerWpf/MainWindow.xaml.cs b/samples/OAuthConsumerWpf/MainWindow.xaml.cs
index 1914621..e62683d 100644
--- a/samples/OAuthConsumerWpf/MainWindow.xaml.cs
+++ b/samples/OAuthConsumerWpf/MainWindow.xaml.cs
@@ -3,32 +3,27 @@
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
+ using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.ServiceModel.Channels;
- using System.Text;
- using System.Threading;
using System.Windows;
using System.Windows.Controls;
- using System.Windows.Data;
- using System.Windows.Documents;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Media.Imaging;
- using System.Windows.Navigation;
- using System.Windows.Shapes;
- using System.Xml;
using System.Xml.Linq;
- using System.Xml.XPath;
- using DotNetOpenAuth;
+
using DotNetOpenAuth.ApplicationBlock;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OAuth;
using DotNetOpenAuth.OAuth.ChannelElements;
using DotNetOpenAuth.Samples.OAuthConsumerWpf.WcfSampleService;
+ using OAuth2;
+
+ using OAuth2 = DotNetOpenAuth.OAuth2;
+ using ProtocolVersion = DotNetOpenAuth.OAuth.ProtocolVersion;
+
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
@@ -86,7 +81,7 @@
return;
}
- Authorize auth = new Authorize(
+ var auth = new Authorize(
this.google,
(DesktopConsumer consumer, out string requestToken) =>
GoogleConsumer.RequestAuthorization(
@@ -198,5 +193,51 @@
MessageBox.Show(this, ex.Message);
}
}
+
+ private void oauth2BeginButton_Click(object sender, RoutedEventArgs e) {
+ var authServer = new DotNetOpenAuth.OAuth2.AuthorizationServerDescription {
+ AuthorizationEndpoint = new Uri(oauth2AuthorizationUrlBox.Text),
+ };
+ if (oauth2TokenEndpointBox.Text.Length > 0) {
+ authServer.TokenEndpoint = new Uri(oauth2TokenEndpointBox.Text);
+ }
+
+ try {
+ var client = new OAuth2.UserAgentClient(authServer, oauth2ClientIdentifierBox.Text, oauth2ClientSecretBox.Text);
+
+ var authorization = new AuthorizationState(OAuthUtilities.SplitScopes(oauth2ScopeBox.Text));
+ var authorizePopup = new Authorize2(client, authorization);
+ authorizePopup.Owner = this;
+ bool? result = authorizePopup.ShowDialog();
+ if (result.HasValue && result.Value) {
+ var requestUri = new UriBuilder(oauth2ResourceUrlBox.Text);
+ if (oauth2ResourceHttpMethodList.SelectedIndex > 0) {
+ requestUri.AppendQueryArgument("access_token", authorization.AccessToken);
+ }
+
+ var request = (HttpWebRequest)WebRequest.Create(requestUri.Uri);
+ request.Method = oauth2ResourceHttpMethodList.SelectedIndex < 2 ? "GET" : "POST";
+ if (oauth2ResourceHttpMethodList.SelectedIndex == 0) {
+ client.AuthorizeRequest(request, authorization);
+ }
+
+ using (var resourceResponse = request.GetResponse()) {
+ using (var responseStream = new StreamReader(resourceResponse.GetResponseStream())) {
+ oauth2ResultsBox.Text = responseStream.ReadToEnd();
+ }
+ }
+ } else {
+ return;
+ }
+ } catch (Messaging.ProtocolException ex) {
+ MessageBox.Show(this, ex.Message);
+ } catch (WebException ex) {
+ string responseText = string.Empty;
+ using (var responseReader = new StreamReader(ex.Response.GetResponseStream())) {
+ responseText = responseReader.ReadToEnd();
+ }
+ MessageBox.Show(this, ex.Message + " " + responseText);
+ }
+ }
}
}
diff --git a/samples/OAuthConsumerWpf/OAuthConsumerWpf.csproj b/samples/OAuthConsumerWpf/OAuthConsumerWpf.csproj
index 32f1093..e6971c0 100644
--- a/samples/OAuthConsumerWpf/OAuthConsumerWpf.csproj
+++ b/samples/OAuthConsumerWpf/OAuthConsumerWpf.csproj
@@ -95,6 +95,8 @@
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
+ <Reference Include="WindowsFormsIntegration" />
+ <Reference Include="System.Windows.Forms" />
<Reference Include="UIAutomationProvider">
<RequiredTargetFramework>3.0</RequiredTargetFramework>
</Reference>
@@ -124,6 +126,10 @@
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
+ <Page Include="Authorize2.xaml">
+ <SubType>Designer</SubType>
+ <Generator>MSBuild:Compile</Generator>
+ </Page>
<Page Include="MainWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
@@ -134,6 +140,9 @@
<DependentUpon>App.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
+ <Compile Include="Authorize2.xaml.cs">
+ <DependentUpon>Authorize2.xaml</DependentUpon>
+ </Compile>
<Compile Include="MainWindow.xaml.cs">
<DependentUpon>MainWindow.xaml</DependentUpon>
<SubType>Code</SubType>
@@ -226,5 +235,12 @@
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
+ Other similar extension points exist, see Microsoft.Common.targets.
+ <Target Name="BeforeBuild">
+ </Target>
+ <Target Name="AfterBuild">
+ </Target>
+ -->
<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/samples/OAuthServiceProvider/Code/DatabaseNonceStore.cs b/samples/OAuthServiceProvider/Code/DatabaseNonceStore.cs
index 1f8f56e..f0c10d1 100644
--- a/samples/OAuthServiceProvider/Code/DatabaseNonceStore.cs
+++ b/samples/OAuthServiceProvider/Code/DatabaseNonceStore.cs
@@ -4,6 +4,7 @@
using System.Linq;
using System.Web;
using DotNetOpenAuth.Messaging.Bindings;
+ using System.Data.SqlClient;
/// <summary>
/// A database-persisted nonce store.
@@ -47,6 +48,8 @@
return true;
} catch (System.Data.Linq.DuplicateKeyException) {
return false;
+ } catch (SqlException) {
+ return false;
}
}
diff --git a/samples/OAuthServiceProvider/Code/Global.cs b/samples/OAuthServiceProvider/Code/Global.cs
index ceaeac8..7c2e9f7 100644
--- a/samples/OAuthServiceProvider/Code/Global.cs
+++ b/samples/OAuthServiceProvider/Code/Global.cs
@@ -5,6 +5,8 @@
using System.Text;
using System.Web;
using DotNetOpenAuth.OAuth.Messages;
+ using DotNetOpenAuth.OAuth2;
+ using DotNetOpenAuth.OAuth2.Messages;
/// <summary>
/// The web application global events and properties.
@@ -20,6 +22,8 @@
/// </summary>
public static log4net.ILog Logger = log4net.LogManager.GetLogger("DotNetOpenAuth.OAuthServiceProvider");
+ public static AuthorizationServer AuthorizationServer = new AuthorizationServer(new OAuth2AuthorizationServer());
+
/// <summary>
/// Gets the transaction-protected database connection for the current request.
/// </summary>
@@ -50,6 +54,12 @@
set { HttpContext.Current.Session["authrequest"] = value; }
}
+ public static EndUserAuthorizationRequest PendingOAuth2Authorization
+ {
+ get { return HttpContext.Current.Session["authrequest"] as EndUserAuthorizationRequest; }
+ set { HttpContext.Current.Session["authrequest"] = value; }
+ }
+
private static DataClassesDataContext dataContextSimple {
get {
if (HttpContext.Current != null) {
diff --git a/samples/OAuthServiceProvider/Code/OAuth2AuthorizationServer.cs b/samples/OAuthServiceProvider/Code/OAuth2AuthorizationServer.cs
new file mode 100644
index 0000000..00503c4
--- /dev/null
+++ b/samples/OAuthServiceProvider/Code/OAuth2AuthorizationServer.cs
@@ -0,0 +1,59 @@
+namespace OAuthServiceProvider.Code {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Security.Cryptography;
+ using System.Web;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+ using DotNetOpenAuth.OAuth2;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ internal class OAuth2AuthorizationServer : IAuthorizationServer {
+ internal static readonly RSAParameters AsymmetricKey;
+
+ private static readonly byte[] secret;
+
+ private readonly INonceStore nonceStore = new DatabaseNonceStore();
+
+ static OAuth2AuthorizationServer() {
+ // For this sample, we just generate random secrets.
+ RandomNumberGenerator crypto = new RNGCryptoServiceProvider();
+ secret = new byte[16];
+ crypto.GetBytes(secret);
+
+ AsymmetricKey = new RSACryptoServiceProvider().ExportParameters(true);
+ }
+
+ #region Implementation of IAuthorizationServer
+
+ public byte[] Secret {
+ get { return secret; }
+ }
+
+ public DotNetOpenAuth.Messaging.Bindings.INonceStore VerificationCodeNonceStore {
+ get { return this.nonceStore; }
+ }
+
+ public RSAParameters AccessTokenSigningPrivateKey {
+ get { return AsymmetricKey; }
+ }
+
+ public IConsumerDescription GetClient(string clientIdentifier) {
+ var consumerRow = Global.DataContext.OAuthConsumers.SingleOrDefault(
+ consumerCandidate => consumerCandidate.ConsumerKey == clientIdentifier);
+ if (consumerRow == null) {
+ throw new ArgumentOutOfRangeException("clientIdentifier");
+ }
+
+ return consumerRow;
+ }
+
+ #endregion
+
+ public bool IsAuthorizationValid(IAuthorizationDescription authorization) {
+ // We don't support revoking tokens yet.
+ return true;
+ }
+ }
+} \ No newline at end of file
diff --git a/samples/OAuthServiceProvider/Code/OAuthAuthorizationManager.cs b/samples/OAuthServiceProvider/Code/OAuthAuthorizationManager.cs
index 6d5bfff..3c8a3be 100644
--- a/samples/OAuthServiceProvider/Code/OAuthAuthorizationManager.cs
+++ b/samples/OAuthServiceProvider/Code/OAuthAuthorizationManager.cs
@@ -7,8 +7,13 @@
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
- using DotNetOpenAuth;
+
+ using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OAuth;
+ using DotNetOpenAuth.OAuth.ChannelElements;
+ using DotNetOpenAuth.OAuth2;
+
+ using ProtocolException = System.ServiceModel.ProtocolException;
/// <summary>
/// A WCF extension to authenticate incoming messages using OAuth.
@@ -22,19 +27,16 @@
return false;
}
- HttpRequestMessageProperty httpDetails = operationContext.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
- Uri requestUri = operationContext.RequestContext.RequestMessage.Properties["OriginalHttpRequestUri"] as Uri;
- ServiceProvider sp = Constants.CreateServiceProvider();
- try {
- var auth = sp.ReadProtectedResourceAuthorization(httpDetails, requestUri);
- if (auth != null) {
- var accessToken = Global.DataContext.OAuthTokens.Single(token => token.Token == auth.AccessToken);
+ var httpDetails = operationContext.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
+ var requestUri = operationContext.RequestContext.RequestMessage.Properties["OriginalHttpRequestUri"] as Uri;
- var principal = sp.CreatePrincipal(auth);
+ try {
+ var principal = this.VerifyOAuth2(httpDetails, requestUri);
+ if (principal != null) {
var policy = new OAuthPrincipalAuthorizationPolicy(principal);
var policies = new List<IAuthorizationPolicy> {
- policy,
- };
+ policy,
+ };
var securityContext = new ServiceSecurityContext(policies.AsReadOnly());
if (operationContext.IncomingMessageProperties.Security != null) {
@@ -46,14 +48,13 @@
}
securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> {
- principal.Identity,
- };
+ principal.Identity,
+ };
// Only allow this method call if the access token scope permits it.
- string[] scopes = accessToken.Scope.Split('|');
- if (scopes.Contains(operationContext.IncomingMessageHeaders.Action)) {
- return true;
- }
+ return principal.IsInRole(operationContext.IncomingMessageHeaders.Action);
+ } else {
+ return false;
}
} catch (ProtocolException ex) {
Global.Logger.Error("Error processing OAuth messages.", ex);
@@ -61,5 +62,36 @@
return false;
}
+
+ private OAuthPrincipal VerifyOAuth1(HttpRequestMessageProperty httpDetails, Uri requestUri) {
+ ServiceProvider sp = Constants.CreateServiceProvider();
+ var auth = sp.ReadProtectedResourceAuthorization(httpDetails, requestUri);
+ if (auth != null) {
+ var accessToken = Global.DataContext.OAuthTokens.Single(token => token.Token == auth.AccessToken);
+ var principal = sp.CreatePrincipal(auth);
+ return principal;
+ }
+
+ return null;
+ }
+
+ private OAuthPrincipal VerifyOAuth2(HttpRequestMessageProperty httpDetails, Uri requestUri) {
+ // for this sample where the auth server and resource server are the same site,
+ // we use the same public/private key.
+ var resourceServer = new ResourceServer(
+ new StandardAccessTokenAnalyzer(
+ OAuth2AuthorizationServer.AsymmetricKey,
+ OAuth2AuthorizationServer.AsymmetricKey));
+
+ string username;
+ HashSet<string> scope;
+ var error = resourceServer.VerifyAccess(new HttpRequestInfo(httpDetails, requestUri), out username, out scope);
+ if (error == null) {
+ var principal = new OAuthPrincipal(username, scope.ToArray());
+ return principal;
+ } else {
+ return null;
+ }
+ }
}
} \ No newline at end of file
diff --git a/samples/OAuthServiceProvider/Code/OAuthConsumer.cs b/samples/OAuthServiceProvider/Code/OAuthConsumer.cs
index d7dfc06..8291929 100644
--- a/samples/OAuthServiceProvider/Code/OAuthConsumer.cs
+++ b/samples/OAuthServiceProvider/Code/OAuthConsumer.cs
@@ -11,7 +11,7 @@ namespace OAuthServiceProvider.Code {
using System.Web;
using DotNetOpenAuth.OAuth.ChannelElements;
- public partial class OAuthConsumer : IConsumerDescription {
+ public partial class OAuthConsumer : IConsumerDescription, DotNetOpenAuth.OAuth2.IConsumerDescription {
#region IConsumerDescription Members
string IConsumerDescription.Key {
@@ -39,5 +39,17 @@ namespace OAuthServiceProvider.Code {
}
#endregion
+
+ #region IConsumerDescription Members
+
+ string DotNetOpenAuth.OAuth2.IConsumerDescription.Secret {
+ get { return this.ConsumerSecret; }
+ }
+
+ Uri DotNetOpenAuth.OAuth2.IConsumerDescription.Callback {
+ get { return string.IsNullOrEmpty(this.Callback) ? null : new Uri(this.Callback); }
+ }
+
+ #endregion
}
} \ No newline at end of file
diff --git a/samples/OAuthServiceProvider/Login.aspx b/samples/OAuthServiceProvider/Login.aspx
index d63b2c8..fd858c8 100644
--- a/samples/OAuthServiceProvider/Login.aspx
+++ b/samples/OAuthServiceProvider/Login.aspx
@@ -1,7 +1,11 @@
<%@ Page Title="Login" Language="C#" MasterPageFile="~/MasterPage.master" %>
<%@ Register Assembly="DotNetOpenAuth" Namespace="DotNetOpenAuth.OpenId.RelyingParty" TagPrefix="rp" %>
-
+<script runat="server">
+ protected void Page_Load(object sender, EventArgs e) {
+ OpenIdLogin1.Focus();
+ }
+</script>
<asp:Content ID="Content2" ContentPlaceHolderID="Body" runat="Server">
- <rp:OpenIdLogin runat="server" TabIndex='1' />
+ <rp:OpenIdLogin runat="server" TabIndex='1' ID="OpenIdLogin1" />
</asp:Content>
diff --git a/samples/OAuthServiceProvider/Members/Authorize.aspx b/samples/OAuthServiceProvider/Members/Authorize.aspx
index b3e2c6a..251189a 100644
--- a/samples/OAuthServiceProvider/Members/Authorize.aspx
+++ b/samples/OAuthServiceProvider/Members/Authorize.aspx
@@ -1,4 +1,4 @@
-<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" Inherits="OAuthServiceProvider.Authorize" Codebehind="Authorize.aspx.cs" %>
+<%@ Page Title="Authorize Access" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" Inherits="OAuthServiceProvider.Authorize" Codebehind="Authorize.aspx.cs" %>
<asp:Content ID="Content2" ContentPlaceHolderID="Body" runat="Server">
<asp:MultiView runat="server" ActiveViewIndex="0" ID="multiView">
diff --git a/samples/OAuthServiceProvider/Members/Authorize2.aspx b/samples/OAuthServiceProvider/Members/Authorize2.aspx
new file mode 100644
index 0000000..eb8322f
--- /dev/null
+++ b/samples/OAuthServiceProvider/Members/Authorize2.aspx
@@ -0,0 +1,53 @@
+<%@ Page Title="Authorize Access" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true"
+ CodeBehind="Authorize2.aspx.cs" Inherits="OAuthServiceProvider.Members.Authorize2" %>
+
+<asp:Content ID="Content2" ContentPlaceHolderID="Body" runat="server">
+ <asp:MultiView runat="server" ActiveViewIndex="0" ID="multiView">
+ <asp:View ID="AuthRequest" runat="server">
+ <div style="background-color: Yellow">
+ <b>Warning</b>: Never give your login credentials to another web site or application.
+ </div>
+ <asp:HiddenField runat="server" ID="OAuthAuthorizationSecToken" EnableViewState="false" />
+ <p>The client web site or application <asp:Label ID="consumerLabel" Font-Bold="true"
+ runat="server" Text="[consumer]" /> wants access to your <asp:Label ID="desiredAccessLabel"
+ Font-Bold="true" runat="server" Text="[protected resource]" />. </p>
+ <p>Do you want to allow this? </p>
+ <div style="display: none" id="responseButtonsDiv">
+ <asp:Button ID="allowAccessButton" runat="server" Text="Yes" OnClick="allowAccessButton_Click" />
+ <asp:Button ID="denyAccessButton" runat="server" Text="No" OnClick="denyAccessButton_Click" />
+ </div>
+ <div id="javascriptDisabled">
+ <b>JavaScript appears to be disabled in your browser. </b>This page requires Javascript
+ to be enabled to better protect your security.
+ </div>
+ <p>If you grant access now, you can revoke it at any time by returning to this page.
+ </p>
+ <script language="javascript" type="text/javascript">
+ //<![CDATA[
+ // we use HTML to hide the action buttons and JavaScript to show them
+ // to protect against click-jacking in an iframe whose JavaScript is disabled.
+ document.getElementById('responseButtonsDiv').style.display = 'block';
+ document.getElementById('javascriptDisabled').style.display = 'none';
+
+ // Frame busting code (to protect us from being hosted in an iframe).
+ // This protects us from click-jacking.
+ if (document.location !== window.top.location) {
+ window.top.location = document.location;
+ }
+ //]]>
+ </script>
+ </asp:View>
+ <asp:View ID="AuthGranted" runat="server">
+ <p>Authorization has been granted.</p>
+ <asp:MultiView runat="server" ID="verifierMultiView" ActiveViewIndex="0">
+ <asp:View ID="View3" runat="server">
+ <p>You must enter this verification code at the Consumer: <asp:Label runat="server"
+ ID="verificationCodeLabel" /> </p>
+ </asp:View>
+ <asp:View ID="View4" runat="server">
+ <p>You may now close this window and return to the Consumer. </p>
+ </asp:View>
+ </asp:MultiView>
+ </asp:View>
+ </asp:MultiView>
+</asp:Content>
diff --git a/samples/OAuthServiceProvider/Members/Authorize2.aspx.cs b/samples/OAuthServiceProvider/Members/Authorize2.aspx.cs
new file mode 100644
index 0000000..88c3049
--- /dev/null
+++ b/samples/OAuthServiceProvider/Members/Authorize2.aspx.cs
@@ -0,0 +1,55 @@
+namespace OAuthServiceProvider.Members {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Security.Cryptography;
+ using System.Web;
+ using System.Web.UI;
+ using System.Web.UI.WebControls;
+ using Code;
+
+ using DotNetOpenAuth.OAuth2;
+
+ public partial class Authorize2 : System.Web.UI.Page {
+ private static readonly RandomNumberGenerator CryptoRandomDataGenerator = new RNGCryptoServiceProvider();
+
+ private string AuthorizationSecret {
+ get { return Session["OAuthAuthorizationSecret"] as string; }
+ set { Session["OAuthAuthorizationSecret"] = value; }
+ }
+
+ protected void Page_Load(object sender, EventArgs e) {
+ if (!IsPostBack) {
+ if (Global.PendingOAuth2Authorization == null) {
+ Response.Redirect("~/Members/AuthorizedConsumers.aspx");
+ } else {
+ var pendingRequest = Global.PendingOAuth2Authorization;
+ this.desiredAccessLabel.Text = OAuthUtilities.JoinScopes(pendingRequest.Scope);
+ this.consumerLabel.Text = pendingRequest.ClientIdentifier;
+
+ // Generate an unpredictable secret that goes to the user agent and must come back
+ // with authorization to guarantee the user interacted with this page rather than
+ // being scripted by an evil Consumer.
+ var randomData = new byte[8];
+ CryptoRandomDataGenerator.GetBytes(randomData);
+ this.AuthorizationSecret = Convert.ToBase64String(randomData);
+ this.OAuthAuthorizationSecToken.Value = this.AuthorizationSecret;
+ }
+ }
+ }
+
+ protected void allowAccessButton_Click(object sender, EventArgs e) {
+ if (this.AuthorizationSecret != this.OAuthAuthorizationSecToken.Value) {
+ throw new ArgumentException(); // probably someone trying to hack in.
+ }
+ this.AuthorizationSecret = null; // clear one time use secret
+ this.multiView.SetActiveView(this.AuthGranted);
+
+ Global.AuthorizationServer.ApproveAuthorizationRequest(Global.PendingOAuth2Authorization, User.Identity.Name);
+ }
+
+ protected void denyAccessButton_Click(object sender, EventArgs e) {
+ Global.AuthorizationServer.RejectAuthorizationRequest(Global.PendingOAuth2Authorization);
+ }
+ }
+} \ No newline at end of file
diff --git a/samples/OAuthServiceProvider/Members/Authorize2.aspx.designer.cs b/samples/OAuthServiceProvider/Members/Authorize2.aspx.designer.cs
new file mode 100644
index 0000000..db39669
--- /dev/null
+++ b/samples/OAuthServiceProvider/Members/Authorize2.aspx.designer.cs
@@ -0,0 +1,123 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+// This code was generated by a tool.
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace OAuthServiceProvider.Members {
+
+
+ public partial class Authorize2 {
+
+ /// <summary>
+ /// multiView control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.WebControls.MultiView multiView;
+
+ /// <summary>
+ /// AuthRequest control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.WebControls.View AuthRequest;
+
+ /// <summary>
+ /// OAuthAuthorizationSecToken control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.WebControls.HiddenField OAuthAuthorizationSecToken;
+
+ /// <summary>
+ /// consumerLabel control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.WebControls.Label consumerLabel;
+
+ /// <summary>
+ /// desiredAccessLabel control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.WebControls.Label desiredAccessLabel;
+
+ /// <summary>
+ /// allowAccessButton control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.WebControls.Button allowAccessButton;
+
+ /// <summary>
+ /// denyAccessButton control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.WebControls.Button denyAccessButton;
+
+ /// <summary>
+ /// AuthGranted control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.WebControls.View AuthGranted;
+
+ /// <summary>
+ /// verifierMultiView control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.WebControls.MultiView verifierMultiView;
+
+ /// <summary>
+ /// View3 control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.WebControls.View View3;
+
+ /// <summary>
+ /// verificationCodeLabel control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.WebControls.Label verificationCodeLabel;
+
+ /// <summary>
+ /// View4 control.
+ /// </summary>
+ /// <remarks>
+ /// Auto-generated field.
+ /// To modify move field declaration from designer file to code-behind file.
+ /// </remarks>
+ protected global::System.Web.UI.WebControls.View View4;
+ }
+}
diff --git a/samples/OAuthServiceProvider/OAuth.ashx b/samples/OAuthServiceProvider/OAuth.ashx
index 8a74926..efa8140 100644
--- a/samples/OAuthServiceProvider/OAuth.ashx
+++ b/samples/OAuthServiceProvider/OAuth.ashx
@@ -11,7 +11,7 @@ using DotNetOpenAuth.Messaging;
using OAuthServiceProvider.Code;
public class OAuth : IHttpHandler, IRequiresSessionState {
- ServiceProvider sp;
+ private ServiceProvider sp;
public OAuth() {
sp = new ServiceProvider(Constants.SelfDescription, Global.TokenManager, new CustomOAuthMessageFactory(Global.TokenManager));
diff --git a/samples/OAuthServiceProvider/OAuth2.ashx b/samples/OAuthServiceProvider/OAuth2.ashx
new file mode 100644
index 0000000..e36a105
--- /dev/null
+++ b/samples/OAuthServiceProvider/OAuth2.ashx
@@ -0,0 +1 @@
+<%@ WebHandler Language="C#" CodeBehind="OAuth2.ashx.cs" Class="OAuthServiceProvider.OAuth2" %>
diff --git a/samples/OAuthServiceProvider/OAuth2.ashx.cs b/samples/OAuthServiceProvider/OAuth2.ashx.cs
new file mode 100644
index 0000000..62aa680
--- /dev/null
+++ b/samples/OAuthServiceProvider/OAuth2.ashx.cs
@@ -0,0 +1,48 @@
+namespace OAuthServiceProvider {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Net;
+ using System.Web;
+ using System.Web.SessionState;
+ using Code;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2;
+
+ public class OAuth2 : IHttpHandler, IRequiresSessionState {
+ /// <summary>
+ /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"/> instance.
+ /// </summary>
+ /// <value>Always <c>true</c></value>
+ /// <returns>true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false.
+ /// </returns>
+ public bool IsReusable {
+ get { return true; }
+ }
+
+ /// <summary>
+ /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
+ /// </summary>
+ /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
+ public void ProcessRequest(HttpContext context) {
+ IDirectResponseProtocolMessage response;
+ switch (context.Request.PathInfo) {
+ case "/token":
+ if (Global.AuthorizationServer.TryPrepareAccessTokenResponse(out response)) {
+ Global.AuthorizationServer.Channel.Send(response);
+ }
+ break;
+ case "/auth":
+ var request = Global.AuthorizationServer.ReadAuthorizationRequest();
+ if (request == null) {
+ throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request.");
+ }
+
+ // Redirect the user to a page that requires the user to be logged in.
+ Global.PendingOAuth2Authorization = request;
+ context.Response.Redirect("~/Members/Authorize2.aspx");
+ break;
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/samples/OAuthServiceProvider/OAuthServiceProvider.csproj b/samples/OAuthServiceProvider/OAuthServiceProvider.csproj
index 37af906..94e7bb3 100644
--- a/samples/OAuthServiceProvider/OAuthServiceProvider.csproj
+++ b/samples/OAuthServiceProvider/OAuthServiceProvider.csproj
@@ -60,6 +60,7 @@
<Content Include="Global.asax" />
<Content Include="Login.aspx" />
<Content Include="Members\Authorize.aspx" />
+ <Content Include="Members\Authorize2.aspx" />
<Content Include="Members\AuthorizedConsumers.aspx" />
<Content Include="Members\Logoff.aspx" />
<Content Include="TracePage.aspx" />
@@ -67,9 +68,20 @@
</ItemGroup>
<ItemGroup>
<Compile Include="Code\DatabaseNonceStore.cs" />
+ <Compile Include="Code\OAuth2AuthorizationServer.cs" />
<Compile Include="Default.aspx.designer.cs">
<DependentUpon>Default.aspx</DependentUpon>
</Compile>
+ <Compile Include="Members\Authorize2.aspx.cs">
+ <DependentUpon>Authorize2.aspx</DependentUpon>
+ <SubType>ASPXCodeBehind</SubType>
+ </Compile>
+ <Compile Include="Members\Authorize2.aspx.designer.cs">
+ <DependentUpon>Authorize2.aspx</DependentUpon>
+ </Compile>
+ <Compile Include="OAuth2.ashx.cs">
+ <DependentUpon>OAuth2.ashx</DependentUpon>
+ </Compile>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="DataApi.cs">
<DependentUpon>DataApi.svc</DependentUpon>
@@ -134,6 +146,7 @@
<SubType>Designer</SubType>
</None>
<Content Include="Members\Web.config" />
+ <Content Include="OAuth2.ashx" />
</ItemGroup>
<ItemGroup>
<None Include="Code\DataClasses.dbml.layout">
diff --git a/samples/OAuthServiceProvider/Web.config b/samples/OAuthServiceProvider/Web.config
index dc440fd..76f2232 100644
--- a/samples/OAuthServiceProvider/Web.config
+++ b/samples/OAuthServiceProvider/Web.config
@@ -39,11 +39,14 @@
<dotNetOpenAuth>
<!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. -->
<reporting enabled="true" />
+
+ <!-- FOR TESTING ONLY, we relax the SSL requirements. -->
+ <messaging relaxSslRequirements="true" />
</dotNetOpenAuth>
<appSettings/>
<connectionStrings>
- <add name="DatabaseConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"
+ <add name="DatabaseConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database3.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
diff --git a/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj
index d7f97e5..f4d0bb3 100644
--- a/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj
+++ b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj
@@ -171,6 +171,7 @@
<Reference Include="System.ServiceModel">
<RequiredTargetFramework>3.0</RequiredTargetFramework>
</Reference>
+ <Reference Include="System.ServiceModel.Web" />
<Reference Include="System.Web" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq">
@@ -202,6 +203,7 @@
<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" />
@@ -227,6 +229,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" />
@@ -354,6 +359,7 @@
<EmbeddedResource Include="OpenId\Discovery\xrdsdiscovery\xrds20dual.xml" />
</ItemGroup>
<ItemGroup>
+ <Folder Include="OAuth2\ChannelElements\" />
<Folder Include="OpenId\UI\" />
</ItemGroup>
<ItemGroup>
diff --git a/src/DotNetOpenAuth.Test/Messaging/MessageSerializerTests.cs b/src/DotNetOpenAuth.Test/Messaging/MessageSerializerTests.cs
index 91cccf1..d07cf32 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,6 +55,34 @@ 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);
+ serializer.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);
+ serializer.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));
diff --git a/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs b/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs
index 10084b6..2c2da64 100644
--- a/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs
+++ b/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs
@@ -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/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/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/OAuth2/MessageFactoryTests.cs b/src/DotNetOpenAuth.Test/OAuth2/MessageFactoryTests.cs
new file mode 100644
index 0000000..2514f68
--- /dev/null
+++ b/src/DotNetOpenAuth.Test/OAuth2/MessageFactoryTests.cs
@@ -0,0 +1,139 @@
+//-----------------------------------------------------------------------
+// <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);
+ }
+
+ [TestCase]
+ public void AccessTokenAssertionRequest() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.client_id, "abc" },
+ { Protocol.assertion_type, "abc" },
+ { Protocol.assertion, "abc" },
+ { Protocol.grant_type, "assertion" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(AccessTokenAssertionRequest), request);
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth.Test/OAuth2/OAuth2ChannelTests.cs b/src/DotNetOpenAuth.Test/OAuth2/OAuth2ChannelTests.cs
new file mode 100644
index 0000000..51d0656
--- /dev/null
+++ b/src/DotNetOpenAuth.Test/OAuth2/OAuth2ChannelTests.cs
@@ -0,0 +1,21 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuthWrapChannelTests.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..fa1ed40
--- /dev/null
+++ b/src/DotNetOpenAuth.Test/OAuth2/OAuth2TestBase.cs
@@ -0,0 +1,15 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuthWrapTestBase.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.sln b/src/DotNetOpenAuth.sln
index 2cef1b2..8353bac 100644
--- a/src/DotNetOpenAuth.sln
+++ b/src/DotNetOpenAuth.sln
@@ -13,6 +13,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Specs", "Specs", "{CD57219F-24F4-4136-8741-6063D0D7A031}"
ProjectSection(SolutionItems) = preProject
+ ..\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
diff --git a/src/DotNetOpenAuth/Configuration/DotNetOpenAuth.xsd b/src/DotNetOpenAuth/Configuration/DotNetOpenAuth.xsd
index a3c5de4..6265706 100644
--- a/src/DotNetOpenAuth/Configuration/DotNetOpenAuth.xsd
+++ b/src/DotNetOpenAuth/Configuration/DotNetOpenAuth.xsd
@@ -218,6 +218,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:complexType>
</xs:element>
<xs:element name="openid">
diff --git a/src/DotNetOpenAuth/Configuration/MessagingElement.cs b/src/DotNetOpenAuth/Configuration/MessagingElement.cs
index f130dbc..fae18ec 100644
--- a/src/DotNetOpenAuth/Configuration/MessagingElement.cs
+++ b/src/DotNetOpenAuth/Configuration/MessagingElement.cs
@@ -32,6 +32,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";
@@ -88,6 +93,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>
diff --git a/src/DotNetOpenAuth/DotNetOpenAuth.csproj b/src/DotNetOpenAuth/DotNetOpenAuth.csproj
index c9900ea..f402c95 100644
--- a/src/DotNetOpenAuth/DotNetOpenAuth.csproj
+++ b/src/DotNetOpenAuth/DotNetOpenAuth.csproj
@@ -216,6 +216,7 @@ http://opensource.org/licenses/ms-pl.html
<RequiredTargetFramework>3.0</RequiredTargetFramework>
</Reference>
<Reference Include="System" />
+ <Reference Include="System.Security" />
<Reference Include="System.configuration" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
@@ -315,11 +316,13 @@ http://opensource.org/licenses/ms-pl.html
<Compile Include="InfoCard\WellKnownIssuers.cs" />
<Compile Include="Messaging\CachedDirectWebResponse.cs" />
<Compile Include="Messaging\ChannelContract.cs" />
+ <Compile Include="Messaging\IHttpIndirectResponse.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" />
@@ -340,6 +343,58 @@ http://opensource.org/licenses/ms-pl.html
<Compile Include="Messaging\Reflection\IMessagePartOriginalEncoder.cs" />
<Compile Include="Messaging\Reflection\MessageDescriptionCollection.cs" />
<Compile Include="Mvc\OpenIdAjaxOptions.cs" />
+ <Compile Include="Messaging\StandardMessageFactory.cs" />
+ <Compile Include="OAuth2\AuthorizationServerBase.cs" />
+ <Compile Include="OAuth2\AuthorizationState.cs" />
+ <Compile Include="OAuth2\ChannelElements\AccessRequestBindingElement.cs" />
+ <Compile Include="OAuth2\ChannelElements\AccessToken.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\IDataBagFormatter.cs" />
+ <Compile Include="OAuth2\ChannelElements\OAuth2ChannelBase.cs" />
+ <Compile Include="OAuth2\ChannelElements\OAuth2ClientChannel.cs" />
+ <Compile Include="OAuth2\ChannelElements\ScopeEncoder.cs" />
+ <Compile Include="OAuth2\ChannelElements\UriStyleMessageFormatter.cs" />
+ <Compile Include="OAuth2\ChannelElements\IAuthorizationDescription.cs" />
+ <Compile Include="OAuth2\ChannelElements\ITokenCarryingRequest.cs" />
+ <Compile Include="OAuth2\ChannelElements\OAuth2ResourceServerChannel.cs" />
+ <Compile Include="Messaging\StandardMessageFactoryChannel.cs" />
+ <Compile Include="OAuth2\ChannelElements\RefreshToken.cs" />
+ <Compile Include="OAuth2\ChannelElements\DataBag.cs" />
+ <Compile Include="OAuth2\ChannelElements\TimestampEncoder.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\AccessTokenAssertionRequest.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\IMessageWithClientState.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\ResourceServer.cs" />
+ <Compile Include="OAuth2\StandardAccessTokenAnalyzer.cs" />
+ <Compile Include="OAuth2\UserAgentClient.cs" />
+ <Compile Include="OAuth2\AuthorizationServer.cs" />
+ <Compile Include="OAuth2\OAuthUtilities.cs" />
<Compile Include="OAuth\ChannelElements\ICombinedOpenIdProviderTokenManager.cs" />
<Compile Include="OAuth\ChannelElements\IConsumerDescription.cs" />
<Compile Include="OAuth\ChannelElements\IConsumerTokenManager.cs" />
@@ -483,7 +538,7 @@ http://opensource.org/licenses/ms-pl.html
<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="Messaging\TimespanSecondsEncoder.cs" />
<Compile Include="OpenId\Extensions\SimpleRegistration\ClaimsRequest.cs" />
<Compile Include="OpenId\Extensions\SimpleRegistration\ClaimsResponse.cs" />
<Compile Include="OpenId\Extensions\SimpleRegistration\Constants.cs" />
@@ -610,6 +665,18 @@ http://opensource.org/licenses/ms-pl.html
<Compile Include="Messaging\StandardWebRequestHandler.cs" />
<Compile Include="Messaging\MessageReceivingEndpoint.cs" />
<Compile Include="Reporting.cs" />
+ <Compile Include="OAuth2\ChannelElements\OAuth2AuthorizationServerChannel.cs" />
+ <Compile Include="OAuth2\ClientBase.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" />
+ <Compile Include="OAuth2\WebServerClient.cs" />
<Compile Include="Util.cs" />
<Compile Include="OAuth\Protocol.cs" />
<Compile Include="OAuth\ServiceProvider.cs" />
@@ -636,28 +703,28 @@ http://opensource.org/licenses/ms-pl.html
<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"/>
+ <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" />
@@ -745,6 +812,10 @@ http://opensource.org/licenses/ms-pl.html
<EmbeddedResource Include="OpenId\RelyingParty\OpenIdRelyingPartyAjaxControlBase.js">
<Copyright>$(StandardCopyright)</Copyright>
</EmbeddedResource>
+ <EmbeddedResource Include="OAuth2\OAuthStrings.resx">
+ <Generator>ResXFileCodeGenerator</Generator>
+ <LastGenOutput>OAuthStrings.Designer.cs</LastGenOutput>
+ </EmbeddedResource>
<EmbeddedResource Include="Strings.sr.resx" />
<EmbeddedResource Include="Xrds\XrdsStrings.sr.resx" />
</ItemGroup>
diff --git a/src/DotNetOpenAuth/Messaging/Bindings/ExpiredMessageException.cs b/src/DotNetOpenAuth/Messaging/Bindings/ExpiredMessageException.cs
index 73ce289..31b053e 100644
--- a/src/DotNetOpenAuth/Messaging/Bindings/ExpiredMessageException.cs
+++ b/src/DotNetOpenAuth/Messaging/Bindings/ExpiredMessageException.cs
@@ -22,6 +22,7 @@ namespace DotNetOpenAuth.Messaging.Bindings {
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);
+ Contract.Requires<ArgumentNullException>(faultedMessage != null, "faultedMessage");
}
/// <summary>
diff --git a/src/DotNetOpenAuth/Messaging/Channel.cs b/src/DotNetOpenAuth/Messaging/Channel.cs
index 3d56f02..f168f6f 100644
--- a/src/DotNetOpenAuth/Messaging/Channel.cs
+++ b/src/DotNetOpenAuth/Messaging/Channel.cs
@@ -17,9 +17,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>
@@ -40,6 +42,16 @@ 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 content-type for plain text.
+ /// </summary>
+ 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.
@@ -124,6 +136,13 @@ namespace DotNetOpenAuth.Messaging {
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();
@@ -151,7 +170,7 @@ namespace DotNetOpenAuth.Messaging {
/// <summary>
/// Gets or sets the message descriptions.
/// </summary>
- internal MessageDescriptionCollection MessageDescriptions {
+ internal virtual MessageDescriptionCollection MessageDescriptions {
get {
return this.messageDescriptions;
}
@@ -209,11 +228,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>
@@ -232,6 +252,12 @@ namespace DotNetOpenAuth.Messaging {
}
/// <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.
@@ -660,7 +686,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;
}
@@ -702,6 +728,7 @@ namespace DotNetOpenAuth.Messaging {
protected virtual OutgoingWebResponse PrepareIndirectResponse(IDirectedProtocolMessage message) {
Contract.Requires<ArgumentNullException>(message != null);
Contract.Requires<ArgumentException>(message.Recipient != null, MessagingStrings.DirectedMessageMissingRecipient);
+ Contract.Requires<ArgumentException>((message.HttpMethods & (HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.PostRequest)) != 0, "Neither GET nor POST are allowed for this message.");
Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null);
Contract.Assert(message != null && message.Recipient != null);
@@ -709,10 +736,31 @@ 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 > IndirectMessageGetToPostThreshold) {
+ 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 > IndirectMessageGetToPostThreshold;
+ }
+
+ // 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);
}
@@ -725,9 +773,10 @@ 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) {
+ protected virtual OutgoingWebResponse Create301RedirectResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields, bool payloadInFragment = false) {
Contract.Requires<ArgumentNullException>(message != null);
Contract.Requires<ArgumentException>(message.Recipient != null, MessagingStrings.DirectedMessageMissingRecipient);
Contract.Requires<ArgumentNullException>(fields != null);
@@ -735,7 +784,12 @@ namespace DotNetOpenAuth.Messaging {
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);
Logger.Http.DebugFormat("Redirecting to {0}", builder.Uri.AbsoluteUri);
OutgoingWebResponse response = new OutgoingWebResponse {
@@ -801,7 +855,7 @@ 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) {
@@ -823,6 +877,39 @@ 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>
+ protected virtual string SerializeAsJson(IMessage message) {
+ Contract.Requires<ArgumentNullException>(message != null, "message");
+
+ MessageDictionary messageDictionary = this.MessageDescriptions.GetAccessor(message);
+ var memoryStream = new MemoryStream();
+ var jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(memoryStream, Encoding.UTF8);
+ var serializer = MessageSerializer.Get(message.GetType());
+ serializer.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) {
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(json));
+
+ var dictionary = new Dictionary<string, string>();
+ 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>
@@ -938,7 +1025,7 @@ namespace DotNetOpenAuth.Messaging {
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";
diff --git a/src/DotNetOpenAuth/Messaging/IDirectWebRequestHandler.cs.orig b/src/DotNetOpenAuth/Messaging/IDirectWebRequestHandler.cs.orig
new file mode 100644
index 0000000..a17b379
--- /dev/null
+++ b/src/DotNetOpenAuth/Messaging/IDirectWebRequestHandler.cs.orig
@@ -0,0 +1,222 @@
+//-----------------------------------------------------------------------
+// <copyright file="IDirectWebRequestHandler.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging {
+ using System.Collections.Generic;
+ 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>
+ 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>
+ 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);
+ }
+<<<<<<< HEAD
+=======
+
+ /// <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) {
+ Contract.Requires<ArgumentNullException>(request != null);
+ 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) {
+ Contract.Requires<ArgumentNullException>(request != null);
+ Contract.Requires<NotSupportedException>(((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) {
+ Contract.Requires<ArgumentNullException>(request != null);
+ 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) {
+ Contract.Requires<ArgumentNullException>(request != null);
+ Contract.Requires<NotSupportedException>(((IDirectWebRequestHandler)this).CanSupport(options), MessagingStrings.DirectWebRequestOptionsNotSupported);
+ Contract.Ensures(Contract.Result<IncomingWebResponse>() != null);
+ Contract.Ensures(Contract.Result<IncomingWebResponse>().ResponseStream != null);
+
+ ////ErrorUtilities.VerifySupported(((IDirectWebRequestHandler)this).CanSupport(options), string.Format(MessagingStrings.DirectWebRequestOptionsNotSupported, options, this.GetType().Name));
+ throw new System.NotImplementedException();
+ }
+
+ #endregion
+ }
+>>>>>>> 884bcec... Fixed typo in comments.
+}
diff --git a/src/DotNetOpenAuth/Messaging/IHttpDirectResponse.cs b/src/DotNetOpenAuth/Messaging/IHttpDirectResponse.cs
index c0e7803..20c3d6f 100644
--- a/src/DotNetOpenAuth/Messaging/IHttpDirectResponse.cs
+++ b/src/DotNetOpenAuth/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/Messaging/IHttpDirectResponseContract.cs b/src/DotNetOpenAuth/Messaging/IHttpDirectResponseContract.cs
new file mode 100644
index 0000000..b1ddba2
--- /dev/null
+++ b/src/DotNetOpenAuth/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/Messaging/IHttpIndirectResponse.cs b/src/DotNetOpenAuth/Messaging/IHttpIndirectResponse.cs
new file mode 100644
index 0000000..7d0fe0c
--- /dev/null
+++ b/src/DotNetOpenAuth/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/MessageSerializer.cs b/src/DotNetOpenAuth/Messaging/MessageSerializer.cs
index ccda5d5..d6448ae 100644
--- a/src/DotNetOpenAuth/Messaging/MessageSerializer.cs
+++ b/src/DotNetOpenAuth/Messaging/MessageSerializer.cs
@@ -12,6 +12,7 @@ namespace DotNetOpenAuth.Messaging {
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Reflection;
+ using System.Xml;
using DotNetOpenAuth.Messaging.Reflection;
using DotNetOpenAuth.OAuth.ChannelElements;
@@ -53,6 +54,29 @@ namespace DotNetOpenAuth.Messaging {
}
/// <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) {
+ Contract.Requires<ArgumentNullException>(messageDictionary != null, "messageDictionary");
+ Contract.Requires<ArgumentNullException>(reader != null, "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 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>
@@ -66,7 +90,7 @@ namespace DotNetOpenAuth.Messaging {
// 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;
@@ -85,6 +109,52 @@ namespace DotNetOpenAuth.Messaging {
}
/// <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 void Serialize(MessageDictionary messageDictionary, XmlDictionaryWriter writer) {
+ Contract.Requires<ArgumentNullException>(messageDictionary != null);
+ Contract.Requires<ArgumentNullException>(writer != null, "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 name=value pairs into a message.
/// </summary>
/// <param name="fields">The name=value pairs that were read in from the transport.</param>
@@ -109,6 +179,45 @@ namespace DotNetOpenAuth.Messaging {
messageDictionary.Message.EnsureValidMessage();
}
+ /// <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 void Deserialize(MessageDictionary messageDictionary, XmlDictionaryReader reader) {
+ Contract.Requires<ArgumentNullException>(messageDictionary != null);
+ Contract.Requires<ArgumentNullException>(reader != null, "reader");
+
+ DeserializeJsonAsFlatDictionary(messageDictionary, reader);
+
+ // Make sure all the required parts are present and valid.
+ messageDictionary.Description.EnsureMessagePartsPassBasicValidation(messageDictionary);
+ messageDictionary.Message.EnsureValidMessage();
+ }
+
+ /// <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/MessagingStrings.Designer.cs b/src/DotNetOpenAuth/Messaging/MessagingStrings.Designer.cs
index ca69f5f..f600330 100644
--- a/src/DotNetOpenAuth/Messaging/MessagingStrings.Designer.cs
+++ b/src/DotNetOpenAuth/Messaging/MessagingStrings.Designer.cs
@@ -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 {
@@ -358,6 +367,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 {
@@ -430,6 +448,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 {
diff --git a/src/DotNetOpenAuth/Messaging/MessagingStrings.resx b/src/DotNetOpenAuth/Messaging/MessagingStrings.resx
index 102f044..7f9d91b 100644
--- a/src/DotNetOpenAuth/Messaging/MessagingStrings.resx
+++ b/src/DotNetOpenAuth/Messaging/MessagingStrings.resx
@@ -303,6 +303,15 @@
<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>
diff --git a/src/DotNetOpenAuth/Messaging/MessagingUtilities.cs b/src/DotNetOpenAuth/Messaging/MessagingUtilities.cs
index 7c25f73..9dbd1b9 100644
--- a/src/DotNetOpenAuth/Messaging/MessagingUtilities.cs
+++ b/src/DotNetOpenAuth/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;
@@ -59,6 +60,21 @@ namespace DotNetOpenAuth.Messaging {
internal const string AlphaNumericNoLookAlikes = "23456789abcdefghjkmnpqrstwxyzABCDEFGHJKMNPQRSTWXYZ";
/// <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[] { "!", "*", "'", "(", ")" };
@@ -193,6 +209,85 @@ 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) {
+ Contract.Requires<ArgumentNullException>(collection != null, "collection");
+ Contract.Requires<ArgumentNullException>(values != null, "values");
+
+ foreach (var value in values) {
+ collection.Add(value);
+ }
+ }
+
+ /// <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) {
+ Contract.Requires<ArgumentNullException>(collection != null, "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) {
+ Contract.Requires<ArgumentNullException>(uri != null, "uri");
+ Contract.Requires<ArgumentNullException>(messageDescription != null, "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>
@@ -246,6 +341,61 @@ 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) {
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(scheme));
+ Contract.Requires<ArgumentNullException>(fields != null, "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) {
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(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 = authorizationHeader.Split(';'); // TODO: is this the right delimiter?
+ foreach (string authorization in authorizationSections) {
+ string trimmedAuth = authorization.Trim();
+ if (trimmedAuth.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) {
+ 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>
/// Gets a buffer of random data (not cryptographically strong).
/// </summary>
/// <param name="length">The length of the sequence to generate.</param>
@@ -298,6 +448,240 @@ 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) {
+ Contract.Requires<ArgumentNullException>(algorithm != null, "algorithm");
+ Contract.Requires<ArgumentNullException>(value != null, "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) {
+ Contract.Requires<ArgumentNullException>(algorithm != null, "algorithm");
+ Contract.Requires<ArgumentNullException>(data != null, "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) {
+ Contract.Requires<ArgumentNullException>(algorithm != null, "algorithm");
+ Contract.Requires<ArgumentNullException>(sortedData != null, "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, and 256.</param>
+ /// <returns>The encrypted buffer</returns>
+ internal static byte[] Encrypt(byte[] buffer, byte[] key) {
+ SymmetricAlgorithm crypto = CreateSymmetricAlgorithm(key);
+
+ var ms = new MemoryStream();
+ var binaryWriter = new BinaryWriter(ms);
+ binaryWriter.Write(crypto.IV.Length);
+ 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>
+ internal static byte[] Decrypt(byte[] buffer, byte[] key) {
+ SymmetricAlgorithm crypto = CreateSymmetricAlgorithm(key);
+
+ var ms = new MemoryStream(buffer);
+ var binaryReader = new BinaryReader(ms);
+ int ivLength = binaryReader.ReadInt32();
+ crypto.IV = binaryReader.ReadBytes(ivLength);
+
+ // 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) {
+ Contract.Requires<ArgumentNullException>(crypto != null, "crypto");
+ Contract.Requires<ArgumentNullException>(buffer != null, "buffer");
+
+ var symmetricCrypto = new RijndaelManaged {
+ Mode = CipherMode.CBC,
+ };
+
+ 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>
+ internal static byte[] DecryptWithRandomSymmetricKey(this RSACryptoServiceProvider crypto, byte[] buffer) {
+ Contract.Requires<ArgumentNullException>(crypto != null, "crypto");
+ Contract.Requires<ArgumentNullException>(buffer != null, "buffer");
+
+ var encryptedStream = new MemoryStream(buffer);
+ var encryptedStreamReader = new BinaryReader(encryptedStream);
+
+ byte[] encryptedPrequel = encryptedStreamReader.ReadBytes(encryptedStreamReader.ReadInt32());
+ byte[] prequel = crypto.Decrypt(encryptedPrequel, false);
+
+ var symmetricCrypto = new RijndaelManaged {
+ 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>
+ /// Compresses a given buffer.
+ /// </summary>
+ /// <param name="buffer">The buffer to compress.</param>
+ /// <returns>The compressed data.</returns>
+ internal static byte[] Compress(byte[] buffer) {
+ var ms = new MemoryStream();
+ using (var compressingStream = new GZipStream(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) {
+ var compressedDataStream = new MemoryStream(buffer);
+ var decompressedDataStream = new MemoryStream();
+ using (var decompressingStream = new GZipStream(compressedDataStream, CompressionMode.Decompress, true)) {
+ decompressingStream.CopyTo(decompressedDataStream);
+ }
+
+ return decompressedDataStream.ToArray();
+ }
+
+ /// <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>
@@ -548,6 +932,32 @@ 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>
+ /// <typeparam name="T">The type of elements in the arrays.</typeparam>
+ /// <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) {
+ Contract.Requires<ArgumentNullException>(first != null);
+ Contract.Requires<ArgumentNullException>(second != null);
+ 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>
@@ -688,6 +1098,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) {
+ Contract.Requires<ArgumentNullException>(builder != null);
+
+ 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>
@@ -780,6 +1219,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) {
+ Contract.Requires<ArgumentNullException>(sequence != null, "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>
@@ -985,6 +1436,18 @@ 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) {
+ return new RijndaelManaged {
+ Mode = CipherMode.CBC,
+ Key = key,
+ };
+ }
+
+ /// <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>
diff --git a/src/DotNetOpenAuth/Messaging/Reflection/MessageDescription.cs b/src/DotNetOpenAuth/Messaging/Reflection/MessageDescription.cs
index 3b41b35..7dbab80 100644
--- a/src/DotNetOpenAuth/Messaging/Reflection/MessageDescription.cs
+++ b/src/DotNetOpenAuth/Messaging/Reflection/MessageDescription.cs
@@ -19,16 +19,6 @@ namespace DotNetOpenAuth.Messaging.Reflection {
/// </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>
@@ -44,8 +34,8 @@ namespace DotNetOpenAuth.Messaging.Reflection {
Contract.Requires<ArgumentException>(typeof(IMessage).IsAssignableFrom(messageType));
Contract.Requires<ArgumentNullException>(messageVersion != null);
- this.messageType = messageType;
- this.messageVersion = messageVersion;
+ this.MessageType = messageType;
+ this.MessageVersion = messageVersion;
this.ReflectMessageType();
}
@@ -58,6 +48,32 @@ namespace DotNetOpenAuth.Messaging.Reflection {
}
/// <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>
@@ -83,51 +99,18 @@ namespace DotNetOpenAuth.Messaging.Reflection {
}
/// <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);
+ 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} with these message parts:{1}{2}",
- this.messageType.Name,
+ this.MessageType.Name,
Environment.NewLine,
parts.ToStringDeferred());
throw;
@@ -135,42 +118,168 @@ namespace DotNetOpenAuth.Messaging.Reflection {
}
/// <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) {
+ Contract.Requires<ArgumentNullException>(parts != null);
+
+ 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>
- /// <exception cref="ProtocolException">Thrown when required parts of a message are not in <paramref name="keys"/></exception>
- private void EnsureRequiredMessagePartsArePresent(IEnumerable<string> keys) {
+ /// <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) {
+ Contract.Requires<ArgumentNullException>(keys != null);
+
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,
+ if (throwOnFailure) {
+ ErrorUtilities.ThrowProtocol(
+ MessagingStrings.RequiredParametersMissing,
+ this.MessageType.FullName,
+ string.Join(", ", missingKeys));
+ } else {
+ Logger.Messaging.DebugFormat(
MessagingStrings.RequiredParametersMissing,
- this.messageType.FullName,
- string.Join(", ", missingKeys)));
+ 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>
- private void EnsureRequiredProtocolMessagePartsAreNotEmpty(IDictionary<string, string> partValues) {
+ /// <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) {
+ Contract.Requires<ArgumentNullException>(partValues != null);
+
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,
+ if (throwOnFailure) {
+ ErrorUtilities.ThrowProtocol(
MessagingStrings.RequiredNonEmptyParameterWasEmpty,
- this.messageType.FullName,
- string.Join(", ", emptyValuedKeys)));
+ 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)
+ {
+ Contract.Requires<ArgumentNullException>(partValues != null);
+
+ 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/Messaging/Reflection/MessageDescriptionCollection.cs
index 125742c..754b9d0 100644
--- a/src/DotNetOpenAuth/Messaging/Reflection/MessageDescriptionCollection.cs
+++ b/src/DotNetOpenAuth/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.
diff --git a/src/DotNetOpenAuth/Messaging/Reflection/MessagePart.cs b/src/DotNetOpenAuth/Messaging/Reflection/MessagePart.cs
index b876ec4..df6dc73 100644
--- a/src/DotNetOpenAuth/Messaging/Reflection/MessagePart.cs
+++ b/src/DotNetOpenAuth/Messaging/Reflection/MessagePart.cs
@@ -93,6 +93,7 @@ namespace DotNetOpenAuth.Messaging.Reflection {
};
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);
@@ -163,6 +164,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,6 +200,28 @@ 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 {
+ Contract.Requires<InvalidOperationException>(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>
/// Sets the member of a given message to some given value.
/// Used in deserialization.
/// </summary>
@@ -337,7 +361,11 @@ namespace DotNetOpenAuth.Messaging.Reflection {
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;
diff --git a/src/DotNetOpenAuth/Messaging/StandardMessageFactory.cs b/src/DotNetOpenAuth/Messaging/StandardMessageFactory.cs
new file mode 100644
index 0000000..d5aeba4
--- /dev/null
+++ b/src/DotNetOpenAuth/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) {
+ Contract.Requires<ArgumentNullException>(messageTypes != null);
+ Contract.Requires<ArgumentException>(messageTypes.All(msg => msg != null));
+
+ 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) {
+ Contract.Requires<ArgumentNullException>(recipient != null);
+ Contract.Requires<ArgumentNullException>(fields != null);
+
+ var matches = this.requestMessageTypes.Keys
+ .Where(message => message.CheckMessagePartsPassBasicValidation(fields))
+ .OrderByDescending(message => this.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) {
+ Contract.Requires<ArgumentNullException>(request != null);
+ Contract.Requires<ArgumentNullException>(fields != null);
+
+ 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()),
+ this.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) {
+ Contract.Requires<ArgumentNullException>(messageDescription != null);
+ Contract.Requires<ArgumentNullException>(recipient != null);
+ 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) {
+ Contract.Requires<ArgumentNullException>(messageDescription != null);
+ Contract.Requires<ArgumentNullException>(request != null);
+ 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) {
+ Contract.Requires<ArgumentNullException>(assignableType != null, "assignableType");
+ Contract.Requires<ArgumentNullException>(derivedType != null, "derivedType");
+ Contract.Requires<ArgumentException>(assignableType.IsAssignableFrom(derivedType));
+
+ // 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>
+ /// 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) {
+ Contract.Requires<ArgumentNullException>(messageDescription != null);
+ Contract.Requires<ArgumentNullException>(requestType != null);
+
+ return this.responseMessageTypes[messageDescription].Where(pair => pair.Key.IsAssignableFrom(requestType)).Select(pair => pair.Value);
+ }
+
+ /// <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 int CountInCommon(ICollection<string> collection1, ICollection<string> collection2, StringComparison comparison = StringComparison.Ordinal) {
+ Contract.Requires<ArgumentNullException>(collection1 != null, "collection1");
+ Contract.Requires<ArgumentNullException>(collection2 != null, "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)));
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/StandardMessageFactoryChannel.cs b/src/DotNetOpenAuth/Messaging/StandardMessageFactoryChannel.cs
new file mode 100644
index 0000000..147b420
--- /dev/null
+++ b/src/DotNetOpenAuth/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) {
+ Contract.Requires<ArgumentNullException>(messageTypes != null, "messageTypes");
+ Contract.Requires<ArgumentNullException>(versions != null, "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 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 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)
+ {
+ Contract.Requires<ArgumentNullException>(messageTypes != null, "messageTypes");
+ Contract.Requires<ArgumentNullException>(descriptionsCache != null);
+ 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/Messaging/StandardWebRequestHandler.cs
index 48cc6e6..a5725cd 100644
--- a/src/DotNetOpenAuth/Messaging/StandardWebRequestHandler.cs
+++ b/src/DotNetOpenAuth/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;
@@ -229,6 +230,14 @@ namespace DotNetOpenAuth.Messaging {
// 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/Messaging/TimespanSecondsEncoder.cs
index cc3f7cc..b28e5a8 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/TimespanSecondsEncoder.cs
+++ b/src/DotNetOpenAuth/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/OAuth/ChannelElements/OAuthChannel.cs b/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthChannel.cs
index f2d69f5..d1d4f18 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthChannel.cs
+++ b/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthChannel.cs
@@ -116,36 +116,14 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// <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) {
@@ -346,20 +324,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
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthPrincipal.cs b/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthPrincipal.cs
index 025ef09..83954bf 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthPrincipal.cs
+++ b/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthPrincipal.cs
@@ -28,6 +28,15 @@ 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) {
@@ -47,15 +56,6 @@ 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>
diff --git a/src/DotNetOpenAuth/OAuth/Protocol.cs b/src/DotNetOpenAuth/OAuth/Protocol.cs
index a524ba7..71a25f8 100644
--- a/src/DotNetOpenAuth/OAuth/Protocol.cs
+++ b/src/DotNetOpenAuth/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; }
diff --git a/src/DotNetOpenAuth/OAuth2/AuthorizationServer.cs b/src/DotNetOpenAuth/OAuth2/AuthorizationServer.cs
new file mode 100644
index 0000000..37be337
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/AuthorizationServer.cs
@@ -0,0 +1,154 @@
+//-----------------------------------------------------------------------
+// <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 : AuthorizationServerBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthorizationServer"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ public AuthorizationServer(IAuthorizationServer authorizationServer)
+ : base(authorizationServer) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null, "authorizationServer");
+ }
+
+ /// <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;
+ this.Channel.TryReadFromRequest(request, out message);
+ return message;
+ }
+
+ public void ApproveAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, string username, IEnumerable<string> scopes = null, Uri callback = null) {
+ Contract.Requires<ArgumentNullException>(authorizationRequest != null, "authorizationRequest");
+
+ var response = this.PrepareApproveAuthorizationRequest(authorizationRequest, username, callback);
+
+ // Customize the approved scope if the authorization server has decided to do so.
+ if (scopes != null) {
+ response.Scope.ResetContents(scopes);
+ }
+
+ this.Channel.Send(response);
+ }
+
+ public void RejectAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, Uri callback = null) {
+ Contract.Requires<ArgumentNullException>(authorizationRequest != null, "authorizationRequest");
+
+ var response = this.PrepareRejectAuthorizationRequest(authorizationRequest, callback);
+ this.Channel.Send(response);
+ }
+
+ public bool TryPrepareAccessTokenResponse(out IDirectResponseProtocolMessage response) {
+ return this.TryPrepareAccessTokenResponse(this.Channel.GetRequestFromContext(), out response);
+ }
+
+ public bool TryPrepareAccessTokenResponse(HttpRequestInfo httpRequestInfo, out IDirectResponseProtocolMessage response) {
+ Contract.Requires<ArgumentNullException>(httpRequestInfo != null, "httpRequestInfo");
+
+ var request = this.ReadAccessTokenRequest(httpRequestInfo);
+ if (request != null) {
+ // This convenience method only encrypts access tokens assuming that this auth server
+ // doubles as the resource server.
+ RSAParameters resourceServerPublicKey = this.AuthorizationServer.AccessTokenSigningPrivateKey;
+ response = this.PrepareAccessTokenResponse(request, resourceServerPublicKey);
+ return true;
+ }
+
+ response = null;
+ return false;
+ }
+
+ public AccessTokenRequestBase ReadAccessTokenRequest(HttpRequestInfo requestInfo = null) {
+ if (requestInfo == null) {
+ requestInfo = this.Channel.GetRequestFromContext();
+ }
+
+ AccessTokenRequestBase request;
+ this.Channel.TryReadFromRequest(requestInfo, out request);
+ return request;
+ }
+
+ public EndUserAuthorizationFailedResponse PrepareRejectAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, Uri callback = null) {
+ Contract.Requires<ArgumentNullException>(authorizationRequest != null, "authorizationRequest");
+ Contract.Ensures(Contract.Result<EndUserAuthorizationFailedResponse>() != null);
+
+ if (callback == null) {
+ callback = this.GetCallback(authorizationRequest);
+ }
+
+ var response = new EndUserAuthorizationFailedResponse(callback, authorizationRequest);
+ return response;
+ }
+
+ public EndUserAuthorizationSuccessResponseBase PrepareApproveAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, string username, Uri callback = null) {
+ Contract.Requires<ArgumentNullException>(authorizationRequest != null, "authorizationRequest");
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(username));
+ Contract.Ensures(Contract.Result<EndUserAuthorizationSuccessResponseBase>() != null);
+
+ if (callback == null) {
+ callback = this.GetCallback(authorizationRequest);
+ }
+
+ var client = this.AuthorizationServer.GetClientOrThrow(authorizationRequest.ClientIdentifier);
+ EndUserAuthorizationSuccessResponseBase response;
+ switch (authorizationRequest.ResponseType) {
+ case EndUserAuthorizationResponseType.AccessToken:
+ response = new EndUserAuthorizationSuccessAccessTokenResponse(callback, authorizationRequest);
+ break;
+ case EndUserAuthorizationResponseType.Both:
+ case EndUserAuthorizationResponseType.AuthorizationCode:
+ response = new EndUserAuthorizationSuccessAuthCodeResponse(callback, authorizationRequest);
+ break;
+ default:
+ throw ErrorUtilities.ThrowInternal("Unexpected response type.");
+ }
+
+ response.AuthorizingUsername = username;
+ return response;
+ }
+
+ protected Uri GetCallback(EndUserAuthorizationRequest authorizationRequest) {
+ Contract.Requires<ArgumentNullException>(authorizationRequest != null, "authorizationRequest");
+ Contract.Ensures(Contract.Result<Uri>() != null);
+
+ // Prefer a request-specific callback to the pre-registered one (if any).
+ if (authorizationRequest.Callback != null) {
+ return authorizationRequest.Callback;
+ }
+
+ var client = this.AuthorizationServer.GetClient(authorizationRequest.ClientIdentifier);
+ if (client.Callback != null) {
+ return client.Callback;
+ }
+
+ throw ErrorUtilities.ThrowProtocol(OAuthStrings.NoCallback);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/AuthorizationServerBase.cs b/src/DotNetOpenAuth/OAuth2/AuthorizationServerBase.cs
new file mode 100644
index 0000000..9078326
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/AuthorizationServerBase.cs
@@ -0,0 +1,83 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthorizationServerBase.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 ChannelElements;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.Messages;
+ using OAuth.ChannelElements;
+
+ /// <summary>
+ /// A base class for authorization server facade classes.
+ /// </summary>
+ public abstract class AuthorizationServerBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthorizationServerBase"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ protected AuthorizationServerBase(IAuthorizationServer authorizationServer) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null, "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 AuthorizationServer {
+ get { return this.OAuthChannel.AuthorizationServer; }
+ }
+
+ /// <summary>
+ /// Gets the channel.
+ /// </summary>
+ internal OAuth2AuthorizationServerChannel OAuthChannel { get; private set; }
+
+ /// <summary>
+ /// Prepares the response to an access token request.
+ /// </summary>
+ /// <param name="request">The request for an access token.</param>
+ /// <param name="accessTokenEncryptingPublicKey">The public key to encrypt the access token to, such that the resource server will be able to decrypt it.</param>
+ /// <param name="accessTokenLifetime">The access token's lifetime.</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, RSAParameters accessTokenEncryptingPublicKey, TimeSpan? accessTokenLifetime = null, bool includeRefreshToken = true) {
+ Contract.Requires<ArgumentNullException>(request != null, "request");
+
+ var tokenRequest = (ITokenCarryingRequest)request;
+ var accessTokenFormatter = AccessToken.CreateFormatter(this.AuthorizationServer.AccessTokenSigningPrivateKey, accessTokenEncryptingPublicKey);
+ var accessToken = new AccessToken(tokenRequest.AuthorizationDescription, accessTokenLifetime);
+
+ var response = new AccessTokenSuccessResponse(request) {
+ AccessToken = accessTokenFormatter.Serialize(accessToken),
+ Lifetime = accessToken.Lifetime,
+ };
+ response.Scope.ResetContents(tokenRequest.AuthorizationDescription.Scope);
+
+ if (includeRefreshToken) {
+ var refreshTokenFormatter = RefreshToken.CreateFormatter(this.AuthorizationServer.Secret);
+ var refreshToken = new RefreshToken(tokenRequest.AuthorizationDescription);
+ response.RefreshToken = refreshTokenFormatter.Serialize(refreshToken);
+ }
+
+ return response;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/AuthorizationServerDescription.cs b/src/DotNetOpenAuth/OAuth2/AuthorizationServerDescription.cs
new file mode 100644
index 0000000..756c980
--- /dev/null
+++ b/src/DotNetOpenAuth/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.
+ /// </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 HTTP or 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/AuthorizationState.cs b/src/DotNetOpenAuth/OAuth2/AuthorizationState.cs
new file mode 100644
index 0000000..7682900
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/AuthorizationState.cs
@@ -0,0 +1,92 @@
+//-----------------------------------------------------------------------
+// <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 memory-only copy of an authorization state.
+ /// </summary>
+ [Serializable]
+ public class AuthorizationState : IAuthorizationState {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthorizationState"/> class.
+ /// </summary>
+ 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 or sets 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/ChannelElements/AccessRequestBindingElement.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/AccessRequestBindingElement.cs
new file mode 100644
index 0000000..2404963
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/AccessRequestBindingElement.cs
@@ -0,0 +1,144 @@
+//-----------------------------------------------------------------------
+// <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.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 ITokenCarryingRequest;
+ 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;
+ 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.None || 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 ITokenCarryingRequest;
+ 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.Secret);
+ 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);
+ ErrorUtilities.VerifyProtocol(string.Equals(client.Secret, accessRequest.ClientSecret, StringComparison.Ordinal), Protocol.incorrect_client_credentials);
+
+ // Make sure the scope the client is requesting does not exceed the scope in the grant.
+ ErrorUtilities.VerifyProtocol(accessRequest.Scope.IsSubsetOf(tokenRequest.AuthorizationDescription.Scope), OAuthStrings.AccessScopeExceedsGrantScope, accessRequest.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/ChannelElements/AccessToken.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/AccessToken.cs
new file mode 100644
index 0000000..de24428
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/AccessToken.cs
@@ -0,0 +1,80 @@
+//-----------------------------------------------------------------------
+// <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.Linq;
+ using System.Security.Cryptography;
+ using System.Text;
+ 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) {
+ Contract.Requires<ArgumentNullException>(authorization != null, "authorization");
+
+ this.ClientIdentifier = authorization.ClientIdentifier;
+ this.UtcCreationDate = authorization.UtcIssued;
+ this.User = authorization.User;
+ this.Scope.ResetContents(authorization.Scope);
+ this.Lifetime = lifetime;
+ }
+
+ /// <summary>
+ /// Gets or sets the lifetime of the access token.
+ /// </summary>
+ /// <value>The lifetime.</value>
+ [MessagePart]
+ internal TimeSpan? Lifetime { get; set; }
+
+ internal static IDataBagFormatter<AccessToken> CreateFormatter(RSAParameters signingKey, RSAParameters encryptingKey)
+ {
+ 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/ChannelElements/AuthServerAllFlowsBindingElement.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthServerAllFlowsBindingElement.cs
new file mode 100644
index 0000000..1bf8c79
--- /dev/null
+++ b/src/DotNetOpenAuth/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(client.Callback == null || client.Callback == authorizationRequest.Callback, OAuthStrings.CallbackMismatch, client.Callback, authorizationRequest.Callback);
+ ErrorUtilities.VerifyProtocol(client.Callback != null || authorizationRequest.Callback != null, OAuthStrings.NoCallback);
+
+ return MessageProtections.None;
+ }
+
+ return null;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthServerBindingElementBase.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthServerBindingElementBase.cs
new file mode 100644
index 0000000..9d3e78f
--- /dev/null
+++ b/src/DotNetOpenAuth/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/ChannelElements/AuthorizationCode.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationCode.cs
new file mode 100644
index 0000000..1ec6b41
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationCode.cs
@@ -0,0 +1,92 @@
+//-----------------------------------------------------------------------
+// <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;
+ using DotNetOpenAuth.Messaging.Bindings;
+
+ /// <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 hash algorithm used on the callback URI.
+ /// </summary>
+ private readonly HashAlgorithm hasher = new SHA256Managed();
+
+ /// <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) {
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(clientIdentifier));
+ Contract.Requires<ArgumentNullException>(callback != null, "callback");
+
+ this.ClientIdentifier = clientIdentifier;
+ this.CallbackHash = this.CalculateCallbackHash(callback);
+ this.Scope.ResetContents(scopes);
+ this.User = username;
+ }
+
+ /// <summary>
+ /// Gets or sets the hash of the callback URL.
+ /// </summary>
+ [MessagePart("cb")]
+ private byte[] CallbackHash { get; set; }
+
+ internal static IDataBagFormatter<AuthorizationCode> CreateFormatter(IAuthorizationServer authorizationServer) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null, "authorizationServer");
+ Contract.Ensures(Contract.Result<IDataBagFormatter<AuthorizationCode>>() != null);
+
+ return new UriStyleMessageFormatter<AuthorizationCode>(
+ authorizationServer.Secret,
+ true,
+ true,
+ false,
+ AuthorizationCodeBindingElement.MaximumMessageAge,
+ 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, this.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 byte[] CalculateCallbackHash(Uri callback) {
+ return this.hasher.ComputeHash(Encoding.UTF8.GetBytes(callback.AbsoluteUri));
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationCodeBindingElement.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationCodeBindingElement.cs
new file mode 100644
index 0000000..21fc258
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationCodeBindingElement.cs
@@ -0,0 +1,100 @@
+//-----------------------------------------------------------------------
+// <copyright file="WebServerVerificationCodeBindingElement.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>
+ internal static TimeSpan MaximumMessageAge {
+ get { return StandardExpirationBindingElement.MaximumMessageAge; }
+ }
+
+ /// <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;
+ ITokenCarryingRequest tokenCarryingResponse = response;
+ tokenCarryingResponse.AuthorizationDescription = new AuthorizationCode(request.ClientIdentifier, request.Callback, request.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) {
+ ITokenCarryingRequest tokenRequest = request;
+ ((AuthorizationCode)tokenRequest.AuthorizationDescription).VerifyCallback(request.Callback);
+
+ return MessageProtections.None;
+ }
+
+ return null;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationDataBag.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationDataBag.cs
new file mode 100644
index 0000000..2ca8c34
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationDataBag.cs
@@ -0,0 +1,55 @@
+//-----------------------------------------------------------------------
+// <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 System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Security.Cryptography;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+
+ /// <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 or sets 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/ChannelElements/DataBag.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/DataBag.cs
new file mode 100644
index 0000000..cefd24d
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/DataBag.cs
@@ -0,0 +1,71 @@
+//-----------------------------------------------------------------------
+// <copyright file="DataBag.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.Security.Cryptography;
+ using System.Security.Cryptography.X509Certificates;
+ using System.Text;
+ using System.Web;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+ using DotNetOpenAuth.Messaging.Reflection;
+ using DotNetOpenAuth.OAuth2.Messages;
+
+ /// <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 : MessageBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DataBag"/> class.
+ /// </summary>
+ protected DataBag()
+ : base(Protocol.Default.Version) {
+ }
+
+ /// <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("timestamp", IsRequired = true, Encoder = typeof(TimestampEncoder))]
+ internal DateTime UtcCreationDate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the signature.
+ /// </summary>
+ /// <value>The signature.</value>
+ [MessagePart("sig")]
+ 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>
+ [MessagePart("t", IsRequired = true, AllowEmpty = false)]
+ private string BagType {
+ get { return this.GetType().Name; }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/EndUserAuthorizationResponseTypeEncoder.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/EndUserAuthorizationResponseTypeEncoder.cs
new file mode 100644
index 0000000..7ad6940
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/EndUserAuthorizationResponseTypeEncoder.cs
@@ -0,0 +1,67 @@
+//-----------------------------------------------------------------------
+// <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;
+
+ 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.Both:
+ return Protocol.ResponseTypes.CodeAndToken;
+ 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.CodeAndToken:
+ return EndUserAuthorizationResponseType.Both;
+ 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/ChannelElements/GrantTypeEncoder.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/GrantTypeEncoder.cs
new file mode 100644
index 0000000..f39eecd
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/GrantTypeEncoder.cs
@@ -0,0 +1,75 @@
+//-----------------------------------------------------------------------
+// <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;
+
+ 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.None:
+ return Protocol.GrantTypes.None;
+ case GrantType.AuthorizationCode:
+ return Protocol.GrantTypes.AuthorizationCode;
+ case GrantType.RefreshToken:
+ return Protocol.GrantTypes.RefreshToken;
+ case GrantType.BasicCredentials:
+ return Protocol.GrantTypes.BasicCredentials;
+ 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.None:
+ return GrantType.None;
+ case Protocol.GrantTypes.Assertion:
+ return GrantType.Assertion;
+ case Protocol.GrantTypes.BasicCredentials:
+ return GrantType.BasicCredentials;
+ 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/ChannelElements/IAuthorizationDescription.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/IAuthorizationDescription.cs
new file mode 100644
index 0000000..2b3a9ce
--- /dev/null
+++ b/src/DotNetOpenAuth/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/ChannelElements/IDataBagFormatter.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/IDataBagFormatter.cs
new file mode 100644
index 0000000..a9c1875
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/IDataBagFormatter.cs
@@ -0,0 +1,54 @@
+//-----------------------------------------------------------------------
+// <copyright file="IDataBagFormatter.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;
+
+ /// <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() {
+ string Serialize(T message);
+
+ 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
+
+ string IDataBagFormatter<T>.Serialize(T message) {
+ Contract.Requires<ArgumentNullException>(message != null, "message");
+ Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>()));
+
+ throw new System.NotImplementedException();
+ }
+
+ T IDataBagFormatter<T>.Deserialize(IProtocolMessage containingMessage, string data) {
+ Contract.Requires<ArgumentNullException>(containingMessage != null, "containingMessage");
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(data));
+ Contract.Ensures(Contract.Result<T>() != null);
+
+ throw new System.NotImplementedException();
+ }
+
+ #endregion
+ }
+} \ No newline at end of file
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/ITokenCarryingRequest.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/ITokenCarryingRequest.cs
new file mode 100644
index 0000000..4c8d33f
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/ITokenCarryingRequest.cs
@@ -0,0 +1,54 @@
+//-----------------------------------------------------------------------
+// <copyright file="ITokenCarryingRequest.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 ITokenCarryingRequest : 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/ChannelElements/OAuth2AuthorizationServerChannel.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2AuthorizationServerChannel.cs
new file mode 100644
index 0000000..5ecf01c
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2AuthorizationServerChannel.cs
@@ -0,0 +1,107 @@
+//-----------------------------------------------------------------------
+// <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)) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null, "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) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null, "authorizationServer");
+ var bindingElements = new List<IChannelBindingElement>();
+
+ bindingElements.Add(new AuthServerAllFlowsBindingElement());
+ bindingElements.Add(new AuthorizationCodeBindingElement());
+ bindingElements.Add(new AccessRequestBindingElement());
+
+ return bindingElements.ToArray();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ChannelBase.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ChannelBase.cs
new file mode 100644
index 0000000..2a959ff
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ChannelBase.cs
@@ -0,0 +1,48 @@
+//-----------------------------------------------------------------------
+// <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;
+
+ 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(AccessTokenAssertionRequest),
+ 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) {
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ClientChannel.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ClientChannel.cs
new file mode 100644
index 0000000..256a28d
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ClientChannel.cs
@@ -0,0 +1,91 @@
+//-----------------------------------------------------------------------
+// <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;
+
+ 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;
+ }
+
+ 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
+ string body = response.GetResponseReader().ReadToEnd();
+ if (response.ContentType.MediaType == JsonEncoded) {
+ 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);
+ }
+ }
+
+ 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);
+ }
+
+ protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) {
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ResourceServerChannel.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ResourceServerChannel.cs
new file mode 100644
index 0000000..60e464c
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ResourceServerChannel.cs
@@ -0,0 +1,152 @@
+//-----------------------------------------------------------------------
+// <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) {
+ // First search the Authorization header.
+ var fields = MessagingUtilities.ParseAuthorizationHeader(
+ Protocol.HttpAuthorizationScheme,
+ request.Headers[HttpRequestHeader.Authorization]).ToDictionary();
+
+ // Failing that, try the query string (for GET or POST or any other method)
+ if (fields.Count == 0) {
+ if (request.QueryStringBeforeRewriting["oauth_token"] != null) {
+ // We're only interested in the oauth_token parameter -- not the others that can appear in an Authorization header.
+ // Note that we intentionally change the name of the key here
+ // because depending on the method used to obtain the token, the token's key changes
+ // but we need to consolidate to one name so it works with the rest of the system.
+ fields.Add("token", request.QueryStringBeforeRewriting["oauth_token"]);
+ }
+ }
+
+ // Failing that, scan the entity
+ if (fields.Count == 0) {
+ // The spec calls out that this is allowed only for these three HTTP methods.
+ if (request.HttpMethod == "POST" || request.HttpMethod == "DELETE" || request.HttpMethod == "PUT") {
+ 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["oauth_token"] != null) {
+ // We're only interested in the oauth_token parameter -- not the others that can appear in an Authorization header.
+ // Note that we intentionally change the name of the key here
+ // because depending on the method used to obtain the token, the token's key changes
+ // but we need to consolidate to one name so it works with the rest of the system.
+ fields.Add("token", request.Form["oauth_token"]);
+ }
+ }
+ }
+ }
+ }
+
+ if (fields.Count > 0) {
+ MessageReceivingEndpoint recipient;
+ try {
+ recipient = request.GetRecipient();
+ } catch (ArgumentException ex) {
+ Logger.OAuth.WarnFormat("Unrecognized HTTP request: " + ex.ToString());
+ return null;
+ }
+
+ // TODO: remove this after signatures are supported.
+ ErrorUtilities.VerifyProtocol(!fields.ContainsKey("signature"), "OAuth signatures not supported yet.");
+
+ // 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.HttpAuthorizationScheme, fields);
+ return webResponse;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/RefreshToken.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/RefreshToken.cs
new file mode 100644
index 0000000..a88bf9f
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/RefreshToken.cs
@@ -0,0 +1,47 @@
+//-----------------------------------------------------------------------
+// <copyright file="RefreshToken.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.Messaging;
+
+ /// <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>
+ /// 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) {
+ Contract.Requires<ArgumentNullException>(authorization != null, "authorization");
+
+ this.ClientIdentifier = authorization.ClientIdentifier;
+ this.UtcCreationDate = authorization.UtcIssued;
+ this.User = authorization.User;
+ this.Scope.ResetContents(authorization.Scope);
+ }
+
+ internal static IDataBagFormatter<RefreshToken> CreateFormatter(byte[] symmetricSecret)
+ {
+ Contract.Requires<ArgumentNullException>(symmetricSecret != null, "symmetricSecret");
+ Contract.Ensures(Contract.Result<IDataBagFormatter<RefreshToken>>() != null);
+
+ return new UriStyleMessageFormatter<RefreshToken>(symmetricSecret, true, true);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/ScopeEncoder.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/ScopeEncoder.cs
new file mode 100644
index 0000000..d35f982
--- /dev/null
+++ b/src/DotNetOpenAuth/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 ? 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/ChannelElements/TimestampEncoder.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/TimestampEncoder.cs
new file mode 100644
index 0000000..7c6aafb
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/TimestampEncoder.cs
@@ -0,0 +1,61 @@
+//-----------------------------------------------------------------------
+// <copyright file="TimestampEncoder.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ 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>
+ private 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/OAuth2/ChannelElements/UriStyleMessageFormatter.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/UriStyleMessageFormatter.cs
new file mode 100644
index 0000000..cf1b522
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/UriStyleMessageFormatter.cs
@@ -0,0 +1,306 @@
+//-----------------------------------------------------------------------
+// <copyright file="UriStyleMessageFormatter.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.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> : IDataBagFormatter<T> where T : DataBag, new() {
+ /// <summary>
+ /// The length of the nonce to include in tokens that can be decoded once only.
+ /// </summary>
+ private const int NonceLength = 6;
+
+ /// <summary>
+ /// The message description cache to use for data bag types.
+ /// </summary>
+ private static readonly MessageDescriptionCollection MessageDescriptions = new MessageDescriptionCollection();
+
+ /// <summary>
+ /// The symmetric secret used for signing/encryption of verification codes and refresh tokens.
+ /// </summary>
+ private readonly byte[] symmetricSecret;
+
+ /// <summary>
+ /// The hashing algorithm to use while signing when using a symmetric secret.
+ /// </summary>
+ private readonly HashAlgorithm symmetricHasher;
+
+ /// <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>
+ /// The hashing algorithm to use for asymmetric signatures.
+ /// </summary>
+ private readonly HashAlgorithm hasherForAsymmetricSigning;
+
+ /// <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="UriStyleMessageFormatter&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 <see cref="decodeOnceOnly"/> is <c>true</c>.</param>
+ /// <param name="decodeOnceOnly">The nonce store to use to ensure that this instance is only decoded once.</param>
+ internal UriStyleMessageFormatter(bool signed = false, bool encrypted = false, bool compressed = false, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null) {
+ Contract.Requires<ArgumentException>(signed || decodeOnceOnly == null, "A signature must be applied if this data is meant to be decoded only once.");
+ Contract.Requires<ArgumentException>(maximumAge.HasValue || decodeOnceOnly == null, "A maximum age must be given if a message can only be decoded once.");
+
+ this.signed = signed;
+ this.maximumAge = maximumAge;
+ this.decodeOnceOnly = decodeOnceOnly;
+ this.encrypted = encrypted;
+ this.compressed = compressed;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UriStyleMessageFormatter&lt;T&gt;"/> class.
+ /// </summary>
+ /// <param name="signingKey">The asymmetric private key to use for signing the token.</param>
+ /// <param name="encryptingKey">The asymmetric public key to use for encrypting 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 <see cref="decodeOnceOnly"/> is <c>true</c>.</param>
+ /// <param name="decodeOnceOnly">The nonce store to use to ensure that this instance is only decoded once.</param>
+ internal UriStyleMessageFormatter(RSAParameters? signingKey = null, RSAParameters? encryptingKey = null, bool compressed = false, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null)
+ : this(signingKey.HasValue, encryptingKey.HasValue, compressed, maximumAge, decodeOnceOnly) {
+ if (signingKey.HasValue) {
+ this.asymmetricSigning = new RSACryptoServiceProvider();
+ this.asymmetricSigning.ImportParameters(signingKey.Value);
+ }
+
+ if (encryptingKey.HasValue) {
+ this.asymmetricEncrypting = new RSACryptoServiceProvider();
+ this.asymmetricEncrypting.ImportParameters(encryptingKey.Value);
+ }
+
+ this.hasherForAsymmetricSigning = new SHA1CryptoServiceProvider();
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UriStyleMessageFormatter&lt;T&gt;"/> class.
+ /// </summary>
+ /// <param name="symmetricSecret">The symmetric secret to use for signing and encrypting.</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="maximumAge">The maximum age of a token that can be decoded; useful only when <see cref="decodeOnceOnly"/> is <c>true</c>.</param>
+ /// <param name="decodeOnceOnly">The nonce store to use to ensure that this instance is only decoded once.</param>
+ internal UriStyleMessageFormatter(byte[] symmetricSecret = null, bool signed = false, bool encrypted = false, bool compressed = false, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null)
+ : this(signed, encrypted, compressed, maximumAge, decodeOnceOnly) {
+ Contract.Requires<ArgumentException>(symmetricSecret != null || (!signed && !encrypted), "A secret is required when signing or encrypting is required.");
+
+ if (symmetricSecret != null) {
+ this.symmetricHasher = new HMACSHA256(symmetricSecret);
+ }
+
+ this.symmetricSecret = symmetricSecret;
+ }
+
+ public string Serialize(T message) {
+ message.UtcCreationDate = DateTime.UtcNow;
+
+ if (this.decodeOnceOnly != null) {
+ message.Nonce = MessagingUtilities.GetNonCryptoRandomData(NonceLength);
+ }
+
+ if (this.signed) {
+ message.Signature = this.CalculateSignature(message);
+ }
+
+ var fields = MessageSerializer.Get(message.GetType()).Serialize(MessageDescriptions.GetAccessor(message));
+ string value = MessagingUtilities.CreateQueryString(fields);
+
+ byte[] encoded = Encoding.UTF8.GetBytes(value);
+
+ if (this.compressed) {
+ encoded = MessagingUtilities.Compress(encoded);
+ }
+
+ if (this.encrypted) {
+ encoded = this.Encrypt(encoded);
+ }
+
+ return Convert.ToBase64String(encoded);
+ }
+
+ public T Deserialize(IProtocolMessage containingMessage, string value) {
+ var message = new T();
+ message.ContainingMessage = containingMessage;
+ byte[] data = Convert.FromBase64String(value);
+
+ if (this.encrypted) {
+ data = this.Decrypt(data);
+ }
+
+ if (this.compressed) {
+ data = MessagingUtilities.Decompress(data);
+ }
+
+ 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);
+
+ if (this.signed) {
+ // Verify that the verification code was issued by message authorization server.
+ ErrorUtilities.VerifyProtocol(this.IsSignatureValid(message), Protocol.bad_verification_code);
+ }
+
+ 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>
+ /// Determines whether the signature on this instance is valid.
+ /// </summary>
+ /// <param name="message">The message whose signature is to be checked.</param>
+ /// <returns>
+ /// <c>true</c> if the signature is valid; otherwise, <c>false</c>.
+ /// </returns>
+ private bool IsSignatureValid(DataBag message) {
+ Contract.Requires<ArgumentNullException>(message != null, "message");
+
+ if (this.asymmetricSigning != null) {
+ byte[] bytesToSign = this.GetBytesToSign(message);
+ return this.asymmetricSigning.VerifyData(bytesToSign, this.hasherForAsymmetricSigning, message.Signature);
+ } else {
+ return MessagingUtilities.AreEquivalentConstantTime(message.Signature, this.CalculateSignature(message));
+ }
+ }
+
+ /// <summary>
+ /// Calculates the signature for the data in this verification code.
+ /// </summary>
+ /// <param name="message">The message whose signature is to be calculated.</param>
+ /// <returns>The calculated signature.</returns>
+ private byte[] CalculateSignature(DataBag message) {
+ Contract.Requires<ArgumentNullException>(message != null, "message");
+ Contract.Requires<InvalidOperationException>(this.asymmetricSigning != null || this.symmetricHasher != null);
+ Contract.Ensures(Contract.Result<byte[]>() != null);
+
+ byte[] bytesToSign = this.GetBytesToSign(message);
+ if (this.asymmetricSigning != null) {
+ return this.asymmetricSigning.SignData(bytesToSign, this.hasherForAsymmetricSigning);
+ } else {
+ return this.symmetricHasher.ComputeHash(bytesToSign);
+ }
+ }
+
+ /// <summary>
+ /// Gets the bytes to sign.
+ /// </summary>
+ /// <param name="message">The message to be encoded as normalized bytes for signing.</param>
+ /// <returns>A buffer of the bytes to sign.</returns>
+ private byte[] GetBytesToSign(DataBag message) {
+ Contract.Requires<ArgumentNullException>(message != null, "message");
+
+ // Sign the data, being sure to avoid any impact of the signature field itself.
+ var fields = MessageDescriptions.GetAccessor(message);
+ var fieldsCopy = fields.ToDictionary();
+ fieldsCopy.Remove("sig");
+
+ var sortedData = new SortedDictionary<string, string>(fieldsCopy, StringComparer.OrdinalIgnoreCase);
+ string value = MessagingUtilities.CreateQueryString(sortedData);
+ byte[] bytesToSign = Encoding.UTF8.GetBytes(value);
+ return bytesToSign;
+ }
+
+ /// <summary>
+ /// Encrypts the specified value using either the symmetric or asymmetric encryption algorithm as appropriate.
+ /// </summary>
+ /// <param name="value">The value.</param>
+ /// <returns>The encrypted value.</returns>
+ private byte[] Encrypt(byte[] value) {
+ Contract.Requires<InvalidOperationException>(this.asymmetricEncrypting != null || this.symmetricSecret != null);
+
+ if (this.asymmetricEncrypting != null) {
+ return this.asymmetricEncrypting.EncryptWithRandomSymmetricKey(value);
+ } else {
+ return MessagingUtilities.Encrypt(value, this.symmetricSecret);
+ }
+ }
+
+ /// <summary>
+ /// Decrypts the specified value using either the symmetric or asymmetric encryption algorithm as appropriate.
+ /// </summary>
+ /// <param name="value">The value.</param>
+ /// <returns>The decrypted value.</returns>
+ private byte[] Decrypt(byte[] value) {
+ Contract.Requires<InvalidOperationException>(this.asymmetricEncrypting != null || this.symmetricSecret != null);
+
+ if (this.asymmetricEncrypting != null) {
+ return this.asymmetricEncrypting.DecryptWithRandomSymmetricKey(value);
+ } else {
+ return MessagingUtilities.Decrypt(value, this.symmetricSecret);
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ClientBase.cs b/src/DotNetOpenAuth/OAuth2/ClientBase.cs
new file mode 100644
index 0000000..d9d9232
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ClientBase.cs
@@ -0,0 +1,226 @@
+//-----------------------------------------------------------------------
+// <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) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null);
+ 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 void AuthorizeRequest(HttpWebRequest request, string accessToken) {
+ Contract.Requires<ArgumentNullException>(request != null);
+ Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(accessToken));
+
+ OAuthUtilities.AuthorizeWithOAuthWrap(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) {
+ Contract.Requires<ArgumentNullException>(request != null);
+ Contract.Requires<ArgumentNullException>(authorization != null);
+ Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(authorization.AccessToken));
+ Contract.Requires<ProtocolException>(!authorization.AccessTokenExpirationUtc.HasValue || authorization.AccessTokenExpirationUtc < DateTime.UtcNow || authorization.RefreshToken != null);
+
+ if (authorization.AccessTokenExpirationUtc.HasValue && authorization.AccessTokenExpirationUtc.Value < DateTime.UtcNow) {
+ ErrorUtilities.VerifyProtocol(authorization.RefreshToken != null, "Access token has expired and cannot be automatically refreshed.");
+ this.RefreshToken(authorization);
+ }
+
+ this.AuthorizeRequest(request, authorization.AccessToken);
+ }
+
+ /// <summary>
+ /// Refreshes a short-lived access token using a longer-lived refresh token.
+ /// </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>
+ public void RefreshToken(IAuthorizationState authorization, TimeSpan? skipIfUsefulLifeExceeds = null) {
+ Contract.Requires<ArgumentNullException>(authorization != null, "authorization");
+ Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(authorization.RefreshToken));
+
+ 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;
+ }
+ }
+
+ var request = new AccessTokenRefreshRequest(this.AuthorizationServer) {
+ ClientIdentifier = this.ClientIdentifier,
+ ClientSecret = this.ClientSecret,
+ RefreshToken = authorization.RefreshToken,
+ };
+
+ var response = this.Channel.Request<AccessTokenSuccessResponse>(request);
+ authorization.AccessToken = response.AccessToken;
+ authorization.AccessTokenExpirationUtc = DateTime.UtcNow + response.Lifetime;
+ authorization.AccessTokenIssueDateUtc = DateTime.UtcNow;
+
+ // Just in case the scope has changed...
+ if (response.Scope != null) {
+ authorization.Scope.ResetContents(response.Scope);
+ }
+
+ // The authorization server MAY choose to renew the refresh token itself.
+ if (response.RefreshToken != null) {
+ authorization.RefreshToken = response.RefreshToken;
+ }
+
+ authorization.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 void UpdateAuthorizationWithResponse(IAuthorizationState authorizationState, AccessTokenSuccessResponse accessTokenSuccess) {
+ Contract.Requires<ArgumentNullException>(authorizationState != null, "authorizationState");
+ Contract.Requires<ArgumentNullException>(accessTokenSuccess != null, "accessTokenSuccess");
+
+ authorizationState.AccessToken = accessTokenSuccess.AccessToken;
+ authorizationState.RefreshToken = accessTokenSuccess.RefreshToken;
+ 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 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 void UpdateAuthorizationWithResponse(IAuthorizationState authorizationState, EndUserAuthorizationSuccessAccessTokenResponse accessTokenSuccess) {
+ Contract.Requires<ArgumentNullException>(authorizationState != null, "authorizationState");
+ Contract.Requires<ArgumentNullException>(accessTokenSuccess != null, "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();
+ }
+
+ internal void UpdateAuthorizationWithResponse(IAuthorizationState authorizationState, EndUserAuthorizationSuccessAuthCodeResponse authorizationSuccess) {
+ Contract.Requires<ArgumentNullException>(authorizationState != null, "authorizationState");
+ Contract.Requires<ArgumentNullException>(authorizationSuccess != null, "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) {
+ this.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 double ProportionalLifeRemaining(IAuthorizationState authorization) {
+ Contract.Requires<ArgumentNullException>(authorization != null, "authorization");
+ Contract.Requires<ArgumentException>(authorization.AccessTokenIssueDateUtc.HasValue);
+ Contract.Requires<ArgumentException>(authorization.AccessTokenExpirationUtc.HasValue);
+
+ // 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/IAccessTokenAnalyzer.cs b/src/DotNetOpenAuth/OAuth2/IAccessTokenAnalyzer.cs
new file mode 100644
index 0000000..ed6cd63
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/IAccessTokenAnalyzer.cs
@@ -0,0 +1,61 @@
+//-----------------------------------------------------------------------
+// <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.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>
+ 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) {
+ Contract.Requires<ArgumentNullException>(message != null, "message");
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(accessToken));
+ Contract.Ensures(Contract.Result<bool>() == (Contract.ValueAtReturn<string>(out user) != null));
+
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/IAuthorizationServer.cs b/src/DotNetOpenAuth/OAuth2/IAuthorizationServer.cs
new file mode 100644
index 0000000..83b5191
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/IAuthorizationServer.cs
@@ -0,0 +1,169 @@
+//-----------------------------------------------------------------------
+// <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.Bindings;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// Provides host-specific authorization server services needed by this library.
+ /// </summary>
+ [ContractClass(typeof(IAuthorizationServerContract))]
+ public interface IAuthorizationServer {
+ /// <summary>
+ /// Gets the secret used to symmetrically encrypt and sign authorization codes and refresh tokens.
+ /// </summary>
+ /// <remarks>
+ /// This secret should be kept strictly confidential in the authorization server(s)
+ /// and NOT shared with the resource server. Anyone with this secret can mint
+ /// tokens to essentially grant themselves access to anything they want.
+ /// </remarks>
+ byte[] Secret { get; }
+
+ /// <summary>
+ /// Gets the asymmetric private key to use for signing access tokens.
+ /// </summary>
+ /// <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>
+ RSAParameters AccessTokenSigningPrivateKey { 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 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 secret used to symmetrically encrypt and sign authorization codes and refresh tokens.
+ /// </summary>
+ /// <value></value>
+ /// <remarks>
+ /// This secret should be kept strictly confidential in the authorization server(s)
+ /// and NOT shared with the resource server. Anyone with this secret can mint
+ /// tokens to essentially grant themselves access to anything they want.
+ /// </remarks>
+ byte[] IAuthorizationServer.Secret {
+ get {
+ Contract.Ensures(Contract.Result<byte[]>() != null);
+ throw new NotImplementedException();
+ }
+ }
+
+ /// <summary>
+ /// Gets the asymmetric private key to use for signing access tokens.
+ /// </summary>
+ /// <value></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>
+ RSAParameters IAuthorizationServer.AccessTokenSigningPrivateKey {
+ get { 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 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) {
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(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) {
+ Contract.Requires<ArgumentNullException>(authorization != null, "authorization");
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/IAuthorizationState.cs b/src/DotNetOpenAuth/OAuth2/IAuthorizationState.cs
new file mode 100644
index 0000000..68a109b
--- /dev/null
+++ b/src/DotNetOpenAuth/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 or sets 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/IClientAuthorizationTracker.cs b/src/DotNetOpenAuth/OAuth2/IClientAuthorizationTracker.cs
new file mode 100644
index 0000000..97294e6
--- /dev/null
+++ b/src/DotNetOpenAuth/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) {
+ Contract.Requires<ArgumentNullException>(callbackUrl != null);
+ throw new NotImplementedException();
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/IConsumerDescription.cs b/src/DotNetOpenAuth/OAuth2/IConsumerDescription.cs
new file mode 100644
index 0000000..4e2bc4f
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/IConsumerDescription.cs
@@ -0,0 +1,25 @@
+//-----------------------------------------------------------------------
+// <copyright file="IConsumerDescription.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+
+ /// <summary>
+ /// A description of a client from an Authorization Server's point of view.
+ /// </summary>
+ public interface IConsumerDescription {
+ /// <summary>
+ /// Gets the client secret.
+ /// </summary>
+ string Secret { get; }
+
+ /// <summary>
+ /// Gets the callback URI that this client has pre-registered with the service provider, if any.
+ /// </summary>
+ /// <value>A URI that user authorization responses should be directed to; or <c>null</c> if no preregistered callback was arranged.</value>
+ Uri Callback { get; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AccessProtectedResourceRequest.cs b/src/DotNetOpenAuth/OAuth2/Messages/AccessProtectedResourceRequest.cs
new file mode 100644
index 0000000..f49efce
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/AccessProtectedResourceRequest.cs
@@ -0,0 +1,119 @@
+//-----------------------------------------------------------------------
+// <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>
+ internal class AccessProtectedResourceRequest : MessageBase, ITokenCarryingRequest {
+ /// <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 ITokenCarryingRequest.CodeOrTokenType {
+ get { return CodeOrTokenType.AccessToken; }
+ }
+
+ /// <summary>
+ /// Gets or sets the verification code or refresh/access token.
+ /// </summary>
+ /// <value>The code or token.</value>
+ string ITokenCarryingRequest.CodeOrToken {
+ get { return this.AccessToken; }
+ set { this.AccessToken = value; }
+ }
+
+ /// <summary>
+ /// Gets or sets the authorization that the token describes.
+ /// </summary>
+ IAuthorizationDescription ITokenCarryingRequest.AuthorizationDescription { get; set; }
+
+ /// <summary>
+ /// Gets or sets the access token.
+ /// </summary>
+ /// <value>The access token.</value>
+ [MessagePart("token", IsRequired = true, AllowEmpty = false)]
+ internal string AccessToken { get; set; }
+
+ /// <summary>
+ /// Gets or sets the nonce.
+ /// </summary>
+ /// <value>The nonce.</value>
+ [MessagePart("nonce")]
+ internal string Nonce { get; set; }
+
+ /// <summary>
+ /// Gets or sets the timestamp.
+ /// </summary>
+ /// <value>The timestamp.</value>
+ [MessagePart("timestamp", Encoder = typeof(TimestampEncoder))]
+ internal DateTime? Timestamp { get; set; }
+
+ /// <summary>
+ /// Gets or sets the signature.
+ /// </summary>
+ /// <value>The signature.</value>
+ [MessagePart("signature")]
+ internal string Signature { get; set; }
+
+ /// <summary>
+ /// Gets or sets the algorithm.
+ /// </summary>
+ /// <value>The algorithm.</value>
+ [MessagePart("algorithm")]
+ internal string Algorithm { get; set; }
+
+ /// <summary>
+ /// Gets a value indicating whether this request is signed.
+ /// </summary>
+ internal bool SignedRequest {
+ get { return this.Signature != null; }
+ }
+
+ /// <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();
+
+ // If any of the optional parameters are present, all of them are required.
+ if (this.Signature == null) {
+ ErrorUtilities.VerifyProtocol(this.Algorithm == null, this, MessagingStrings.UnexpectedMessagePartValue, "algorithm", this.Algorithm);
+ ErrorUtilities.VerifyProtocol(!this.Timestamp.HasValue, this, MessagingStrings.UnexpectedMessagePartValue, "timestamp", this.Timestamp);
+ ErrorUtilities.VerifyProtocol(this.Nonce == null, this, MessagingStrings.UnexpectedMessagePartValue, "nonce", this.Nonce);
+ } else {
+ ErrorUtilities.VerifyProtocol(this.Algorithm != null, this, MessagingStrings.RequiredParametersMissing, "algorithm");
+ ErrorUtilities.VerifyProtocol(this.Timestamp.HasValue, this, MessagingStrings.RequiredParametersMissing, "timestamp");
+ ErrorUtilities.VerifyProtocol(this.Nonce != null, this, MessagingStrings.RequiredParametersMissing, "nonce");
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenAssertionRequest.cs b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenAssertionRequest.cs
new file mode 100644
index 0000000..8c2ef2b
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenAssertionRequest.cs
@@ -0,0 +1,37 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessTokenAssertionRequest.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;
+
+ internal class AccessTokenAssertionRequest : AccessTokenRequestBase {
+ internal AccessTokenAssertionRequest(Uri tokenEndpoint, Version version)
+ : base(tokenEndpoint, version) {
+ }
+
+ /// <summary>
+ /// Gets or sets the format of the assertion as defined by the Authorization Server.
+ /// </summary>
+ /// <value>The assertion format.</value>
+ [MessagePart(Protocol.assertion_type, IsRequired = true, AllowEmpty = false)]
+ internal Uri AssertionType { get; set; }
+
+ /// <summary>
+ /// Gets or sets the assertion.
+ /// </summary>
+ /// <value>The assertion.</value>
+ [MessagePart(Protocol.assertion, IsRequired = true, AllowEmpty = false)]
+ internal string Assertion { get; set; }
+
+ internal override GrantType GrantType {
+ get { return GrantType.Assertion; }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenAuthorizationCodeRequest.cs b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenAuthorizationCodeRequest.cs
new file mode 100644
index 0000000..86c1a4b
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenAuthorizationCodeRequest.cs
@@ -0,0 +1,77 @@
+//-----------------------------------------------------------------------
+// <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;
+
+ internal class AccessTokenAuthorizationCodeRequest : AccessTokenRequestBase, ITokenCarryingRequest {
+ /// <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) {
+ }
+
+
+ internal AccessTokenAuthorizationCodeRequest(AuthorizationServerDescription authorizationServer)
+ : this(authorizationServer.TokenEndpoint, authorizationServer.Version)
+ {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null, "authorizationServer");
+ }
+
+ internal override GrantType GrantType {
+ get { return Messages.GrantType.AuthorizationCode; }
+ }
+
+ /// <summary>
+ /// Gets the type of the code or token.
+ /// </summary>
+ /// <value>The type of the code or token.</value>
+ CodeOrTokenType ITokenCarryingRequest.CodeOrTokenType {
+ get { return CodeOrTokenType.AuthorizationCode; }
+ }
+
+ /// <summary>
+ /// Gets or sets the verification code or refresh/access token.
+ /// </summary>
+ /// <value>The code or token.</value>
+ string ITokenCarryingRequest.CodeOrToken {
+ get { return this.AuthorizationCode; }
+ set { this.AuthorizationCode = value; }
+ }
+
+ /// <summary>
+ /// Gets or sets the authorization that the token describes.
+ /// </summary>
+ IAuthorizationDescription ITokenCarryingRequest.AuthorizationDescription { get; set; }
+
+ /// <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, AllowEmpty = false)]
+ 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, AllowEmpty = false)]
+ internal Uri Callback { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenClientCredentialsRequest.cs b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenClientCredentialsRequest.cs
new file mode 100644
index 0000000..59b0758
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenClientCredentialsRequest.cs
@@ -0,0 +1,54 @@
+//-----------------------------------------------------------------------
+// <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 : AccessTokenRequestBase {
+ /// <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>
+ /// 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(this.Recipient.IsTransportSecure(), OAuthStrings.HttpsRequired);
+ }
+
+ internal override GrantType GrantType {
+ get { return Messages.GrantType.None; }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenFailedResponse.cs b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenFailedResponse.cs
new file mode 100644
index 0000000..90c5e67
--- /dev/null
+++ b/src/DotNetOpenAuth/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;
+ }
+
+ /// <summary>
+ /// Gets or sets the error.
+ /// </summary>
+ /// <value>One of the values given in <see cref="Protocol.AccessTokenRequestErrorCodes"/>.</value>
+ [MessagePart(Protocol.error, IsRequired = true, AllowEmpty = false)]
+ 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, AllowEmpty = true, 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, AllowEmpty = false, IsRequired = false)]
+ internal Uri ErrorUri { get; set; }
+
+ #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
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenRefreshRequest.cs b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenRefreshRequest.cs
new file mode 100644
index 0000000..f15f190
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenRefreshRequest.cs
@@ -0,0 +1,71 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessTokenRefreshRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ 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 : AccessTokenRequestBase, ITokenCarryingRequest {
+ /// <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 ITokenCarryingRequest.CodeOrTokenType {
+ get { return CodeOrTokenType.RefreshToken; }
+ }
+
+
+ /// <summary>
+ /// Gets or sets the verification code or refresh/access token.
+ /// </summary>
+ /// <value>The code or token.</value>
+ string ITokenCarryingRequest.CodeOrToken {
+ get { return this.RefreshToken; }
+ set { this.RefreshToken = value; }
+ }
+
+ /// <summary>
+ /// Gets or sets the authorization that the token describes.
+ /// </summary>
+ IAuthorizationDescription ITokenCarryingRequest.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, AllowEmpty = false)]
+ internal string RefreshToken { get; set; }
+
+ internal override GrantType GrantType {
+ get { return Messages.GrantType.RefreshToken; }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenRequestBase.cs b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenRequestBase.cs
new file mode 100644
index 0000000..943308e
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenRequestBase.cs
@@ -0,0 +1,60 @@
+//-----------------------------------------------------------------------
+// <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 {
+ /// <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;
+ this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer);
+ }
+
+ /// <summary>
+ /// Gets the type of the grant.
+ /// </summary>
+ /// <value>The type of the grant.</value>
+ [MessagePart(Protocol.grant_type, IsRequired = true, AllowEmpty = false, Encoder = typeof(GrantTypeEncoder))]
+ internal abstract GrantType GrantType { get; }
+
+ [MessagePart(Protocol.scope, IsRequired = false, AllowEmpty = true, Encoder = typeof(ScopeEncoder))]
+ internal 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>
+ /// <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.Configuration.Messaging.RelaxSslRequirements || this.Recipient.IsTransportSecure(),
+ OAuthStrings.HttpsRequired);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenResourceOwnerPasswordCredentialsRequest.cs b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenResourceOwnerPasswordCredentialsRequest.cs
new file mode 100644
index 0000000..98b1068
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenResourceOwnerPasswordCredentialsRequest.cs
@@ -0,0 +1,42 @@
+//-----------------------------------------------------------------------
+// <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;
+
+ internal class AccessTokenResourceOwnerPasswordCredentialsRequest : AccessTokenRequestBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenResourceOwnerPasswordCredentialsRequest"/> class.
+ /// </summary>
+ internal AccessTokenResourceOwnerPasswordCredentialsRequest(Uri accessTokenEndpoint, Version version)
+ : base(accessTokenEndpoint, version) {
+ }
+
+ internal override GrantType GrantType {
+ get { return Messages.GrantType.BasicCredentials; }
+ }
+
+ /// <summary>
+ /// Gets or sets the user's account username.
+ /// </summary>
+ /// <value>The username on the user's account.</value>
+ [MessagePart(Protocol.username, IsRequired = true, AllowEmpty = false)]
+ internal string UserName { get; set; }
+
+ /// <summary>
+ /// Gets or sets the user's password.
+ /// </summary>
+ /// <value>The password.</value>
+ [MessagePart(Protocol.password, IsRequired = true, AllowEmpty = true)]
+ internal string Password { get; set; }
+
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenSuccessResponse.cs b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenSuccessResponse.cs
new file mode 100644
index 0000000..37a4684
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenSuccessResponse.cs
@@ -0,0 +1,83 @@
+//-----------------------------------------------------------------------
+// <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);
+ }
+
+ /// <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, AllowEmpty = false)]
+ public string AccessToken { 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, AllowEmpty = false)]
+ public string RefreshToken { get; internal set; }
+
+ /// <summary>
+ /// Gets or sets 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, AllowEmpty = true, Encoder = typeof(ScopeEncoder))]
+ public HashSet<string> Scope { get; private set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AuthenticatedClientRequestBase.cs b/src/DotNetOpenAuth/OAuth2/Messages/AuthenticatedClientRequestBase.cs
new file mode 100644
index 0000000..292ea95
--- /dev/null
+++ b/src/DotNetOpenAuth/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 or sets the client identifier previously obtained from the Authorization Server.
+ /// </summary>
+ /// <value>The client identifier.</value>
+ [MessagePart(Protocol.client_id, IsRequired = true, AllowEmpty = false)]
+ public string ClientIdentifier { get; internal set; }
+
+ /// <summary>
+ /// Gets or sets 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, AllowEmpty = true)]
+ public string ClientSecret { get; internal set; }
+ }
+} \ No newline at end of file
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationFailedResponse.cs b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationFailedResponse.cs
new file mode 100644
index 0000000..b125c67
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationFailedResponse.cs
@@ -0,0 +1,70 @@
+//-----------------------------------------------------------------------
+// <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;
+
+ public class EndUserAuthorizationFailedResponse : 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 EndUserAuthorizationFailedResponse(Uri clientCallback, Version version)
+ : base(version, MessageTransport.Indirect, clientCallback) {
+ Contract.Requires<ArgumentNullException>(version != null);
+ Contract.Requires<ArgumentNullException>(clientCallback != null);
+ }
+
+ /// <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) {
+ Contract.Requires<ArgumentNullException>(request != null, "request");
+ ((IMessageWithClientState)this).ClientState = request.ClientState;
+ }
+
+ /// <summary>
+ /// Gets or sets the error.
+ /// </summary>
+ /// <value>One of the values given in <see cref="Protocol.EndUserAuthorizationRequestErrorCodes"/>.</value>
+ [MessagePart(Protocol.error, IsRequired = true, AllowEmpty = false)]
+ 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, AllowEmpty = true, 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, AllowEmpty = false, 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, AllowEmpty = true)]
+ string IMessageWithClientState.ClientState { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationRequest.cs b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationRequest.cs
new file mode 100644
index 0000000..a4e8b89
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationRequest.cs
@@ -0,0 +1,93 @@
+//-----------------------------------------------------------------------
+// <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.Contracts;
+ 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 {
+ /// <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) {
+ Contract.Requires<ArgumentNullException>(authorizationEndpoint != null);
+ Contract.Requires<ArgumentNullException>(version != null);
+ this.HttpMethods = HttpDeliveryMethods.GetRequest;
+ this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer);
+ }
+
+ /// <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) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null);
+ Contract.Requires<ArgumentException>(authorizationServer.Version != null);
+ Contract.Requires<ArgumentException>(authorizationServer.AuthorizationEndpoint != null);
+ }
+
+ /// <summary>
+ /// Gets the type of the authorization 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, AllowEmpty = false, Encoder = typeof(EndUserAuthorizationResponseTypeEncoder))]
+ public EndUserAuthorizationResponseType ResponseType
+ {
+ get { return EndUserAuthorizationResponseType.AuthorizationCode; }
+ }
+
+ /// <summary>
+ /// Gets or sets the identifier by which this client is known to the Authorization Server.
+ /// </summary>
+ [MessagePart(Protocol.client_id, IsRequired = true, AllowEmpty = false)]
+ public string ClientIdentifier { get; set; }
+
+ /// <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, AllowEmpty = 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>
+ /// REQUIRED. The client identifier as described in Section 3.4 (Client Credentials).
+ /// </remarks>
+ [MessagePart(Protocol.state, IsRequired = false, AllowEmpty = true)]
+ public string ClientState { get; set; }
+
+ /// <summary>
+ /// Gets or sets 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, AllowEmpty = true, Encoder = typeof(ScopeEncoder))]
+ public HashSet<string> Scope { get; private set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationResponseType.cs b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationResponseType.cs
new file mode 100644
index 0000000..3afcae5
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationResponseType.cs
@@ -0,0 +1,31 @@
+//-----------------------------------------------------------------------
+// <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>
+ [Flags]
+ public enum EndUserAuthorizationResponseType {
+ /// <summary>
+ /// An access token should be returned immediately.
+ /// </summary>
+ AccessToken = 0x1,
+
+ /// <summary>
+ /// An authorization code should be returned, which can later be exchanged for refresh and access tokens.
+ /// </summary>
+ AuthorizationCode = 0x2,
+
+ /// <summary>
+ /// Both an access token and an authorization code should be returned.
+ /// </summary>
+ Both = AccessToken | AuthorizationCode,
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessAccessTokenResponse.cs b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessAccessTokenResponse.cs
new file mode 100644
index 0000000..41c7e68
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessAccessTokenResponse.cs
@@ -0,0 +1,64 @@
+//-----------------------------------------------------------------------
+// <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, ITokenCarryingRequest {
+ /// <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) {
+ Contract.Requires<ArgumentNullException>(version != null);
+ Contract.Requires<ArgumentNullException>(clientCallback != null);
+ }
+
+ /// <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) {
+ Contract.Requires<ArgumentNullException>(clientCallback != null, "clientCallback");
+ Contract.Requires<ArgumentNullException>(request != null, "request");
+ ((IMessageWithClientState)this).ClientState = request.ClientState;
+ }
+
+ [MessagePart(Protocol.access_token, AllowEmpty = false, IsRequired = true)]
+ internal string AccessToken { get; set; }
+
+ #region ITokenCarryingRequest Members
+
+ string ITokenCarryingRequest.CodeOrToken {
+ get { return this.AccessToken; }
+ set { this.AccessToken = value; }
+ }
+
+ CodeOrTokenType ITokenCarryingRequest.CodeOrTokenType {
+ get { return CodeOrTokenType.AccessToken; }
+ }
+
+ IAuthorizationDescription ITokenCarryingRequest.AuthorizationDescription { get; set; }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessAuthCodeResponse.cs b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessAuthCodeResponse.cs
new file mode 100644
index 0000000..5ef501b
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessAuthCodeResponse.cs
@@ -0,0 +1,67 @@
+//-----------------------------------------------------------------------
+// <copyright file="EndUserAuthorizationSuccessAuthCodeResponse.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 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, ITokenCarryingRequest {
+ /// <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) {
+ Contract.Requires<ArgumentNullException>(version != null);
+ Contract.Requires<ArgumentNullException>(clientCallback != null);
+ }
+
+ /// <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) {
+ Contract.Requires<ArgumentNullException>(clientCallback != null, "clientCallback");
+ Contract.Requires<ArgumentNullException>(request != null, "request");
+ ((IMessageWithClientState)this).ClientState = request.ClientState;
+ }
+
+ [MessagePart(Protocol.code, AllowEmpty = false, IsRequired = true)]
+ internal string AuthorizationCode { get; set; }
+
+ [MessagePart(Protocol.access_token, AllowEmpty = false, IsRequired = false)]
+ internal string AccessToken { get; set; }
+
+ #region ITokenCarryingRequest Members
+
+ string ITokenCarryingRequest.CodeOrToken {
+ get { return this.AuthorizationCode; }
+ set { this.AuthorizationCode = value; }
+ }
+
+ CodeOrTokenType ITokenCarryingRequest.CodeOrTokenType {
+ get { return CodeOrTokenType.AuthorizationCode; }
+ }
+
+ IAuthorizationDescription ITokenCarryingRequest.AuthorizationDescription { get; set; }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessResponseBase.cs b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessResponseBase.cs
new file mode 100644
index 0000000..305c0e6
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessResponseBase.cs
@@ -0,0 +1,76 @@
+//-----------------------------------------------------------------------
+// <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) {
+ Contract.Requires<ArgumentNullException>(version != null);
+ Contract.Requires<ArgumentNullException>(clientCallback != null);
+ 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) {
+ Contract.Requires<ArgumentNullException>(clientCallback != null, "clientCallback");
+ Contract.Requires<ArgumentNullException>(request != null, "request");
+ ((IMessageWithClientState)this).ClientState = request.ClientState;
+ this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer);
+ }
+
+ /// <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, AllowEmpty = true)]
+ string IMessageWithClientState.ClientState { get; set; }
+
+ /// <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; }
+
+ /// <summary>
+ /// Gets 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, AllowEmpty = true, Encoder = typeof(ScopeEncoder))]
+ public ICollection<string> Scope { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the authorizing user's account name.
+ /// </summary>
+ internal string AuthorizingUsername { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/GrantType.cs b/src/DotNetOpenAuth/OAuth2/Messages/GrantType.cs
new file mode 100644
index 0000000..1321ac2
--- /dev/null
+++ b/src/DotNetOpenAuth/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>
+ BasicCredentials,
+
+ /// <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>
+ None,
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/IMessageWithClientState.cs b/src/DotNetOpenAuth/OAuth2/Messages/IMessageWithClientState.cs
new file mode 100644
index 0000000..fa371ae
--- /dev/null
+++ b/src/DotNetOpenAuth/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/Messages/MessageBase.cs b/src/DotNetOpenAuth/OAuth2/Messages/MessageBase.cs
new file mode 100644
index 0000000..3233360
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/MessageBase.cs
@@ -0,0 +1,210 @@
+//-----------------------------------------------------------------------
+// <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.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) {
+ Contract.Requires<ArgumentNullException>(version != null);
+ 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) {
+ Contract.Requires<ArgumentNullException>(request != null);
+ 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) {
+ Contract.Requires<ArgumentNullException>(version != null);
+ Contract.Requires<ArgumentNullException>(recipient != null);
+
+ 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 MessageProtections.None; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether this is a direct or indirect message.
+ /// </summary>
+ /// <value></value>
+ MessageTransport IProtocolMessage.Transport {
+ get { return this.messageTransport; }
+ }
+
+ #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 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 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/Messages/UnauthorizedResponse.cs b/src/DotNetOpenAuth/OAuth2/Messages/UnauthorizedResponse.cs
new file mode 100644
index 0000000..0f12a8c
--- /dev/null
+++ b/src/DotNetOpenAuth/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) {
+ Contract.Requires<ArgumentNullException>(exception != null, "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) {
+ Contract.Requires<ArgumentNullException>(exception != null, "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.HttpAuthorizationScheme },
+ };
+ }
+ }
+
+ #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/OAuthStrings.Designer.cs b/src/DotNetOpenAuth/OAuth2/OAuthStrings.Designer.cs
new file mode 100644
index 0000000..f4a74cc
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/OAuthStrings.Designer.cs
@@ -0,0 +1,135 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.1
+//
+// 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 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 Client&apos;s pre-registered callback URL ({0}) does not match the one found in the authorization request ({1})..
+ /// </summary>
+ internal static string CallbackMismatch {
+ get {
+ return ResourceManager.GetString("CallbackMismatch", 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 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/OAuthStrings.resx b/src/DotNetOpenAuth/OAuth2/OAuthStrings.resx
new file mode 100644
index 0000000..dacd9fc
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/OAuthStrings.resx
@@ -0,0 +1,144 @@
+<?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="AccessScopeExceedsGrantScope" xml:space="preserve">
+ <value>The requested access scope ("{0}") exceeds the grant scope ("{1}").</value>
+ </data>
+ <data name="CallbackMismatch" xml:space="preserve">
+ <value>Client's pre-registered callback URL ({0}) does not match the one found in the authorization request ({1}).</value>
+ </data>
+ <data name="CannotObtainAccessTokenWithReason" xml:space="preserve">
+ <value>Failed to obtain access token. Authorization Server reports reason: {0}</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/OAuthUtilities.cs b/src/DotNetOpenAuth/OAuth2/OAuthUtilities.cs
new file mode 100644
index 0000000..6b4c42a
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/OAuthUtilities.cs
@@ -0,0 +1,117 @@
+//-----------------------------------------------------------------------
+// <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 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 +
+ @"!#$%&'()*+-./:<=>?@[]^_`{|}~\,;";
+
+ public static readonly StringComparer ScopeStringComparer = StringComparer.Ordinal;
+
+ /// <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 scope.</param>
+ /// <param name="scopeComparer">The scope comparer, allowing scopes to be case sensitive or insensitive.
+ /// Usually <see cref="StringComparer.Ordinal"/> or <see cref="StringComparer.OrdinalIgnoreCase"/>.</param>
+ /// <returns></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);
+ }
+
+ public static string JoinScopes(HashSet<string> scopes) {
+ Contract.Requires<ArgumentNullException>(scopes != null, "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 AuthorizeWithOAuthWrap(this HttpWebRequest request, string accessToken) {
+ Contract.Requires<ArgumentNullException>(request != null);
+ Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(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.HttpAuthorizationHeaderFormat,
+ 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) {
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(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/Protocol.cs b/src/DotNetOpenAuth/OAuth2/Protocol.cs
new file mode 100644
index 0000000..a8a67bb
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Protocol.cs
@@ -0,0 +1,330 @@
+// <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 "OAuth";
+ /// </summary>
+ internal const string HttpAuthorizationScheme = "OAuth";
+
+ /// <summary>
+ /// The format of the HTTP Authorization header value that authorizes OAuth 2.0 requests.
+ /// </summary>
+ internal const string HttpAuthorizationHeaderFormat = "OAuth token=\"{0}\"";
+
+ /// <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 "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 "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");
+ }
+ }
+
+ internal static class ResponseTypes
+ {
+ internal const string Code = "code";
+ internal const string Token = "token";
+ internal const string CodeAndToken = "code-and-token";
+ }
+
+ internal static class GrantTypes
+ {
+ internal const string AuthorizationCode = "authorization-code";
+
+ internal const string BasicCredentials = "basic-credentials";
+
+ internal const string Assertion = "assertion";
+
+ internal const string RefreshToken = "refresh-token";
+
+ internal const string None = "none";
+ }
+
+ /// <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 identifier provided is invalid, the client failed to authenticate, or the client provided multiple client credentials.
+ /// </summary>
+ internal const string InvalidClientCredentials = "invalid-client-credentials";
+
+ /// <summary>
+ /// The client is not authorized to use the access grant type provided.
+ /// </summary>
+ internal const string UnauthorizedClient = "unauthorized-client";
+
+ /// <summary>
+ /// The provided access grant is invalid, expired, or revoked (e.g. invalid assertion, expired authorization token, bad end-user basic credentials, or mismatching authorization code and redirection URI).
+ /// </summary>
+ internal const string InvalidGrant = "invalid-grant";
+
+ /// <summary>
+ /// The access grant included - its type or another attribute - is not supported by the authorization server.
+ /// </summary>
+ internal const string UnsupportedGrantType = "unsupported-grant-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 identifier provided is invalid.
+ /// </summary>
+ internal const string InvalidClientId = "invalid-client-id";
+
+ /// <summary>
+ /// The client is not authorized to use the requested response type.
+ /// </summary>
+ internal const string UnauthorizedClient = "unauthorized-client";
+
+ /// <summary>
+ /// The redirection URI provided does not match a pre-registered value.
+ /// </summary>
+ internal const string RedirectUriMismatch = "redirect-uri-mismatch";
+
+ /// <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";
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ResourceServer.cs b/src/DotNetOpenAuth/OAuth2/ResourceServer.cs
new file mode 100644
index 0000000..a2afdae
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ResourceServer.cs
@@ -0,0 +1,144 @@
+//-----------------------------------------------------------------------
+// <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.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) {
+ Contract.Requires<ArgumentNullException>(accessTokenAnalyzer != null, "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 or sets the endpoint information for an authorization server that may be used
+ /// to obtain an access token for this resource.
+ /// </summary>
+ /// <value>The authorization server description.</value>
+ /// <remarks>
+ /// This value is optional. If set, this information will be used to generate
+ /// more useful HTTP 401 Unauthorized responses for requests that lack an OAuth access token.
+ /// </remarks>
+ public AuthorizationServerDescription AuthorizationServerDescription { get; 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>
+ 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>
+ public virtual OutgoingWebResponse VerifyAccess(HttpRequestInfo httpRequestInfo, out string username, out HashSet<string> scope) {
+ Contract.Requires<ArgumentNullException>(httpRequestInfo != null, "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>
+ public virtual OutgoingWebResponse VerifyAccess(HttpRequestInfo httpRequestInfo, out IPrincipal principal) {
+ string username;
+ HashSet<string> scope;
+ var result = this.VerifyAccess(httpRequestInfo, out username, out scope);
+ if (result == null) {
+ principal = new OAuth.ChannelElements.OAuthPrincipal(username, scope != null ? scope.ToArray() : new string[0]);
+ } else {
+ principal = 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>
+ public virtual OutgoingWebResponse VerifyAccess(HttpRequestMessageProperty request, Uri requestUri, out IPrincipal principal) {
+ Contract.Requires<ArgumentNullException>(request != null, "request");
+ Contract.Requires<ArgumentNullException>(requestUri != null, "requestUri");
+
+ return this.VerifyAccess(new HttpRequestInfo(request, requestUri), out principal);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/StandardAccessTokenAnalyzer.cs b/src/DotNetOpenAuth/OAuth2/StandardAccessTokenAnalyzer.cs
new file mode 100644
index 0000000..d4d4c2f
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/StandardAccessTokenAnalyzer.cs
@@ -0,0 +1,62 @@
+//-----------------------------------------------------------------------
+// <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.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 authorization server public signing key.</param>
+ /// <param name="resourceServerPrivateEncryptionKey">The resource server private encryption key.</param>
+ public StandardAccessTokenAnalyzer(RSAParameters authorizationServerPublicSigningKey, RSAParameters 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 RSAParameters AuthorizationServerPublicSigningKey { get; private set; }
+
+ /// <summary>
+ /// Gets the resource server private encryption key.
+ /// </summary>
+ /// <value>The resource server private encryption key.</value>
+ public RSAParameters 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/UserAgentClient.cs b/src/DotNetOpenAuth/OAuth2/UserAgentClient.cs
new file mode 100644
index 0000000..367a36a
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/UserAgentClient.cs
@@ -0,0 +1,107 @@
+//-----------------------------------------------------------------------
+// <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>
+ 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>
+ public UserAgentClient(Uri authorizationEndpoint)
+ : base(new AuthorizationServerDescription { AuthorizationEndpoint = authorizationEndpoint }) {
+ Contract.Requires<ArgumentNullException>(authorizationEndpoint != null, "authorizationEndpoint");
+ }
+
+ /// <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>
+ /// <returns>A fully-qualified URL suitable to initiate the authorization flow.</returns>
+ public Uri RequestUserAuthorization(IEnumerable<string> scope = null) {
+ var authorization = new AuthorizationState(scope);
+ 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>
+ /// <returns>A fully-qualified URL suitable to initiate the authorization flow.</returns>
+ public Uri RequestUserAuthorization(IAuthorizationState authorization) {
+ Contract.Requires<ArgumentNullException>(authorization != null, "authorization");
+ Contract.Requires<InvalidOperationException>(!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,
+ };
+ 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) {
+ Contract.Requires<ArgumentNullException>(actualRedirectUrl != null, "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) {
+ this.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/WebServerClient.cs b/src/DotNetOpenAuth/OAuth2/WebServerClient.cs
new file mode 100644
index 0000000..091b022
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/WebServerClient.cs
@@ -0,0 +1,126 @@
+//-----------------------------------------------------------------------
+// <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>
+ /// <returns>The authorization request as an HTTP response that causes a redirect.</returns>
+ public OutgoingWebResponse RequestUserAuthorization(IEnumerable<string> scope = null) {
+ var response = this.PrepareRequestUserAuthorization(scope);
+ return this.Channel.PrepareResponse(response);
+ }
+
+ /// <summary>
+ /// Prepares a request for user authorization from an authorization server.
+ /// </summary>
+ /// <param name="scope">The scope of authorized access requested.</param>
+ /// <returns>The authorization request.</returns>
+ public EndUserAuthorizationRequest PrepareRequestUserAuthorization(IEnumerable<string> scopes = null) {
+ var authorizationState = new AuthorizationState(scopes);
+ return this.PrepareRequestUserAuthorization(authorizationState);
+ }
+
+ /// <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>
+ /// <returns>The authorization request.</returns>
+ public EndUserAuthorizationRequest PrepareRequestUserAuthorization(IAuthorizationState authorization) {
+ Contract.Requires<ArgumentNullException>(authorization != null);
+ Contract.Requires<InvalidOperationException>(authorization.Callback != null || (HttpContext.Current != null && HttpContext.Current.Request != null), MessagingStrings.HttpContextRequired);
+ Contract.Requires<InvalidOperationException>(!string.IsNullOrEmpty(this.ClientIdentifier));
+ Contract.Ensures(Contract.Result<EndUserAuthorizationRequest>() != null);
+ Contract.Ensures(Contract.Result<EndUserAuthorizationRequest>().ClientIdentifier == this.ClientIdentifier);
+ Contract.Ensures(Contract.Result<EndUserAuthorizationRequest>().Callback == authorization.Callback);
+
+ 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,
+ };
+ request.Scope.ResetContents(authorization.Scope);
+
+ return 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) {
+ Contract.Requires<InvalidOperationException>(!string.IsNullOrEmpty(this.ClientIdentifier));
+ Contract.Requires<InvalidOperationException>(!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) {
+ 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/OpenId/Behaviors/GsaIcamProfile.cs b/src/DotNetOpenAuth/OpenId/Behaviors/GsaIcamProfile.cs
index 20c207f..97a55c1 100644
--- a/src/DotNetOpenAuth/OpenId/Behaviors/GsaIcamProfile.cs
+++ b/src/DotNetOpenAuth/OpenId/Behaviors/GsaIcamProfile.cs
@@ -9,6 +9,7 @@ namespace DotNetOpenAuth.OpenId.Behaviors {
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;
@@ -34,6 +35,13 @@ namespace DotNetOpenAuth.OpenId.Behaviors {
private static readonly TimeSpan MaximumAssociationLifetime = TimeSpan.FromSeconds(86400);
/// <summary>
+ /// Initializes static members of the <see cref="GsaIcamProfile"/> class.
+ /// </summary>
+ static GsaIcamProfile() {
+ DisableSslRequirement = DotNetOpenAuthSection.Configuration.Messaging.RelaxSslRequirements;
+ }
+
+ /// <summary>
/// Initializes a new instance of the <see cref="GsaIcamProfile"/> class.
/// </summary>
public GsaIcamProfile() {
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/SimpleRegistration/Gender.cs b/src/DotNetOpenAuth/OpenId/Extensions/SimpleRegistration/Gender.cs
index 3cc47c6..979c481 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/SimpleRegistration/Gender.cs
+++ b/src/DotNetOpenAuth/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/Messages/DirectErrorResponse.cs b/src/DotNetOpenAuth/OpenId/Messages/DirectErrorResponse.cs
index ad20ff7..607a139 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/DirectErrorResponse.cs
+++ b/src/DotNetOpenAuth/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/version.txt b/src/version.txt
index 1cf8253..1545d96 100644
--- a/src/version.txt
+++ b/src/version.txt
@@ -1 +1 @@
-3.4.6
+3.5.0