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.html3419
-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/InMemoryClientTokenManager.cs53
-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.csproj19
-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.cs112
-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.cs56
-rw-r--r--samples/OAuthConsumerWpf/MainWindow.xaml322
-rw-r--r--samples/OAuthConsumerWpf/MainWindow.xaml.cs43
-rw-r--r--samples/OAuthConsumerWpf/OAuthConsumerWpf.csproj11
-rw-r--r--samples/OAuthServiceProvider/Code/Global.cs10
-rw-r--r--samples/OAuthServiceProvider/Code/OAuth2AuthorizationServer.cs60
-rw-r--r--samples/OAuthServiceProvider/Code/OAuthAuthorizationManager.cs58
-rw-r--r--samples/OAuthServiceProvider/Members/Authorize.aspx2
-rw-r--r--samples/OAuthServiceProvider/Members/Authorize2.aspx53
-rw-r--r--samples/OAuthServiceProvider/Members/Authorize2.aspx.cs53
-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.cs53
-rw-r--r--samples/OAuthServiceProvider/OAuthServiceProvider.csproj13
-rw-r--r--samples/OAuthServiceProvider/Web.config5
-rw-r--r--src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj5
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/MessageSerializerTests.cs31
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs15
-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/OAuthWrap/MessageFactoryTests.cs254
-rw-r--r--src/DotNetOpenAuth.Test/OAuthWrap/OAuthWrapChannelTests.cs21
-rw-r--r--src/DotNetOpenAuth.Test/OAuthWrap/OAuthWrapTestBase.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.csproj109
-rw-r--r--src/DotNetOpenAuth/Logger.cs10
-rw-r--r--src/DotNetOpenAuth/Messaging/Bindings/ExpiredMessageException.cs1
-rw-r--r--src/DotNetOpenAuth/Messaging/Channel.cs109
-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.cs20
-rw-r--r--src/DotNetOpenAuth/Messaging/MessagingStrings.resx6
-rw-r--r--src/DotNetOpenAuth/Messaging/MessagingUtilities.cs382
-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.cs24
-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.cs40
-rw-r--r--src/DotNetOpenAuth/OAuth/ChannelElements/OAuthPrincipal.cs18
-rw-r--r--src/DotNetOpenAuth/OAuth/Protocol.cs2
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/AuthorizationServerBase.cs85
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/AuthorizationServerDescription.cs62
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/AuthorizationState.cs96
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/ChannelElements/AccessRequestBindingElement.cs119
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/ChannelElements/AccessToken.cs90
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/ChannelElements/AuthServerAllFlowsBindingElement.cs83
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/ChannelElements/AuthServerBindingElementBase.cs92
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/ChannelElements/AuthorizationDataBag.cs73
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/ChannelElements/DataBag.cs343
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/ChannelElements/IAccessTokenRequest.cs36
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/ChannelElements/IAuthorizationDescription.cs87
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/ChannelElements/ITokenCarryingRequest.cs52
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/ChannelElements/OAuthWrapAuthorizationServerChannel.cs201
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/ChannelElements/OAuthWrapResourceServerChannel.cs152
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/ChannelElements/RefreshToken.cs63
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/ChannelElements/TimestampEncoder.cs61
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/ChannelElements/VerificationCode.cs115
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/ChannelElements/WebServerVerificationCodeBindingElement.cs93
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/ClientBase.cs177
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/IAccessTokenAnalyzer.cs59
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/IAuthorizationServer.cs170
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/IAuthorizationState.cs78
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/IClientTokenManager.cs53
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/AccessProtectedResourceRequest.cs119
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/AccessTokenFailedResponse.cs38
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/AccessTokenSuccessResponse.cs91
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/Assertion/AssertionRequest.cs114
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/ClientCredentials/ClientCredentialsRequest.cs95
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/Device/DeviceAccessTokenRequest.cs116
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/Device/DeviceRequest.cs79
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/Device/DeviceResponse.cs76
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/IAccessTokenSuccessResponse.cs48
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/IMessageWithClientState.cs21
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/IOAuthDirectResponseFormat.cs23
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/IRequestWithRedirectUri.cs29
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/MessageBase.cs209
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/RefreshAccessTokenRequest.cs116
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/ResponseFormat.cs27
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/ResponseFormatEncoder.cs71
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/UnauthorizedResponse.cs104
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/UserAgent/UserAgentFailedResponse.cs53
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/UserAgent/UserAgentRequest.cs100
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/UserAgent/UserAgentSuccessResponse.cs88
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordCaptchaResponse.cs54
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordFailedResponse.cs22
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordRequest.cs150
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordSuccessResponse.cs51
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordVerificationResponse.cs55
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebServerAccessTokenRequest.cs148
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebServerFailedResponse.cs59
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebServerRequest.cs107
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebServerSuccessResponse.cs78
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/OAuthWrapStrings.Designer.cs108
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/OAuthWrapStrings.resx135
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Protocol.cs245
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/ResourceServer.cs101
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/StandardAccessTokenAnalyzer.cs55
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/UserAgentClient.cs100
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/WebServerAuthorizationServer.cs137
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/WebServerClient.cs122
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/WrapUtilities.cs55
-rw-r--r--src/DotNetOpenAuth/OpenId/Behaviors/GsaIcamProfile.cs8
-rw-r--r--src/DotNetOpenAuth/OpenId/Messages/DirectErrorResponse.cs8
-rw-r--r--src/version.txt2
134 files changed, 12739 insertions, 313 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..a594581
--- /dev/null
+++ b/doc/specs/draft-ietf-oauth.html
@@ -0,0 +1,3419 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+<html lang="en"><head><title>The OAuth 2.0 Protocol</title>
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+<meta name="description" content="The OAuth 2.0 Protocol">
+<meta name="generator" content="xml2rfc v1.35 (http://xml.resource.org/)">
+<style type='text/css'><!--
+ body {
+ font-family: verdana, charcoal, helvetica, arial, sans-serif;
+ font-size: small; 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: small; 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: small; 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: small; 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"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<table summary="layout" width="66%" border="0" cellpadding="0" cellspacing="0"><tr><td><table summary="layout" width="100%" border="0" cellpadding="2" cellspacing="1">
+<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">Intended status: Standards Track</td><td class="header">D. Recordon</td></tr>
+<tr><td class="header">Expires: October 23, 2010</td><td class="header">Facebook</td></tr>
+<tr><td class="header">&nbsp;</td><td class="header">D. Hardt</td></tr>
+<tr><td class="header">&nbsp;</td><td class="header">April 21, 2010</td></tr>
+</table></td></tr></table>
+<h1><br />The OAuth 2.0 Protocol<br />draft-ietf-oauth-00</h1>
+
+<h3>Abstract</h3>
+
+<p>
+ This specification describes the OAuth 2.0 protocol. OAuth provides a method for making
+ authenticated HTTP requests using a token - an identifier used to denote an access grant
+ with specific scope, duration, and other attributes. Tokens are issued to third-party
+ clients by an authorization server with the approval of the resource owner. OAuth defines
+ multiple flows for obtaining a token to support a wide range of client types and user
+ experience.
+
+</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 &ldquo;work in progress.&rdquo;</p>
+<p>
+This Internet-Draft will expire on October 23, 2010.</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="#anchor1">1.</a>&nbsp;
+Authors<br />
+<a href="#anchor2">2.</a>&nbsp;
+Introduction<br />
+&nbsp;&nbsp;&nbsp;&nbsp;<a href="#anchor3">2.1.</a>&nbsp;
+Terminology<br />
+&nbsp;&nbsp;&nbsp;&nbsp;<a href="#anchor4">2.2.</a>&nbsp;
+Overview<br />
+&nbsp;&nbsp;&nbsp;&nbsp;<a href="#anchor5">2.3.</a>&nbsp;
+Example<br />
+&nbsp;&nbsp;&nbsp;&nbsp;<a href="#anchor6">2.4.</a>&nbsp;
+Notational Conventions<br />
+&nbsp;&nbsp;&nbsp;&nbsp;<a href="#anchor7">2.5.</a>&nbsp;
+Conformance<br />
+<a href="#get_token">3.</a>&nbsp;
+Obtaining an Access Token<br />
+&nbsp;&nbsp;&nbsp;&nbsp;<a href="#anchor8">3.1.</a>&nbsp;
+Authorization Endpoint<br />
+&nbsp;&nbsp;&nbsp;&nbsp;<a href="#anchor9">3.2.</a>&nbsp;
+Token Endpoint<br />
+&nbsp;&nbsp;&nbsp;&nbsp;<a href="#anchor10">3.3.</a>&nbsp;
+Flow Parameters<br />
+&nbsp;&nbsp;&nbsp;&nbsp;<a href="#client_id">3.4.</a>&nbsp;
+Client Credentials<br />
+&nbsp;&nbsp;&nbsp;&nbsp;<a href="#anchor11">3.5.</a>&nbsp;
+User Delegation Flows<br />
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#user_agent_flow">3.5.1.</a>&nbsp;
+User-Agent Flow<br />
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#web_server_flow">3.5.2.</a>&nbsp;
+Web Server Flow<br />
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#device_flow">3.5.3.</a>&nbsp;
+Device Flow<br />
+&nbsp;&nbsp;&nbsp;&nbsp;<a href="#anchor24">3.6.</a>&nbsp;
+End User Credentials Flows<br />
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#username_password_flow">3.6.1.</a>&nbsp;
+Username and Password Flow<br />
+&nbsp;&nbsp;&nbsp;&nbsp;<a href="#anchor26">3.7.</a>&nbsp;
+Autonomous Client Flows<br />
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#client_credentials_flow">3.7.1.</a>&nbsp;
+Client Credentials Flow<br />
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#assertion_flow">3.7.2.</a>&nbsp;
+Assertion Flow<br />
+<a href="#token_refresh">4.</a>&nbsp;
+Refreshing an Access Token<br />
+<a href="#access_resource">5.</a>&nbsp;
+Accessing a Protected Resource<br />
+&nbsp;&nbsp;&nbsp;&nbsp;<a href="#authz_header">5.1.</a>&nbsp;
+The Authorization Request Header<br />
+&nbsp;&nbsp;&nbsp;&nbsp;<a href="#bearer_token">5.2.</a>&nbsp;
+Bearer Token Requests<br />
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#query_param">5.2.1.</a>&nbsp;
+URI Query Parameter<br />
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#body_param">5.2.2.</a>&nbsp;
+Form-Encoded Body Parameter<br />
+&nbsp;&nbsp;&nbsp;&nbsp;<a href="#crypto_token">5.3.</a>&nbsp;
+Cryptographic Tokens Requests<br />
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#hmac-sha256">5.3.1.</a>&nbsp;
+The 'hmac-sha256' Algorithm<br />
+<a href="#anchor29">6.</a>&nbsp;
+Identifying a Protected Resource<br />
+&nbsp;&nbsp;&nbsp;&nbsp;<a href="#authn_header">6.1.</a>&nbsp;
+The WWW-Authenticate Response Header<br />
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#anchor30">6.1.1.</a>&nbsp;
+The 'realm' Attribute<br />
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#authz_uri_attribute">6.1.2.</a>&nbsp;
+The 'authorization-uri' Attribute<br />
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#anchor31">6.1.3.</a>&nbsp;
+The 'algorithms' Attribute<br />
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#anchor32">6.1.4.</a>&nbsp;
+The 'error' Attribute<br />
+<a href="#anchor33">7.</a>&nbsp;
+Security Considerations<br />
+<a href="#anchor34">8.</a>&nbsp;
+IANA Considerations<br />
+<a href="#anchor35">9.</a>&nbsp;
+Acknowledgements<br />
+<a href="#anchor36">Appendix&nbsp;A.</a>&nbsp;
+Differences from OAuth 1.0a<br />
+<a href="#anchor37">Appendix&nbsp;B.</a>&nbsp;
+Document History<br />
+<a href="#rfc.references1">10.</a>&nbsp;
+References<br />
+&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rfc.references1">10.1.</a>&nbsp;
+Normative References<br />
+&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rfc.references2">10.2.</a>&nbsp;
+Informative References<br />
+<a href="#rfc.authors">&#167;</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"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.1"></a><h3>1.&nbsp;
+Authors</h3>
+
+<p>
+ This specification was authored with the participation and based on the work of
+ Allen Tom (Yahoo!), Brian Eaton (Google), Brent Goldman (Facebook), Luke Shepard
+ (Facebook), Raffi Krikorian (Twitter), and Yaron Goland (Microsoft).
+
+</p>
+<a name="anchor2"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.2"></a><h3>2.&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). In the traditional client-server authentication model, a client
+ accessing a protected resource on a server presents the resource owner's credentials in
+ order to authenticate and gain access.
+
+</p>
+<p>
+ Resource owners should not be required to share their credentials when granting third-party
+ applications access to their protected resources. They should also have the ability to
+ restrict access to a limited subset of the resources they control, to limit access
+ duration, or to limit access to the methods supported by these resources.
+
+</p>
+<p>
+ OAuth provides a method for making authenticated HTTP requests using a token - an
+ identifier used to denote an access grant with specific scope, duration, and other
+ attributes. Tokens are issued to third-party clients by an authorization server with the
+ approval of the resource owner. Instead of sharing their credentials with the client,
+ resource owners grant access by authenticating directly with the authorization server which
+ in turn issues a token to the client. The client uses the token (and optional secret) to
+ authenticate with the resource server and gain access.
+
+</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 the photo sharing service (authorization server) which issues the printing service
+ delegation-specific credentials (token).
+
+</p>
+<p>
+ The use of OAuth with any other transport protocol than <a class='info' href='#RFC2616'>HTTP<span> (</span><span class='info'>Fielding, R., Gettys, J., Mogul, J., Frystyk, H., Masinter, L., Leach, P., and T. Berners-Lee, &ldquo;Hypertext Transfer Protocol -- HTTP/1.1,&rdquo; June&nbsp;1999.</span><span>)</span></a> [RFC2616]
+ (or HTTP over TLS 1.0 as defined by <a class='info' href='#RFC2818'>[RFC2818]<span> (</span><span class='info'>Rescorla, E., &ldquo;HTTP Over TLS,&rdquo; May&nbsp;2000.</span><span>)</span></a> is undefined.
+
+</p>
+<a name="anchor3"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.2.1"></a><h3>2.1.&nbsp;
+Terminology</h3>
+
+<p>
+ </p>
+<blockquote class="text"><dl>
+<dt>resource server</dt>
+<dd>
+
+ An <a class='info' href='#RFC2616'>HTTP<span> (</span><span class='info'>Fielding, R., Gettys, J., Mogul, J., Frystyk, H., Masinter, L., Leach, P., and T. Berners-Lee, &ldquo;Hypertext Transfer Protocol -- HTTP/1.1,&rdquo; June&nbsp;1999.</span><span>)</span></a> [RFC2616] server capable of accepting authenticated
+ resource requests using the OAuth protocol.
+
+</dd>
+<dt>protected resource</dt>
+<dd>
+
+ An access-restricted resource which can be obtained from a resource server using
+ an OAuth-authenticated request.
+
+</dd>
+<dt>client</dt>
+<dd>
+
+ An HTTP client capable of making authenticated requests for protected resources using
+ the OAuth protocol.
+
+</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>access token</dt>
+<dd>
+
+ A unique identifier used by the client to make authenticated requests on behalf of
+ the resource owner. Access tokens may have a matching secret.
+
+</dd>
+<dt>authorization server</dt>
+<dd>
+
+ An HTTP 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>authorization endpoint</dt>
+<dd>
+
+ The authorization server's HTTP endpoint capable of authenticating the resource
+ owner and obtaining authorization.
+
+</dd>
+<dt>token endpoint</dt>
+<dd>
+
+ The authorization server's HTTP endpoint capable of issuing tokens and refreshing
+ expired tokens.
+
+</dd>
+<dt>client identifier</dt>
+<dd>
+
+ An unique identifier issued to the client to identify itself to the authorization
+ server. Client identifiers may have a matching secret.
+
+</dd>
+<dt>refresh token</dt>
+<dd>
+
+ A unique identifier used by the client to replace an expired access token with a new
+ access token without having to involve the resource owner. A refresh token is used
+ when the access token is valid for a shorter time period than the duration of the
+ access grant approved by the resource owner.
+
+</dd>
+</dl></blockquote><p>
+
+</p>
+<a name="anchor4"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.2.2"></a><h3>2.2.&nbsp;
+Overview</h3>
+
+<p>
+ Clients interact with a protected resource, first by requesting access (which is granted
+ in the form of an access token) from the authorization server, and then by authenticating
+ with the resource server by presenting the access token. <a class='info' href='#Figure 1'>Figure&nbsp;1</a>
+ demonstrates the flow between the client and authorization server (A, B), and the flow
+ between the client and resource server (C, D), when the client is acting autonomously
+ (the client is also the resource owner).
+
+</p><br /><hr class="insert" />
+<a name="Figure 1"></a>
+<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
+ +--------+ +---------------+
+ | |--(A)------ Credentials ---------&gt;| Authorization |
+ | | | Server |
+ | |&lt;-(B)------ Access Token ---------| |
+ | | (w/ Optional Refresh Token) +---------------+
+ | Client |
+ | | HTTP Request +---------------+
+ | |--(C)--- with Access Token ------&gt;| Resource |
+ | | | Server |
+ | |&lt;-(D)------ HTTP Response --------| |
+ +--------+ +---------------+
+
+</pre></div><table border="0" cellpadding="0" cellspacing="2" align="center"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;Figure&nbsp;1&nbsp;</b></font><br /></td></tr></table><hr class="insert" />
+
+<p>
+ Access token strings can use any internal structure agreed upon between the authorization
+ server and the resource server, but their structure is opaque to the client. Since the
+ access token provides the client access to the protected resource for the life of the
+ access token (or until revoked), the authorization server should issue access tokens
+ which expire within an appropriate time, usually much shorter than the duration of the
+ access grant.
+
+</p>
+<p>
+ When an access token expires, the client can request a new access token from the
+ authorization server by presenting its credentials again (<a class='info' href='#Figure 1'>Figure&nbsp;1</a>), or
+ by using the refresh token (if issued with the access token) as shown in
+ <a class='info' href='#Figure 2'>Figure&nbsp;2</a>. Once an expired access token has been replaced with a new
+ access token (A, B), the client uses the new access token as before (C, D).
+
+</p><br /><hr class="insert" />
+<a name="Figure 2"></a>
+<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
+ +--------+ +---------------+
+ | |--(A)------ Refresh Token -------&gt;| Authorization |
+ | | | Server |
+ | |&lt;-(B)------ Access Token ---------| |
+ | | (with Optional Secret) +---------------+
+ | Client |
+ | | HTTP Request +---------------+
+ | |--(C)--- with Access Token ------&gt;| Resource |
+ | | | Server |
+ | |&lt;-(D)----- HTTP Response ---------| |
+ +--------+ +---------------+
+
+</pre></div><table border="0" cellpadding="0" cellspacing="2" align="center"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;Figure&nbsp;2&nbsp;</b></font><br /></td></tr></table><hr class="insert" />
+
+<p>
+ This specification defines a number of authorization flows to support different client
+ types and scenarios. These authorization flows can be separated into three groups:
+ user delegation flows where the client is acting on behalf of an end user, end user
+ credentials flows where the client uses the end user's credentials directly to obtain
+ authorization, and autonomous flows where the client is acting for itself (the client is
+ also the resource owner).
+
+</p>
+<p>
+ Additional authorization flows may be defined by other specifications to cover different
+ scenarios and client types.
+
+</p>
+<p>
+ The user delegation authorization flows defined by this specifications are:
+
+ </p>
+<ul class="text">
+<li>
+ User-Agent Flow - This flow is designed for clients running inside a user-agent
+ (typically a web browser), and therefore cannot receive incoming requests from the
+ authorization server. This flow is described in <a class='info' href='#user_agent_flow'>Section&nbsp;3.5.1<span> (</span><span class='info'>User-Agent Flow</span><span>)</span></a>.
+
+</li>
+<li>
+ Web Server Flow - This flow is optimized for cases where the client is capable of
+ receiving incoming HTTP requests (act as an HTTP server). This flow is described in
+ <a class='info' href='#web_server_flow'>Section&nbsp;3.5.2<span> (</span><span class='info'>Web Server Flow</span><span>)</span></a>.
+
+</li>
+<li>
+ Device Flow - This flow suitable for clients executing on limited devices, but where
+ the end user has separate access to a user-agent on another computer or device. This
+ flow is described in <a class='info' href='#device_flow'>Section&nbsp;3.5.3<span> (</span><span class='info'>Device Flow</span><span>)</span></a>.
+
+</li>
+</ul><p>
+
+</p>
+<p>
+ The end user credentials flow defined by this specification is:
+
+ </p>
+<ul class="text">
+<li>
+ Username and Password Flow - This flow is used in cases where the end user trusts
+ the client to handle its credentials but it is still undesirable for the client to
+ store the end user's username and password. This flow is described in
+ <a class='info' href='#username_password_flow'>Section&nbsp;3.6.1<span> (</span><span class='info'>Username and Password Flow</span><span>)</span></a>.
+
+</li>
+</ul><p>
+
+</p>
+<p>
+ The autonomous authorization flows defined by this specifications are:
+
+ </p>
+<ul class="text">
+<li>
+ Client Credentials Flow - The client uses its credentials to obtain an access token.
+ This flow is described in <a class='info' href='#client_credentials_flow'>Section&nbsp;3.7.1<span> (</span><span class='info'>Client Credentials Flow</span><span>)</span></a>.
+
+</li>
+<li>
+ Assertion Flow - The client presents an assertion such as a
+ <a class='info' href='#OASIS.saml-core-2.0-os'>SAML<span> (</span><span class='info'>Cantor, S., Kemp, J., Philpott, R., and E. Maler, &ldquo;Assertions and Protocol for the OASIS Security Assertion Markup Language (SAML) V2.0,&rdquo; March&nbsp;2005.</span><span>)</span></a> [OASIS.saml&#8209;core&#8209;2.0&#8209;os] assertion to the authorization
+ server in exchange for an access token. This flow is described in
+ <a class='info' href='#assertion_flow'>Section&nbsp;3.7.2<span> (</span><span class='info'>Assertion Flow</span><span>)</span></a>.
+
+</li>
+</ul><p>
+
+</p>
+<a name="anchor5"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.2.3"></a><h3>2.3.&nbsp;
+Example</h3>
+
+<p>
+ [[ Todo ]]
+
+</p>
+<a name="anchor6"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.2.4"></a><h3>2.4.&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='#RFC2119'>[RFC2119]<span> (</span><span class='info'>Bradner, S., &ldquo;Key words for use in RFCs to Indicate Requirement Levels,&rdquo; March&nbsp;1997.</span><span>)</span></a>.
+
+</p>
+<p>
+ This document uses the Augmented Backus-Naur Form (ABNF) notation of
+ <a class='info' href='#I-D.ietf-httpbis-p1-messaging'>[I&#8209;D.ietf&#8209;httpbis&#8209;p1&#8209;messaging]<span> (</span><span class='info'>Fielding, R., Gettys, J., Mogul, J., Nielsen, H., Masinter, L., Leach, P., Berners-Lee, T., and J. Reschke, &ldquo;HTTP/1.1, part 1: URIs, Connections, and Message Parsing,&rdquo; March&nbsp;2010.</span><span>)</span></a>. Additionally, the realm and auth-param
+ rules are included from <a class='info' href='#RFC2617'>[RFC2617]<span> (</span><span class='info'>Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P., Luotonen, A., and L. Stewart, &ldquo;HTTP Authentication: Basic and Digest Access Authentication,&rdquo; June&nbsp;1999.</span><span>)</span></a>, and the URI-Reference rule from
+ <a class='info' href='#RFC3986'>[RFC3986]<span> (</span><span class='info'>Berners-Lee, T., Fielding, R., and L. Masinter, &ldquo;Uniform Resource Identifier (URI): Generic Syntax,&rdquo; January&nbsp;2005.</span><span>)</span></a>.
+
+</p>
+<a name="anchor7"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.2.5"></a><h3>2.5.&nbsp;
+Conformance</h3>
+
+<p>
+ An implementation is not compliant if it fails to satisfy one or more of the MUST or
+ REQUIRED level requirements for the flows it implements. An implementation that
+ satisfies all the MUST or REQUIRED level and all the SHOULD level requirements for its
+ flows is said to be "unconditionally compliant"; one that satisfies all the MUST
+ level requirements but not all the SHOULD level requirements for its flows is said to
+ be "conditionally compliant."
+
+</p>
+<a name="get_token"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3"></a><h3>3.&nbsp;
+Obtaining an Access Token</h3>
+
+<p>
+ The client obtains an access token by using one of the authorization flows supported by the
+ authorization server. The authorization flows all use the same authorization and token
+ endpoints, each with a different set of request parameters and values.
+
+</p>
+<p>
+ When issuing an access token, the scope, duration, and other access attributes granted by
+ the resource owner must be retained and enforced by the resource server when receiving a
+ protected resource request and by the authorization server when receiving a token refresh
+ request made with the access token issued.
+
+</p>
+<p>
+ In many cases it is desirable to issue access tokens with a shorter lifetime than the
+ duration of the authorization grant. However, it may be undesirable to require the resource
+ owner to authorize the request again. Instead, the authorization server issues a refresh
+ token in addition to the access token. When the access token expires, the client can
+ request a new access token without involving the resource owner as long as the
+ authorization grant is still valid. The token refresh method is described in
+ <a class='info' href='#token_refresh'>Section&nbsp;4<span> (</span><span class='info'>Refreshing an Access Token</span><span>)</span></a>.
+
+</p>
+<a name="anchor8"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.1"></a><h3>3.1.&nbsp;
+Authorization Endpoint</h3>
+
+<p>
+ Clients direct the resource owner to the authorization endpoint to approve their access
+ request. Before granting access, the resource owner first authenticate 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.
+
+</p>
+<p>
+ 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
+ <tt>WWW-Authenticate</tt> response header
+ <a class='info' href='#authz_uri_attribute'>auth-uri<span> (</span><span class='info'>The 'authorization-uri' Attribute</span><span>)</span></a> attribute).
+
+</p>
+<p>
+ The authorization endpoint advertised by the resource server MAY include a query
+ components as defined by <a class='info' href='#RFC3986'>[RFC3986]<span> (</span><span class='info'>Berners-Lee, T., Fielding, R., and L. Masinter, &ldquo;Uniform Resource Identifier (URI): Generic Syntax,&rdquo; January&nbsp;2005.</span><span>)</span></a> section 3.
+
+</p>
+<p>
+ 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 or SSL (or a secure channel with
+ equivalent protections) when sending requests to the authorization endpoints.
+
+</p>
+<a name="anchor9"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.2"></a><h3>3.2.&nbsp;
+Token Endpoint</h3>
+
+<p>
+ After obtaining authorization from the resource owner, clients request an access token
+ from the authorization server's token endpoint.
+
+</p>
+<p>
+ 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
+ <tt>WWW-Authenticate</tt> response header
+ <a class='info' href='#authz_uri_attribute'>token-uri<span> (</span><span class='info'>The 'authorization-uri' Attribute</span><span>)</span></a> attribute).
+
+</p>
+<p>
+ The token endpoint advertised by the resource server MAY include a query components as
+ defined by <a class='info' href='#RFC3986'>[RFC3986]<span> (</span><span class='info'>Berners-Lee, T., Fielding, R., and L. Masinter, &ldquo;Uniform Resource Identifier (URI): Generic Syntax,&rdquo; January&nbsp;2005.</span><span>)</span></a> section 3.
+
+</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 mechanism such as TLS or SSL (or a secure channel with
+ equivalent protections) when sending requests to the token endpoints.
+
+</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>
+<a name="anchor10"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.3"></a><h3>3.3.&nbsp;
+Flow Parameters</h3>
+
+<p>
+ Clients should avoid making assumptions about the size of tokens and other values
+ received from the authorization server, which are left undefined by this specification.
+ Servers should document the expected size of any value they issue.
+
+</p>
+<a name="client_id"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.4"></a><h3>3.4.&nbsp;
+Client Credentials</h3>
+
+<p>
+ When requesting access from the authorization server, the client identifies itself using
+ its authorization-server-issued client credentials. The client credentials include a
+ client identifier and an OPTIONAL symmetric shared secret. The means through which the
+ client obtains these credentials are beyond the scope of this specification, but usually
+ involve registration with the authorization server.
+
+</p>
+<p>
+ The client identifier is used by the authorization server to establish the identity of
+ the client for the purpose of presenting information to the resource owner prior to
+ granting access, as well as for providing different service levels to different clients.
+ They can also be used to block unauthorized clients from requesting access.
+
+</p>
+<p>
+ Due to the nature of some clients, authorization servers SHOULD NOT make assumptions
+ about the confidentiality of client credentials without establishing trust with the
+ client operator. Authorization servers SHOULD NOT issue client secrets to the client
+ incapable or keeping their secrets confidential.
+
+</p>
+<a name="anchor11"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.5"></a><h3>3.5.&nbsp;
+User Delegation Flows</h3>
+
+<p>
+ User delegation flows are used to grant client access to protected resources by the end
+ user without sharing the end user credentials (e.g. a username and password) with the
+ client. Instead, the end user authenticates directly with the authorization server, and
+ grants client access to its protected resources.
+
+</p>
+<a name="user_agent_flow"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.5.1"></a><h3>3.5.1.&nbsp;
+User-Agent Flow</h3>
+
+<p>
+ The user-agent flow is a user delegation flow suitable for client applications residing
+ in a user-agent, typically implemented in a browser using a scripting language such as
+ JavaScript. The client is capable of interacting with the end user's user-agent but is
+ incapable of receiving incoming requests from the authorization server (incapable of
+ acting as an HTTP server).
+
+</p>
+<p>
+ Instead of receiving incoming requests, the client requests the authorization server to
+ redirect the user-agent to another web server or local resource accessible to the
+ browser which is capable of extracting the access token from the response and passing
+ it to the client.
+
+</p>
+<p>
+ This user-agent flow 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 client is incapable of receiving incoming requests, the
+ access token is encoded into the redirection URI which exposes it 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 | (w/ Optional Refresh Token) +----------------+
+ | Browser | in Fragment
+ | | +----------------+
+ | |&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"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;Figure&nbsp;3&nbsp;</b></font><br /></td></tr></table><hr class="insert" />
+
+<p>
+ The user-agent flow illustrated in <a class='info' href='#Figure 5'>Figure&nbsp;3</a> includes the following
+ steps:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>(A)</dt>
+<dd>
+ The client sends the user-agent to the authorization server and includes its client
+ identifier and redirection URI in the request.
+
+</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 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 containing a script capable of extracting the
+ access token from the URI fragment retained by the user-agent.
+
+</dd>
+<dt>(F)</dt>
+<dd>
+ The user-agent executes the script provided by the web server which extracts the
+ access token and passes it to the client.
+
+</dd>
+</dl></blockquote><p>
+
+</p>
+<a name="anchor12"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.5.1.1"></a><h3>3.5.1.1.&nbsp;
+Client Requests Authorization</h3>
+
+<p>
+ In order for the end user to grant the client access, the client sends the end user
+ to the authorization server. The client constructs the request URI by adding the
+ following URI query parameters to the user authorization endpoint URI:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>type</dt>
+<dd>
+
+ REQUIRED. The parameter value MUST be set to
+ <tt>user_agent</tt> (case sensitive).
+
+</dd>
+<dt>client_id</dt>
+<dd>
+
+ REQUIRED. The client identifier as described in <a class='info' href='#client_id'>Section&nbsp;3.4<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 SOULD require the client to pre-register
+ their redirection URI. The redirection URI MUST NOT includes a query component
+ as defined by <a class='info' href='#RFC3986'>[RFC3986]<span> (</span><span class='info'>Berners-Lee, T., Fielding, R., and L. Masinter, &ldquo;Uniform Resource Identifier (URI): Generic Syntax,&rdquo; January&nbsp;2005.</span><span>)</span></a> section 3 if the
+ <tt>state</tt> parameter is present.
+
+</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>
+<dt>immediate</dt>
+<dd>
+
+ OPTIONAL. The parameter value must be set to <tt>true</tt> or
+ <tt>false</tt> (case sensitive). If set to
+ <tt>true</tt>, the authorization server MUST NOT prompt the
+ end user to authenticate or approve access. Instead, the authorization server
+ attempts to establish the end user's identity via other means (e.g. browser
+ cookies) and checks if the end user has previously approved an identical access
+ request by the same client and if that access grant is still active. If the
+ authorization server does not support an immediate check or if it is unable to
+ establish the end user's identity or approval status, it MUST deny the request
+ without prompting the end user. Defaults to <tt>false</tt> if
+ omitted.
+
+</dd>
+<dt>secret_type</dt>
+<dd>
+
+ OPTIONAL. The access token secret type as described by
+ <a class='info' href='#crypto_token'>Section&nbsp;5.3<span> (</span><span class='info'>Cryptographic Tokens Requests</span><span>)</span></a>. If omitted, the authorization server will issue a
+ bearer token (an access token without a matching secret) as described by
+ <a class='info' href='#bearer_token'>Section&nbsp;5.2<span> (</span><span class='info'>Bearer Token Requests</span><span>)</span></a>.
+
+</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
+ request MUST use the HTTP <tt>GET</tt> method.
+
+</p>
+<p>
+ For example, the client directs the end user's user-agent to make the following
+ HTTPS request (line breaks are for display purposes only):
+
+</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
+ GET /authorize?type=user_agent&amp;client_id=s6BhdRkqt3&amp;
+ redirect_uri=https%3A%2F%2FEexample%2Ecom%2Frd 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.
+
+</p>
+<p>
+ The authorization server authenticates the end user and obtains an authorization
+ decision (by asking the end user or establishing approval via other means). The
+ authorization server sends the end user's user-agent to the provided client
+ redirection URI using an HTTP redirection response.
+
+</p>
+<a name="anchor13"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.5.1.1.1"></a><h3>3.5.1.1.1.&nbsp;
+End User Grants Authorization</h3>
+
+<p>
+ If the end user authorizes the access request, the authorization server issues an
+ access token and delivers it to the client by adding the following parameters, using
+ the <tt>application/x-www-form-urlencoded</tt> format as defined
+ by <a class='info' href='#W3C.REC-html40-19980424'>[W3C.REC&#8209;html40&#8209;19980424]<span> (</span><span class='info'>Hors, A., Jacobs, I., and D. Raggett, &ldquo;HTML 4.0 Specification,&rdquo; April&nbsp;1998.</span><span>)</span></a>, to the redirection URI fragment:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>access_token</dt>
+<dd>
+
+ REQUIRED. The access token.
+
+</dd>
+<dt>expires_in</dt>
+<dd>
+
+ OPTIONAL. The duration in seconds of the access token lifetime.
+
+</dd>
+<dt>refresh_token</dt>
+<dd>
+
+ OPTIONAL. The refresh token.
+
+</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>
+<dt>access_token_secret</dt>
+<dd>
+
+ REQUIRED if requested by the client. The corresponding access token secret as
+ requested by 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: http://example.com/rd#access_token=FJQbwq9&amp;expires_in=3600
+
+</pre></div>
+<a name="anchor14"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.5.1.1.2"></a><h3>3.5.1.1.2.&nbsp;
+End User Denies Authorization</h3>
+
+<p>
+ If the end user denied the access request, the authorization server responds to the
+ client by adding the following parameters, using the
+ <tt>application/x-www-form-urlencoded</tt> format as defined by
+ <a class='info' href='#W3C.REC-html40-19980424'>[W3C.REC&#8209;html40&#8209;19980424]<span> (</span><span class='info'>Hors, A., Jacobs, I., and D. Raggett, &ldquo;HTML 4.0 Specification,&rdquo; April&nbsp;1998.</span><span>)</span></a>, to the redirection URI fragment:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>error</dt>
+<dd>
+
+ REQUIRED. The parameter value MUST be set to
+ <tt>user_denied</tt> (case sensitive).
+
+</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 responds with the following:
+
+</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
+ HTTP/1.1 302 Found
+ Location: http://example.com/rd#error=user_denied
+
+</pre></div>
+<p>
+ The authorization flow concludes unsuccessfully. To extract the error message, the
+ client follows the steps described in <a class='info' href='#user_agent_extract'>Section&nbsp;3.5.1.2<span> (</span><span class='info'>Client Extracts Access Token</span><span>)</span></a>.
+
+</p>
+<a name="user_agent_extract"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.5.1.2"></a><h3>3.5.1.2.&nbsp;
+Client Extracts Access Token</h3>
+
+<p>
+ The user-agent follows the authorization server redirection response by making an
+ HTTP <tt>GET</tt> request to the URI received in the
+ <tt>Location</tt> HTTP response header. The user-agent SHALL NOT
+ include the fragment component with the request.
+
+</p>
+<p>
+ For example, the user-agent makes the following HTTP
+ <tt>GET</tt> request in response to the redirection directive
+ received from the authorization server:
+
+</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
+ GET /rd HTTP/1.1
+ Host: example.com
+
+</pre></div>
+<p>
+ The HTTP response to the redirection request 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.
+
+</p>
+<a name="web_server_flow"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.5.2"></a><h3>3.5.2.&nbsp;
+Web Server Flow</h3>
+
+<p>
+ The web server flow is a user delegation flow 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 3"></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)-- Verification Code ----&lt;| |
+ +-|----|---+ +---------------+
+ | | ^ v
+ (A) (C) | |
+ | | | |
+ ^ v | |
+ +---------+ | |
+ | |&gt;---(D)-- Client Credentials, --------' |
+ | Web | Verification Code, |
+ | Client | &amp; Redirect URI |
+ | | |
+ | |&lt;---(E)------- Access Token -----------------'
+ +---------+ (w/ Optional Refresh Token)
+
+</pre></div><table border="0" cellpadding="0" cellspacing="2" align="center"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;Figure&nbsp;4&nbsp;</b></font><br /></td></tr></table><hr class="insert" />
+
+<p>
+ The web server flow illustrated in <a class='info' href='#Figure 3'>Figure&nbsp;4</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
+ authorization endpoint with its client identifier and a redirect URI to which the
+ authorization server will send the end user back once authorization is received (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 a verification 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 including its
+ client credentials (identifier and secret), as well as the verification code
+ received in the previous step.
+
+</dd>
+<dt>(E)</dt>
+<dd>
+ The authorization server validates the client credentials and the verification
+ code and responds back with the access token.
+
+</dd>
+</dl></blockquote><p>
+
+</p>
+<a name="anchor15"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.5.2.1"></a><h3>3.5.2.1.&nbsp;
+Client Requests Authorization</h3>
+
+<p>
+ In order for the end user to grant the client access, the client sends the end user
+ to the authorization server. The client constructs the request URI by adding the
+ following URI query parameters to the user authorization endpoint URI:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>type</dt>
+<dd>
+
+ REQUIRED. The parameter value MUST be set to
+ <tt>web_server</tt> (case sensitive).
+
+</dd>
+<dt>client_id</dt>
+<dd>
+
+ REQUIRED. The client identifier as described in <a class='info' href='#client_id'>Section&nbsp;3.4<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 MAY require the client to pre-register
+ their redirection URI. The redirection URI MUST NOT includes a query component
+ as defined by <a class='info' href='#RFC3986'>[RFC3986]<span> (</span><span class='info'>Berners-Lee, T., Fielding, R., and L. Masinter, &ldquo;Uniform Resource Identifier (URI): Generic Syntax,&rdquo; January&nbsp;2005.</span><span>)</span></a> section 3 if the
+ <tt>state</tt> parameter is present.
+
+</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>
+<dt>immediate</dt>
+<dd>
+
+ OPTIONAL. The parameter value must be set to <tt>true</tt> or
+ <tt>false</tt> (case sensitive). If set to
+ <tt>true</tt>, the authorization server MUST NOT prompt the
+ end user to authenticate or approve access. Instead, the authorization server
+ attempts to establish the end user's identity via other means (e.g. browser
+ cookies) and checks if the end user has previously approved an identical access
+ request by the same client and if that access grant is still active. If the
+ authorization server does not support an immediate check or if it is unable to
+ establish the end user's identity or approval status, it MUST deny the request
+ without prompting the end user. Defaults to <tt>false</tt> if
+ omitted.
+
+</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
+ request MUST use the HTTP <tt>GET</tt> method.
+
+</p>
+<p>
+ For example, the client directs the end user's user-agent to make the
+ following HTTPS requests (line breaks are for display purposes only):
+
+</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
+ GET /authorize?type=web_server&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.
+
+</p>
+<p>
+ The authorization server authenticates the end user and obtains an authorization
+ decision (by asking the end user or establishing approval via other means). The
+ authorization server sends 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="anchor16"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.5.2.1.1"></a><h3>3.5.2.1.1.&nbsp;
+End User Grants Authorization</h3>
+
+<p>
+ If the end user authorizes the access request, the authorization server generates a
+ verification code and associates it with the client identifier and redirection URI. The
+ authorization server constructs the request URI by adding the following parameters to
+ the query component of redirection URI provided by the client:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>code</dt>
+<dd>
+
+ REQUIRED. The verification code generated by the authorization server.
+
+</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 verification code SHOULD expire shortly after it is issued and allowed for a
+ single use.
+
+</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>
+ In turn, the end user's user-agent makes the following HTTPS
+ <tt>GET</tt> request:
+
+</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
+ GET /cb?code=i1WsRn1uB1 HTTP/1.1
+ Host: client.example.com
+
+</pre></div>
+<a name="anchor17"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.5.2.1.2"></a><h3>3.5.2.1.2.&nbsp;
+End User Denies Authorization</h3>
+
+<p>
+ If the end user denied the access request, the authorization server constructs the
+ request URI by adding the following parameters to the query component of the
+ redirection URI provided by the client:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>error</dt>
+<dd>
+
+ REQUIRED. The parameter value MUST be set to
+ <tt>user_denied</tt> (case sensitive).
+
+</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 directs the client to make the following HTTP
+ request:
+
+</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
+ GET /cb?error=user_denied HTTP/1.1
+ Host: client.example.com
+
+</pre></div>
+<p>
+ The authorization flow concludes unsuccessfully.
+
+</p>
+<a name="anchor18"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.5.2.2"></a><h3>3.5.2.2.&nbsp;
+Client Requests Access Token</h3>
+
+<p>
+ The client obtains an access token from the authorization server by making an HTTP
+ <tt>POST</tt> request to the token endpoint. The client
+ constructs a request URI by adding the following parameters to the request:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>type</dt>
+<dd>
+
+ REQUIRED. The parameter value MUST be set to
+ <tt>web_server</tt> (case sensitive).
+
+</dd>
+<dt>client_id</dt>
+<dd>
+
+ REQUIRED. The client identifier as described in <a class='info' href='#client_id'>Section&nbsp;3.4<span> (</span><span class='info'>Client Credentials</span><span>)</span></a>.
+
+</dd>
+<dt>client_secret</dt>
+<dd>
+
+ REQUIRED if the client identifier has a matching secret. The client secret as
+ described in <a class='info' href='#client_id'>Section&nbsp;3.4<span> (</span><span class='info'>Client Credentials</span><span>)</span></a>.
+
+</dd>
+<dt>code</dt>
+<dd>
+
+ REQUIRED. The verification code received from the authorization server.
+
+</dd>
+<dt>redirect_uri</dt>
+<dd>
+
+ REQUIRED. The redirection URI used in the initial request.
+
+</dd>
+<dt>secret_type</dt>
+<dd>
+
+ OPTIONAL. The access token secret type as described by
+ <a class='info' href='#crypto_token'>Section&nbsp;5.3<span> (</span><span class='info'>Cryptographic Tokens Requests</span><span>)</span></a>. If omitted, the authorization server will issue a
+ bearer token (an access token without a matching secret) as described by
+ <a class='info' href='#bearer_token'>Section&nbsp;5.2<span> (</span><span class='info'>Bearer Token Requests</span><span>)</span></a>.
+
+</dd>
+</dl></blockquote><p>
+
+</p>
+<p>
+ For example, the client makes the following HTTPS request (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
+
+ type=web_server&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 verify that the verification code, client identity,
+ client secret, and redirection URI are all valid and match its stored association. If
+ the request is valid, the authorization server issues an access token and delivers it
+ to the client in the HTTP response body using the
+ <tt>application/x-www-form-urlencoded</tt> content type as defined
+ by <a class='info' href='#W3C.REC-html40-19980424'>[W3C.REC&#8209;html40&#8209;19980424]<span> (</span><span class='info'>Hors, A., Jacobs, I., and D. Raggett, &ldquo;HTML 4.0 Specification,&rdquo; April&nbsp;1998.</span><span>)</span></a> with a 200 status code (OK).
+
+</p>
+<p>
+ The response contains the following parameters:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>access_token</dt>
+<dd>
+
+ REQUIRED. The access token issued by the authorization server.
+
+</dd>
+<dt>expires_in</dt>
+<dd>
+
+ OPTIONAL. The duration in seconds of the access token lifetime.
+
+</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='#token_refresh'>Section&nbsp;4<span> (</span><span class='info'>Refreshing an Access Token</span><span>)</span></a>.
+
+</dd>
+<dt>access_token_secret</dt>
+<dd>
+
+ REQUIRED if requested by the client. The corresponding access token secret as
+ requested by the client.
+
+</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 200 OK
+ Content-Type: application/x-www-form-urlencoded
+
+ access_token=SlAV32hkKG&amp;expires_in=3600&amp;refresh_token=8xLOxBtZp8
+
+</pre></div>
+<p>
+ If the request is invalid, the authorization server returns an error message in the
+ HTTP response body using the
+ <tt>application/x-www-form-urlencoded</tt> content type as defined
+ by <a class='info' href='#W3C.REC-html40-19980424'>[W3C.REC&#8209;html40&#8209;19980424]<span> (</span><span class='info'>Hors, A., Jacobs, I., and D. Raggett, &ldquo;HTML 4.0 Specification,&rdquo; April&nbsp;1998.</span><span>)</span></a> with a 400 status code (Bad Request).
+
+</p>
+<p>
+ The response contains the following parameter:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>error</dt>
+<dd>
+
+ OPTIONAL. The parameter value MUST be set to either
+ <tt>redirect_uri_mismatch</tt> or
+ <tt>expired_verification_code</tt> (case sensitive).
+
+</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/x-www-form-urlencoded
+
+ error=expired_verification_code
+
+</pre></div>
+<a name="device_flow"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.5.3"></a><h3>3.5.3.&nbsp;
+Device Flow</h3>
+
+<p>
+ The device flow is a user delegation flow suitable for clients executing on devices
+ which do not have an easy data-entry method (e.g. game consoles or media hub), but
+ where the end user has separate access to a user-agent on another computer or device
+ (e.g. home computer, a laptop, or a smartphone). The client is incapable of receiving
+ incoming requests from the authorization server (incapable of acting as an HTTP
+ server).
+
+</p>
+<p>
+ Instead of interacting with the end user's user-agent, the client instructs the end
+ user to use another computer or device and connect to the authorization server to
+ approve the access request. Since the client cannot receive incoming requests, it polls the
+ authorization server repeatedly until the end user completes the approval process.
+
+</p>
+<p>
+ This device flow does not utilize the client secret since the client executables
+ reside on a local device which makes the client secret accessible and exploitable.
+
+</p><br /><hr class="insert" />
+<a name="Figure 6"></a>
+<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
+ +----------+ +----------------+
+ | |&gt;---(A)-- Client Identifier ---&gt;| |
+ | | | |
+ | |&lt;---(B)-- Verification Code, --&lt;| |
+ | | User Code, | |
+ | | &amp; Verification URI | |
+ | Device | | |
+ | Client | Client Identifier &amp; | |
+ | |&gt;---(E)-- Verification Code ---&gt;| |
+ | | ... | |
+ | |&gt;---(E)---&gt; | |
+ | | | Authorization |
+ | |&lt;---(F)-- Access Token --------&lt;| Server |
+ +----------+ (w/ Optional Refresh Token) | |
+ v | |
+ : | |
+ (C) User Code &amp; Verification URI | |
+ : | |
+ v | |
+ +----------+ | |
+ | End User | | |
+ | at |&lt;---(D)-- User authenticates --&gt;| |
+ | Browser | | |
+ +----------+ +----------------+
+
+</pre></div><table border="0" cellpadding="0" cellspacing="2" align="center"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;Figure&nbsp;5&nbsp;</b></font><br /></td></tr></table><hr class="insert" />
+
+<p>
+ The device flow illustrated in <a class='info' href='#Figure 6'>Figure&nbsp;5</a> includes the following
+ steps:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>(A)</dt>
+<dd>
+ The client requests access from the authorization server and includes its client
+ identifier in the request.
+
+</dd>
+<dt>(B)</dt>
+<dd>
+ The authorization server issues a verification code, a user code, and provides the
+ end user authorization URI.
+
+</dd>
+<dt>(C)</dt>
+<dd>
+ The client instructs the end user to use its user-agent (elsewhere) and visit the
+ provided authorization URI. The client provides the user with the user code to
+ enter in order to grant access.
+
+</dd>
+<dt>(D)</dt>
+<dd>
+ The authorization server authenticates the end user (via the user-agent) and
+ prompts the end user to grant the client's access request by entering the user
+ code provided by the client.
+
+</dd>
+<dt>(E)</dt>
+<dd>
+ While the end user authorizes (or denies) the client's request (D), the client
+ repeatedly polls the authorization server to find out if the end user completed the
+ user authorization step. The client includes the verification code and its client
+ identifier.
+
+</dd>
+<dt>(F)</dt>
+<dd>
+ Assuming the end user granted access, the authorization server validates the
+ verification code provided by the client and responds back with the access token.
+
+</dd>
+</dl></blockquote><p>
+
+</p>
+<a name="anchor19"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.5.3.1"></a><h3>3.5.3.1.&nbsp;
+Client Requests Authorization</h3>
+
+<p>
+ The client initiates the flow by requesting a set of verification codes from the
+ authorization server by making an HTTP <tt>GET</tt> request to the
+ authorization endpoint. The client constructs a request URI by adding the following
+ parameters to the request:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>type</dt>
+<dd>
+
+ REQUIRED. The parameter value MUST be set to 'device' (case sensitive).
+
+</dd>
+<dt>client_id</dt>
+<dd>
+
+ REQUIRED. The client identifier as described in <a class='info' href='#client_id'>Section&nbsp;3.4<span> (</span><span class='info'>Client Credentials</span><span>)</span></a>.
+
+</dd>
+</dl></blockquote><p>
+
+</p>
+<p>
+ For example, the client makes the following HTTPS request (line breaks are for
+ display purposes only):
+
+</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
+ GET /authorize?type=device&amp;client_id=s6BhdRkqt3
+ HTTP/1.1
+ Host: server.example.com
+
+</pre></div>
+<p>
+ In response, the authorization server generates a verification code and a user code
+ and includes them in the HTTP response body using the
+ <tt>application/x-www-form-urlencoded</tt> format as defined by
+ <a class='info' href='#W3C.REC-html40-19980424'>[W3C.REC&#8209;html40&#8209;19980424]<span> (</span><span class='info'>Hors, A., Jacobs, I., and D. Raggett, &ldquo;HTML 4.0 Specification,&rdquo; April&nbsp;1998.</span><span>)</span></a> with a 200 status code (OK). The
+ response contains the following parameters:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>code</dt>
+<dd>
+
+ REQUIRED. The verification code.
+
+</dd>
+<dt>user_code</dt>
+<dd>
+
+ REQUIRED. The user code.
+
+</dd>
+<dt>user_uri</dt>
+<dd>
+
+ REQUIRED. The user authorization URI on the authorization server.
+
+</dd>
+<dt>expires_in</dt>
+<dd>
+
+ OPTIONAL. The duration in seconds of the verification code lifetime.
+
+</dd>
+<dt>interval</dt>
+<dd>
+
+ OPTIONAL. The minimum amount of time in seconds that the client SHOULD wait
+ between polling requests to the token endpoint.
+
+</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>
+ HTTP/1.1 200 OK
+ Content-Type: application/x-www-form-urlencoded
+
+ device_code=74tq5miHKB&amp;user_code=94248&amp;user_uri=http%3A%2F%2
+ Fwww%2Eexample%2Ecom%2Fdevice&amp;interval=5
+
+</pre></div>
+<p>
+ The client displays the user code and the user authorization URI to the end-user, and
+ instructs the end user to visit the URI using a user-agent and enter the user code.
+
+</p>
+<p>
+ The end user manually types the provided URI and authenticates with the authorization
+ server. The authorization server prompts the end user to authorize the client's
+ request by entering the user code provided by the client. Once the end user approves
+ or denies the request, the authorization server informs the end user to return to the
+ device for further instructions.
+
+</p>
+<a name="anchor20"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.5.3.2"></a><h3>3.5.3.2.&nbsp;
+Client Requests Access Token</h3>
+
+<p>
+ Since the client is unable to receive incoming requests from the authorization
+ server, it polls the authorization server repeatedly until the end user grants or
+ denies the request, or the verification code expires.
+
+</p>
+<p>
+ The client makes the following request at an arbitrary but reasonable interval which
+ MUST NOT exceed the minimum interval rate provided by the authorization server (if
+ present via the <tt>interval</tt> parameter). Alternatively, the
+ client MAY provide a user interface for the end user to manually inform it when
+ authorization was granted.
+
+</p>
+<p>
+ The client requests an access token by making an HTTP <tt>GET</tt>
+ request to the token endpoint. The client constructs a request URI by adding
+ the following parameters to the request:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>type</dt>
+<dd>
+
+ REQUIRED. The parameter value MUST be set to 'device' (case sensitive).
+
+</dd>
+<dt>client_id</dt>
+<dd>
+
+ REQUIRED. The client identifier as described in <a class='info' href='#client_id'>Section&nbsp;3.4<span> (</span><span class='info'>Client Credentials</span><span>)</span></a>.
+
+</dd>
+<dt>code</dt>
+<dd>
+
+ The verification code received from the authorization server.
+
+</dd>
+<dt>secret_type</dt>
+<dd>
+
+ OPTIONAL. The access token secret type as described by
+ <a class='info' href='#crypto_token'>Section&nbsp;5.3<span> (</span><span class='info'>Cryptographic Tokens Requests</span><span>)</span></a>. If omitted, the authorization server will issue a
+ bearer token (an access token without a matching secret) as described by
+ <a class='info' href='#bearer_token'>Section&nbsp;5.2<span> (</span><span class='info'>Bearer Token Requests</span><span>)</span></a>.
+
+</dd>
+</dl></blockquote><p>
+
+</p>
+<p>
+ For example, the client makes the following HTTPS request (line breaks are for display
+ purposes only):
+
+</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
+ GET /token?type=device&amp;client_id=s6BhdRkqt3
+ &amp;code=J2vC42OifV HTTP/1.1
+ Host: server.example.com
+
+</pre></div>
+<a name="anchor21"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.5.3.2.1"></a><h3>3.5.3.2.1.&nbsp;
+End User Grants Authorization</h3>
+
+<p>
+ If the end user authorized the request, the authorization server issues an access
+ token and delivers it to the client by including it in the HTTP response
+ body using the <tt>application/x-www-form-urlencoded</tt>
+ content type as defined by <a class='info' href='#W3C.REC-html40-19980424'>[W3C.REC&#8209;html40&#8209;19980424]<span> (</span><span class='info'>Hors, A., Jacobs, I., and D. Raggett, &ldquo;HTML 4.0 Specification,&rdquo; April&nbsp;1998.</span><span>)</span></a> with a 200
+ status code (OK). The response contains the following parameters:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>access_token</dt>
+<dd>
+
+ REQUIRED. The access token.
+
+</dd>
+<dt>expires_in</dt>
+<dd>
+
+ OPTIONAL. The duration in seconds of the access token lifetime.
+
+</dd>
+<dt>refresh_token</dt>
+<dd>
+
+ OPTIONAL. The refresh token.
+
+</dd>
+<dt>access_token_secret</dt>
+<dd>
+
+ REQUIRED if requested by the client. The corresponding access token secret as
+ requested by the client.
+
+</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 200 OK
+ Content-Type: application/x-www-form-urlencoded
+
+ access_token=FJQbwq9OD8&amp;expires_in=3600
+
+</pre></div>
+<a name="anchor22"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.5.3.2.2"></a><h3>3.5.3.2.2.&nbsp;
+End User Denies Authorization</h3>
+
+<p>
+ If the end user denied the request, the authorization server provides the client
+ with the error message in the HTTP response body using the
+ <tt>application/x-www-form-urlencoded</tt> content type as
+ defined by <a class='info' href='#W3C.REC-html40-19980424'>[W3C.REC&#8209;html40&#8209;19980424]<span> (</span><span class='info'>Hors, A., Jacobs, I., and D. Raggett, &ldquo;HTML 4.0 Specification,&rdquo; April&nbsp;1998.</span><span>)</span></a> with a 400 status code
+ (Bad Request). The response contains the following parameters:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>error</dt>
+<dd>
+
+ REQUIRED. Value must be set to
+ <tt>authorization_declined</tt>.
+
+</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/x-www-form-urlencoded
+
+ error=authorization_declined
+
+</pre></div>
+<a name="anchor23"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.5.3.2.3"></a><h3>3.5.3.2.3.&nbsp;
+End User Authorization Pending or Expired</h3>
+
+<p>
+ If the end user authorization is pending or expired without receiving any response
+ from the end user, or the client is exceeding the allowed polling interval, the
+ authorization server provides the client with the error message in the HTTP
+ response body using the <tt>application/x-www-form-urlencoded</tt>
+ content type as defined by <a class='info' href='#W3C.REC-html40-19980424'>[W3C.REC&#8209;html40&#8209;19980424]<span> (</span><span class='info'>Hors, A., Jacobs, I., and D. Raggett, &ldquo;HTML 4.0 Specification,&rdquo; April&nbsp;1998.</span><span>)</span></a> with a 400
+ status code (Bad Request). The response contains the following parameters:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>error</dt>
+<dd>
+
+ REQUIRED. Value MUST be set to
+ <tt>authorization_pending</tt>,
+ <tt>slow_down</tt>, or
+ <tt>code_expired</tt> (case sensitive).
+
+</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/x-www-form-urlencoded
+
+ error=authorization_pending
+
+</pre></div>
+<a name="anchor24"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.6"></a><h3>3.6.&nbsp;
+End User Credentials Flows</h3>
+
+<p>
+ End user credential flows are used to grant client access to protected resources by the
+ end user directly sharing the end user credentials (typically a username and password)
+ with the client. Unlike user delegation flows, end user credentials flows require a much
+ higher degree of trust between the client and end user.
+
+</p>
+<p>
+ These flows are suitable in cases where the end user already has a trust relationship
+ with the client, such as its computer operating system or highly privileged applications.
+ Authorization servers SHOULD take special care when enabling user credentials flows, and
+ SHOULD only do so when other delegation flows are not viable.
+
+</p>
+<p>
+ However, unlike the HTTP Basic authentication scheme defined in
+ <a class='info' href='#RFC2617'>[RFC2617]<span> (</span><span class='info'>Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P., Luotonen, A., and L. Stewart, &ldquo;HTTP Authentication: Basic and Digest Access Authentication,&rdquo; June&nbsp;1999.</span><span>)</span></a>, the end user's credentials are used in a single request and
+ are exchanged for an access token and refresh token which eliminates the client need to
+ store them for future use.
+
+</p>
+<a name="username_password_flow"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.6.1"></a><h3>3.6.1.&nbsp;
+Username and Password Flow</h3>
+
+<p>
+ The username and password flow is an end user credentials flow suitable for clients
+ capable of asking end users for their usernames and passwords. It is also used to
+ migrate existing clients using direct authentication schemes such as HTTP Basic or
+ Digest authentication to OAuth by converting the end user credentials stored with
+ tokens.
+
+</p>
+<p>
+ The methods through which the client prompts end users for their usernames and
+ passwords is beyond the scope of this specification. The client MUST discard the
+ usernames and passwords once an access token has been obtained.
+
+</p><br /><hr class="insert" />
+<a name="Figure 7"></a>
+<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
+ End User
+ v
+ :
+ (A)
+ :
+ v
+ +--------+ +---------------+
+ | | Client Credentials | |
+ | |&gt;--(B)--- &amp; User Credentials ----&gt;| Authorization |
+ | Client | | Server |
+ | |&lt;--(C)---- Access Token ---------&lt;| |
+ | | (w/ Optional Refresh Token) | |
+ +--------+ +---------------+
+
+</pre></div><table border="0" cellpadding="0" cellspacing="2" align="center"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;Figure&nbsp;6&nbsp;</b></font><br /></td></tr></table><hr class="insert" />
+
+<p>
+ The username and password flow illustrated in <a class='info' href='#Figure 7'>Figure&nbsp;6</a> includes the
+ following steps:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>(A)</dt>
+<dd>
+ The end user provides the client with its username and password.
+
+</dd>
+<dt>(B)</dt>
+<dd>
+ The client sends an access token request to the authorization server and includes
+ its client identifier and client secret, and the end user's username and password.
+
+</dd>
+<dt>(C)</dt>
+<dd>
+ The authorization server validates the end user credentials and the client
+ credentials and issues an access token.
+
+</dd>
+</dl></blockquote><p>
+
+</p>
+<a name="anchor25"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.6.1.1"></a><h3>3.6.1.1.&nbsp;
+Client Requests Access Token</h3>
+
+<p>
+ The client requests an access token by making an HTTP <tt>POST</tt>
+ request to the token endpoint. The client constructs a request URI by adding
+ the following parameters to the request:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>type</dt>
+<dd>
+
+ REQUIRED. The parameter value MUST be set to 'username' (case sensitive).
+
+</dd>
+<dt>client_id</dt>
+<dd>
+
+ REQUIRED. The client identifier as described in <a class='info' href='#client_id'>Section&nbsp;3.4<span> (</span><span class='info'>Client Credentials</span><span>)</span></a>.
+
+</dd>
+<dt>client_secret</dt>
+<dd>
+
+ REQUIRED. The client secret as described in <a class='info' href='#client_id'>Section&nbsp;3.4<span> (</span><span class='info'>Client Credentials</span><span>)</span></a>. OPTIONAL
+ if no client secret was issued.
+
+</dd>
+<dt>username</dt>
+<dd>
+
+ REQUIRED. The end user's username.
+
+</dd>
+<dt>password</dt>
+<dd>
+
+ REQUIRED. The end user's password.
+
+</dd>
+<dt>secret_type</dt>
+<dd>
+
+ OPTIONAL. The access token secret type as described by
+ <a class='info' href='#crypto_token'>Section&nbsp;5.3<span> (</span><span class='info'>Cryptographic Tokens Requests</span><span>)</span></a>. If omitted, the authorization server will issue a
+ bearer token (an access token without a matching secret) as described by
+ <a class='info' href='#bearer_token'>Section&nbsp;5.2<span> (</span><span class='info'>Bearer Token Requests</span><span>)</span></a>.
+
+</dd>
+</dl></blockquote><p>
+
+</p>
+<p>
+ For example, the client makes the following HTTPS request (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
+
+ type=username&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 and end user credentials
+ and if valid issue an access token and deliver to the client in the HTTP response body
+ using the <tt>application/x-www-form-urlencoded</tt> content type as
+ defined by <a class='info' href='#W3C.REC-html40-19980424'>[W3C.REC&#8209;html40&#8209;19980424]<span> (</span><span class='info'>Hors, A., Jacobs, I., and D. Raggett, &ldquo;HTML 4.0 Specification,&rdquo; April&nbsp;1998.</span><span>)</span></a> with a 200 status code (OK).
+
+</p>
+<p>
+ The response contains the following parameters:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>access_token</dt>
+<dd>
+
+ REQUIRED. The access token.
+
+</dd>
+<dt>expires_in</dt>
+<dd>
+
+ OPTIONAL. The duration in seconds of the access token lifetime.
+
+</dd>
+<dt>refresh_token</dt>
+<dd>
+
+ OPTIONAL. The refresh token.
+
+</dd>
+<dt>access_token_secret</dt>
+<dd>
+
+ REQUIRED if requested by the client. The corresponding access token secret as
+ requested by the client.
+
+</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 200 OK
+ Content-Type: application/x-www-form-urlencoded
+
+ access_token=FJQbwq9OD8&amp;refresh_token=gO3CHNqpH8
+
+</pre></div>
+<p>
+ If the request is invalid, the authorization server returns an error message in the
+ HTTP response body using the
+ <tt>application/x-www-form-urlencoded</tt> content type as defined
+ by <a class='info' href='#W3C.REC-html40-19980424'>[W3C.REC&#8209;html40&#8209;19980424]<span> (</span><span class='info'>Hors, A., Jacobs, I., and D. Raggett, &ldquo;HTML 4.0 Specification,&rdquo; April&nbsp;1998.</span><span>)</span></a> with a 400 status code (Bad Request).
+
+</p>
+<p>
+ The response contains the following parameter:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>error</dt>
+<dd>
+
+ OPTIONAL. The parameter value MUST be set to either
+ <tt>incorrect_credentials</tt> or
+ <tt>unauthorized_client</tt> (case sensitive).
+
+</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/x-www-form-urlencoded
+
+ error=incorrect_credentials
+
+</pre></div>
+<a name="anchor26"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.7"></a><h3>3.7.&nbsp;
+Autonomous Client Flows</h3>
+
+<p>
+ Autonomous client flows are used to grant client access to protected resources controlled
+ by the client (i.e. the client is the resource owner). For example, these flows are
+ useful when a service provides both client-specific resources in addition to end user
+ resources.
+
+</p>
+<a name="client_credentials_flow"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.7.1"></a><h3>3.7.1.&nbsp;
+Client Credentials Flow</h3>
+
+<p>
+ The client credentials flow is used when the client acts autonomously without acting on
+ behalf of a separate resource owner. The client secret is assumed to be high-entropy
+ since it is not designed to be memorize by an end user.
+
+</p><br /><hr class="insert" />
+<a name="Figure 8"></a>
+<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
+
+ +--------+ +---------------+
+ | | | |
+ | |&gt;--(A)--- Client Credentials ----&gt;| Authorization |
+ | Client | | Server |
+ | |&lt;--(B)---- Access Token ---------&lt;| |
+ | | (w/ Optional Refresh Token) | |
+ +--------+ +---------------+
+
+</pre></div><table border="0" cellpadding="0" cellspacing="2" align="center"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;Figure&nbsp;7&nbsp;</b></font><br /></td></tr></table><hr class="insert" />
+
+<p>
+ The client credential flow illustrated in <a class='info' href='#Figure 8'>Figure&nbsp;7</a> includes the
+ following steps:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>(A)</dt>
+<dd>
+ The client sends an access token request to the authorization server and includes
+ its client identifier and client secret.
+
+</dd>
+<dt>(B)</dt>
+<dd>
+ The authorization server validates the client credentials and issues an access
+ token.
+
+</dd>
+</dl></blockquote><p>
+
+</p>
+<a name="anchor27"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.7.1.1"></a><h3>3.7.1.1.&nbsp;
+Client Requests Access Token</h3>
+
+<p>
+ The client requests an access token by making an HTTP <tt>POST</tt>
+ request to the token endpoint. The client constructs a request URI by adding
+ the following parameters to the request:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>type</dt>
+<dd>
+
+ REQUIRED. The parameter value MUST be set to 'client_cred' (case sensitive).
+
+</dd>
+<dt>client_id</dt>
+<dd>
+
+ REQUIRED. The client identifier as described in <a class='info' href='#client_id'>Section&nbsp;3.4<span> (</span><span class='info'>Client Credentials</span><span>)</span></a>.
+
+</dd>
+<dt>client_secret</dt>
+<dd>
+
+ REQUIRED. The client secret as described in <a class='info' href='#client_id'>Section&nbsp;3.4<span> (</span><span class='info'>Client Credentials</span><span>)</span></a>.
+
+</dd>
+<dt>secret_type</dt>
+<dd>
+
+ OPTIONAL. The access token secret type as described by
+ <a class='info' href='#crypto_token'>Section&nbsp;5.3<span> (</span><span class='info'>Cryptographic Tokens Requests</span><span>)</span></a>. If omitted, the authorization server will issue a
+ bearer token (an access token without a matching secret) as described by
+ <a class='info' href='#bearer_token'>Section&nbsp;5.2<span> (</span><span class='info'>Bearer Token Requests</span><span>)</span></a>.
+
+</dd>
+</dl></blockquote><p>
+
+</p>
+<p>
+ For example, the client makes the following HTTPS request (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
+
+ type=client_cred&amp;client_id=s6BhdRkqt3&amp;client_secret=47HDu8s
+
+</pre></div>
+<p>
+ The authorization server MUST validate the client credentials and if valid issue an
+ access token and deliver to the client in the HTTP response body using the
+ <tt>application/x-www-form-urlencoded</tt> content type as defined
+ by <a class='info' href='#W3C.REC-html40-19980424'>[W3C.REC&#8209;html40&#8209;19980424]<span> (</span><span class='info'>Hors, A., Jacobs, I., and D. Raggett, &ldquo;HTML 4.0 Specification,&rdquo; April&nbsp;1998.</span><span>)</span></a> with a 200 status code (OK).
+
+</p>
+<p>
+ The response contains the following parameters:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>access_token</dt>
+<dd>
+
+ REQUIRED. The access token.
+
+</dd>
+<dt>expires_in</dt>
+<dd>
+
+ OPTIONAL. The duration in seconds of the access token lifetime.
+
+</dd>
+<dt>refresh_token</dt>
+<dd>
+
+ OPTIONAL. The refresh token.
+
+</dd>
+<dt>access_token_secret</dt>
+<dd>
+
+ REQUIRED if requested by the client. The corresponding access token secret as
+ requested by the client.
+
+</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 200 OK
+ Content-Type: application/x-www-form-urlencoded
+
+ access_token=FJQbwq9OD8
+
+</pre></div>
+<p>
+ If the request is invalid, the authorization server returns an error message in the
+ HTTP response body using the
+ <tt>application/x-www-form-urlencoded</tt> content type as defined
+ by <a class='info' href='#W3C.REC-html40-19980424'>[W3C.REC&#8209;html40&#8209;19980424]<span> (</span><span class='info'>Hors, A., Jacobs, I., and D. Raggett, &ldquo;HTML 4.0 Specification,&rdquo; April&nbsp;1998.</span><span>)</span></a> with a 400 status code (Bad Request).
+
+</p>
+<p>
+ The response contains the following parameter:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>error</dt>
+<dd>
+
+ OPTIONAL. The parameter value MUST be set to either
+ <tt>incorrect_credentials</tt> or
+ <tt>unauthorized_client</tt> (case sensitive).
+
+</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/x-www-form-urlencoded
+
+ error=incorrect_credentials
+
+</pre></div>
+<a name="assertion_flow"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.7.2"></a><h3>3.7.2.&nbsp;
+Assertion Flow</h3>
+
+<p>
+ The assertion flow requires the client to obtain a assertion such as a
+ <a class='info' href='#OASIS.saml-core-2.0-os'>SAML<span> (</span><span class='info'>Cantor, S., Kemp, J., Philpott, R., and E. Maler, &ldquo;Assertions and Protocol for the OASIS Security Assertion Markup Language (SAML) V2.0,&rdquo; March&nbsp;2005.</span><span>)</span></a> [OASIS.saml&#8209;core&#8209;2.0&#8209;os] assertion from an assertion issuer
+ prior to initiating the flow. The process in which the assertion is obtained is defined
+ by the assertion issuer and the authorization server, and is beyond the scope of this
+ specification.
+
+</p>
+<p>
+ The client credentials flow is used when the client acts autonomously without acting on
+ behalf of a separate resource owner.
+
+</p><br /><hr class="insert" />
+<a name="Figure 9"></a>
+<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
+
+ +--------+ +---------------+
+ | | | |
+ | |&gt;--(A)------ Assertion ----------&gt;| Authorization |
+ | Client | | Server |
+ | |&lt;--(B)---- Access Token ---------&lt;| |
+ | | (w/ Optional Refresh Token) | |
+ +--------+ +---------------+
+
+</pre></div><table border="0" cellpadding="0" cellspacing="2" align="center"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;Figure&nbsp;8&nbsp;</b></font><br /></td></tr></table><hr class="insert" />
+
+<p>
+ The client credential flow illustrated in <a class='info' href='#Figure 9'>Figure&nbsp;8</a> includes the
+ following steps:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>(A)</dt>
+<dd>
+ The client sends an access token request to the authorization server and includes
+ an assertion.
+
+</dd>
+<dt>(B)</dt>
+<dd>
+ The authorization server validates the assertion and issues an access token.
+
+</dd>
+</dl></blockquote><p>
+
+</p>
+<a name="anchor28"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.3.7.2.1"></a><h3>3.7.2.1.&nbsp;
+Client Requests Access Token</h3>
+
+<p>
+ The client requests an access token by making an HTTP <tt>POST</tt>
+ request to the token endpoint. The client constructs a request URI by adding
+ the following parameters to the request:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>type</dt>
+<dd>
+
+ REQUIRED. The parameter value MUST be set to 'assertion' (case sensitive).
+
+</dd>
+<dt>format</dt>
+<dd>
+
+ REQUIRED. The format of the assertion as defined by the authorization server.
+
+</dd>
+<dt>assertion</dt>
+<dd>
+
+ REQUIRED. The assertion.
+
+</dd>
+<dt>secret_type</dt>
+<dd>
+
+ OPTIONAL. The access token secret type as described by
+ <a class='info' href='#crypto_token'>Section&nbsp;5.3<span> (</span><span class='info'>Cryptographic Tokens Requests</span><span>)</span></a>. If omitted, the authorization server will issue a
+ bearer token (an access token without a matching secret) as described by
+ <a class='info' href='#bearer_token'>Section&nbsp;5.2<span> (</span><span class='info'>Bearer Token Requests</span><span>)</span></a>.
+
+</dd>
+</dl></blockquote><p>
+
+</p>
+<p>
+ For example, the client makes the following HTTPS request (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
+
+ type=assertion&amp;format=_______&amp;assertion=_______
+
+</pre></div>
+<p>
+ The authorization server MUST validate the assertion and if valid issue an access
+ token and deliver to the client in the HTTP response body using the
+ <tt>application/x-www-form-urlencoded</tt> content type as defined
+ by <a class='info' href='#W3C.REC-html40-19980424'>[W3C.REC&#8209;html40&#8209;19980424]<span> (</span><span class='info'>Hors, A., Jacobs, I., and D. Raggett, &ldquo;HTML 4.0 Specification,&rdquo; April&nbsp;1998.</span><span>)</span></a> with a 200 status code (OK).
+
+</p>
+<p>
+ The response contains the following parameters:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>access_token</dt>
+<dd>
+
+ REQUIRED. The access token.
+
+</dd>
+<dt>expires_in</dt>
+<dd>
+
+ OPTIONAL. The duration in seconds of the access token lifetime.
+
+</dd>
+<dt>refresh_token</dt>
+<dd>
+
+ OPTIONAL. The refresh token.
+
+</dd>
+<dt>access_token_secret</dt>
+<dd>
+
+ REQUIRED if requested by the client. The corresponding access token secret as
+ requested by the client.
+
+</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 200 OK
+ Content-Type: application/x-www-form-urlencoded
+
+ access_token=FJQbwq9OD8
+
+</pre></div>
+<p>
+ If the assertion is invalid, the authorization server returns an error message in the
+ HTTP response body using the
+ <tt>application/x-www-form-urlencoded</tt> content type as defined
+ by <a class='info' href='#W3C.REC-html40-19980424'>[W3C.REC&#8209;html40&#8209;19980424]<span> (</span><span class='info'>Hors, A., Jacobs, I., and D. Raggett, &ldquo;HTML 4.0 Specification,&rdquo; April&nbsp;1998.</span><span>)</span></a> with a 400 status code (Bad Request).
+
+</p>
+<p>
+ The response contains the following parameter:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>error</dt>
+<dd>
+
+ OPTIONAL. The parameter value MUST be set to either
+ <tt>invalid_assertion</tt> or
+ <tt>unknown_format</tt> (case sensitive).
+
+</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/x-www-form-urlencoded
+
+ error=incorrect_credentials
+
+</pre></div>
+<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"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.4"></a><h3>4.&nbsp;
+Refreshing an Access Token</h3>
+
+<p>
+ Token refresh is used when the lifetime of an access token is shorter than the lifetime of
+ the authorization grant. It allows clients to obtain a new access token without having to
+ go through the authorization flow again or involve the resource owner. It is also used to
+ obtain a new token with different security properties (e.g. bearer token, token with
+ shared symmetric secret).
+
+</p><br /><hr class="insert" />
+<a name="Figure 10"></a>
+<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
+ +--------+ Client Credentials, +---------------+
+ | | Refresh Token, | |
+ | |&gt;--(A)----- &amp; Secret Type -------&gt;| Authorization |
+ | Client | | Server |
+ | |&lt;--(B)----- Access Token --------&lt;| |
+ | | &amp; Optional Secret | |
+ +--------+ +---------------+
+
+</pre></div><table border="0" cellpadding="0" cellspacing="2" align="center"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;Figure&nbsp;9&nbsp;</b></font><br /></td></tr></table><hr class="insert" />
+
+<p>
+ To refresh a token, the client constructs an HTTP <tt>POST</tt> request
+ to the token endpoint and includes the following parameters in the HTTP request
+ body using the <tt>application/x-www-form-urlencoded</tt> content type
+ as defined by <a class='info' href='#W3C.REC-html40-19980424'>[W3C.REC&#8209;html40&#8209;19980424]<span> (</span><span class='info'>Hors, A., Jacobs, I., and D. Raggett, &ldquo;HTML 4.0 Specification,&rdquo; April&nbsp;1998.</span><span>)</span></a>:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>type</dt>
+<dd>
+
+ REQUIRED. The parameter value MUST be set to 'refresh' (case sensitive).
+
+</dd>
+<dt>client_id</dt>
+<dd>
+
+ REQUIRED. The client identifier as described in <a class='info' href='#client_id'>Section&nbsp;3.4<span> (</span><span class='info'>Client Credentials</span><span>)</span></a>.
+
+</dd>
+<dt>client_secret</dt>
+<dd>
+
+ REQUIRED if the client was issued a secret. The client secret.
+
+</dd>
+<dt>refresh_token</dt>
+<dd>
+
+ REQUIRED. The refresh token associated with the access token to be refreshed.
+
+</dd>
+<dt>secret_type</dt>
+<dd>
+
+ OPTIONAL. The access token secret type as described by <a class='info' href='#crypto_token'>Section&nbsp;5.3<span> (</span><span class='info'>Cryptographic Tokens Requests</span><span>)</span></a>.
+ If omitted, the authorization server will issue a bearer token (an access token without
+ a matching secret) as described by <a class='info' href='#bearer_token'>Section&nbsp;5.2<span> (</span><span class='info'>Bearer Token Requests</span><span>)</span></a>.
+
+</dd>
+</dl></blockquote><p>
+
+</p>
+<p>
+ For example, the client makes the following HTTPS request (line break are for display
+ purposes only):
+
+</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
+
+ POST /authorize HTTP/1.1
+ Host: server.example.com
+ Content-Type: application/x-www-form-urlencoded
+
+ type=refresh_token&amp;client_id=s6BhdRkqt3&amp;client_secret=8eSEIpnqmM
+ &amp;refresh_token=n4E9O119d&amp;secret_type=hmac-sha256
+
+</pre></div>
+<p>
+ The authorization server MUST verify the client credential, 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 a new access token and includes the following parameters in
+ the HTTP response body using the
+ <tt>application/x-www-form-urlencoded</tt> content type as defined by
+ <a class='info' href='#W3C.REC-html40-19980424'>[W3C.REC&#8209;html40&#8209;19980424]<span> (</span><span class='info'>Hors, A., Jacobs, I., and D. Raggett, &ldquo;HTML 4.0 Specification,&rdquo; April&nbsp;1998.</span><span>)</span></a> with a 200 status code (OK):
+
+ </p>
+<blockquote class="text"><dl>
+<dt>access_token</dt>
+<dd>
+
+ REQUIRED. The access token.
+
+</dd>
+<dt>expires_in</dt>
+<dd>
+
+ OPTIONAL. The duration in seconds of the access token lifetime.
+
+</dd>
+<dt>access_token_secret</dt>
+<dd>
+
+ REQUIRED if requested by the client. The corresponding access token secret as requested
+ by the client.
+
+</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 200 OK
+ Content-Type: application/x-www-form-urlencoded
+
+ access_token=8F44J2HGMl&amp;access_token_secret=hfd83hjd&amp;expires_in=3600
+
+</pre></div>
+<p>
+ If the request fails verification, the authorization server returns an error message in the
+ HTTP response body using the
+ <tt>application/x-www-form-urlencoded</tt> content type as defined
+ by <a class='info' href='#W3C.REC-html40-19980424'>[W3C.REC&#8209;html40&#8209;19980424]<span> (</span><span class='info'>Hors, A., Jacobs, I., and D. Raggett, &ldquo;HTML 4.0 Specification,&rdquo; April&nbsp;1998.</span><span>)</span></a> with a 400 status code (Bad Request).
+
+</p>
+<p>
+ The response contains the following parameter:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>error</dt>
+<dd>
+
+ OPTIONAL. The parameter value MUST be set to either
+ <tt>incorrect_credentials</tt>,
+ <tt>authorization_expired</tt>, or
+ <tt>unsupported_secret_type</tt> (case sensitive).
+
+</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/x-www-form-urlencoded
+
+ error=incorrect_credentials
+
+</pre></div>
+<a name="access_resource"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></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.
+ 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>
+<p>
+ The method in which a client uses an access token depends on the security properties of the
+ access tokens. By default, access tokens are issued without a matching secret. Clients MAY
+ request an access token with a matchin secret by specifying the desired secret type using
+ the <tt>secret_type</tt> token request parameter.
+
+</p>
+<p>
+ When an access token does not include a matching secret, the access token acts as a bearer
+ token, where the token string is a shared symmetric secret. This requires treating the
+ access token with the same care as other secrets (e.g. user passwords). Access tokens
+ SHOULD NOT be sent in the clear over an insecure channel.
+
+</p>
+<p>
+ However, when it is necessary to transmit bearer tokens in the clear without a secure
+ channel, authorization servers must issue access tokens with limited scope and lifetime to
+ reduce the potential risk from a compromised access token. Clients SHOULD request and
+ utilize an access token with a matching secret when making protected resource requests over
+ an insecure channel (e.g. an HTTP request without using SSL/TLS).
+
+</p>
+<p>
+ When an access token includes a matching secret, the secret is not included directly in the
+ request but is used instead to generate a cryptographic signature of the request. The
+ signature can only be generated and verified by entities with access to the secret.
+
+</p>
+<p>
+ Clients SHOULD NOT make authenticated requests with an access token to unfamiliar resource
+ servers, especially when using bearer tokens, regardless of the presence of a secure
+ channel.
+
+</p>
+<a name="authz_header"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.5.1"></a><h3>5.1.&nbsp;
+The Authorization Request Header</h3>
+
+<p>
+ The <tt>Authorization</tt> request header field is used by clients to
+ make both bearer token and cryptographic token requests. When making bearer token
+ requests, the client uses the <tt>token</tt> attribute to include the
+ access token in the request without any of the other attributes. Additional methods for
+ making bearer token requests are described in <a class='info' href='#bearer_token'>Section&nbsp;5.2<span> (</span><span class='info'>Bearer Token Requests</span><span>)</span></a>.
+
+</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: Token token="vF9dft4qmT"
+
+</pre></div>
+<p>
+ When making a cryptographic token request (using an access token with a matching secret)
+ the client uses the <tt>token</tt> attribute to include the access
+ token in the request, and uses the <tt>nonce</tt>,
+ <tt>timestamp</tt>, <tt>algorithm</tt>, and
+ <tt>signature</tt> attributes to apply the matching secret.
+
+</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: Token token="vF9dft4qmT",
+ nonce="s8djwd",
+ timestamp="137131200",
+ algorithm="hmac-sha256",
+ signature="wOJIO9A2W5mFwDgiDvZbTSMK/PY="
+
+</pre></div>
+<p>
+ The <tt>Authorization</tt> header field uses the framework defined by
+ <a class='info' href='#RFC2617'>[RFC2617]<span> (</span><span class='info'>Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P., Luotonen, A., and L. Stewart, &ldquo;HTTP Authentication: Basic and Digest Access Authentication,&rdquo; June&nbsp;1999.</span><span>)</span></a> as follows:
+
+</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
+ credentials = "Token" RWS token-response
+
+ token-response = token-id
+ [ CS nonce ]
+ [ CS timestamp ]
+ [ CS algorithm ]
+ [ CS signature ]
+
+ token-id = "token" "=" &lt;"&gt; token &lt;"&gt;
+ timestamp = "timestamp" "=" &lt;"&gt; 1*DIGIT &lt;"&gt;
+ nonce = "nonce" "=" &lt;"&gt; token &lt;"&gt;
+
+ algorithm = "algorithm" "=" algorithm-name
+ algorithm-name = "hmac-sha256" /
+ token
+
+ signature = "signature" "=" &lt;"&gt; token &lt;"&gt;
+
+</pre></div>
+<a name="bearer_token"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.5.2"></a><h3>5.2.&nbsp;
+Bearer Token Requests</h3>
+
+<p>
+ Clients make bearer token requests by including the access token using the HTTP
+ <tt>Authorization</tt> request header with the
+ <tt>Token</tt> authentication scheme as described in
+ <a class='info' href='#authz_header'>Section&nbsp;5.1<span> (</span><span class='info'>The Authorization Request Header</span><span>)</span></a>. The access token is included using the
+ <tt>token</tt> parameter.
+
+</p>
+<p>
+ For example, the client makes the following HTTPS request:
+
+</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
+ GET /resource HTTP/1.1
+ Host: server.example.com
+ Authorization: Token token="vF9dft4qmT"
+
+</pre></div>
+<p>
+ The resource server MUST validate the access token and ensure it has not expired and
+ that its scope covers the requested resource. If the token expired or is invalid, the
+ resource server MUST reply with an HTTP 401 status code (Unauthorized) and include
+ the HTTP <tt>WWW-Authenticate</tt> response header as described in
+ <a class='info' href='#authn_header'>Section&nbsp;6.1<span> (</span><span class='info'>The WWW-Authenticate Response Header</span><span>)</span></a>.
+
+</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: Token realm='Service', error='token_expired'
+
+</pre></div>
+<p>
+ Alternatively, the client MAY include the access token using the HTTP request URI in the
+ query component as described in <a class='info' href='#query_param'>Section&nbsp;5.2.1<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='#body_param'>Section&nbsp;5.2.2<span> (</span><span class='info'>Form-Encoded Body Parameter</span><span>)</span></a>. Clients SHOULD only use the request URI or
+ body when the <tt>Authorization</tt> request header is not available,
+ and MUST NOT use more than one method in each request.
+
+</p>
+<a name="query_param"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.5.2.1"></a><h3>5.2.1.&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='#RFC3986'>[RFC3986]<span> (</span><span class='info'>Berners-Lee, T., Fielding, R., and L. Masinter, &ldquo;Uniform Resource Identifier (URI): Generic Syntax,&rdquo; January&nbsp;2005.</span><span>)</span></a> using
+ the <tt>oauth_token</tt> parameter.
+
+</p>
+<p>
+ For example, the client makes the following HTTPS request:
+
+</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>
+ The resource server MUST validate the access token and ensure it has not expired and
+ its includes the requested resource. If the resource expired or is not valid, the
+ resource server MUST reply with an HTTP 401 status code (Unauthorized) and include the
+ HTTP <tt>WWW-Authenticate</tt> response header as described in
+ <a class='info' href='#authn_header'>Section&nbsp;6.1<span> (</span><span class='info'>The WWW-Authenticate Response Header</span><span>)</span></a>.
+
+</p>
+<a name="body_param"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.5.2.2"></a><h3>5.2.2.&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='#W3C.REC-html40-19980424'>[W3C.REC&#8209;html40&#8209;19980424]<span> (</span><span class='info'>Hors, A., Jacobs, I., and D. Raggett, &ldquo;HTML 4.0 Specification,&rdquo; April&nbsp;1998.</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 HTTPS request:
+
+</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>
+ The resource server MUST validate the access token and ensure it has not expired and
+ its includes the requested resource. If the resource expired or is not valid, the
+ resource server MUST reply with an HTTP 401 status code (Unauthorized) and include the
+ HTTP <tt>WWW-Authenticate</tt> response header as described in
+ <a class='info' href='#authn_header'>Section&nbsp;6.1<span> (</span><span class='info'>The WWW-Authenticate Response Header</span><span>)</span></a>.
+
+</p>
+<a name="crypto_token"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.5.3"></a><h3>5.3.&nbsp;
+Cryptographic Tokens Requests</h3>
+
+<p>
+ Clients make authenticated protected resource requests using an access token with a
+ matching secret by calculating a set of values and including them in the request using
+ the <tt>Authorization</tt> header field. The way clients calculate
+ these values depends on the access token secret type as issued by the authorization
+ server.
+
+</p>
+<p>
+ This specification defines the <tt>hmac-sha256</tt> algorithm, and
+ establishes a registry for providing additional algorithms. Clients obtain an access
+ token with a matchin <tt>hmac-sha256</tt> secret by using the
+ <tt>token_type</tt> parameter when requesting an access token.
+
+</p>
+<a name="hmac-sha256"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.5.3.1"></a><h3>5.3.1.&nbsp;
+The 'hmac-sha256' Algorithm</h3>
+
+<p>
+ The <tt>hmac-sha256</tt> algorithm uses the HMAC method as defined
+ in <a class='info' href='#RFC2104'>[RFC2104]<span> (</span><span class='info'>Krawczyk, H., Bellare, M., and R. Canetti, &ldquo;HMAC: Keyed-Hashing for Message Authentication,&rdquo; February&nbsp;1997.</span><span>)</span></a> together with the SHA-256 hash function defined in
+ <a class='info' href='#NIST FIPS-180-3'>[NIST FIPS&#8209;180&#8209;3]<span> (</span><span class='info'>National Institute of Standards and Technology, &ldquo;Secure Hash Standard (SHS). FIPS PUB 180-3, October 2008,&rdquo; .</span><span>)</span></a> to apply the access token secret to the request and
+ generate a signature value that is included in the request instead of transmitting
+ the secret in the clear.
+
+</p>
+<p>
+ To use the <tt>hmac-sha256</tt> algorithm, clients:
+
+ </p>
+<ol class="text">
+<li>
+ Calculate the request timestamp and generate a request nonce as described in
+ <a class='info' href='#nonce_ts'>Section&nbsp;5.3.1.1<span> (</span><span class='info'>Nonce and Timestamp</span><span>)</span></a>.
+
+</li>
+<li>
+ Construct the normalized request string as described in
+ <a class='info' href='#base_string'>Section&nbsp;5.3.1.2<span> (</span><span class='info'>Normalized String Construction</span><span>)</span></a>.
+
+</li>
+<li>
+ Calculate the request signature as described in
+ <a class='info' href='#hmac_sha256_function'>Section&nbsp;5.3.1.3<span> (</span><span class='info'>Signature Calculation</span><span>)</span></a>.
+
+</li>
+<li>
+ Include the timestamp, nonce, algorithm name, and calculated signature in the
+ request using the <tt>Authorization</tt> header field.
+
+</li>
+</ol><p>
+
+</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: Token token="vF9dft4qmT",
+ nonce="s8djwd",
+ timestamp="137131200",
+ algorithm="hmac-sha256",
+ signature="wOJIO9A2W5mFwDgiDvZbTSMK/PY="
+
+</pre></div>
+<p>
+ The resource server MUST validate the access token and ensure it has not expired and
+ that its scope covers the requested resource. The resource server MUST also recalculate
+ the request signature using the attributes provided by the client and compare it to the
+ signature provided. If the token expired or is invalid, or if the signature is
+ incorrect, the resource server MUST reply with an HTTP 401 status code (Unauthorized)
+ and include the HTTP <tt>WWW-Authenticate</tt> response header as
+ described in <a class='info' href='#authn_header'>Section&nbsp;6.1<span> (</span><span class='info'>The WWW-Authenticate Response Header</span><span>)</span></a>.
+
+</p>
+<p>
+ For example:
+
+</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
+ HTTP/1.1 401 Unauthorized
+ Date: Tue, 15 Nov 2010 08:12:31 GMT
+ WWW-Authenticate: Token realm='Service',
+ algorithms='hmac-sha256',
+ error='invalid_signature'
+
+</pre></div>
+<p>
+ [[ Errors list ]]
+
+</p>
+<a name="nonce_ts"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.5.3.1.1"></a><h3>5.3.1.1.&nbsp;
+Nonce and Timestamp</h3>
+
+<p>
+ A timestamp in combination with unique nonce values is used to protect against
+ replay attacks when transmitted over an insecure channel.
+
+</p>
+<p>
+ The nonce is a random string, uniquely generated by the client to allow the resource
+ server to verify that a request has never been made before and helps prevent replay
+ attacks when requests are made over a non-secure channel. The nonce value MUST be
+ unique across all requests with the same timestamp and token combinations.
+
+</p>
+<p>
+ The timestamp value is the current time expressed in the number of seconds since
+ January 1, 1970 00:00:00 GMT, and MUST be a positive integer.
+
+</p>
+<p>
+ To avoid the need to retain an infinite number of nonce values for future checks,
+ resource servers MAY choose to restrict the time period after which a request with an
+ old timestamp is rejected. When resource servers apply such a restriction, clients
+ SHOULD synchronize their clocks by using the resource server's time as indicated by
+ the HTTP <tt>Date</tt> response header field as defined in
+ <a class='info' href='#RFC2616'>[RFC2616]<span> (</span><span class='info'>Fielding, R., Gettys, J., Mogul, J., Frystyk, H., Masinter, L., Leach, P., and T. Berners-Lee, &ldquo;Hypertext Transfer Protocol -- HTTP/1.1,&rdquo; June&nbsp;1999.</span><span>)</span></a>.
+
+</p>
+<a name="base_string"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.5.3.1.2"></a><h3>5.3.1.2.&nbsp;
+Normalized String Construction</h3>
+
+<p>
+ The normalized request string is a consistent, reproducible concatenation of
+ several of the HTTP request elements into a single string. The string is used as an
+ input to the selected cryptographic method and includes the HTTP request method
+ (e.g. <tt>GET</tt>, <tt>POST</tt>, etc.), the
+ authority as declared by the HTTP <tt>Host</tt> request header,
+ and the request resource URI.
+
+</p>
+<p>
+ The normalized request string does not cover the entire HTTP request. Most notably,
+ it does not include the entity-body or most HTTP entity-headers. It is important to
+ note that the resource server cannot verify the authenticity of the excluded request
+ elements without using additional protections such as SSL/TLS.
+
+</p>
+<p>
+ The normalized request string is constructed by concatenating together, in order,
+ the following HTTP request elements, separated by the <tt>,</tt>
+ character (ASCII code 44):
+
+ </p>
+<ol class="text">
+<li>
+ The request timestamp as described in <a class='info' href='#nonce_ts'>Section&nbsp;5.3.1.1<span> (</span><span class='info'>Nonce and Timestamp</span><span>)</span></a>.
+
+</li>
+<li>
+ The request nonce as described in <a class='info' href='#nonce_ts'>Section&nbsp;5.3.1.1<span> (</span><span class='info'>Nonce and Timestamp</span><span>)</span></a>.
+
+</li>
+<li>
+ The cryptographic algorithm used.
+
+</li>
+<li>
+ The HTTP request method in uppercase. For example:
+ <tt>HEAD</tt>, <tt>GET</tt>,
+ <tt>POST</tt>, etc.
+
+</li>
+<li>
+ The hostname, colon-separated (ASCII code 58) from the TCP port used to make
+ the request as included in the HTTP request <tt>Host</tt>
+ header field. The port MUST be included even if it is not included in the
+ <tt>Host</tt> header field (i.e. the default port for the
+ scheme).
+
+</li>
+<li>
+ The request resource URI.
+
+</li>
+</ol><p>
+
+</p>
+<p>
+ For example, the normalized request string for the
+ <tt>GET</tt> request URI
+ <tt>http://example.com/resource</tt>, request timestamp
+ <tt>137131200</tt>, request nonce
+ <tt>s8djwd</tt>, and <tt>hmac-sha256</tt>
+ algorithm (line breaks are for display purposes only):
+
+</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
+ 137131200,s8djwd,hmac-sha256,GET,example.com:80,
+ http://example.com/resource
+
+</pre></div>
+<a name="hmac_sha256_function"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.5.3.1.3"></a><h3>5.3.1.3.&nbsp;
+Signature Calculation</h3>
+
+<p>
+ Clients calculate the request signature using the HMAC-SHA256 function:
+
+</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
+ digest = HMAC-SHA256 (key, text)
+
+</pre></div>
+<p>
+ by setting the function variables are follows:
+
+ </p>
+<blockquote class="text"><dl>
+<dt>text</dt>
+<dd>
+
+ is set to the value of the normalize request string as described in
+ <a class='info' href='#base_string'>Section&nbsp;5.3.1.2<span> (</span><span class='info'>Normalized String Construction</span><span>)</span></a>.
+
+</dd>
+<dt>key</dt>
+<dd>
+
+ is set to the access token secret.
+
+</dd>
+</dl></blockquote><p>
+
+</p>
+<p>
+ The request signature is the calculated value of the
+ <tt>digest</tt> variable after the result octet string is
+ base64-encoded per <a class='info' href='#RFC2045'>[RFC2045]<span> (</span><span class='info'>Freed, N. and N. Borenstein, &ldquo;Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies,&rdquo; November&nbsp;1996.</span><span>)</span></a> section 6.8.
+
+</p>
+<a name="anchor29"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.6"></a><h3>6.&nbsp;
+Identifying a Protected Resource</h3>
+
+<p>
+ Clients access protected resources after locating the appropriate authorization and token endpoints
+ and obtaining an access token. In many cases, interacting with a protected resource requires
+ prior knowledge of the protected resource properties and methods, as well as its
+ authentication requirements (i.e. establishing client identity, locating the authorization
+ and token endpoints).
+
+</p>
+<p>
+ However, there are cases in which clients are unfamiliar with the protected resource,
+ including whether the resource requires authentication. When clients attempt to access an
+ unfamiliar protected resource without an access token, the resource server denies the
+ request and informs the client of the required credentials using an HTTP authentication
+ challenge.
+
+</p>
+<p>
+ In addition, when receiving an invalid authenticated request, the resource server issues an
+ authentication challenge including the error type and message.
+
+</p>
+<a name="authn_header"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.6.1"></a><h3>6.1.&nbsp;
+The WWW-Authenticate Response Header</h3>
+
+<p>
+ A resource server receiving a request for a protected resource without a valid access
+ token MUST respond with a 401 HTTP status code (Unauthorized), and includes at least one
+ <tt>Token</tt> <tt>WWW-Authenticate</tt> response
+ header field challenge.
+
+</p>
+<p>
+ The <tt>WWW-Authenticate</tt> header field uses the framework defined by
+ <a class='info' href='#RFC2617'>[RFC2617]<span> (</span><span class='info'>Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P., Luotonen, A., and L. Stewart, &ldquo;HTTP Authentication: Basic and Digest Access Authentication,&rdquo; June&nbsp;1999.</span><span>)</span></a> as follows:
+
+</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
+ challenge = "Token" RWS token-challenge
+
+ token-challenge = realm
+ [ CS authz-uri ]
+ [ CS token-uri ]
+ [ CS algorithms ]
+ [ CS error ]
+
+ authz-uri = "auth-uri" "=" URI-Reference
+ token-uri = "token-uri" "=" URI-Reference
+ algorithms = "algorithms" "=" &lt;"&gt; 1#algorithm-name &lt;"&gt;
+ error = "error" "=" &lt;"&gt; token &lt;"&gt;
+
+ CS = OWS "," OWS
+
+</pre></div>
+<a name="anchor30"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.6.1.1"></a><h3>6.1.1.&nbsp;
+The 'realm' Attribute</h3>
+
+<p>
+ The <tt>realm</tt> attribute is used to provide the protected
+ resources partition as defined by <a class='info' href='#RFC2617'>[RFC2617]<span> (</span><span class='info'>Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P., Luotonen, A., and L. Stewart, &ldquo;HTTP Authentication: Basic and Digest Access Authentication,&rdquo; June&nbsp;1999.</span><span>)</span></a>.
+
+</p>
+<a name="authz_uri_attribute"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.6.1.2"></a><h3>6.1.2.&nbsp;
+The 'authorization-uri' Attribute</h3>
+
+<p>
+
+</p>
+<a name="anchor31"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.6.1.3"></a><h3>6.1.3.&nbsp;
+The 'algorithms' Attribute</h3>
+
+<p>
+
+</p>
+<a name="anchor32"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.6.1.4"></a><h3>6.1.4.&nbsp;
+The 'error' Attribute</h3>
+
+<p>
+
+</p>
+<a name="anchor33"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.7"></a><h3>7.&nbsp;
+Security Considerations</h3>
+
+<p>
+ [[ Todo ]]
+
+</p>
+<a name="anchor34"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.8"></a><h3>8.&nbsp;
+IANA Considerations</h3>
+
+<p>
+ [[ Not Yet ]]
+
+</p>
+<a name="anchor35"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.9"></a><h3>9.&nbsp;
+Acknowledgements</h3>
+
+<p>
+ [[ Add OAuth 1.0a authors + WG contributors ]]
+
+</p>
+<a name="anchor36"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.A"></a><h3>Appendix A.&nbsp;
+Differences from OAuth 1.0a</h3>
+
+<p>
+ [[ Todo ]]
+
+</p>
+<a name="anchor37"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.B"></a><h3>Appendix B.&nbsp;
+Document History</h3>
+
+<p>
+ [[ to be removed by RFC editor before publication as an RFC ]]
+
+</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"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<a name="rfc.section.10"></a><h3>10.&nbsp;
+References</h3>
+
+<a name="rfc.references1"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<h3>10.1.&nbsp;Normative References</h3>
+<table width="99%" border="0">
+<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, &ldquo;<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>,&rdquo; 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, &ldquo;<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>.&rdquo;</td></tr>
+<tr><td class="author-text" valign="top"><a name="RFC2045">[RFC2045]</a></td>
+<td class="author-text"><a href="mailto:ned@innosoft.com">Freed, N.</a> and <a href="mailto:nsb@nsb.fv.com">N. Borenstein</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc2045">Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies</a>,&rdquo; 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="mailto:hugo@watson.ibm.com">Krawczyk, H.</a>, <a href="mailto:mihir@cs.ucsd.edu">Bellare, M.</a>, and <a href="mailto:canetti@watson.ibm.com">R. Canetti</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc2104">HMAC: Keyed-Hashing for Message Authentication</a>,&rdquo; 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="mailto:sob@harvard.edu">Bradner, S.</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc2119">Key words for use in RFCs to Indicate Requirement Levels</a>,&rdquo; 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="mailto:fielding@ics.uci.edu">Fielding, R.</a>, <a href="mailto:jg@w3.org">Gettys, J.</a>, <a href="mailto:mogul@wrl.dec.com">Mogul, J.</a>, <a href="mailto:frystyk@w3.org">Frystyk, H.</a>, <a href="mailto:masinter@parc.xerox.com">Masinter, L.</a>, <a href="mailto:paulle@microsoft.com">Leach, P.</a>, and <a href="mailto:timbl@w3.org">T. Berners-Lee</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc2616">Hypertext Transfer Protocol -- HTTP/1.1</a>,&rdquo; 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="mailto:john@math.nwu.edu">Franks, J.</a>, <a href="mailto:pbaker@verisign.com">Hallam-Baker, P.</a>, <a href="mailto:jeff@AbiSource.com">Hostetler, J.</a>, <a href="mailto:lawrence@agranat.com">Lawrence, S.</a>, <a href="mailto:paulle@microsoft.com">Leach, P.</a>, Luotonen, A., and <a href="mailto:stewart@OpenMarket.com">L. Stewart</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc2617">HTTP Authentication: Basic and Digest Access Authentication</a>,&rdquo; 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., &ldquo;<a href="http://tools.ietf.org/html/rfc2818">HTTP Over TLS</a>,&rdquo; 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="RFC3447">[RFC3447]</a></td>
+<td class="author-text">Jonsson, J. and B. Kaliski, &ldquo;<a href="http://tools.ietf.org/html/rfc3447">Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1</a>,&rdquo; 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., &ldquo;<a href="http://tools.ietf.org/html/rfc3629">UTF-8, a transformation format of ISO 10646</a>,&rdquo; 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="mailto:timbl@w3.org">Berners-Lee, T.</a>, <a href="mailto:fielding@gbiv.com">Fielding, R.</a>, and <a href="mailto:LMM@acm.org">L. Masinter</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc3986">Uniform Resource Identifier (URI): Generic Syntax</a>,&rdquo; 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="W3C.REC-html40-19980424">[W3C.REC-html40-19980424]</a></td>
+<td class="author-text">Hors, A., Jacobs, I., and D. Raggett, &ldquo;<a href="http://www.w3.org/TR/1998/REC-html40-19980424">HTML 4.0 Specification</a>,&rdquo; World Wide Web Consortium Recommendation&nbsp;REC-html40-19980424, April&nbsp;1998 (<a href="http://www.w3.org/TR/1998/REC-html40-19980424">HTML</a>).</td></tr>
+</table>
+
+<a name="rfc.references2"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<h3>10.2.&nbsp;Informative References</h3>
+<table width="99%" border="0">
+<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., &ldquo;<a href="http://www.ietf.org/internet-drafts/draft-hammer-oauth-10.txt">The OAuth 1.0 Protocol</a>,&rdquo; 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, &ldquo;<a href="http://www.ietf.org/internet-drafts/draft-hardt-oauth-01.txt">OAuth Web Resource Authorization Profiles</a>,&rdquo; 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="mailto:cantor.2@osu.edu">Cantor, S.</a>, <a href="mailto:John.Kemp@nokia.com">Kemp, J.</a>, <a href="mailto:rphilpott@rsasecurity.com">Philpott, R.</a>, and <a href="mailto:eve.maler@sun.com">E. Maler</a>, &ldquo;<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>,&rdquo; OASIS Standard&nbsp;saml-core-2.0-os, March&nbsp;2005.</td></tr>
+</table>
+
+<a name="rfc.authors"></a><br /><hr />
+<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
+<h3>Authors' Addresses</h3>
+<table width="99%" border="0" cellpadding="0" cellspacing="0">
+<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="mailto:eran@hueniverse.com">eran@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="mailto:davidrecordon@facebook.com">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" align="right">Email:&nbsp;</td>
+<td class="author-text"><a href="mailto:dick.hardt@gmail.com">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>
+</table>
+</body></html>
+
diff --git a/samples/DotNetOpenAuth.ApplicationBlock/DotNetOpenAuth.ApplicationBlock.csproj b/samples/DotNetOpenAuth.ApplicationBlock/DotNetOpenAuth.ApplicationBlock.csproj
index 6739bf9..7e1a0dd 100644
--- a/samples/DotNetOpenAuth.ApplicationBlock/DotNetOpenAuth.ApplicationBlock.csproj
+++ b/samples/DotNetOpenAuth.ApplicationBlock/DotNetOpenAuth.ApplicationBlock.csproj
@@ -72,6 +72,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>
@@ -86,11 +88,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="InMemoryClientTokenManager.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="YubikeyRelyingParty.cs" />
diff --git a/samples/DotNetOpenAuth.ApplicationBlock/Facebook/FacebookClient.cs b/samples/DotNetOpenAuth.ApplicationBlock/Facebook/FacebookClient.cs
new file mode 100644
index 0000000..2f3840e
--- /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.OAuthWrap;
+
+ 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.TokenManager = 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/InMemoryClientTokenManager.cs b/samples/DotNetOpenAuth.ApplicationBlock/InMemoryClientTokenManager.cs
new file mode 100644
index 0000000..4c86df7
--- /dev/null
+++ b/samples/DotNetOpenAuth.ApplicationBlock/InMemoryClientTokenManager.cs
@@ -0,0 +1,53 @@
+//-----------------------------------------------------------------------
+// <copyright file="InMemoryClientTokenManager.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.OAuthWrap;
+
+#if SAMPLESONLY
+ internal class InMemoryClientTokenManager : IClientTokenManager {
+ 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(string scope, out string clientState) {
+ int counter = Interlocked.Increment(ref this.stateCounter);
+ clientState = counter.ToString(CultureInfo.InvariantCulture);
+ return this.savedStates[counter] = new AuthorizationState {
+ Scope = scope,
+ };
+ }
+ }
+#endif
+}
diff --git a/samples/DotNetOpenAuth.ApplicationBlock/TokenManager.cs b/samples/DotNetOpenAuth.ApplicationBlock/TokenManager.cs
new file mode 100644
index 0000000..22099a3
--- /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.OAuthWrap;
+
+ public class TokenManager : IClientTokenManager {
+ 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..5935859
--- /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.OAuthWrap;
+
+ 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 8092ba2..4f01f97 100644
--- a/samples/OAuthConsumer/OAuthConsumer.csproj
+++ b/samples/OAuthConsumer/OAuthConsumer.csproj
@@ -57,6 +57,7 @@
</ItemGroup>
<ItemGroup>
<Content Include="Default.aspx" />
+ <Content Include="Facebook.aspx" />
<Content Include="favicon.ico" />
<Content Include="Global.asax" />
<Content Include="GoogleAddressBook.aspx" />
@@ -69,6 +70,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" />
@@ -81,9 +83,19 @@
</None>
</ItemGroup>
<ItemGroup>
+ <Compile Include="..\DotNetOpenAuth.ApplicationBlock\InMemoryClientTokenManager.cs">
+ <Link>Code\InMemoryClientTokenManager.cs</Link>
+ </Compile>
<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>
@@ -97,6 +109,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..7fae00b
--- /dev/null
+++ b/samples/OAuthConsumer/SampleWcf2.aspx.cs
@@ -0,0 +1,112 @@
+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.ApplicationBlock;
+ using DotNetOpenAuth.OAuthWrap;
+ using OAuthConsumer.SampleServiceProvider;
+
+ public partial class SampleWcf2 : System.Web.UI.Page {
+ private static InMemoryClientTokenManager tokenManager = new InMemoryClientTokenManager();
+
+ private static IAuthorizationState Authorization {
+ get { return (AuthorizationState)HttpContext.Current.Session["Authorization"]; }
+ set { HttpContext.Current.Session["Authorization"] = value; }
+ }
+
+ protected void Page_Load(object sender, EventArgs e) {
+ var client = CreateClient();
+ if (!IsPostBack) {
+ var authorization = client.ProcessUserAuthorization();
+ if (authorization != null) {
+ Authorization = authorization;
+ }
+ }
+
+ if (Authorization != null) {
+ client.RefreshToken(Authorization, TimeSpan.FromMinutes(1));
+ }
+ }
+
+ 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();
+ string scope = string.Join(" ", scopes);
+
+ var client = CreateClient();
+ string clientState;
+ var response = client.PrepareRequestUserAuthorization(tokenManager.NewAuthorization(scope, out clientState));
+ response.ClientState = clientState;
+ client.Channel.Send(response);
+ }
+
+ 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 static WebServerClient CreateClient() {
+ var authServerDescription = new AuthorizationServerDescription {
+ TokenEndpoint = new Uri("http://localhost:65169/OAuth2.ashx/token"),
+ AuthorizationEndpoint = new Uri("http://localhost:65169/OAuth2.ashx/auth"),
+ };
+
+ var client = new WebServerClient(authServerDescription) {
+ ClientIdentifier = "sampleconsumer",
+ ClientSecret = "samplesecret",
+ TokenManager = tokenManager,
+ };
+
+ return client;
+ }
+
+ private T CallService<T>(Func<DataApiClient, T> predicate) {
+ DataApiClient client = new DataApiClient();
+ ////var serviceEndpoint = new MessageReceivingEndpoint(client.Endpoint.Address.Uri, HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest);
+ if (Authorization == null) {
+ throw new InvalidOperationException("No access token!");
+ }
+
+ var httpRequest = (HttpWebRequest)WebRequest.Create(client.Endpoint.Address.Uri);
+ var oauthClient = CreateClient();
+ oauthClient.AuthorizeRequest(httpRequest, Authorization.AccessToken);
+
+ 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;
+ return predicate(client);
+ }
+ }
+ }
+} \ 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 7753874..20c5822 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,8 +51,13 @@
<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"/>
+ <!-- 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..ea5047f
--- /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" />
+ </WindowsFormsHost>
+ </DockPanel>
+</Window>
diff --git a/samples/OAuthConsumerWpf/Authorize2.xaml.cs b/samples/OAuthConsumerWpf/Authorize2.xaml.cs
new file mode 100644
index 0000000..91435da
--- /dev/null
+++ b/samples/OAuthConsumerWpf/Authorize2.xaml.cs
@@ -0,0 +1,56 @@
+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.OAuthWrap;
+
+ /// <summary>
+ /// Interaction logic for Authorize2.xaml
+ /// </summary>
+ public partial class Authorize2 : Window {
+ private UserAgentClient client;
+
+ internal Authorize2(UserAgentClient client) {
+ Contract.Requires(client != null, "client");
+
+ InitializeComponent();
+
+ this.client = client;
+ this.Authorization = new AuthorizationState();
+ this.webBrowser.Navigate(this.client.RequestUserAuthorization(this.Authorization));
+ }
+
+ 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 == this.Authorization.Callback) {
+ this.client.ProcessUserAuthorization(location, this.Authorization);
+ 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);
+ }
+ }
+}
diff --git a/samples/OAuthConsumerWpf/MainWindow.xaml b/samples/OAuthConsumerWpf/MainWindow.xaml
index c59175c..05370d7 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="*" />
+ </Grid.RowDefinitions>
+ <Grid.ColumnDefinitions>
+ <ColumnDefinition Width="auto" />
+ <ColumnDefinition Width="*" />
+ <ColumnDefinition Width="auto" />
+ </Grid.ColumnDefinitions>
+ <Label Grid.Row="1">Token Endpoint URL</Label>
+ <TextBox Grid.Row="1" Grid.Column="1" x:Name="wrapTokenUrlBox" />
+ <Label Grid.Row="1" Grid.Column="2">POST</Label>
+ <Label Grid.Row="2">User Authorization URL</Label>
+ <TextBox Grid.Row="2" Grid.Column="1" x:Name="wrapAuthorizationUrlBox" Text="https://graph.facebook.com/oauth/authorize?display=popup" />
+ <Label Grid.Row="2" Grid.Column="2">GET</Label>
+ <Label Grid.Row="0">Flow</Label>
+ <ComboBox Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="2" x:Name="flowBox" SelectedIndex="1">
+ <ComboBox.Items>
+ <ComboBoxItem>Web Server</ComboBoxItem>
+ <ComboBoxItem>User Agent</ComboBoxItem>
+ <ComboBoxItem>Device</ComboBoxItem>
+ <ComboBoxItem>Username and Password</ComboBoxItem>
+ <ComboBoxItem>Assertion</ComboBoxItem>
+ <ComboBoxItem>Client Credentials</ComboBoxItem>
+ </ComboBox.Items>
+ </ComboBox>
+ <Label Grid.Row="3">Resource URL</Label>
+ <TextBox Grid.Row="3" Grid.Column="1" x:Name="wrapResourceUrlBox" Text="https://graph.facebook.com/me" />
+ <ComboBox Grid.Row="3" Grid.Column="2" x:Name="wrapResourceHttpMethodList" SelectedIndex="0">
+ <ComboBox.Items>
+ <ComboBoxItem>GET w/ header</ComboBoxItem>
+ <ComboBoxItem>GET w/ querystring</ComboBoxItem>
+ <ComboBoxItem>POST</ComboBoxItem>
+ </ComboBox.Items>
+ </ComboBox>
+ <Label Grid.Row="4">Client Identifier</Label>
+ <TextBox Grid.Row="4" Grid.Column="1" x:Name="wrapClientIdentifierBox" Grid.ColumnSpan="2" Text="367207604173" />
+ <Label Grid.Row="5">Client Secret</Label>
+ <TextBox Grid.Row="5" Grid.Column="1" x:Name="wrapClientSecretBox" Grid.ColumnSpan="2"/>
+ <Label Grid.Row="6">OAuth 2.0 version</Label>
+ <ComboBox Grid.Row="6" Grid.Column="1" SelectedIndex="0" x:Name="wrapVersion">
+ <ComboBox.Items>
+ <ComboBoxItem>2.0 DRAFT 5</ComboBoxItem>
+ </ComboBox.Items>
+ </ComboBox>
+ <Button Grid.Row="7" Grid.Column="1" x:Name="wrapBeginButton" Click="wrapBeginButton_Click">Begin</Button>
+ <TextBox Grid.Column="0" Grid.Row="8" Grid.ColumnSpan="3" Name="wrapResultsBox" IsReadOnly="True" />
+ </Grid>
+ </TabItem>
+ </TabControl>
</Window>
diff --git a/samples/OAuthConsumerWpf/MainWindow.xaml.cs b/samples/OAuthConsumerWpf/MainWindow.xaml.cs
index 5bf157b..749a626 100644
--- a/samples/OAuthConsumerWpf/MainWindow.xaml.cs
+++ b/samples/OAuthConsumerWpf/MainWindow.xaml.cs
@@ -3,6 +3,7 @@
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
+ using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
@@ -28,6 +29,7 @@
using DotNetOpenAuth.OAuth;
using DotNetOpenAuth.OAuth.ChannelElements;
using DotNetOpenAuth.Samples.OAuthConsumerWpf.WcfSampleService;
+ using OAuth2 = DotNetOpenAuth.OAuthWrap;
/// <summary>
/// Interaction logic for MainWindow.xaml
@@ -198,5 +200,46 @@
MessageBox.Show(this, ex.Message);
}
}
+
+ private void wrapBeginButton_Click(object sender, RoutedEventArgs e) {
+ var authServer = new DotNetOpenAuth.OAuthWrap.AuthorizationServerDescription {
+ AuthorizationEndpoint = new Uri(wrapAuthorizationUrlBox.Text),
+ };
+ if (wrapTokenUrlBox.Text.Length > 0) {
+ authServer.TokenEndpoint = new Uri(wrapTokenUrlBox.Text);
+ }
+
+ try {
+ ////var client = new DotNetOpenAuth.OAuthWrap.WebAppClient(authServer);
+ ////client.PrepareRequestUserAuthorization();
+ var client = new OAuth2.UserAgentClient(authServer) {
+ ClientIdentifier = wrapClientIdentifierBox.Text,
+ };
+
+ var authorizePopup = new Authorize2(client);
+ authorizePopup.Owner = this;
+ bool? result = authorizePopup.ShowDialog();
+ if (result.HasValue && result.Value) {
+ // One method of OAuth authorization is to tack the ?access_token= onto the query string.
+ var address = new Uri(wrapResourceUrlBox.Text);
+ address = new Uri(wrapResourceUrlBox.Text + (string.IsNullOrEmpty(address.Query) ? "?" : string.Empty) + "access_token=" + Uri.EscapeDataString(authorizePopup.Authorization.AccessToken));
+ var request = (HttpWebRequest)WebRequest.Create(address);
+
+ // This method tacks on the Authorization header
+ client.AuthorizeRequest(request, authorizePopup.Authorization);
+
+ request.Method = wrapResourceHttpMethodList.SelectedIndex < 2 ? "GET" : "POST";
+ using (var resourceResponse = request.GetResponse()) {
+ using (var responseStream = new StreamReader(resourceResponse.GetResponseStream())) {
+ wrapResultsBox.Text = responseStream.ReadToEnd();
+ }
+ }
+ } else {
+ return;
+ }
+ } catch (DotNetOpenAuth.Messaging.ProtocolException ex) {
+ MessageBox.Show(this, ex.Message);
+ }
+ }
}
}
diff --git a/samples/OAuthConsumerWpf/OAuthConsumerWpf.csproj b/samples/OAuthConsumerWpf/OAuthConsumerWpf.csproj
index cdb95aa..9a26bd6 100644
--- a/samples/OAuthConsumerWpf/OAuthConsumerWpf.csproj
+++ b/samples/OAuthConsumerWpf/OAuthConsumerWpf.csproj
@@ -94,6 +94,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>
@@ -123,6 +125,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>
@@ -133,6 +139,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>
@@ -232,4 +241,4 @@
<Target Name="AfterBuild">
</Target>
-->
-</Project> \ No newline at end of file
+</Project>
diff --git a/samples/OAuthServiceProvider/Code/Global.cs b/samples/OAuthServiceProvider/Code/Global.cs
index ceaeac8..fd7d475 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.OAuthWrap;
+ using DotNetOpenAuth.OAuthWrap.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 WebServerAuthorizationServer AuthorizationServer = new WebServerAuthorizationServer(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 WebServerRequest PendingOAuth2Authorization
+ {
+ get { return HttpContext.Current.Session["authrequest"] as WebServerRequest; }
+ 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..e281b07
--- /dev/null
+++ b/samples/OAuthServiceProvider/Code/OAuth2AuthorizationServer.cs
@@ -0,0 +1,60 @@
+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.OAuth.ChannelElements;
+ using DotNetOpenAuth.OAuthWrap;
+ using DotNetOpenAuth.OAuthWrap.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..92038bd 100644
--- a/samples/OAuthServiceProvider/Code/OAuthAuthorizationManager.cs
+++ b/samples/OAuthServiceProvider/Code/OAuthAuthorizationManager.cs
@@ -7,8 +7,9 @@
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
- using DotNetOpenAuth;
using DotNetOpenAuth.OAuth;
+ using DotNetOpenAuth.OAuth.ChannelElements;
+ using DotNetOpenAuth.OAuthWrap;
/// <summary>
/// A WCF extension to authenticate incoming messages using OAuth.
@@ -24,17 +25,14 @@
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 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 +44,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 +58,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, scope;
+ var error = resourceServer.VerifyAccess(new DotNetOpenAuth.Messaging.HttpRequestInfo(httpDetails, requestUri), out username, out scope);
+ if (error == null) {
+ string[] scopes = scope.Split(new char[] { ' ' });
+ var principal = new OAuthPrincipal(username, scopes);
+ return principal;
+ } else {
+ return null;
+ }
+ }
}
} \ No newline at end of file
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..0c14bfd
--- /dev/null
+++ b/samples/OAuthServiceProvider/Members/Authorize2.aspx.cs
@@ -0,0 +1,53 @@
+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;
+
+ 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 = 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..272502c
--- /dev/null
+++ b/samples/OAuthServiceProvider/OAuth2.ashx.cs
@@ -0,0 +1,53 @@
+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.OAuthWrap;
+
+ 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.");
+ }
+
+ // This sample doesn't implement support for immediate mode.
+ if (!request.IsUserInteractionAllowed) {
+ Global.AuthorizationServer.RejectAuthorizationRequest(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 68b2d90..c31e8bf 100644
--- a/samples/OAuthServiceProvider/OAuthServiceProvider.csproj
+++ b/samples/OAuthServiceProvider/OAuthServiceProvider.csproj
@@ -59,6 +59,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" />
@@ -66,9 +67,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>
@@ -133,6 +145,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 df29b1f..26d870b 100644
--- a/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj
+++ b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj
@@ -157,6 +157,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">
@@ -188,6 +189,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" />
@@ -213,6 +215,9 @@
<Compile Include="Mocks\TestChannel.cs" />
<Compile Include="Mocks\TestMessage.cs" />
<Compile Include="Mocks\TestMessageFactory.cs" />
+ <Compile Include="OAuthWrap\MessageFactoryTests.cs" />
+ <Compile Include="OAuthWrap\OAuthWrapChannelTests.cs" />
+ <Compile Include="OAuthWrap\OAuthWrapTestBase.cs" />
<Compile Include="OAuth\ChannelElements\HmacSha1SigningBindingElementTests.cs" />
<Compile Include="OAuth\ChannelElements\OAuthChannelTests.cs" />
<Compile Include="OAuth\ChannelElements\PlaintextSigningBindingElementTest.cs" />
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 2b0e8f9..1e0ede5 100644
--- a/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs
+++ b/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs
@@ -4,8 +4,7 @@
// </copyright>
//-----------------------------------------------------------------------
-namespace DotNetOpenAuth.Test.Messaging
-{
+namespace DotNetOpenAuth.Test.Messaging {
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
@@ -216,5 +215,17 @@ namespace DotNetOpenAuth.Test.Messaging
public void GetHttpDeliveryMethodOutOfRangeTest() {
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);
+ }
}
}
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/OAuthWrap/MessageFactoryTests.cs b/src/DotNetOpenAuth.Test/OAuthWrap/MessageFactoryTests.cs
new file mode 100644
index 0000000..827027e
--- /dev/null
+++ b/src/DotNetOpenAuth.Test/OAuthWrap/MessageFactoryTests.cs
@@ -0,0 +1,254 @@
+//-----------------------------------------------------------------------
+// <copyright file="MessageFactoryTests.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Test.OAuthWrap {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuthWrap;
+ using DotNetOpenAuth.OAuthWrap.ChannelElements;
+ using DotNetOpenAuth.OAuthWrap.Messages;
+ using NUnit.Framework;
+
+ /// <summary>
+ /// Verifies that the WRAP message types are recognized.
+ /// </summary>
+ public class MessageFactoryTests : OAuthWrapTestBase {
+ private readonly MessageReceivingEndpoint recipient = new MessageReceivingEndpoint("http://who", HttpDeliveryMethods.PostRequest);
+ private OAuthWrapAuthorizationServerChannel channel;
+ private IMessageFactory messageFactory;
+
+ public override void SetUp() {
+ base.SetUp();
+
+ this.channel = new OAuthWrapAuthorizationServerChannel();
+ this.messageFactory = OAuthWrapAuthorizationServerChannel_Accessor.AttachShadow(this.channel).MessageFactory;
+ }
+
+ #region Refresh Access Token messages
+
+ [TestCase]
+ public void RefreshAccessTokenRequest() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.refresh_token, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(RefreshAccessTokenRequest), request);
+ }
+
+ [TestCase]
+ public void RefreshAccessTokenSuccessResponse() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.access_token, "abc" },
+ };
+ var request = new RefreshAccessTokenRequest(this.recipient.Location, Protocol.Default.Version);
+ Assert.IsInstanceOf(
+ typeof(AccessTokenSuccessResponse),
+ this.messageFactory.GetNewResponseMessage(request, fields));
+ }
+
+ [TestCase]
+ public void RefreshAccessTokenFailedResponse() {
+ var fields = new Dictionary<string, string> {
+ };
+ var request = new RefreshAccessTokenRequest(this.recipient.Location, Protocol.Default.Version);
+ Assert.IsInstanceOf(
+ typeof(AccessTokenFailedResponse),
+ this.messageFactory.GetNewResponseMessage(request, fields));
+ }
+
+ #endregion
+
+ #region Web App profile messages
+
+ [TestCase]
+ public void WebAppRequestRequest() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.client_id, "abc" },
+ { Protocol.redirect_uri, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(WebServerRequest), request);
+ }
+
+ [TestCase]
+ public void WebAppFailedResponse() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.error, "user_denied" },
+ };
+ var request = new WebServerRequest(this.recipient.Location, Protocol.Default.Version);
+ Assert.IsInstanceOf(
+ typeof(WebServerFailedResponse),
+ this.messageFactory.GetNewResponseMessage(request, fields));
+ }
+
+ [TestCase]
+ public void WebAppSuccessResponse() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.code, "abc" },
+ };
+ var request = new WebServerRequest(this.recipient.Location, Protocol.Default.Version);
+ Assert.IsInstanceOf(
+ typeof(WebServerSuccessResponse),
+ this.messageFactory.GetNewResponseMessage(request, fields));
+ }
+
+ [TestCase]
+ public void WebAppAccessTokenRequest() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.client_id, "abc" },
+ { Protocol.client_secret, "abc" },
+ { Protocol.code, "abc" },
+ { Protocol.redirect_uri, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(WebServerAccessTokenRequest), request);
+ }
+
+ [TestCase, Ignore("Not implemented")]
+ public void WebAppAccessTokenFailedResponse() {
+ // HTTP 400 Bad Request
+ }
+
+ [TestCase, Ignore("Not implemented")]
+ public void WebAppAccessTokenBadClientResponse() {
+ // HTTP 401 Unauthorized
+ // WWW-Authenticate: WRAP
+ }
+
+ #endregion
+
+ #region Username and Password profile messages
+
+ [TestCase]
+ public void UserNamePasswordRequest() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.client_id, "abc" },
+ { Protocol.client_secret, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(UserNamePasswordRequest), request);
+ }
+
+ [TestCase]
+ public void UserNamePasswordSuccessResponse() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.access_token, "abc" },
+ };
+ var request = new UserNamePasswordRequest(this.recipient.Location, Protocol.Default.Version);
+ Assert.IsInstanceOf(
+ typeof(UserNamePasswordSuccessResponse),
+ this.messageFactory.GetNewResponseMessage(request, fields));
+ }
+
+ [TestCase]
+ public void UserNamePasswordVerificationResponse() {
+ // HTTP 400 Bad Request
+ var fields = new Dictionary<string, string> {
+ { Protocol.code, "abc" },
+ };
+ var request = new UserNamePasswordRequest(this.recipient.Location, Protocol.Default.Version);
+ Assert.IsInstanceOf(
+ typeof(UserNamePasswordVerificationResponse),
+ this.messageFactory.GetNewResponseMessage(request, fields));
+ }
+
+ [TestCase, Ignore("Not implemented")]
+ public void UserNamePasswordFailedResponse() {
+ // HTTP 401 Unauthorized
+ // WWW-Authenticate: WRAP
+ }
+
+ [TestCase]
+ public void UsernamePasswordCaptchaResponse() {
+ // HTTP 400 Bad Request
+ var fields = new Dictionary<string, string> {
+ { Protocol.wrap_captcha_url, "abc" },
+ };
+ var request = new UserNamePasswordRequest(this.recipient.Location, Protocol.Default.Version);
+ Assert.IsInstanceOf(
+ typeof(UsernamePasswordCaptchaResponse),
+ this.messageFactory.GetNewResponseMessage(request, fields));
+ }
+
+ #endregion
+
+ #region Rich App profile messages
+
+ [TestCase]
+ public void RichAppRequest() {
+ // include just required parameters
+ var fields = new Dictionary<string, string> {
+ { Protocol.client_id, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(DeviceRequest), request);
+
+ // including optional parts
+ fields = new Dictionary<string, string> {
+ { Protocol.client_id, "abc" },
+ { Protocol.redirect_uri, "abc" },
+ { Protocol.state, "abc" },
+ { Protocol.scope, "abc" },
+ };
+ request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(DeviceRequest), request);
+ }
+
+ [TestCase]
+ public void RichAppResponse() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.refresh_token, "abc" },
+ { Protocol.access_token, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(DeviceResponse), request);
+ }
+
+ [TestCase]
+ public void RichAppAccessTokenRequest() {
+ // include just required parameters
+ var fields = new Dictionary<string, string> {
+ { Protocol.client_id, "abc" },
+ { Protocol.code, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(DeviceAccessTokenRequest), request);
+ }
+
+ #endregion
+
+ #region Client Account and Password profile messages
+
+ [TestCase]
+ public void ClientCredentialsRequest() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.client_id, "abc" },
+ { Protocol.client_secret, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(ClientCredentialsRequest), request);
+ }
+
+ #endregion
+
+ #region Assertion profile messages
+
+ [TestCase]
+ public void AssertionRequest() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.format, "abc" },
+ { Protocol.assertion, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(AssertionRequest), request);
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth.Test/OAuthWrap/OAuthWrapChannelTests.cs b/src/DotNetOpenAuth.Test/OAuthWrap/OAuthWrapChannelTests.cs
new file mode 100644
index 0000000..c7fe48f
--- /dev/null
+++ b/src/DotNetOpenAuth.Test/OAuthWrap/OAuthWrapChannelTests.cs
@@ -0,0 +1,21 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuthWrapChannelTests.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Test.OAuthWrap {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuthWrap;
+ using DotNetOpenAuth.OAuthWrap.ChannelElements;
+ using DotNetOpenAuth.OAuthWrap.Messages;
+ using NUnit.Framework;
+
+ [TestFixture]
+ public class OAuthWrapChannelTests : OAuthWrapTestBase {
+ }
+}
diff --git a/src/DotNetOpenAuth.Test/OAuthWrap/OAuthWrapTestBase.cs b/src/DotNetOpenAuth.Test/OAuthWrap/OAuthWrapTestBase.cs
new file mode 100644
index 0000000..08c9da6
--- /dev/null
+++ b/src/DotNetOpenAuth.Test/OAuthWrap/OAuthWrapTestBase.cs
@@ -0,0 +1,15 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuthWrapTestBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Test.OAuthWrap {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+
+ public class OAuthWrapTestBase : TestBase {
+ }
+}
diff --git a/src/DotNetOpenAuth.sln b/src/DotNetOpenAuth.sln
index f6f3d03..60dffe6 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 3164ec5..9913017 100644
--- a/src/DotNetOpenAuth/Configuration/DotNetOpenAuth.xsd
+++ b/src/DotNetOpenAuth/Configuration/DotNetOpenAuth.xsd
@@ -206,6 +206,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 919d1f2..3626101 100644
--- a/src/DotNetOpenAuth/DotNetOpenAuth.csproj
+++ b/src/DotNetOpenAuth/DotNetOpenAuth.csproj
@@ -173,6 +173,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>
@@ -221,13 +222,13 @@ http://opensource.org/licenses/ms-pl.html
</Reference>
</ItemGroup>
<ItemGroup Condition=" '$(ClrVersion)' == '4' ">
- <Reference Include="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"/>
+ <Reference Include="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
</ItemGroup>
<ItemGroup Condition=" '$(ClrVersion)' != '4' ">
<!-- MVC 2 can run on CLR 2 (it doesn't require CLR 4) but since MVC 2 apps tend to use type forwarding,
it's a more broadly consumable idea to bind against MVC 1 for the library unless we're building on CLR 4,
which will definitely have MVC 2 available. -->
- <Reference Include="System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"/>
+ <Reference Include="System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
</ItemGroup>
<ItemGroup>
<Compile Include="ComponentModel\ClaimTypeSuggestions.cs" />
@@ -276,11 +277,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" />
@@ -302,6 +305,54 @@ http://opensource.org/licenses/ms-pl.html
<Compile Include="Messaging\Reflection\MessageDescriptionCollection.cs" />
<Compile Include="Mvc\OpenIdHelper.cs" />
<Compile Include="Mvc\OpenIdAjaxOptions.cs" />
+ <Compile Include="Messaging\StandardMessageFactory.cs" />
+ <Compile Include="OAuthWrap\AuthorizationServerBase.cs" />
+ <Compile Include="OAuthWrap\AuthorizationState.cs" />
+ <Compile Include="OAuthWrap\ChannelElements\AccessRequestBindingElement.cs" />
+ <Compile Include="OAuthWrap\ChannelElements\AccessToken.cs" />
+ <Compile Include="OAuthWrap\ChannelElements\AuthorizationDataBag.cs" />
+ <Compile Include="OAuthWrap\ChannelElements\AuthServerBindingElementBase.cs" />
+ <Compile Include="OAuthWrap\ChannelElements\IAccessTokenRequest.cs" />
+ <Compile Include="OAuthWrap\ChannelElements\IAuthorizationDescription.cs" />
+ <Compile Include="OAuthWrap\ChannelElements\ITokenCarryingRequest.cs" />
+ <Compile Include="OAuthWrap\ChannelElements\OAuthWrapResourceServerChannel.cs" />
+ <Compile Include="Messaging\StandardMessageFactoryChannel.cs" />
+ <Compile Include="OAuthWrap\ChannelElements\RefreshToken.cs" />
+ <Compile Include="OAuthWrap\ChannelElements\DataBag.cs" />
+ <Compile Include="OAuthWrap\ChannelElements\TimestampEncoder.cs" />
+ <Compile Include="OAuthWrap\ChannelElements\VerificationCode.cs" />
+ <Compile Include="OAuthWrap\ChannelElements\WebServerVerificationCodeBindingElement.cs" />
+ <Compile Include="OAuthWrap\ChannelElements\AuthServerAllFlowsBindingElement.cs" />
+ <Compile Include="OAuthWrap\IAccessTokenAnalyzer.cs" />
+ <Compile Include="OAuthWrap\IAuthorizationServer.cs" />
+ <Compile Include="OAuthWrap\IAuthorizationState.cs" />
+ <Compile Include="OAuthWrap\IClientTokenManager.cs" />
+ <Compile Include="OAuthWrap\Messages\AccessProtectedResourceRequest.cs" />
+ <Compile Include="OAuthWrap\Messages\Assertion\AssertionRequest.cs" />
+ <Compile Include="OAuthWrap\Messages\ClientCredentials\ClientCredentialsRequest.cs" />
+ <Compile Include="OAuthWrap\Messages\IAccessTokenSuccessResponse.cs" />
+ <Compile Include="OAuthWrap\Messages\IMessageWithClientState.cs" />
+ <Compile Include="OAuthWrap\Messages\IOAuthDirectResponseFormat.cs" />
+ <Compile Include="OAuthWrap\Messages\IRequestWithRedirectUri.cs" />
+ <Compile Include="OAuthWrap\Messages\RefreshAccessTokenRequest.cs" />
+ <Compile Include="OAuthWrap\Messages\Device\DeviceAccessTokenRequest.cs" />
+ <Compile Include="OAuthWrap\Messages\Device\DeviceRequest.cs" />
+ <Compile Include="OAuthWrap\Messages\Device\DeviceResponse.cs" />
+ <Compile Include="OAuthWrap\Messages\UnauthorizedResponse.cs" />
+ <Compile Include="OAuthWrap\Messages\AccessTokenFailedResponse.cs" />
+ <Compile Include="OAuthWrap\Messages\AccessTokenSuccessResponse.cs" />
+ <Compile Include="OAuthWrap\Messages\UserAgent\UserAgentFailedResponse.cs" />
+ <Compile Include="OAuthWrap\Messages\UserAgent\UserAgentRequest.cs" />
+ <Compile Include="OAuthWrap\Messages\UserAgent\UserAgentSuccessResponse.cs" />
+ <Compile Include="OAuthWrap\Messages\UsernameAndPassword\UserNamePasswordCaptchaResponse.cs" />
+ <Compile Include="OAuthWrap\Messages\UsernameAndPassword\UserNamePasswordVerificationResponse.cs" />
+ <Compile Include="OAuthWrap\Messages\ResponseFormat.cs" />
+ <Compile Include="OAuthWrap\Messages\ResponseFormatEncoder.cs" />
+ <Compile Include="OAuthWrap\ResourceServer.cs" />
+ <Compile Include="OAuthWrap\StandardAccessTokenAnalyzer.cs" />
+ <Compile Include="OAuthWrap\UserAgentClient.cs" />
+ <Compile Include="OAuthWrap\WebServerAuthorizationServer.cs" />
+ <Compile Include="OAuthWrap\WrapUtilities.cs" />
<Compile Include="OAuth\ChannelElements\ICombinedOpenIdProviderTokenManager.cs" />
<Compile Include="OAuth\ChannelElements\IConsumerDescription.cs" />
<Compile Include="OAuth\ChannelElements\IConsumerTokenManager.cs" />
@@ -445,7 +496,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" />
@@ -588,6 +639,24 @@ http://opensource.org/licenses/ms-pl.html
<Compile Include="Messaging\StandardWebRequestHandler.cs" />
<Compile Include="Messaging\MessageReceivingEndpoint.cs" />
<Compile Include="Reporting.cs" />
+ <Compile Include="OAuthWrap\ChannelElements\OAuthWrapAuthorizationServerChannel.cs" />
+ <Compile Include="OAuthWrap\ClientBase.cs" />
+ <Compile Include="OAuthWrap\Messages\MessageBase.cs" />
+ <Compile Include="OAuthWrap\Messages\WebServer\WebServerAccessTokenRequest.cs" />
+ <Compile Include="OAuthWrap\Messages\WebServer\WebServerFailedResponse.cs" />
+ <Compile Include="OAuthWrap\Messages\WebServer\WebServerRequest.cs" />
+ <Compile Include="OAuthWrap\Messages\WebServer\WebServerSuccessResponse.cs" />
+ <Compile Include="OAuthWrap\Messages\UsernameAndPassword\UserNamePasswordFailedResponse.cs" />
+ <Compile Include="OAuthWrap\Messages\UsernameAndPassword\UserNamePasswordRequest.cs" />
+ <Compile Include="OAuthWrap\Messages\UsernameAndPassword\UserNamePasswordSuccessResponse.cs" />
+ <Compile Include="OAuthWrap\Protocol.cs" />
+ <Compile Include="OAuthWrap\OAuthWrapStrings.Designer.cs">
+ <AutoGen>True</AutoGen>
+ <DesignTime>True</DesignTime>
+ <DependentUpon>OAuthWrapStrings.resx</DependentUpon>
+ </Compile>
+ <Compile Include="OAuthWrap\AuthorizationServerDescription.cs" />
+ <Compile Include="OAuthWrap\WebServerClient.cs" />
<Compile Include="Util.cs" />
<Compile Include="OAuth\Protocol.cs" />
<Compile Include="OAuth\ServiceProvider.cs" />
@@ -700,6 +769,10 @@ http://opensource.org/licenses/ms-pl.html
<EmbeddedResource Include="OpenId\RelyingParty\OpenIdRelyingPartyAjaxControlBase.js">
<Copyright>$(StandardCopyright)</Copyright>
</EmbeddedResource>
+ <EmbeddedResource Include="OAuthWrap\OAuthWrapStrings.resx">
+ <Generator>ResXFileCodeGenerator</Generator>
+ <LastGenOutput>OAuthWrapStrings.Designer.cs</LastGenOutput>
+ </EmbeddedResource>
<EmbeddedResource Include="Strings.sr.resx" />
<EmbeddedResource Include="Xrds\XrdsStrings.sr.resx" />
</ItemGroup>
@@ -730,31 +803,19 @@ http://opensource.org/licenses/ms-pl.html
</BootstrapperPackage>
<Content Include="DotNetOpenAuth.ico" />
</ItemGroup>
-
<ItemGroup>
<SignDependsOn Include="BuildUnifiedProduct" />
- <DelaySignedAssemblies Include="$(ILMergeOutputAssembly);
- $(OutputPath)CodeContracts\$(ProductName).Contracts.dll;
- " />
+ <DelaySignedAssemblies Include="$(ILMergeOutputAssembly);&#xD;&#xA; $(OutputPath)CodeContracts\$(ProductName).Contracts.dll;&#xD;&#xA; " />
</ItemGroup>
- <PropertyGroup>
- <!-- Don't sign the non-unified version of the assembly. -->
- <SuppressTargetPathDelaySignedAssembly>true</SuppressTargetPathDelaySignedAssembly>
- </PropertyGroup>
-
- <Target Name="BuildUnifiedProduct"
- DependsOnTargets="Build"
- Inputs="@(ILMergeInputAssemblies)"
- Outputs="$(ILMergeOutputAssembly)">
+ <ItemGroup />
+ <PropertyGroup>
+ <!-- Don't sign the non-unified version of the assembly. -->
+ <SuppressTargetPathDelaySignedAssembly>true</SuppressTargetPathDelaySignedAssembly>
+ </PropertyGroup>
+ <Target Name="BuildUnifiedProduct" DependsOnTargets="Build" Inputs="@(ILMergeInputAssemblies)" Outputs="$(ILMergeOutputAssembly)">
<MakeDir Directories="$(ILMergeOutputAssemblyDirectory)" />
- <ILMerge ExcludeFile="$(ProjectRoot)ILMergeInternalizeExceptions.txt"
- InputAssemblies="@(ILMergeInputAssemblies)"
- OutputFile="$(ILMergeOutputAssembly)"
- KeyFile="$(PublicKeyFile)"
- DelaySign="true"
- />
+ <ILMerge ExcludeFile="$(ProjectRoot)ILMergeInternalizeExceptions.txt" InputAssemblies="@(ILMergeInputAssemblies)" OutputFile="$(ILMergeOutputAssembly)" KeyFile="$(PublicKeyFile)" DelaySign="true" />
</Target>
-
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
-</Project>
+</Project> \ No newline at end of file
diff --git a/src/DotNetOpenAuth/Logger.cs b/src/DotNetOpenAuth/Logger.cs
index 48007ed..7c8691c 100644
--- a/src/DotNetOpenAuth/Logger.cs
+++ b/src/DotNetOpenAuth/Logger.cs
@@ -75,6 +75,11 @@ namespace DotNetOpenAuth {
private static readonly ILog oauth = Create("DotNetOpenAuth.OAuth");
/// <summary>
+ /// Backing field for the <see cref="Wrap"/> property.
+ /// </summary>
+ private static readonly ILog wrap = Create("DotNetOpenAuth.WRAP");
+
+ /// <summary>
/// Backing field for the <see cref="InfoCard"/> property.
/// </summary>
private static readonly ILog infocard = Create("DotNetOpenAuth.InfoCard");
@@ -130,6 +135,11 @@ namespace DotNetOpenAuth {
internal static ILog OAuth { get { return oauth; } }
/// <summary>
+ /// Gets the logger for the high-level OAuth WRAP events.
+ /// </summary>
+ internal static ILog Wrap { get { return wrap; } }
+
+ /// <summary>
/// Gets the logger for high-level InfoCard events.
/// </summary>
internal static ILog InfoCard { get { return infocard; } }
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 cc411c8..76dab88 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;
}
@@ -201,11 +220,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>
@@ -224,6 +244,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.
@@ -634,6 +660,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);
@@ -641,10 +668,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);
}
@@ -657,9 +705,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);
@@ -667,7 +716,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 {
@@ -733,7 +787,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) {
@@ -755,6 +809,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>
@@ -870,7 +957,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..950791f 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"/>
+ /// 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"/>
+ /// 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 6f8c4f9..21fd53a 100644
--- a/src/DotNetOpenAuth/Messaging/MessagingStrings.Designer.cs
+++ b/src/DotNetOpenAuth/Messaging/MessagingStrings.Designer.cs
@@ -1,7 +1,7 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
-// Runtime Version:4.0.30319.1
+// Runtime Version:4.0.30426.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
@@ -349,6 +349,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 {
@@ -421,6 +430,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 bdf4f68..3a265f1 100644
--- a/src/DotNetOpenAuth/Messaging/MessagingStrings.resx
+++ b/src/DotNetOpenAuth/Messaging/MessagingStrings.resx
@@ -303,4 +303,10 @@
<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>
</root> \ No newline at end of file
diff --git a/src/DotNetOpenAuth/Messaging/MessagingUtilities.cs b/src/DotNetOpenAuth/Messaging/MessagingUtilities.cs
index 6a55bc9..60fbdd8 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,30 @@ namespace DotNetOpenAuth.Messaging {
}
/// <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 +286,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 +393,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>
/// Adds a set of HTTP headers to an <see cref="HttpResponse"/> instance,
/// taking care to set some headers to the appropriate properties of
/// <see cref="HttpResponse" />
@@ -651,6 +980,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>
@@ -743,6 +1101,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>
@@ -948,6 +1318,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..c1e7aa2 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));
+ }
+ }
+
+ /// <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>
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 dc59b56..fe1f89c 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthChannel.cs
+++ b/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthChannel.cs
@@ -116,34 +116,13 @@ 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);
- }
- }
- }
- }
+ var fields = MessagingUtilities.ParseAuthorizationHeader(Protocol.AuthorizationHeaderScheme, authorization).ToDictionary();
// 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) {
@@ -344,20 +323,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/OAuthWrap/AuthorizationServerBase.cs b/src/DotNetOpenAuth/OAuthWrap/AuthorizationServerBase.cs
new file mode 100644
index 0000000..db6aa2d
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/AuthorizationServerBase.cs
@@ -0,0 +1,85 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthorizationServerBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap {
+ 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.OAuthWrap.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 OAuthWrapAuthorizationServerChannel(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 OAuthWrapAuthorizationServerChannel 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(IAccessTokenRequest request, RSAParameters accessTokenEncryptingPublicKey, TimeSpan? accessTokenLifetime = null, bool includeRefreshToken = true) {
+ Contract.Requires<ArgumentNullException>(request != null, "request");
+
+ var tokenRequest = (ITokenCarryingRequest)request;
+ var accessToken = new AccessToken(
+ this.AuthorizationServer.AccessTokenSigningPrivateKey,
+ accessTokenEncryptingPublicKey,
+ tokenRequest.AuthorizationDescription,
+ accessTokenLifetime);
+
+ var response = new AccessTokenSuccessResponse(request) {
+ Scope = tokenRequest.AuthorizationDescription.Scope,
+ AccessToken = accessToken.Encode(),
+ Lifetime = accessToken.Lifetime,
+ };
+
+ if (includeRefreshToken) {
+ var refreshToken = new RefreshToken(this.AuthorizationServer.Secret, tokenRequest.AuthorizationDescription);
+ response.RefreshToken = refreshToken.Encode();
+ }
+
+ return response;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/AuthorizationServerDescription.cs b/src/DotNetOpenAuth/OAuthWrap/AuthorizationServerDescription.cs
new file mode 100644
index 0000000..93cc1e1
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/AuthorizationServerDescription.cs
@@ -0,0 +1,62 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthorizationServerDescription.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+
+ /// <summary>
+ /// A description of an OAuth WRAP 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 WRAP version supported by the Authorization Server.
+ /// </summary>
+ public ProtocolVersion ProtocolVersion { get; set; }
+
+ /// <summary>
+ /// Gets the version of the OAuth WRAP 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/OAuthWrap/AuthorizationState.cs b/src/DotNetOpenAuth/OAuthWrap/AuthorizationState.cs
new file mode 100644
index 0000000..6ca7b4f
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/AuthorizationState.cs
@@ -0,0 +1,96 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthorizationState.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap {
+ using System;
+
+ /// <summary>
+ /// A simple memory-only copy of an authorization state.
+ /// </summary>
+ public class AuthorizationState : IAuthorizationState {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthorizationState"/> class.
+ /// </summary>
+ public AuthorizationState() {
+ }
+
+ /// <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 secret.
+ /// </summary>
+ /// <value>The access token secret.</value>
+ public string AccessTokenSecret { get; set; }
+
+ /// <summary>
+ /// Gets or sets the type of the access token secret.
+ /// </summary>
+ /// <value>The type of the access token secret.</value>
+ public string AccessTokenSecretType { 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 string Scope { get; 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/OAuthWrap/ChannelElements/AccessRequestBindingElement.cs b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/AccessRequestBindingElement.cs
new file mode 100644
index 0000000..1943021
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/AccessRequestBindingElement.cs
@@ -0,0 +1,119 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessRequestBindingElement.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+
+ /// <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 tokenRequest = message as ITokenCarryingRequest;
+ if (tokenRequest != null) {
+ var tokenBag = (AuthorizationDataBag)tokenRequest.AuthorizationDescription;
+ tokenRequest.CodeOrToken = tokenBag.Encode();
+
+ 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 tokenRequest = message as ITokenCarryingRequest;
+ if (tokenRequest != null) {
+ try {
+ switch (tokenRequest.CodeOrTokenType) {
+ case CodeOrTokenType.VerificationCode:
+ tokenRequest.AuthorizationDescription = VerificationCode.Decode(this.AuthorizationServer.Secret, this.AuthorizationServer.VerificationCodeNonceStore, tokenRequest.CodeOrToken, message);
+ break;
+ case CodeOrTokenType.RefreshToken:
+ tokenRequest.AuthorizationDescription = RefreshToken.Decode(this.AuthorizationServer.Secret, tokenRequest.CodeOrToken, message);
+ 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 IAccessTokenRequest;
+ 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 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/OAuthWrap/ChannelElements/AccessToken.cs b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/AccessToken.cs
new file mode 100644
index 0000000..0fba167
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/AccessToken.cs
@@ -0,0 +1,90 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessToken.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.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>
+ /// <param name="signingKey">The signing key.</param>
+ /// <param name="encryptingKey">The encrypting key.</param>
+ /// <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(RSAParameters signingKey, RSAParameters encryptingKey, IAuthorizationDescription authorization, TimeSpan? lifetime)
+ : this(signingKey, encryptingKey) {
+ Contract.Requires<ArgumentNullException>(authorization != null, "authorization");
+
+ this.ClientIdentifier = authorization.ClientIdentifier;
+ this.UtcCreationDate = authorization.UtcIssued;
+ this.User = authorization.User;
+ this.Scope = authorization.Scope;
+ this.Lifetime = lifetime;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessToken"/> class.
+ /// </summary>
+ /// <param name="signingKey">The signing key.</param>
+ /// <param name="encryptingKey">The encrypting key.</param>
+ private AccessToken(RSAParameters signingKey, RSAParameters encryptingKey)
+ : base(signingKey, encryptingKey) {
+ }
+
+ /// <summary>
+ /// Gets or sets the lifetime of the access token.
+ /// </summary>
+ /// <value>The lifetime.</value>
+ [MessagePart]
+ internal TimeSpan? Lifetime { get; set; }
+
+ /// <summary>
+ /// Deserializes an access token.
+ /// </summary>
+ /// <param name="signingKey">The signing public key.</param>
+ /// <param name="encryptingKey">The encrypting private key.</param>
+ /// <param name="value">The access token.</param>
+ /// <param name="containingMessage">The message containing this token.</param>
+ /// <returns>The access token.</returns>
+ internal static AccessToken Decode(RSAParameters signingKey, RSAParameters encryptingKey, string value, IProtocolMessage containingMessage) {
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(value));
+ Contract.Requires<ArgumentNullException>(containingMessage != null, "containingMessage");
+ Contract.Ensures(Contract.Result<AccessToken>() != null);
+
+ var self = new AccessToken(signingKey, encryptingKey);
+ self.Decode(value, containingMessage);
+ return self;
+ }
+
+ /// <summary>
+ /// Populates this instance with data from a given string.
+ /// </summary>
+ /// <param name="value">The value to deserialize from.</param>
+ /// <param name="containingMessage">The message that contained this token.</param>
+ protected override void Decode(string value, IProtocolMessage containingMessage) {
+ base.Decode(value, containingMessage);
+
+ // Has this token expired?
+ if (this.Lifetime.HasValue) {
+ DateTime expirationDate = this.UtcCreationDate + this.Lifetime.Value;
+ if (expirationDate < DateTime.UtcNow) {
+ throw new ExpiredMessageException(expirationDate, containingMessage);
+ }
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/ChannelElements/AuthServerAllFlowsBindingElement.cs b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/AuthServerAllFlowsBindingElement.cs
new file mode 100644
index 0000000..3c4d3e2
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/AuthServerAllFlowsBindingElement.cs
@@ -0,0 +1,83 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthServerAllFlowsBindingElement.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.OAuthWrap.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 IRequestWithRedirectUri;
+ if (authorizationRequest != null) {
+ var client = this.AuthorizationServer.GetClientOrThrow(authorizationRequest.ClientIdentifier);
+ ErrorUtilities.VerifyProtocol(client.Callback == null || client.Callback == authorizationRequest.Callback, OAuthWrapStrings.CallbackMismatch, client.Callback, authorizationRequest.Callback);
+ ErrorUtilities.VerifyProtocol(client.Callback != null || authorizationRequest.Callback != null, OAuthWrapStrings.NoCallback);
+
+ return MessageProtections.None;
+ }
+
+ return null;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/ChannelElements/AuthServerBindingElementBase.cs b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/AuthServerBindingElementBase.cs
new file mode 100644
index 0000000..dfc03f8
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/AuthServerBindingElementBase.cs
@@ -0,0 +1,92 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthServerBindingElementBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.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 OAuthWrapAuthorizationServerChannel OAuthChannel {
+ get { return (OAuthWrapAuthorizationServerChannel)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/OAuthWrap/ChannelElements/AuthorizationDataBag.cs b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/AuthorizationDataBag.cs
new file mode 100644
index 0000000..ef7e390
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/AuthorizationDataBag.cs
@@ -0,0 +1,73 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthorizationDataBag.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.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>
+ /// <param name="secret">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>
+ protected AuthorizationDataBag(byte[] secret, bool signed = false, bool encrypted = false, bool compressed = false, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null)
+ : base(secret, signed, encrypted, compressed, maximumAge, decodeOnceOnly) {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthorizationDataBag"/> 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>
+ protected AuthorizationDataBag(RSAParameters? signingKey = null, RSAParameters? encryptingKey = null, bool compressed = false, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null)
+ : base(signingKey, encryptingKey, compressed, maximumAge, decodeOnceOnly) {
+ }
+
+ /// <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]
+ public string Scope { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/ChannelElements/DataBag.cs b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/DataBag.cs
new file mode 100644
index 0000000..4994468
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/DataBag.cs
@@ -0,0 +1,343 @@
+//-----------------------------------------------------------------------
+// <copyright file="DataBag.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.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.OAuthWrap.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>
+ /// The message description cache to use for data bag types.
+ /// </summary>
+ private static readonly MessageDescriptionCollection MessageDescriptions = new MessageDescriptionCollection();
+
+ /// <summary>
+ /// The length of the nonce to include in tokens that can be decoded once only.
+ /// </summary>
+ private const int NonceLength = 6;
+
+ /// <summary>
+ /// The 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="DataBag"/> 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>
+ protected DataBag(bool signed = false, bool encrypted = false, bool compressed = false, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null)
+ : base(Protocol.Default.Version) {
+ 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="DataBag"/> 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>
+ protected DataBag(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="DataBag"/> 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>
+ protected DataBag(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;
+ }
+
+ /// <summary>
+ /// Gets or sets the nonce.
+ /// </summary>
+ /// <value>The nonce.</value>
+ [MessagePart]
+ internal string 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 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; }
+ }
+
+ /// <summary>
+ /// Gets or sets the signature.
+ /// </summary>
+ /// <value>The signature.</value>
+ [MessagePart("sig")]
+ private string Signature { get; set; }
+
+ /// <summary>
+ /// Serializes this instance as a string that can be sent as part of a larger message.
+ /// </summary>
+ /// <returns>The serialized version of the data in this instance.</returns>
+ internal virtual string Encode() {
+ Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()));
+
+ this.UtcCreationDate = DateTime.UtcNow;
+
+ if (this.decodeOnceOnly != null) {
+ this.Nonce = Convert.ToBase64String(MessagingUtilities.GetNonCryptoRandomData(NonceLength));
+ }
+
+ if (this.signed) {
+ this.Signature = this.CalculateSignature();
+ }
+
+ var fields = MessageSerializer.Get(this.GetType()).Serialize(MessageDescriptions.GetAccessor(this));
+ 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);
+ }
+
+ /// <summary>
+ /// Populates this instance with data from a given string.
+ /// </summary>
+ /// <param name="value">The value to deserialize from.</param>
+ /// <param name="containingMessage">The message that contained this token.</param>
+ protected virtual void Decode(string value, IProtocolMessage containingMessage) {
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(value));
+ Contract.Requires<ArgumentNullException>(containingMessage != null, "containingMessage");
+
+ byte[] encoded = Convert.FromBase64String(value);
+
+ if (this.encrypted) {
+ encoded = this.Decrypt(encoded);
+ }
+
+ if (this.compressed) {
+ encoded = MessagingUtilities.Decompress(encoded);
+ }
+
+ value = Encoding.UTF8.GetString(encoded);
+
+ // Deserialize into this newly created instance.
+ var serializer = MessageSerializer.Get(this.GetType());
+ var fields = MessageDescriptions.GetAccessor(this);
+ serializer.Deserialize(HttpUtility.ParseQueryString(value).ToDictionary(), fields);
+
+ if (this.signed) {
+ // Verify that the verification code was issued by this authorization server.
+ ErrorUtilities.VerifyProtocol(this.IsSignatureValid(), Protocol.bad_verification_code);
+ }
+
+ if (this.maximumAge.HasValue) {
+ // Has this verification code expired?
+ DateTime expirationDate = this.UtcCreationDate + this.maximumAge.Value;
+ if (expirationDate < DateTime.UtcNow) {
+ throw new ExpiredMessageException(expirationDate, containingMessage);
+ }
+ }
+
+ // Has this 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, this.Nonce, this.UtcCreationDate)) {
+ Logger.OpenId.ErrorFormat("Replayed nonce detected ({0} {1}). Rejecting message.", this.Nonce, this.UtcCreationDate);
+ throw new ReplayedMessageException(containingMessage);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Determines whether the signature on this instance is valid.
+ /// </summary>
+ /// <returns>
+ /// <c>true</c> if the signature is valid; otherwise, <c>false</c>.
+ /// </returns>
+ private bool IsSignatureValid() {
+ if (this.asymmetricSigning != null) {
+ byte[] bytesToSign = this.GetBytesToSign();
+ byte[] signature = Convert.FromBase64String(this.Signature);
+ return this.asymmetricSigning.VerifyData(bytesToSign, this.hasherForAsymmetricSigning, signature);
+ } else {
+ return string.Equals(this.Signature, this.CalculateSignature(), StringComparison.Ordinal);
+ }
+ }
+
+ /// <summary>
+ /// Calculates the signature for the data in this verification code.
+ /// </summary>
+ /// <returns>The calculated signature.</returns>
+ private string CalculateSignature() {
+ Contract.Requires<InvalidOperationException>(this.asymmetricSigning != null || this.symmetricHasher != null);
+
+ byte[] bytesToSign = this.GetBytesToSign();
+ if (this.asymmetricSigning != null) {
+ byte[] signature = this.asymmetricSigning.SignData(bytesToSign, this.hasherForAsymmetricSigning);
+ return Convert.ToBase64String(signature);
+ } else {
+ return Convert.ToBase64String(this.symmetricHasher.ComputeHash(bytesToSign));
+ }
+ }
+
+ /// <summary>
+ /// Gets the bytes to sign.
+ /// </summary>
+ /// <returns>A buffer of the bytes to sign.</returns>
+ private byte[] GetBytesToSign() {
+ // Sign the data, being sure to avoid any impact of the signature field itself.
+ var fields = MessageDescriptions.GetAccessor(this);
+ 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/OAuthWrap/ChannelElements/IAccessTokenRequest.cs b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/IAccessTokenRequest.cs
new file mode 100644
index 0000000..e270eac
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/IAccessTokenRequest.cs
@@ -0,0 +1,36 @@
+//-----------------------------------------------------------------------
+// <copyright file="IAccessTokenRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using Messages;
+ using Messaging;
+
+ /// <summary>
+ /// A message from the client to the authorization server requesting an access token.
+ /// </summary>
+ public interface IAccessTokenRequest : IDirectedProtocolMessage {
+ /// <summary>
+ /// Gets the client identifier.
+ /// </summary>
+ /// <value>The client identifier.</value>
+ string ClientIdentifier { get; }
+
+ /// <summary>
+ /// Gets the client secret.
+ /// </summary>
+ /// <value>The client secret.</value>
+ string ClientSecret { get; }
+
+ /// <summary>
+ /// Gets the type of access token secret requested.
+ /// </summary>
+ string SecretType { get; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/ChannelElements/IAuthorizationDescription.cs b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/IAuthorizationDescription.cs
new file mode 100644
index 0000000..9e75594
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/IAuthorizationDescription.cs
@@ -0,0 +1,87 @@
+//-----------------------------------------------------------------------
+// <copyright file="IAuthorizationDescription.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.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>
+ 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>
+ string IAuthorizationDescription.Scope {
+ get { throw new NotImplementedException(); }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/ChannelElements/ITokenCarryingRequest.cs b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/ITokenCarryingRequest.cs
new file mode 100644
index 0000000..335bf28
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/ITokenCarryingRequest.cs
@@ -0,0 +1,52 @@
+//-----------------------------------------------------------------------
+// <copyright file="ITokenCarryingRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.ChannelElements {
+ 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>
+ VerificationCode,
+
+ /// <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/OAuthWrap/ChannelElements/OAuthWrapAuthorizationServerChannel.cs b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/OAuthWrapAuthorizationServerChannel.cs
new file mode 100644
index 0000000..029d583
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/OAuthWrapAuthorizationServerChannel.cs
@@ -0,0 +1,201 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuthWrapAuthorizationServerChannel.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Net;
+ using System.Net.Mime;
+ using System.Runtime.Serialization.Json;
+ using System.Security.Cryptography;
+ using System.Text;
+ using System.Web;
+ using System.Web.Script.Serialization;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+ using DotNetOpenAuth.Messaging.Reflection;
+ using DotNetOpenAuth.OAuthWrap.Messages;
+
+ /// <summary>
+ /// The channel for the OAuth WRAP protocol.
+ /// </summary>
+ internal class OAuthWrapAuthorizationServerChannel : StandardMessageFactoryChannel {
+ /// <summary>
+ /// The messages receivable by this channel.
+ /// </summary>
+ private static readonly Type[] MessageTypes = new Type[] {
+ typeof(Messages.RefreshAccessTokenRequest),
+ typeof(Messages.AccessTokenSuccessResponse),
+ typeof(Messages.AccessTokenFailedResponse),
+ typeof(Messages.UnauthorizedResponse),
+ typeof(Messages.AssertionRequest),
+ typeof(Messages.ClientCredentialsRequest),
+ typeof(Messages.DeviceRequest),
+ typeof(Messages.DeviceResponse),
+ typeof(Messages.DeviceAccessTokenRequest),
+ typeof(Messages.UserNamePasswordRequest),
+ typeof(Messages.UserNamePasswordSuccessResponse),
+ typeof(Messages.UserNamePasswordVerificationResponse),
+ typeof(Messages.UserNamePasswordFailedResponse),
+ typeof(Messages.UsernamePasswordCaptchaResponse),
+ typeof(Messages.WebServerRequest),
+ typeof(Messages.WebServerSuccessResponse),
+ typeof(Messages.WebServerFailedResponse),
+ typeof(Messages.WebServerAccessTokenRequest),
+ typeof(Messages.UserAgentRequest),
+ typeof(Messages.UserAgentSuccessResponse),
+ typeof(Messages.UserAgentFailedResponse),
+ };
+
+ /// <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="OAuthWrapAuthorizationServerChannel"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ protected internal OAuthWrapAuthorizationServerChannel(IAuthorizationServer authorizationServer = null)
+ : base(MessageTypes, Versions, InitializeBindingElements(authorizationServer)) {
+ this.AuthorizationServer = authorizationServer;
+ }
+
+ /// <summary>
+ /// Gets the authorization server.
+ /// </summary>
+ /// <value>The authorization server. Will be null for channels serving clients.</value>
+ public IAuthorizationServer AuthorizationServer { get; private set; }
+
+ /// <summary>
+ /// Prepares an HTTP request that carries a given message.
+ /// </summary>
+ /// <param name="request">The message to send.</param>
+ /// <returns>
+ /// The <see cref="HttpWebRequest"/> prepared to send the request.
+ /// </returns>
+ /// <remarks>
+ /// This method must be overridden by a derived class, unless the <see cref="Channel.RequestCore"/> method
+ /// is overridden and does not require this method.
+ /// </remarks>
+ protected override HttpWebRequest CreateHttpRequest(IDirectedProtocolMessage request) {
+ HttpWebRequest httpRequest;
+ if ((request.HttpMethods & HttpDeliveryMethods.GetRequest) != 0) {
+ httpRequest = InitializeRequestAsGet(request);
+ } else if ((request.HttpMethods & HttpDeliveryMethods.PostRequest) != 0) {
+ httpRequest = InitializeRequestAsPost(request);
+ } else {
+ throw new NotSupportedException();
+ }
+
+ return httpRequest;
+ }
+
+ /// <summary>
+ /// Gets the protocol message that may be in the given HTTP response.
+ /// </summary>
+ /// <param name="response">The response that is anticipated to contain an protocol message.</param>
+ /// <returns>
+ /// The deserialized message parts, if found. Null otherwise.
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown when the response is not valid.</exception>
+ protected override IDictionary<string, string> ReadFromResponseCore(IncomingWebResponse response) {
+ // The spec says direct responses should be JSON objects, but Facebook uses HttpFormUrlEncoded instead, calling it text/plain
+ 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);
+ }
+ }
+
+ /// <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();
+ var fields = this.MessageDescriptions.GetAccessor(response);
+
+ var directResponse = (IDirectResponseProtocolMessage)response;
+ var formatSpecifyingRequest = directResponse.OriginatingRequest as IOAuthDirectResponseFormat;
+ if (formatSpecifyingRequest != null) {
+ ResponseFormat format = formatSpecifyingRequest.Format;
+ switch (format) {
+ case ResponseFormat.Xml:
+ // NOTE: the spec is missing details on how to formulate this.
+ throw new NotImplementedException();
+ case ResponseFormat.Form:
+ string form = MessagingUtilities.CreateQueryString(fields);
+ webResponse.SetResponse(form, HttpFormUrlEncodedContentType);
+ break;
+ case ResponseFormat.Json:
+ string json = this.SerializeAsJson(response);
+ webResponse.SetResponse(json, new ContentType(JsonEncoded));
+ break;
+ default:
+ throw ErrorUtilities.ThrowInternal("Unrecognized value of ResponseFormat enum: " + format);
+ }
+ }
+
+ 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) {
+ var bindingElements = new List<IChannelBindingElement>();
+
+ if (authorizationServer != null) {
+ bindingElements.Add(new AuthServerAllFlowsBindingElement());
+ bindingElements.Add(new WebServerVerificationCodeBindingElement());
+ bindingElements.Add(new AccessRequestBindingElement());
+ }
+
+ return bindingElements.ToArray();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/ChannelElements/OAuthWrapResourceServerChannel.cs b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/OAuthWrapResourceServerChannel.cs
new file mode 100644
index 0000000..53821d2
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/OAuthWrapResourceServerChannel.cs
@@ -0,0 +1,152 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuthWrapResourceServerChannel.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.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.OAuthWrap.Messages;
+
+ /// <summary>
+ /// The channel for the OAuth WRAP protocol.
+ /// </summary>
+ internal class OAuthWrapResourceServerChannel : 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="OAuthWrapResourceServerChannel"/> class.
+ /// </summary>
+ protected internal OAuthWrapResourceServerChannel()
+ : 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/OAuthWrap/ChannelElements/RefreshToken.cs b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/RefreshToken.cs
new file mode 100644
index 0000000..e95c5cc
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/RefreshToken.cs
@@ -0,0 +1,63 @@
+//-----------------------------------------------------------------------
+// <copyright file="RefreshToken.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.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>
+ /// <param name="secret">The symmetric secret used to sign/encrypt refresh tokens.</param>
+ /// <param name="authorization">The authorization this refresh token should describe.</param>
+ internal RefreshToken(byte[] secret, IAuthorizationDescription authorization)
+ : this(secret) {
+ Contract.Requires<ArgumentNullException>(secret != null, "secret");
+ Contract.Requires<ArgumentNullException>(authorization != null, "authorization");
+
+ this.ClientIdentifier = authorization.ClientIdentifier;
+ this.UtcCreationDate = authorization.UtcIssued;
+ this.User = authorization.User;
+ this.Scope = authorization.Scope;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RefreshToken"/> class.
+ /// </summary>
+ /// <param name="secret">The symmetric secret used to sign/encrypt refresh tokens.</param>
+ private RefreshToken(byte[] secret)
+ : base(secret, true, true) {
+ Contract.Requires<ArgumentNullException>(secret != null, "secret");
+ }
+
+ /// <summary>
+ /// Deserializes a refresh token.
+ /// </summary>
+ /// <param name="secret">The symmetric secret used to sign and encrypt the token.</param>
+ /// <param name="value">The token.</param>
+ /// <param name="containingMessage">The message containing this token.</param>
+ /// <returns>The refresh token.</returns>
+ internal static RefreshToken Decode(byte[] secret, string value, IProtocolMessage containingMessage) {
+ Contract.Requires<ArgumentNullException>(secret != null, "secret");
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(value));
+ Contract.Requires<ArgumentNullException>(containingMessage != null, "containingMessage");
+ Contract.Ensures(Contract.Result<RefreshToken>() != null);
+
+ var self = new RefreshToken(secret);
+ self.Decode(value, containingMessage);
+ return self;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/ChannelElements/TimestampEncoder.cs b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/TimestampEncoder.cs
new file mode 100644
index 0000000..26b3508
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/TimestampEncoder.cs
@@ -0,0 +1,61 @@
+//-----------------------------------------------------------------------
+// <copyright file="TimestampEncoder.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.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/OAuthWrap/ChannelElements/VerificationCode.cs b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/VerificationCode.cs
new file mode 100644
index 0000000..dcbec63
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/VerificationCode.cs
@@ -0,0 +1,115 @@
+//-----------------------------------------------------------------------
+// <copyright file="VerificationCode.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.ChannelElements {
+ using System;
+ using System.Diagnostics.Contracts;
+ using System.Security.Cryptography;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+
+ /// <summary>
+ /// Represents the verification code created when a user approves authorization that
+ /// allows the client to request an access/refresh token.
+ /// </summary>
+ internal class VerificationCode : 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="VerificationCode"/> class.
+ /// </summary>
+ /// <param name="secret">The symmetric secret to use in signing/encryption.</param>
+ /// <param name="nonceStore">The nonce store to use to ensure verification codes are used only once.</param>
+ /// <param name="clientIdentifier">The client identifier.</param>
+ /// <param name="callback">The callback the client used to obtain authorization.</param>
+ /// <param name="scope">The scope.</param>
+ /// <param name="username">The name on the account that authorized access.</param>
+ internal VerificationCode(byte[] secret, INonceStore nonceStore, string clientIdentifier, Uri callback, string scope, string username)
+ : this(secret, nonceStore) {
+ Contract.Requires<ArgumentNullException>(secret != null, "secret");
+ Contract.Requires<ArgumentNullException>(nonceStore != null, "nonceStore");
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(clientIdentifier));
+ Contract.Requires<ArgumentNullException>(secret != null, "secret");
+ Contract.Requires<ArgumentNullException>(callback != null, "callback");
+
+ this.ClientIdentifier = clientIdentifier;
+ this.CallbackHash = this.CalculateCallbackHash(callback);
+ this.Scope = scope;
+ this.User = username;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="VerificationCode"/> class.
+ /// </summary>
+ /// <param name="secret">The symmetric secret to use in signing/encryption.</param>
+ /// <param name="nonceStore">The nonce store to use to ensure verification codes are used only once.</param>
+ private VerificationCode(byte[] secret, INonceStore nonceStore)
+ : base(secret, true, true, false, MaximumMessageAge, nonceStore) {
+ Contract.Requires<ArgumentNullException>(secret != null, "secret");
+ Contract.Requires<ArgumentNullException>(nonceStore != null, "nonceStore");
+ }
+
+ /// <summary>
+ /// Gets the maximum message age from the standard expiration binding element.
+ /// </summary>
+ private static TimeSpan MaximumMessageAge {
+ get { return StandardExpirationBindingElement.MaximumMessageAge; }
+ }
+
+ /// <summary>
+ /// Gets or sets the hash of the callback URL.
+ /// </summary>
+ [MessagePart("cb")]
+ private string CallbackHash { get; set; }
+
+ /// <summary>
+ /// Deserializes a verification code.
+ /// </summary>
+ /// <param name="secret">The symmetric secret used to sign and encrypt the token.</param>
+ /// <param name="nonceStore">The nonce store to use to ensure verification codes can only be exchanged once.</param>
+ /// <param name="value">The verification token.</param>
+ /// <param name="containingMessage">The message containing this verification code.</param>
+ /// <returns>The verification code.</returns>
+ internal static VerificationCode Decode(byte[] secret, INonceStore nonceStore, string value, IProtocolMessage containingMessage) {
+ Contract.Requires<ArgumentNullException>(secret != null, "secret");
+ Contract.Requires<ArgumentNullException>(nonceStore != null, "nonceStore");
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(value));
+ Contract.Requires<ArgumentNullException>(containingMessage != null, "containingMessage");
+ Contract.Ensures(Contract.Result<VerificationCode>() != null);
+
+ var self = new VerificationCode(secret, nonceStore);
+ self.Decode(value, containingMessage);
+ return self;
+ }
+
+ /// <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(string.Equals(this.CallbackHash, this.CalculateCallbackHash(callback), StringComparison.Ordinal), 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 string CalculateCallbackHash(Uri callback) {
+ return this.hasher.ComputeHash(callback.AbsoluteUri);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/ChannelElements/WebServerVerificationCodeBindingElement.cs b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/WebServerVerificationCodeBindingElement.cs
new file mode 100644
index 0000000..1f0666f
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/WebServerVerificationCodeBindingElement.cs
@@ -0,0 +1,93 @@
+//-----------------------------------------------------------------------
+// <copyright file="WebServerVerificationCodeBindingElement.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.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 verification codes as part of obtaining access/refresh tokens.
+ /// </summary>
+ internal class WebServerVerificationCodeBindingElement : AuthServerBindingElementBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="WebServerVerificationCodeBindingElement"/> class.
+ /// </summary>
+ internal WebServerVerificationCodeBindingElement() {
+ }
+
+ /// <summary>
+ /// Gets the protection commonly offered (if any) by this binding element.
+ /// </summary>
+ /// <value>Always <c>MessageProtections.None</c></value>
+ /// <remarks>
+ /// This value is used to assist in sorting binding elements in the channel stack.
+ /// </remarks>
+ public override MessageProtections Protection {
+ get { return MessageProtections.None; }
+ }
+
+ /// <summary>
+ /// Prepares a message for sending based on the rules of this channel binding element.
+ /// </summary>
+ /// <param name="message">The message to prepare for sending.</param>
+ /// <returns>
+ /// The protections (if any) that this binding element applied to the message.
+ /// Null if this binding element did not even apply to this binding element.
+ /// </returns>
+ /// <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 WebServerSuccessResponse;
+ if (response != null) {
+ var directResponse = (IDirectResponseProtocolMessage)response;
+ var request = (WebServerRequest)directResponse.OriginatingRequest;
+ ITokenCarryingRequest tokenCarryingResponse = response;
+ tokenCarryingResponse.AuthorizationDescription = new VerificationCode(this.AuthorizationServer.Secret, this.AuthorizationServer.VerificationCodeNonceStore, 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 WebServerAccessTokenRequest;
+ if (request != null) {
+ ITokenCarryingRequest tokenRequest = request;
+ ((VerificationCode)tokenRequest.AuthorizationDescription).VerifyCallback(request.Callback);
+
+ return MessageProtections.None;
+ }
+
+ return null;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/ClientBase.cs b/src/DotNetOpenAuth/OAuthWrap/ClientBase.cs
new file mode 100644
index 0000000..a733b9b
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/ClientBase.cs
@@ -0,0 +1,177 @@
+//-----------------------------------------------------------------------
+// <copyright file="ClientBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap {
+ 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.OAuthWrap.ChannelElements;
+ using DotNetOpenAuth.OAuthWrap.Messages;
+
+ /// <summary>
+ /// A base class for common OAuth WRAP 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>
+ protected ClientBase(AuthorizationServerDescription authorizationServer) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null);
+ this.AuthorizationServer = authorizationServer;
+ this.Channel = new OAuthWrapAuthorizationServerChannel();
+ }
+
+ /// <summary>
+ /// Gets the token issuer.
+ /// </summary>
+ /// <value>The token issuer.</value>
+ public AuthorizationServerDescription AuthorizationServer { get; private set; }
+
+ /// <summary>
+ /// Gets the OAuth WRAP 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));
+
+ WrapUtilities.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 WRAP.</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.Wrap.DebugFormat("Skipping token refresh step because access token's remaining life is {0}, which exceeds {1}.", usefulLifeRemaining, skipIfUsefulLifeExceeds.Value);
+ return;
+ }
+ }
+
+ var request = new RefreshAccessTokenRequest(this.AuthorizationServer) {
+ ClientIdentifier = this.ClientIdentifier,
+ ClientSecret = this.ClientSecret,
+ RefreshToken = authorization.RefreshToken,
+ SecretType = authorization.AccessTokenSecretType,
+ };
+
+ var response = this.Channel.Request<AccessTokenSuccessResponse>(request);
+ authorization.AccessToken = response.AccessToken;
+ authorization.AccessTokenExpirationUtc = DateTime.UtcNow + response.Lifetime;
+ authorization.AccessTokenSecret = response.AccessTokenSecret;
+ authorization.AccessTokenIssueDateUtc = DateTime.UtcNow;
+
+ // Just in case the scope has changed...
+ if (response.Scope != null) {
+ authorization.Scope = 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, IAccessTokenSuccessResponse accessTokenSuccess) {
+ Contract.Requires<ArgumentNullException>(authorizationState != null, "authorizationState");
+ Contract.Requires<ArgumentNullException>(accessTokenSuccess != null, "accessTokenSuccess");
+
+ authorizationState.AccessToken = accessTokenSuccess.AccessToken;
+ authorizationState.AccessTokenSecret = accessTokenSuccess.AccessTokenSecret;
+ 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.Wrap.InfoFormat(
+ "Requested scope of \"{0}\" changed to \"{1}\" by authorization server.",
+ authorizationState.Scope,
+ accessTokenSuccess.Scope);
+ }
+
+ authorizationState.Scope = accessTokenSuccess.Scope;
+ }
+
+ authorizationState.SaveChanges();
+ }
+
+ /// <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/OAuthWrap/IAccessTokenAnalyzer.cs b/src/DotNetOpenAuth/OAuthWrap/IAccessTokenAnalyzer.cs
new file mode 100644
index 0000000..4e692c6
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/IAccessTokenAnalyzer.cs
@@ -0,0 +1,59 @@
+//-----------------------------------------------------------------------
+// <copyright file="IAccessTokenAnalyzer.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap {
+ 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>
+ 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 string scope);
+ }
+
+ /// <summary>
+ /// Code contract for the <see cref="IAccessTokenAnalyzer"/> interface.
+ /// </summary>
+ 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 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/OAuthWrap/IAuthorizationServer.cs b/src/DotNetOpenAuth/OAuthWrap/IAuthorizationServer.cs
new file mode 100644
index 0000000..c263277
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/IAuthorizationServer.cs
@@ -0,0 +1,170 @@
+//-----------------------------------------------------------------------
+// <copyright file="IAuthorizationServer.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap {
+ 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.OAuth.ChannelElements;
+ using DotNetOpenAuth.OAuthWrap.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 verification 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 verification code nonce store to use to ensure that verification codes can only be used once.
+ /// </summary>
+ /// <value>The verification 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 verification 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 verification code nonce store to use to ensure that verification codes can only be used once.
+ /// </summary>
+ /// <value>The verification 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/OAuthWrap/IAuthorizationState.cs b/src/DotNetOpenAuth/OAuthWrap/IAuthorizationState.cs
new file mode 100644
index 0000000..c0ac80d
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/IAuthorizationState.cs
@@ -0,0 +1,78 @@
+//-----------------------------------------------------------------------
+// <copyright file="IAuthorizationState.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap {
+ using System;
+
+ /// <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 secret.
+ /// </summary>
+ /// <value>The access token secret.</value>
+ string AccessTokenSecret { get; set; }
+
+ /// <summary>
+ /// Gets or sets the type of the access token secret.
+ /// </summary>
+ /// <value>The type of the access token secret.</value>
+ string AccessTokenSecretType { 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>
+ string Scope { 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>
+ 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/OAuthWrap/IClientTokenManager.cs b/src/DotNetOpenAuth/OAuthWrap/IClientTokenManager.cs
new file mode 100644
index 0000000..c6beb90
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/IClientTokenManager.cs
@@ -0,0 +1,53 @@
+//-----------------------------------------------------------------------
+// <copyright file="IClientTokenManager.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap {
+ using System;
+ using System.Diagnostics.Contracts;
+
+ /// <summary>
+ /// A token manager implemented by some clients to assist in tracking authorization state.
+ /// </summary>
+ [ContractClass(typeof(IClientTokenManagerContract))]
+ public interface 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>
+ IAuthorizationState GetAuthorizationState(Uri callbackUrl, string clientState);
+ }
+
+ /// <summary>
+ /// Contract class for the <see cref="IClientTokenManager"/> interface.
+ /// </summary>
+ [ContractClassFor(typeof(IClientTokenManager))]
+ internal abstract class IClientTokenManagerContract : IClientTokenManager {
+ /// <summary>
+ /// Prevents a default instance of the <see cref="IClientTokenManagerContract"/> class from being created.
+ /// </summary>
+ private IClientTokenManagerContract() {
+ }
+
+ #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 IClientTokenManager.GetAuthorizationState(Uri callbackUrl, string clientState) {
+ Contract.Requires<ArgumentNullException>(callbackUrl != null);
+ throw new NotImplementedException();
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/AccessProtectedResourceRequest.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/AccessProtectedResourceRequest.cs
new file mode 100644
index 0000000..c6f2de7
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/AccessProtectedResourceRequest.cs
@@ -0,0 +1,119 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessProtectedResourceRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.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/OAuthWrap/Messages/AccessTokenFailedResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/AccessTokenFailedResponse.cs
new file mode 100644
index 0000000..4a44aa3
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/AccessTokenFailedResponse.cs
@@ -0,0 +1,38 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessTokenFailedResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using ChannelElements;
+ 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 : UnauthorizedResponse {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenFailedResponse"/> class.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ internal AccessTokenFailedResponse(IAccessTokenRequest request)
+ : base(request) {
+ }
+
+ /// <summary>
+ /// Gets or sets the error.
+ /// </summary>
+ /// <value>The error.</value>
+ /// <remarks>
+ /// REQUIRED. The parameter value MUST be set to one of the values specified by each flow.
+ /// </remarks>
+ [MessagePart(Protocol.error, IsRequired = true, AllowEmpty = false)]
+ internal string Error { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/AccessTokenSuccessResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/AccessTokenSuccessResponse.cs
new file mode 100644
index 0000000..cf1a90e
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/AccessTokenSuccessResponse.cs
@@ -0,0 +1,91 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessTokenSuccessResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Net;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuthWrap.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, IAccessTokenSuccessResponse {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenSuccessResponse"/> class.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ internal AccessTokenSuccessResponse(IAccessTokenRequest request)
+ : base(request) {
+ }
+
+ /// <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 access token secret.
+ /// </summary>
+ /// <value>The access token secret.</value>
+ /// <remarks>
+ /// REQUIRED if requested by the client. The corresponding access token secret as requested by the client.
+ /// </remarks>
+ [MessagePart(Protocol.access_token_secret, IsRequired = false, AllowEmpty = false)]
+ public string AccessTokenSecret { 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)]
+ public string Scope { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/Assertion/AssertionRequest.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/Assertion/AssertionRequest.cs
new file mode 100644
index 0000000..6137d19
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/Assertion/AssertionRequest.cs
@@ -0,0 +1,114 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssertionRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuthWrap.ChannelElements;
+
+ /// <summary>
+ /// A request from a Client to an Authorization Server with some assertion for an access token.
+ /// </summary>
+ internal class AssertionRequest : MessageBase, IAccessTokenRequest, IOAuthDirectResponseFormat {
+ /// <summary>
+ /// The type of message.
+ /// </summary>
+ [MessagePart(Protocol.type, IsRequired = true)]
+ private const string Type = "assertion";
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AssertionRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ /// <param name="version">The version.</param>
+ internal AssertionRequest(Uri authorizationServer, Version version)
+ : base(version, MessageTransport.Direct, authorizationServer) {
+ this.HttpMethods = HttpDeliveryMethods.PostRequest;
+ }
+
+ /// <summary>
+ /// Gets or sets the identifier by which this client is known to the Authorization Server.
+ /// </summary>
+ /// <value>The client identifier.</value>
+ [MessagePart(Protocol.client_id, IsRequired = true, AllowEmpty = false)]
+ public string ClientIdentifier { get; set; }
+
+ /// <summary>
+ /// Gets or sets the client secret.
+ /// </summary>
+ /// <value>The client secret.</value>
+ /// <remarks>
+ /// REQUIRED if the client identifier has a matching secret. The client secret as described in Section 3.4 (Client Credentials).
+ /// </remarks>
+ [MessagePart(Protocol.client_secret, IsRequired = false, AllowEmpty = true)]
+ public string ClientSecret { get; set; }
+
+ /// <summary>
+ /// Gets or sets an optional authorization scope as defined by the Authorization Server.
+ /// </summary>
+ [MessagePart(Protocol.scope, IsRequired = false, AllowEmpty = true)]
+ public string Scope { get; internal set; }
+
+ /// <summary>
+ /// Gets or sets the type of the secret.
+ /// </summary>
+ /// <value>The type of the secret.</value>
+ /// <remarks>
+ /// OPTIONAL. The access token secret type as described by Section 5.3 (Cryptographic Tokens Requests). If omitted, the authorization server will issue a bearer token (an access token without a matching secret) as described by Section 5.2 (Bearer Token Requests).
+ /// </remarks>
+ [MessagePart(Protocol.secret_type, IsRequired = false, AllowEmpty = false)]
+ public string SecretType { get; internal set; }
+
+ /// <summary>
+ /// Gets the format the client is requesting the authorization server should deliver the request in.
+ /// </summary>
+ /// <value>The format.</value>
+ ResponseFormat IOAuthDirectResponseFormat.Format {
+ get { return this.Format.HasValue ? this.Format.Value : ResponseFormat.Json; }
+ }
+
+ /// <summary>
+ /// Gets or sets the format of the assertion as defined by the Authorization Server.
+ /// </summary>
+ /// <value>The assertion format.</value>
+ [MessagePart(Protocol.assertion_format, IsRequired = true, AllowEmpty = false)]
+ internal string AssertionFormat { 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; }
+
+ /// <summary>
+ /// Gets or sets the format the client is requesting the authorization server should deliver the request in.
+ /// </summary>
+ /// <value>The format.</value>
+ [MessagePart(Protocol.format, Encoder = typeof(ResponseFormatEncoder))]
+ private ResponseFormat? Format { get; set; }
+
+ /// <summary>
+ /// Checks the message state for conformity to the protocol specification
+ /// and throws an exception if the message is invalid.
+ /// </summary>
+ /// <remarks>
+ /// <para>Some messages have required fields, or combinations of fields that must relate to each other
+ /// in specialized ways. After deserializing a message, this method checks the state of the
+ /// message to see if it conforms to the protocol.</para>
+ /// <para>Note that this property should <i>not</i> check signatures or perform any state checks
+ /// outside this scope of this particular message.</para>
+ /// </remarks>
+ /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception>
+ protected override void EnsureValidMessage() {
+ base.EnsureValidMessage();
+ ErrorUtilities.VerifyProtocol(this.Recipient.IsTransportSecure(), OAuthWrapStrings.HttpsRequired);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/ClientCredentials/ClientCredentialsRequest.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/ClientCredentials/ClientCredentialsRequest.cs
new file mode 100644
index 0000000..56d5e3e
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/ClientCredentials/ClientCredentialsRequest.cs
@@ -0,0 +1,95 @@
+//-----------------------------------------------------------------------
+// <copyright file="ClientCredentialsRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuthWrap.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 ClientCredentialsRequest : MessageBase, IAccessTokenRequest, IOAuthDirectResponseFormat {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ClientCredentialsRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ /// <param name="version">The version.</param>
+ internal ClientCredentialsRequest(Uri authorizationServer, Version version)
+ : base(version, MessageTransport.Direct, authorizationServer) {
+ this.HttpMethods = HttpDeliveryMethods.PostRequest;
+ }
+
+ /// <summary>
+ /// Gets or sets the account name.
+ /// </summary>
+ /// <value>The name on the account.</value>
+ [MessagePart(Protocol.client_id, IsRequired = true, AllowEmpty = false)]
+ public string ClientIdentifier { get; internal set; }
+
+ /// <summary>
+ /// Gets or sets the user's password.
+ /// </summary>
+ /// <value>The password.</value>
+ [MessagePart(Protocol.client_secret, IsRequired = true, AllowEmpty = false)]
+ public string ClientSecret { get; internal set; }
+
+ /// <summary>
+ /// Gets or sets the type of the secret.
+ /// </summary>
+ /// <value>The type of the secret.</value>
+ /// <remarks>
+ /// OPTIONAL. The access token secret type as described by Section 5.3 (Cryptographic Tokens Requests). If omitted, the authorization server will issue a bearer token (an access token without a matching secret) as described by Section 5.2 (Bearer Token Requests).
+ /// </remarks>
+ [MessagePart(Protocol.secret_type, IsRequired = false, AllowEmpty = false)]
+ public string SecretType { get; set; }
+
+ /// <summary>
+ /// Gets the format the client is requesting the authorization server should deliver the request in.
+ /// </summary>
+ /// <value>The format.</value>
+ ResponseFormat IOAuthDirectResponseFormat.Format {
+ get { return this.Format.HasValue ? this.Format.Value : ResponseFormat.Json; }
+ }
+
+ /// <summary>
+ /// Gets or sets an optional authorization scope as defined by the Authorization Server.
+ /// </summary>
+ [MessagePart(Protocol.scope, IsRequired = false, AllowEmpty = true)]
+ internal string Scope { get; set; }
+
+ /// <summary>
+ /// Gets or sets the format the client is requesting the authorization server should deliver the request in.
+ /// </summary>
+ /// <value>The format.</value>
+ [MessagePart(Protocol.format, Encoder = typeof(ResponseFormatEncoder))]
+ private ResponseFormat? Format { get; set; }
+
+ /// <summary>
+ /// Checks the message state for conformity to the protocol specification
+ /// and throws an exception if the message is invalid.
+ /// </summary>
+ /// <remarks>
+ /// <para>Some messages have required fields, or combinations of fields that must relate to each other
+ /// in specialized ways. After deserializing a message, this method checks the state of the
+ /// message to see if it conforms to the protocol.</para>
+ /// <para>Note that this property should <i>not</i> check signatures or perform any state checks
+ /// outside this scope of this particular message.</para>
+ /// </remarks>
+ /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception>
+ protected override void EnsureValidMessage() {
+ base.EnsureValidMessage();
+ ErrorUtilities.VerifyProtocol(this.Recipient.IsTransportSecure(), OAuthWrapStrings.HttpsRequired);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/Device/DeviceAccessTokenRequest.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/Device/DeviceAccessTokenRequest.cs
new file mode 100644
index 0000000..4e1f850
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/Device/DeviceAccessTokenRequest.cs
@@ -0,0 +1,116 @@
+//-----------------------------------------------------------------------
+// <copyright file="DeviceAccessTokenRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuthWrap.ChannelElements;
+
+ /// <summary>
+ /// A message from the Client to the Authorization Server exchanging a
+ /// verification code for refresh and access tokens.
+ /// </summary>
+ internal class DeviceAccessTokenRequest : MessageBase, IAccessTokenRequest, IOAuthDirectResponseFormat {
+ /// <summary>
+ /// A constant that identifies the flow this message belongs to.
+ /// </summary>
+ [MessagePart(Protocol.type, IsRequired = true)]
+ private const string MessageType = "device_token";
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DeviceAccessTokenRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ /// <param name="version">The version.</param>
+ internal DeviceAccessTokenRequest(Uri authorizationServer, Version version)
+ : base(version, MessageTransport.Direct, authorizationServer) {
+ this.HttpMethods = HttpDeliveryMethods.PostRequest;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DeviceAccessTokenRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ internal DeviceAccessTokenRequest(AuthorizationServerDescription authorizationServer)
+ : this(authorizationServer.TokenEndpoint, authorizationServer.Version) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null);
+ Contract.Requires<ArgumentException>(authorizationServer.Version != null);
+ Contract.Requires<ArgumentException>(authorizationServer.TokenEndpoint != null);
+
+ // We prefer URL encoding of the data.
+ this.Format = ResponseFormat.Form;
+ }
+
+ /// <summary>
+ /// Gets or sets the identifier by which this client is known to 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 the client secret.
+ /// </summary>
+ /// <value>The client secret.</value>
+ string IAccessTokenRequest.ClientSecret {
+ get { return null; }
+ }
+
+ /// <summary>
+ /// Gets or sets the type of the secret.
+ /// </summary>
+ /// <value>The type of the secret.</value>
+ /// <remarks>
+ /// OPTIONAL. The access token secret type as described by Section 5.3 (Cryptographic Tokens Requests). If omitted, the authorization server will issue a bearer token (an access token without a matching secret) as described by Section 5.2 (Bearer Token Requests).
+ /// </remarks>
+ [MessagePart(Protocol.secret_type, IsRequired = false, AllowEmpty = false)]
+ public string SecretType { get; set; }
+
+ /// <summary>
+ /// Gets the format the client is requesting the authorization server should deliver the request in.
+ /// </summary>
+ /// <value>The format.</value>
+ ResponseFormat IOAuthDirectResponseFormat.Format {
+ get { return this.Format.HasValue ? this.Format.Value : ResponseFormat.Json; }
+ }
+
+ /// <summary>
+ /// Gets or sets the verification code previously communicated to the Client
+ /// in <see cref="DeviceResponse.VerificationCode"/>.
+ /// </summary>
+ /// <value>The verification code.</value>
+ [MessagePart(Protocol.code, IsRequired = true, AllowEmpty = false)]
+ internal string VerificationCode { get; set; }
+
+ /// <summary>
+ /// Gets or sets the format the client is requesting the authorization server should deliver the request in.
+ /// </summary>
+ /// <value>The format.</value>
+ [MessagePart(Protocol.format, Encoder = typeof(ResponseFormatEncoder))]
+ private ResponseFormat? Format { get; set; }
+
+ /// <summary>
+ /// Checks the message state for conformity to the protocol specification
+ /// and throws an exception if the message is invalid.
+ /// </summary>
+ /// <remarks>
+ /// <para>Some messages have required fields, or combinations of fields that must relate to each other
+ /// in specialized ways. After deserializing a message, this method checks the state of the
+ /// message to see if it conforms to the protocol.</para>
+ /// <para>Note that this property should <i>not</i> check signatures or perform any state checks
+ /// outside this scope of this particular message.</para>
+ /// </remarks>
+ /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception>
+ protected override void EnsureValidMessage() {
+ base.EnsureValidMessage();
+ ErrorUtilities.VerifyProtocol(this.Recipient.IsTransportSecure(), OAuthWrapStrings.HttpsRequired);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/Device/DeviceRequest.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/Device/DeviceRequest.cs
new file mode 100644
index 0000000..dfffe20
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/Device/DeviceRequest.cs
@@ -0,0 +1,79 @@
+//-----------------------------------------------------------------------
+// <copyright file="DeviceRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A request from a rich app Client to an Authorization Server requested
+ /// authorization to access user Protected Data.
+ /// </summary>
+ internal class DeviceRequest : MessageBase, IOAuthDirectResponseFormat {
+ /// <summary>
+ /// A constant that identifies the type of message coming into the auth server.
+ /// </summary>
+ [MessagePart(Protocol.type, IsRequired = true)]
+ private const string MessageType = "device_code";
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DeviceRequest"/> class.
+ /// </summary>
+ /// <param name="tokenEndpoint">The authorization server.</param>
+ /// <param name="version">The version.</param>
+ internal DeviceRequest(Uri tokenEndpoint, Version version)
+ : base(version, MessageTransport.Direct, tokenEndpoint) {
+ this.HttpMethods = HttpDeliveryMethods.GetRequest;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DeviceRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ internal DeviceRequest(AuthorizationServerDescription authorizationServer)
+ : this(authorizationServer.TokenEndpoint, authorizationServer.Version) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null);
+ Contract.Requires<ArgumentException>(authorizationServer.Version != null);
+ Contract.Requires<ArgumentException>(authorizationServer.TokenEndpoint != null);
+
+ // We prefer URL encoding of the data.
+ this.Format = ResponseFormat.Form;
+ }
+
+ /// <summary>
+ /// Gets the format the client is requesting the authorization server should deliver the request in.
+ /// </summary>
+ /// <value>The format.</value>
+ ResponseFormat IOAuthDirectResponseFormat.Format {
+ get { return this.Format.HasValue ? this.Format.Value : ResponseFormat.Json; }
+ }
+
+ /// <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)]
+ internal string ClientIdentifier { get; set; }
+
+ /// <summary>
+ /// Gets or sets the scope.
+ /// </summary>
+ /// <value>The Authorization Server MAY define authorization scope values for the Client to include.</value>
+ [MessagePart(Protocol.scope, IsRequired = false, AllowEmpty = true)]
+ internal string Scope { get; set; }
+
+ /// <summary>
+ /// Gets or sets the format the client is requesting the authorization server should deliver the request in.
+ /// </summary>
+ /// <value>The format.</value>
+ [MessagePart(Protocol.format, Encoder = typeof(ResponseFormatEncoder))]
+ private ResponseFormat? Format { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/Device/DeviceResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/Device/DeviceResponse.cs
new file mode 100644
index 0000000..783ddaa
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/Device/DeviceResponse.cs
@@ -0,0 +1,76 @@
+//-----------------------------------------------------------------------
+// <copyright file="DeviceResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// An indirect response from the Authorization Server to the rich app Client
+ /// with the verification code.
+ /// </summary>
+ internal class DeviceResponse : MessageBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DeviceResponse"/> class.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ internal DeviceResponse(DeviceRequest request)
+ : base(request) {
+ }
+
+ /// <summary>
+ /// Gets or sets the verification code.
+ /// </summary>
+ /// <value>
+ /// The long-lived credential assigned by the Authorization Server to this Client for
+ /// use in accessing the authorizing user's protected resources.
+ /// </value>
+ [MessagePart(Protocol.code, IsRequired = true, AllowEmpty = false)]
+ internal string VerificationCode { get; set; }
+
+ /// <summary>
+ /// Gets or sets the code the user must enter on the authorization page.
+ /// </summary>
+ /// <value>The user code.</value>
+ [MessagePart(Protocol.user_code, IsRequired = true, AllowEmpty = false)]
+ internal string UserCode { get; set; }
+
+ /// <summary>
+ /// Gets or sets the user authorization URI on the authorization server.
+ /// </summary>
+ /// <value>
+ /// REQUIRED. The end-user verification URI on the authorization server. The URI should be short and easy to remember as end-users will be asked to manually type it into their user-agent.
+ /// </value>
+ [MessagePart(Protocol.verification_uri, IsRequired = true)]
+ internal Uri VerificationUri { get; set; }
+
+ /// <summary>
+ /// Gets or sets the lifetime.
+ /// </summary>
+ /// <value>The lifetime.</value>
+ [MessagePart(Protocol.expires_in, IsRequired = false, Encoder = typeof(TimespanSecondsEncoder))]
+ internal TimeSpan? Lifetime { get; set; }
+
+ /// <summary>
+ /// Gets or sets the minimum amount of time that the client SHOULD wait between polling requests to the token endpoint.
+ /// </summary>
+ [MessagePart(Protocol.interval, IsRequired = false, Encoder = typeof(TimespanSecondsEncoder))]
+ internal TimeSpan? PollingInterval { get; set; }
+
+ /// <summary>
+ /// Gets a value indicating whether the user granted the authorization request.
+ /// </summary>
+ /// <value>
+ /// <c>true</c> if authorization is granted; otherwise, <c>false</c>.
+ /// </value>
+ internal bool IsGranted {
+ get { return !string.IsNullOrEmpty(this.VerificationCode) && this.VerificationCode != Protocol.user_denied; }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/IAccessTokenSuccessResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/IAccessTokenSuccessResponse.cs
new file mode 100644
index 0000000..12e7b66
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/IAccessTokenSuccessResponse.cs
@@ -0,0 +1,48 @@
+//-----------------------------------------------------------------------
+// <copyright file="IAccessTokenSuccessResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+
+ /// <summary>
+ /// A response message from the authorization server to the client that contains an access token
+ /// and possibly a refresh token
+ /// </summary>
+ internal interface IAccessTokenSuccessResponse {
+ /// <summary>
+ /// Gets the access token.
+ /// </summary>
+ /// <value>The access token.</value>
+ string AccessToken { get; }
+
+ /// <summary>
+ /// Gets the access token secret.
+ /// </summary>
+ /// <value>The access token secret.</value>
+ string AccessTokenSecret { get; }
+
+ /// <summary>
+ /// Gets the refresh token.
+ /// </summary>
+ /// <value>The refresh token.</value>
+ string RefreshToken { get; }
+
+ /// <summary>
+ /// Gets the lifetime.
+ /// </summary>
+ /// <value>The lifetime.</value>
+ TimeSpan? Lifetime { get; }
+
+ /// <summary>
+ /// Gets the scope.
+ /// </summary>
+ /// <value>The scope.</value>
+ string Scope { get; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/IMessageWithClientState.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/IMessageWithClientState.cs
new file mode 100644
index 0000000..1d42f54
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/IMessageWithClientState.cs
@@ -0,0 +1,21 @@
+//-----------------------------------------------------------------------
+// <copyright file="IMessageWithClientState.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.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/OAuthWrap/Messages/IOAuthDirectResponseFormat.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/IOAuthDirectResponseFormat.cs
new file mode 100644
index 0000000..5063995
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/IOAuthDirectResponseFormat.cs
@@ -0,0 +1,23 @@
+//-----------------------------------------------------------------------
+// <copyright file="IOAuthDirectResponseFormat.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+
+ /// <summary>
+ /// A message the includes a request for the format the response message should come in.
+ /// </summary>
+ internal interface IOAuthDirectResponseFormat {
+ /// <summary>
+ /// Gets the format the client is requesting the authorization server should deliver the request in.
+ /// </summary>
+ /// <value>The format.</value>
+ ResponseFormat Format { get; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/IRequestWithRedirectUri.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/IRequestWithRedirectUri.cs
new file mode 100644
index 0000000..49fa0bb
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/IRequestWithRedirectUri.cs
@@ -0,0 +1,29 @@
+//-----------------------------------------------------------------------
+// <copyright file="IRequestWithRedirectUri.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+
+ /// <summary>
+ /// A message that contains a callback parameter.
+ /// </summary>
+ internal interface IRequestWithRedirectUri {
+ /// <summary>
+ /// Gets the client identifier.
+ /// </summary>
+ /// <value>The client identifier.</value>
+ string ClientIdentifier { get; }
+
+ /// <summary>
+ /// Gets the callback.
+ /// </summary>
+ /// <value>The callback.</value>
+ Uri Callback { get; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/MessageBase.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/MessageBase.cs
new file mode 100644
index 0000000..1a8094e
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/MessageBase.cs
@@ -0,0 +1,209 @@
+//-----------------------------------------------------------------------
+// <copyright file="MessageBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A common message base class for OAuth WRAP messages.
+ /// </summary>
+ 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/OAuthWrap/Messages/RefreshAccessTokenRequest.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/RefreshAccessTokenRequest.cs
new file mode 100644
index 0000000..ba40f30
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/RefreshAccessTokenRequest.cs
@@ -0,0 +1,116 @@
+//-----------------------------------------------------------------------
+// <copyright file="RefreshAccessTokenRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuthWrap.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 RefreshAccessTokenRequest : MessageBase, IAccessTokenRequest, ITokenCarryingRequest, IOAuthDirectResponseFormat {
+ /// <summary>
+ /// The type of message.
+ /// </summary>
+ [MessagePart(Protocol.type, IsRequired = true)]
+ private const string Type = "refresh";
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RefreshAccessTokenRequest"/> class.
+ /// </summary>
+ /// <param name="tokenEndpoint">The token endpoint.</param>
+ /// <param name="version">The version.</param>
+ internal RefreshAccessTokenRequest(Uri tokenEndpoint, Version version)
+ : base(version, MessageTransport.Direct, tokenEndpoint) {
+ // We prefer URL encoding of the data.
+ this.Format = ResponseFormat.Form;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RefreshAccessTokenRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ internal RefreshAccessTokenRequest(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 type of the secret.
+ /// </summary>
+ /// <value>The type of the secret.</value>
+ /// <remarks>
+ /// OPTIONAL. The access token secret type as described by Section 5.3 (Cryptographic Tokens Requests). If omitted, the authorization server will issue a bearer token (an access token without a matching secret) as described by Section 5.2 (Bearer Token Requests).
+ /// </remarks>
+ [MessagePart(Protocol.secret_type, IsRequired = false, AllowEmpty = false)]
+ public string SecretType { get; set; }
+
+ /// <summary>
+ /// Gets or sets the identifier by which this client is known to the Authorization Server.
+ /// </summary>
+ /// <value>The client identifier.</value>
+ [MessagePart(Protocol.client_id, IsRequired = true, AllowEmpty = false)]
+ public string ClientIdentifier { get; set; }
+
+ /// <summary>
+ /// Gets or sets the client secret.
+ /// </summary>
+ /// <value>The client secret.</value>
+ /// <remarks>
+ /// REQUIRED if the client identifier has a matching secret. The client secret as described in Section 3.4 (Client Credentials).
+ /// </remarks>
+ [MessagePart(Protocol.client_secret, IsRequired = false, AllowEmpty = true)]
+ public string ClientSecret { get; set; }
+
+ /// <summary>
+ /// Gets the format the client is requesting the authorization server should deliver the request in.
+ /// </summary>
+ /// <value>The format.</value>
+ ResponseFormat IOAuthDirectResponseFormat.Format {
+ get { return this.Format.HasValue ? this.Format.Value : ResponseFormat.Json; }
+ }
+
+ /// <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; }
+
+ /// <summary>
+ /// Gets or sets the format the client is requesting the authorization server should deliver the request in.
+ /// </summary>
+ /// <value>The format.</value>
+ [MessagePart(Protocol.format, Encoder = typeof(ResponseFormatEncoder))]
+ private ResponseFormat? Format { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/ResponseFormat.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/ResponseFormat.cs
new file mode 100644
index 0000000..985ec3e
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/ResponseFormat.cs
@@ -0,0 +1,27 @@
+//-----------------------------------------------------------------------
+// <copyright file="ResponseFormat.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ /// <summary>
+ /// The various formats a client can request a response to come in from an authorization server.
+ /// </summary>
+ public enum ResponseFormat {
+ /// <summary>
+ /// The response should be JSON encoded.
+ /// </summary>
+ Json,
+
+ /// <summary>
+ /// The response should be XML encoded.
+ /// </summary>
+ Xml,
+
+ /// <summary>
+ /// The response should be URL encoded.
+ /// </summary>
+ Form,
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/ResponseFormatEncoder.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/ResponseFormatEncoder.cs
new file mode 100644
index 0000000..6cf879c
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/ResponseFormatEncoder.cs
@@ -0,0 +1,71 @@
+//-----------------------------------------------------------------------
+// <copyright file="ResponseFormatEncoder.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Reflection;
+
+ /// <summary>
+ /// Provides encoding/decoding of the json/xml/form enum type.
+ /// </summary>
+ public class ResponseFormatEncoder : IMessagePartEncoder {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ResponseFormatEncoder"/> class.
+ /// </summary>
+ public ResponseFormatEncoder() {
+ }
+
+ /// <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 format = (ResponseFormat)value;
+ switch (format) {
+ case ResponseFormat.Xml:
+ return Protocol.ResponseFormats.Xml;
+ case ResponseFormat.Json:
+ return Protocol.ResponseFormats.Json;
+ case ResponseFormat.Form:
+ return Protocol.ResponseFormats.Form;
+ default:
+ throw new ArgumentOutOfRangeException("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.ResponseFormats.Xml:
+ return ResponseFormat.Xml;
+ case Protocol.ResponseFormats.Json:
+ return ResponseFormat.Json;
+ case Protocol.ResponseFormats.Form:
+ return ResponseFormat.Form;
+ default:
+ throw new ArgumentOutOfRangeException("value");
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/UnauthorizedResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/UnauthorizedResponse.cs
new file mode 100644
index 0000000..f77977d
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/UnauthorizedResponse.cs
@@ -0,0 +1,104 @@
+//-----------------------------------------------------------------------
+// <copyright file="UnauthorizedResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.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="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/OAuthWrap/Messages/UserAgent/UserAgentFailedResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/UserAgent/UserAgentFailedResponse.cs
new file mode 100644
index 0000000..e027267
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/UserAgent/UserAgentFailedResponse.cs
@@ -0,0 +1,53 @@
+//-----------------------------------------------------------------------
+// <copyright file="UserAgentFailedResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// An authorization denied response message in the user-agent flow.
+ /// </summary>
+ internal class UserAgentFailedResponse : MessageBase, IHttpIndirectResponse {
+ /// <summary>
+ /// A constant parameter that indicates the user refused to grant the requested authorization.
+ /// </summary>
+ [MessagePart(Protocol.error, IsRequired = true)]
+ private const string ErrorReason = Protocol.user_denied;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserAgentFailedResponse"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The client callback.</param>
+ /// <param name="version">The version.</param>
+ internal UserAgentFailedResponse(Uri clientCallback, Version version)
+ : base(version, MessageTransport.Indirect, clientCallback) {
+ }
+
+ /// <summary>
+ /// Gets or sets the state of the client that was supplied to the Authorization Server.
+ /// </summary>
+ /// <value>
+ /// An opaque value that Clients can use to maintain state associated with the authorization request.
+ /// </value>
+ /// <remarks>
+ /// If this value is present, the Authorization Server MUST return it to the Client's callback URL.
+ /// </remarks>
+ [MessagePart(Protocol.state, IsRequired = false, AllowEmpty = true)]
+ public string ClientState { get; set; }
+
+ /// <summary>
+ /// Gets a value indicating whether the payload for the message should be included
+ /// in the redirect fragment instead of the query string or POST entity.
+ /// </summary>
+ bool IHttpIndirectResponse.Include301RedirectPayloadInFragment {
+ get { return true; }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/UserAgent/UserAgentRequest.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/UserAgent/UserAgentRequest.cs
new file mode 100644
index 0000000..f4c39a0
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/UserAgent/UserAgentRequest.cs
@@ -0,0 +1,100 @@
+//-----------------------------------------------------------------------
+// <copyright file="UserAgentRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A message requesting user authorization to access protected data on behalf
+ /// of an installed application or browser-hosted Javascript.
+ /// </summary>
+ internal class UserAgentRequest : MessageBase, IRequestWithRedirectUri {
+ /// <summary>
+ /// The type of message.
+ /// </summary>
+ [MessagePart(Protocol.type, IsRequired = true)]
+ private const string Type = "user_agent";
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserAgentRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationEndpoint">The authorization endpoint.</param>
+ /// <param name="version">The version.</param>
+ internal UserAgentRequest(Uri authorizationEndpoint, Version version)
+ : base(version, MessageTransport.Indirect, authorizationEndpoint) {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserAgentRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ internal UserAgentRequest(AuthorizationServerDescription authorizationServer)
+ : this(authorizationServer.AuthorizationEndpoint, authorizationServer.Version) {
+ }
+
+ /// <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>
+ [MessagePart(Protocol.state, IsRequired = false, AllowEmpty = true)]
+ public string ClientState { get; set; }
+
+ /// <summary>
+ /// Gets or sets the identifier by which this client is known to the Authorization Server.
+ /// </summary>
+ [MessagePart(Protocol.client_id, IsRequired = true, 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 a value indicating whether the authorization server is
+ /// required to redirect the browser back to the client immediately.
+ /// </summary>
+ /// <remarks>
+ /// OPTIONAL. The parameter value must be set to true or false. If set to true, the authorization server MUST NOT prompt the end-user to authenticate or approve access. Instead, the authorization server attempts to establish the end-user's identity via other means (e.g. browser cookies) and checks if the end-user has previously approved an identical access request by the same client and if that access grant is still active. If the authorization server does not support an immediate check or if it is unable to establish the end-user's identity or approval status, it MUST deny the request without prompting the end-user. Defaults to false if omitted.
+ /// </remarks>
+ [MessagePart(Protocol.immediate, IsRequired = false, AllowEmpty = false)]
+ internal bool? Immediate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the scope.
+ /// </summary>
+ /// <value>The scope.</value>
+ /// <remarks>
+ /// OPTIONAL. 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 additional access range to the requested scope.
+ /// </remarks>
+ [MessagePart(Protocol.scope, IsRequired = false, AllowEmpty = true)]
+ internal string Scope { get; set; }
+
+ /// <summary>
+ /// Gets or sets the type of the secret.
+ /// </summary>
+ /// <value>The type of the secret.</value>
+ /// <remarks>
+ /// OPTIONAL. The access token secret type as described by Section 5.3 (Cryptographic Tokens Requests). If omitted, the authorization server will issue a bearer token (an access token without a matching secret) as described by Section 5.2 (Bearer Token Requests).
+ /// </remarks>
+ [MessagePart(Protocol.secret_type, IsRequired = false, AllowEmpty = false)]
+ internal string SecretType { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/UserAgent/UserAgentSuccessResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/UserAgent/UserAgentSuccessResponse.cs
new file mode 100644
index 0000000..c7e2ad5
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/UserAgent/UserAgentSuccessResponse.cs
@@ -0,0 +1,88 @@
+//-----------------------------------------------------------------------
+// <copyright file="UserAgentSuccessResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A message from the authorization server to a user-agent client indicating that authorization has been granted.
+ /// </summary>
+ internal class UserAgentSuccessResponse : MessageBase, IHttpIndirectResponse, IAccessTokenSuccessResponse {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserAgentSuccessResponse"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The client callback.</param>
+ /// <param name="version">The version.</param>
+ internal UserAgentSuccessResponse(Uri clientCallback, Version version)
+ : base(version, MessageTransport.Indirect, clientCallback)
+ {
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the payload for the message should be included
+ /// in the redirect fragment instead of the query string or POST entity.
+ /// </summary>
+ bool IHttpIndirectResponse.Include301RedirectPayloadInFragment {
+ get { return true; }
+ }
+
+ /// <summary>
+ /// Gets 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 access token secret.
+ /// </summary>
+ /// <value>The access token secret.</value>
+ /// <remarks>
+ /// REQUIRED if requested by the client. The corresponding access token secret as requested by the client.
+ /// </remarks>
+ [MessagePart(Protocol.access_token_secret, IsRequired = false, AllowEmpty = false)]
+ public string AccessTokenSecret { get; internal set; }
+
+ /// <summary>
+ /// Gets the scope.
+ /// </summary>
+ /// <value>The scope.</value>
+ string IAccessTokenSuccessResponse.Scope {
+ get { return null; }
+ }
+
+ /// <summary>
+ /// Gets or sets the state.
+ /// </summary>
+ /// <value>The state.</value>
+ /// <remarks>
+ /// REQUIRED if the state parameter was present in the client authorization request. Set to the exact value received from the client.
+ /// </remarks>
+ [MessagePart(Protocol.state, IsRequired = false, AllowEmpty = true)]
+ internal string ClientState { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordCaptchaResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordCaptchaResponse.cs
new file mode 100644
index 0000000..192af58
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordCaptchaResponse.cs
@@ -0,0 +1,54 @@
+//-----------------------------------------------------------------------
+// <copyright file="UsernamePasswordCaptchaResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Net;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A response from the Authorization Server indicating the Client must have the user
+ /// complete a CAPTCHA puzzle prior to authorization.
+ /// </summary>
+ internal class UsernamePasswordCaptchaResponse : MessageBase, IHttpDirectResponse {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UsernamePasswordCaptchaResponse"/> class.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ internal UsernamePasswordCaptchaResponse(UserNamePasswordRequest request)
+ : base(request) {
+ }
+
+ #region IHttpDirectResponse Members
+
+ /// <summary>
+ /// Gets the HTTP status code that the direct response should be sent with.
+ /// </summary>
+ HttpStatusCode IHttpDirectResponse.HttpStatusCode {
+ 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>
+ /// Gets or sets the URL to the CAPTCHA puzzle.
+ /// </summary>
+ /// <value>The captcha URL.</value>
+ [MessagePart(Protocol.wrap_captcha_url, IsRequired = true, AllowEmpty = false)]
+ internal Uri CaptchaPuzzle { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordFailedResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordFailedResponse.cs
new file mode 100644
index 0000000..fa98b83
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordFailedResponse.cs
@@ -0,0 +1,22 @@
+//-----------------------------------------------------------------------
+// <copyright file="UserNamePasswordFailedResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ /// <summary>
+ /// A response from the Authorization Server to the Consumer to indicate that a
+ /// request for a delegation code failed, probably due to an invalid
+ /// username and password.
+ /// </summary>
+ internal class UserNamePasswordFailedResponse : UnauthorizedResponse {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserNamePasswordFailedResponse"/> class.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ internal UserNamePasswordFailedResponse(UserNamePasswordRequest request)
+ : base(request) {
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordRequest.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordRequest.cs
new file mode 100644
index 0000000..3bc886a
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordRequest.cs
@@ -0,0 +1,150 @@
+//-----------------------------------------------------------------------
+// <copyright file="UserNamePasswordRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuthWrap.ChannelElements;
+
+ /// <summary>
+ /// A request for a delegation code in exchange for a user's confidential
+ /// username and password.
+ /// </summary>
+ /// <remarks>
+ /// After this request has been sent, the consumer application MUST discard
+ /// the confidential user credentials and use the delegation code going forward.
+ /// </remarks>
+ internal class UserNamePasswordRequest : MessageBase, IAccessTokenRequest, IOAuthDirectResponseFormat {
+ /// <summary>
+ /// A constant that identifies the flow this request belongs to.
+ /// </summary>
+ [MessagePart(Protocol.type, IsRequired = true)]
+ private const string Type = "username";
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserNamePasswordRequest"/> class.
+ /// </summary>
+ /// <param name="tokenEndpoint">The authorization server.</param>
+ /// <param name="version">The version.</param>
+ internal UserNamePasswordRequest(Uri tokenEndpoint, Version version)
+ : base(version, MessageTransport.Direct, tokenEndpoint) {
+ this.HttpMethods = HttpDeliveryMethods.PostRequest;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserNamePasswordRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ internal UserNamePasswordRequest(AuthorizationServerDescription authorizationServer)
+ : this(authorizationServer.TokenEndpoint, authorizationServer.Version) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null);
+ Contract.Requires<ArgumentException>(authorizationServer.Version != null);
+ Contract.Requires<ArgumentException>(authorizationServer.TokenEndpoint != null);
+
+ // We prefer URL encoding of the data.
+ this.Format = ResponseFormat.Form;
+ }
+
+ /// <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 3.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; }
+
+ /// <summary>
+ /// Gets or sets the type of the secret.
+ /// </summary>
+ /// <value>The type of the secret.</value>
+ /// <remarks>
+ /// OPTIONAL. The access token secret type as described by Section 5.3 (Cryptographic Tokens Requests). If omitted, the authorization server will issue a bearer token (an access token without a matching secret) as described by Section 5.2 (Bearer Token Requests).
+ /// </remarks>
+ [MessagePart(Protocol.secret_type, IsRequired = false, AllowEmpty = false)]
+ public string SecretType { get; set; }
+
+ /// <summary>
+ /// Gets the format the client is requesting the authorization server should deliver the request in.
+ /// </summary>
+ /// <value>The format.</value>
+ ResponseFormat IOAuthDirectResponseFormat.Format {
+ get { return this.Format.HasValue ? this.Format.Value : ResponseFormat.Json; }
+ }
+
+ /// <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; }
+
+ /// <summary>
+ /// Gets or sets the CAPTCHA puzzle that the user just solved, if applicable.
+ /// </summary>
+ /// <value>The captcha puzzle location.</value>
+ [MessagePart(Protocol.wrap_captcha_url, IsRequired = false, AllowEmpty = false)]
+ internal Uri CaptchaPuzzle { get; set; }
+
+ /// <summary>
+ /// Gets or sets the solution to the CAPTCHA puzzle the user just solved, if applicable.
+ /// </summary>
+ /// <value>The CAPTCHA solution.</value>
+ [MessagePart(Protocol.wrap_captcha_solution, IsRequired = false, AllowEmpty = false)]
+ internal string CaptchaSolution { get; set; }
+
+ /// <summary>
+ /// Gets or sets the scope.
+ /// </summary>
+ /// <value>The scope.</value>
+ [MessagePart(Protocol.scope, IsRequired = false, AllowEmpty = true)]
+ internal string Scope { get; set; }
+
+ /// <summary>
+ /// Gets or sets the format the client is requesting the authorization server should deliver the request in.
+ /// </summary>
+ /// <value>The format.</value>
+ [MessagePart(Protocol.format, Encoder = typeof(ResponseFormatEncoder))]
+ private ResponseFormat? Format { get; set; }
+
+ /// <summary>
+ /// Checks the message state for conformity to the protocol specification
+ /// and throws an exception if the message is invalid.
+ /// </summary>
+ /// <remarks>
+ /// <para>Some messages have required fields, or combinations of fields that must relate to each other
+ /// in specialized ways. After deserializing a message, this method checks the state of the
+ /// message to see if it conforms to the protocol.</para>
+ /// <para>Note that this property should <i>not</i> check signatures or perform any state checks
+ /// outside this scope of this particular message.</para>
+ /// </remarks>
+ /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception>
+ protected override void EnsureValidMessage() {
+ base.EnsureValidMessage();
+ ErrorUtilities.VerifyProtocol(this.Recipient.IsTransportSecure(), OAuthWrapStrings.HttpsRequired);
+ ErrorUtilities.VerifyProtocol((this.CaptchaPuzzle == null) == (this.CaptchaSolution == null), "CAPTCHA puzzle and solution must either be both absent or both present.");
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordSuccessResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordSuccessResponse.cs
new file mode 100644
index 0000000..db3a7d2
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordSuccessResponse.cs
@@ -0,0 +1,51 @@
+//-----------------------------------------------------------------------
+// <copyright file="UserNamePasswordSuccessResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A response from the Authorization Server to the Client containing a refresh token
+ /// and an access token.
+ /// </summary>
+ internal class UserNamePasswordSuccessResponse : MessageBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserNamePasswordSuccessResponse"/> class.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ internal UserNamePasswordSuccessResponse(UserNamePasswordRequest request)
+ : base(request) {
+ }
+
+ /// <summary>
+ /// Gets or sets the verification code.
+ /// </summary>
+ /// <value>
+ /// The long-lived credential assigned by the Authorization Server to this Client for
+ /// use in accessing the authorizing user's protected resources.
+ /// </value>
+ [MessagePart(Protocol.refresh_token, IsRequired = true, AllowEmpty = false)]
+ internal string RefreshToken { get; set; }
+
+ /// <summary>
+ /// Gets or sets the access token.
+ /// </summary>
+ /// <value>The access token.</value>
+ [MessagePart(Protocol.access_token, IsRequired = true, AllowEmpty = false)]
+ internal string AccessToken { get; 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))]
+ internal TimeSpan? Lifetime { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordVerificationResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordVerificationResponse.cs
new file mode 100644
index 0000000..e24a200
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordVerificationResponse.cs
@@ -0,0 +1,55 @@
+//-----------------------------------------------------------------------
+// <copyright file="UserNamePasswordVerificationResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Net;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A response from the Authorization Server to the client indicating that the user
+ /// must visit a URL to complete an additional verification step before proceeding.
+ /// </summary>
+ internal class UserNamePasswordVerificationResponse : MessageBase, IHttpDirectResponse {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserNamePasswordVerificationResponse"/> class.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ internal UserNamePasswordVerificationResponse(UserNamePasswordRequest request)
+ : base(request) {
+ }
+
+ #region IHttpDirectResponse Members
+
+ /// <summary>
+ /// Gets the HTTP status code that the direct response should be sent with.
+ /// </summary>
+ /// <value><see cref="HttpStatusCode.BadRequest"/></value>
+ HttpStatusCode IHttpDirectResponse.HttpStatusCode {
+ get { return HttpStatusCode.BadRequest; }
+ }
+
+ /// <summary>
+ /// Gets the HTTP headers to add to the response.
+ /// </summary>
+ WebHeaderCollection IHttpDirectResponse.Headers {
+ get { return new WebHeaderCollection(); }
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Gets or sets the verification URL the user must visit with a browser
+ /// to complete some step to defeat automated attacks.
+ /// </summary>
+ /// <value>The verification URL.</value>
+ [MessagePart(Protocol.code, IsRequired = true, AllowEmpty = false)]
+ internal Uri VerificationUrl { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebServerAccessTokenRequest.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebServerAccessTokenRequest.cs
new file mode 100644
index 0000000..56f9d91
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebServerAccessTokenRequest.cs
@@ -0,0 +1,148 @@
+//-----------------------------------------------------------------------
+// <copyright file="WebServerAccessTokenRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Diagnostics.Contracts;
+ using ChannelElements;
+ using Configuration;
+ using Messaging;
+
+ /// <summary>
+ /// A message sent by the Client directly to the Authorization Server to exchange
+ /// the verification code for an Access Token.
+ /// </summary>
+ /// <remarks>
+ /// Used by the Web App (and Rich App?) profiles.
+ /// </remarks>
+ internal class WebServerAccessTokenRequest : MessageBase, IAccessTokenRequest, ITokenCarryingRequest, IOAuthDirectResponseFormat {
+ /// <summary>
+ /// The type of message.
+ /// </summary>
+ [MessagePart(Protocol.type, IsRequired = true)]
+ private const string Type = "web_server";
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="WebServerAccessTokenRequest"/> class.
+ /// </summary>
+ /// <param name="accessTokenEndpoint">The Authorization Server's access token endpoint URL.</param>
+ /// <param name="version">The version.</param>
+ internal WebServerAccessTokenRequest(Uri accessTokenEndpoint, Version version)
+ : base(version, MessageTransport.Direct, accessTokenEndpoint) {
+ this.HttpMethods = HttpDeliveryMethods.PostRequest;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="WebServerAccessTokenRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ internal WebServerAccessTokenRequest(AuthorizationServerDescription authorizationServer)
+ : this(authorizationServer.TokenEndpoint, authorizationServer.Version) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null);
+ Contract.Requires<ArgumentException>(authorizationServer.Version != null);
+ Contract.Requires<ArgumentException>(authorizationServer.TokenEndpoint != null);
+
+ // We prefer URL encoding of the data.
+ this.Format = ResponseFormat.Form;
+ }
+
+ /// <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.VerificationCode; }
+ }
+
+ /// <summary>
+ /// Gets or sets the verification code or refresh/access token.
+ /// </summary>
+ /// <value>The code or token.</value>
+ string ITokenCarryingRequest.CodeOrToken {
+ get { return this.VerificationCode; }
+ set { this.VerificationCode = value; }
+ }
+
+ /// <summary>
+ /// Gets or sets the authorization that the token describes.
+ /// </summary>
+ IAuthorizationDescription ITokenCarryingRequest.AuthorizationDescription { get; set; }
+
+ /// <summary>
+ /// Gets or sets the identifier by which this client is known to the Authorization Server.
+ /// </summary>
+ /// <value>The client identifier.</value>
+ [MessagePart(Protocol.client_id, IsRequired = true, AllowEmpty = false)]
+ public string ClientIdentifier { get; set; }
+
+ /// <summary>
+ /// Gets or sets the client secret.
+ /// </summary>
+ /// <value>The client secret.</value>
+ /// <remarks>
+ /// REQUIRED if the client identifier has a matching secret. The client secret as described in Section 3.4 (Client Credentials).
+ /// </remarks>
+ [MessagePart(Protocol.client_secret, IsRequired = false, AllowEmpty = true)]
+ public string ClientSecret { get; set; }
+
+ /// <summary>
+ /// Gets or sets the type of the secret.
+ /// </summary>
+ /// <value>The type of the secret.</value>
+ /// <remarks>
+ /// OPTIONAL. The access token secret type as described by Section 5.3 (Cryptographic Tokens Requests). If omitted, the authorization server will issue a bearer token (an access token without a matching secret) as described by Section 5.2 (Bearer Token Requests).
+ /// </remarks>
+ [MessagePart(Protocol.secret_type, IsRequired = false, AllowEmpty = false)]
+ public string SecretType { get; set; }
+
+ ResponseFormat IOAuthDirectResponseFormat.Format {
+ get { return this.Format.HasValue ? this.Format.Value : ResponseFormat.Json; }
+ }
+
+ /// <summary>
+ /// Gets or sets the verification code previously communicated to the Client
+ /// in <see cref="WebServerSuccessResponse.VerificationCode"/>.
+ /// </summary>
+ /// <value>The verification code received from the authorization server.</value>
+ [MessagePart(Protocol.code, IsRequired = true, AllowEmpty = false)]
+ internal string VerificationCode { get; set; }
+
+ /// <summary>
+ /// Gets or sets the callback URL used in <see cref="WebServerRequest.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; }
+
+ /// <summary>
+ /// Gets or sets the format the client is requesting the authorization server should deliver the request in.
+ /// </summary>
+ /// <value>The format.</value>
+ [MessagePart(Protocol.format, Encoder = typeof(ResponseFormatEncoder))]
+ private ResponseFormat? Format { get; set; }
+
+ /// <summary>
+ /// Checks the message state for conformity to the protocol specification
+ /// and throws an exception if the message is invalid.
+ /// </summary>
+ /// <remarks>
+ /// <para>Some messages have required fields, or combinations of fields that must relate to each other
+ /// in specialized ways. After deserializing a message, this method checks the state of the
+ /// message to see if it conforms to the protocol.</para>
+ /// <para>Note that this property should <i>not</i> check signatures or perform any state checks
+ /// outside this scope of this particular message.</para>
+ /// </remarks>
+ /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception>
+ protected override void EnsureValidMessage() {
+ base.EnsureValidMessage();
+ ErrorUtilities.VerifyProtocol(
+ DotNetOpenAuthSection.Configuration.Messaging.RelaxSslRequirements || this.Recipient.IsTransportSecure(),
+ OAuthWrapStrings.HttpsRequired);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebServerFailedResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebServerFailedResponse.cs
new file mode 100644
index 0000000..8cb1cb0
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebServerFailedResponse.cs
@@ -0,0 +1,59 @@
+//-----------------------------------------------------------------------
+// <copyright file="WebServerFailedResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Diagnostics.Contracts;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// The message the Authorization Server MAY use to send the user back to the Client
+ /// following the user's denial to grant Consumer with authorization of
+ /// access to requested resources.
+ /// </summary>
+ internal class WebServerFailedResponse : MessageBase, IMessageWithClientState {
+ /// <summary>
+ /// A constant parameter that indicates the user refused to grant the requested authorization.
+ /// </summary>
+ [MessagePart(Protocol.error, IsRequired = true)]
+ private const string ErrorReason = Protocol.user_denied;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="WebServerFailedResponse"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The recipient of the message.</param>
+ /// <param name="version">The version.</param>
+ internal WebServerFailedResponse(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="WebServerFailedResponse"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The client callback.</param>
+ /// <param name="request">The request.</param>
+ internal WebServerFailedResponse(Uri clientCallback, WebServerRequest request)
+ : this(clientCallback, ((IMessage)request).Version) {
+ Contract.Requires<ArgumentNullException>(clientCallback != null, "clientCallback");
+ Contract.Requires<ArgumentNullException>(request != null, "request");
+ ((IMessageWithClientState)this).ClientState = ((IMessageWithClientState)request).ClientState;
+ }
+
+ /// <summary>
+ /// Gets or sets the state of the client that was supplied to the Authorization Server.
+ /// </summary>
+ /// <value>
+ /// An opaque value that Clients can use to maintain state associated with the authorization request.
+ /// </value>
+ /// <remarks>
+ /// If this value is present, the Authorization Server MUST return it to the Client's callback URL.
+ /// </remarks>
+ [MessagePart(Protocol.state, IsRequired = false, AllowEmpty = true)]
+ public string ClientState { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebServerRequest.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebServerRequest.cs
new file mode 100644
index 0000000..dc0332d
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebServerRequest.cs
@@ -0,0 +1,107 @@
+//-----------------------------------------------------------------------
+// <copyright file="WebServerRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Diagnostics.Contracts;
+ using DotNetOpenAuth.Messaging;
+
+ /// <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 WebServerRequest : MessageBase, IMessageWithClientState, IRequestWithRedirectUri {
+ /// <summary>
+ /// The type of message.
+ /// </summary>
+ [MessagePart(Protocol.type, IsRequired = true)]
+#pragma warning disable 169
+ private const string Type = "web_server";
+#pragma warning restore 169
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="WebServerRequest"/> 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 WebServerRequest(Uri authorizationEndpoint, Version version)
+ : base(version, MessageTransport.Indirect, authorizationEndpoint) {
+ Contract.Requires<ArgumentNullException>(authorizationEndpoint != null);
+ Contract.Requires<ArgumentNullException>(version != null);
+ this.HttpMethods = HttpDeliveryMethods.GetRequest;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="WebServerRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ internal WebServerRequest(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 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)]
+ public string Scope { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the authorization server is
+ /// allowed to interact with the user before responding to the client's request.
+ /// </summary>
+ public bool IsUserInteractionAllowed {
+ get { return !this.Immediate.HasValue || !this.Immediate.Value; }
+ set { this.Immediate = value ? (bool?)null : true; }
+ }
+
+ /// <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 a value indicating whether the authorization server is
+ /// required to redirect the browser back to the client immediately.
+ /// </summary>
+ /// <remarks>
+ /// OPTIONAL. The parameter value must be set to true or false. If set to true, the authorization server MUST NOT prompt the end-user to authenticate or approve access. Instead, the authorization server attempts to establish the end-user's identity via other means (e.g. browser cookies) and checks if the end-user has previously approved an identical access request by the same client and if that access grant is still active. If the authorization server does not support an immediate check or if it is unable to establish the end-user's identity or approval status, it MUST deny the request without prompting the end-user. Defaults to false if omitted.
+ /// </remarks>
+ [MessagePart(Protocol.immediate, IsRequired = false, AllowEmpty = false)]
+ internal bool? Immediate { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebServerSuccessResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebServerSuccessResponse.cs
new file mode 100644
index 0000000..4f86d9b
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebServerSuccessResponse.cs
@@ -0,0 +1,78 @@
+//-----------------------------------------------------------------------
+// <copyright file="WebServerSuccessResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Diagnostics.Contracts;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuthWrap.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>
+ internal class WebServerSuccessResponse : MessageBase, IMessageWithClientState, ITokenCarryingRequest {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="WebServerSuccessResponse"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The client callback.</param>
+ /// <param name="version">The protocol version.</param>
+ internal WebServerSuccessResponse(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="WebServerSuccessResponse"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The client callback.</param>
+ /// <param name="request">The request.</param>
+ internal WebServerSuccessResponse(Uri clientCallback, WebServerRequest request)
+ : base(request, clientCallback) {
+ Contract.Requires<ArgumentNullException>(clientCallback != null, "clientCallback");
+ Contract.Requires<ArgumentNullException>(request != null, "request");
+ ((IMessageWithClientState)this).ClientState = ((IMessageWithClientState)request).ClientState;
+ }
+
+ string ITokenCarryingRequest.CodeOrToken {
+ get { return this.VerificationCode; }
+ set { this.VerificationCode = value; }
+ }
+
+ CodeOrTokenType ITokenCarryingRequest.CodeOrTokenType {
+ get { return CodeOrTokenType.VerificationCode; }
+ }
+
+ IAuthorizationDescription ITokenCarryingRequest.AuthorizationDescription { 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="WebServerRequest"/>.
+ /// </remarks>
+ [MessagePart(Protocol.state, IsRequired = false, AllowEmpty = true)]
+ string IMessageWithClientState.ClientState { get; set; }
+
+ /// <summary>
+ /// Gets or sets the verification code.
+ /// </summary>
+ /// <value>
+ /// The long-lived credential assigned by the Authorization Server to this Consumer for
+ /// use in accessing the authorizing user's protected resources.
+ /// </value>
+ [MessagePart(Protocol.code, IsRequired = true, AllowEmpty = true)]
+ internal string VerificationCode { get; set; }
+
+ /// <summary>
+ /// Gets or sets the authorizing user's account name.
+ /// </summary>
+ internal string AuthorizingUsername { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/OAuthWrapStrings.Designer.cs b/src/DotNetOpenAuth/OAuthWrap/OAuthWrapStrings.Designer.cs
new file mode 100644
index 0000000..35417e1
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/OAuthWrapStrings.Designer.cs
@@ -0,0 +1,108 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+// This code was generated by a tool.
+// Runtime Version:4.0.30426.0
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap {
+ 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 OAuthWrapStrings {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal OAuthWrapStrings() {
+ }
+
+ /// <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.OAuthWrap.OAuthWrapStrings", typeof(OAuthWrapStrings).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 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);
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/OAuthWrapStrings.resx b/src/DotNetOpenAuth/OAuthWrap/OAuthWrapStrings.resx
new file mode 100644
index 0000000..ae2cc6c
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/OAuthWrapStrings.resx
@@ -0,0 +1,135 @@
+<?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="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>
+</root> \ No newline at end of file
diff --git a/src/DotNetOpenAuth/OAuthWrap/Protocol.cs b/src/DotNetOpenAuth/OAuthWrap/Protocol.cs
new file mode 100644
index 0000000..074f794
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Protocol.cs
@@ -0,0 +1,245 @@
+// <auto-generated/> // disable StyleCop on this file
+//-----------------------------------------------------------------------
+// <copyright file="Protocol.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap {
+ using System;
+ using System.Collections.Generic;
+
+ /// <summary>
+ /// An enumeration of the OAuth WRAP protocol versions supported by this library.
+ /// </summary>
+ public enum ProtocolVersion {
+ /// <summary>
+ /// The OAuth 2.0 specification.
+ /// </summary>
+ V20,
+ }
+
+ /// <summary>
+ /// Protocol constants for OAuth WRAP.
+ /// </summary>
+ internal class Protocol {
+ /// <summary>
+ /// The HTTP authorization scheme "Token";
+ /// </summary>
+ internal const string HttpAuthorizationScheme = "Token";
+
+ /// <summary>
+ /// The format of the HTTP Authorization header value that authorizes OAuth WRAP requests.
+ /// </summary>
+ internal const string HttpAuthorizationHeaderFormat = "Token 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_format" string.
+ /// </summary>
+ internal const string assertion_format = "assertion_format";
+
+ /// <summary>
+ /// The "wrap_SAML" string.
+ /// </summary>
+ internal const string wrap_saml = "wrap_SAML";
+
+ /// <summary>
+ /// The "wrap_SWT" string.
+ /// </summary>
+ internal const string wrap_swt = "wrap_SWT";
+
+ /// <summary>
+ /// The "wrap_captcha_url" string.
+ /// </summary>
+ internal const string wrap_captcha_url = "wrap_captcha_url";
+
+ /// <summary>
+ /// The "wrap_captcha_solution" string.
+ /// </summary>
+ internal const string wrap_captcha_solution = "wrap_captcha_solution";
+
+ /// <summary>
+ /// The "user_denied" string.
+ /// </summary>
+ internal const string user_denied = "user_denied";
+
+ /// <summary>
+ /// The "secret_type" string.
+ /// </summary>
+ internal const string secret_type = "secret_type";
+
+ /// <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>
+ /// Gets or sets the OAuth WRAP version represented by this instance.
+ /// </summary>
+ /// <value>The version.</value>
+ internal Version Version { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the OAuth WRAP 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 ResponseFormats
+ {
+ internal const string Json = "json";
+ internal const string Xml = "xml";
+ internal const string Form = "form";
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/ResourceServer.cs b/src/DotNetOpenAuth/OAuthWrap/ResourceServer.cs
new file mode 100644
index 0000000..1696ecd
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/ResourceServer.cs
@@ -0,0 +1,101 @@
+//-----------------------------------------------------------------------
+// <copyright file="ResourceServer.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Net;
+ 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 OAuthWrapResourceServerChannel();
+ }
+
+ /// <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 OAuthWrapResourceServerChannel 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 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 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 {
+ throw ErrorUtilities.ThrowProtocol("Missing access token.");
+ }
+ } catch (ProtocolException ex) {
+ var response = new UnauthorizedResponse(request, ex);
+
+ username = null;
+ scope = null;
+ return this.Channel.PrepareResponse(response);
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/StandardAccessTokenAnalyzer.cs b/src/DotNetOpenAuth/OAuthWrap/StandardAccessTokenAnalyzer.cs
new file mode 100644
index 0000000..769fba1
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/StandardAccessTokenAnalyzer.cs
@@ -0,0 +1,55 @@
+//-----------------------------------------------------------------------
+// <copyright file="StandardAccessTokenAnalyzer.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap {
+ using System.Security.Cryptography;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuthWrap.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>
+ public bool TryValidateAccessToken(IDirectedProtocolMessage message, string accessToken, out string user, out string scope) {
+ var token = AccessToken.Decode(this.AuthorizationServerPublicSigningKey, this.ResourceServerPrivateEncryptionKey, accessToken, message);
+ user = token.User;
+ scope = token.Scope;
+ return true;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/UserAgentClient.cs b/src/DotNetOpenAuth/OAuthWrap/UserAgentClient.cs
new file mode 100644
index 0000000..9b23bc1
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/UserAgentClient.cs
@@ -0,0 +1,100 @@
+//-----------------------------------------------------------------------
+// <copyright file="UserAgentClient.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuthWrap.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>
+ public UserAgentClient(AuthorizationServerDescription authorizationServer)
+ : base(authorizationServer) {
+ }
+
+ /// <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="authorization">The authorization state that is tracking this particular request. Optional.</param>
+ /// <param name="immediate">If set to <c>true</c>, the authorization server will return immediately instead of interacting with the user. Authorization will only be granted if the authorization server determines it is safe to do so without asking the user first.</param>
+ /// <returns>A fully-qualified URL suitable to initiate the authorization flow.</returns>
+ public Uri RequestUserAuthorization(IAuthorizationState authorization = null, bool immediate = false) {
+ Contract.Requires<InvalidOperationException>(!string.IsNullOrEmpty(this.ClientIdentifier));
+
+ if (authorization == null) {
+ authorization = new AuthorizationState();
+ }
+
+ if (authorization.Callback == null) {
+ authorization.Callback = new Uri("http://localhost/");
+ }
+
+ var request = new UserAgentRequest(this.AuthorizationServer) {
+ ClientIdentifier = this.ClientIdentifier,
+ Scope = authorization.Scope,
+ SecretType = authorization.AccessTokenSecretType,
+ Callback = authorization.Callback,
+ Immediate = immediate,
+ };
+
+ 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="authorization">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 authorization = null) {
+ Contract.Requires<ArgumentNullException>(actualRedirectUrl != null, "actualRedirectUrl");
+
+ if (authorization == null) {
+ authorization = 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;
+ }
+
+ UserAgentSuccessResponse success;
+ UserAgentFailedResponse failure;
+ if ((success = response as UserAgentSuccessResponse) != null) {
+ this.UpdateAuthorizationWithResponse(authorization, success);
+ } else if ((failure = response as UserAgentFailedResponse) != null) {
+ authorization.Delete();
+ return null;
+ } else {
+ ErrorUtilities.ThrowProtocol(MessagingStrings.UnexpectedMessageReceivedOfMany);
+ }
+
+ return authorization;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/WebServerAuthorizationServer.cs b/src/DotNetOpenAuth/OAuthWrap/WebServerAuthorizationServer.cs
new file mode 100644
index 0000000..de9d5b3
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/WebServerAuthorizationServer.cs
@@ -0,0 +1,137 @@
+//-----------------------------------------------------------------------
+// <copyright file="WebServerAuthorizationServer.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap {
+ 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.OAuthWrap.ChannelElements;
+ using DotNetOpenAuth.OAuthWrap.Messages;
+
+ /// <summary>
+ /// Authorization Server supporting the web server flow.
+ /// </summary>
+ public class WebServerAuthorizationServer : AuthorizationServerBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="WebServerAuthorizationServer"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ public WebServerAuthorizationServer(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 WebServerRequest ReadAuthorizationRequest(HttpRequestInfo request = null) {
+ if (request == null) {
+ request = this.Channel.GetRequestFromContext();
+ }
+
+ WebServerRequest message;
+ this.Channel.TryReadFromRequest(request, out message);
+ return message;
+ }
+
+ public void ApproveAuthorizationRequest(WebServerRequest authorizationRequest, string username, Uri callback = null) {
+ Contract.Requires<ArgumentNullException>(authorizationRequest != null, "authorizationRequest");
+
+ var response = this.PrepareApproveAuthorizationRequest(authorizationRequest, callback);
+ response.AuthorizingUsername = username;
+ this.Channel.Send(response);
+ }
+
+ public void RejectAuthorizationRequest(WebServerRequest 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.
+ response = this.PrepareAccessTokenResponse(request, this.AuthorizationServer.AccessTokenSigningPrivateKey);
+ return true;
+ }
+
+ response = null;
+ return false;
+ }
+
+ public IAccessTokenRequest ReadAccessTokenRequest(HttpRequestInfo requestInfo = null) {
+ if (requestInfo == null) {
+ requestInfo = this.Channel.GetRequestFromContext();
+ }
+
+ IAccessTokenRequest request;
+ this.Channel.TryReadFromRequest(requestInfo, out request);
+ return request;
+ }
+
+ internal WebServerFailedResponse PrepareRejectAuthorizationRequest(WebServerRequest authorizationRequest, Uri callback = null) {
+ Contract.Requires<ArgumentNullException>(authorizationRequest != null, "authorizationRequest");
+ Contract.Ensures(Contract.Result<WebServerFailedResponse>() != null);
+
+ if (callback == null) {
+ callback = this.GetCallback(authorizationRequest);
+ }
+
+ var response = new WebServerFailedResponse(callback, authorizationRequest);
+ return response;
+ }
+
+ internal WebServerSuccessResponse PrepareApproveAuthorizationRequest(WebServerRequest authorizationRequest, Uri callback = null) {
+ Contract.Requires<ArgumentNullException>(authorizationRequest != null, "authorizationRequest");
+ Contract.Ensures(Contract.Result<WebServerSuccessResponse>() != null);
+
+ if (callback == null) {
+ callback = this.GetCallback(authorizationRequest);
+ }
+
+ var client = this.AuthorizationServer.GetClientOrThrow(authorizationRequest.ClientIdentifier);
+ var response = new WebServerSuccessResponse(callback, authorizationRequest);
+ return response;
+ }
+
+ protected Uri GetCallback(WebServerRequest 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(OAuthWrapStrings.NoCallback);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/WebServerClient.cs b/src/DotNetOpenAuth/OAuthWrap/WebServerClient.cs
new file mode 100644
index 0000000..7e883b1
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/WebServerClient.cs
@@ -0,0 +1,122 @@
+//-----------------------------------------------------------------------
+// <copyright file="WebServerClient.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap {
+ 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.OAuthWrap.Messages;
+
+ /// <summary>
+ /// An OAuth WRAP 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>
+ public WebServerClient(AuthorizationServerDescription authorizationServer)
+ : base(authorizationServer) {
+ }
+
+ /// <summary>
+ /// Gets or sets the token manager.
+ /// </summary>
+ /// <value>The token manager.</value>
+ public IClientTokenManager TokenManager { get; set; }
+
+ /// <summary>
+ /// Prepares a request for user authorization from an authorization server.
+ /// </summary>
+ /// <returns>The authorization request.</returns>
+ public WebServerRequest PrepareRequestUserAuthorization() {
+ return this.PrepareRequestUserAuthorization(new 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 WebServerRequest 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<WebServerRequest>() != null);
+ Contract.Ensures(Contract.Result<WebServerRequest>().ClientIdentifier == this.ClientIdentifier);
+ Contract.Ensures(Contract.Result<WebServerRequest>().Callback == authorization.Callback);
+
+ if (authorization.Callback == null) {
+ authorization.Callback = this.Channel.GetRequestFromContext().UrlBeforeRewriting
+ .StripMessagePartsFromQueryString(this.Channel.MessageDescriptions.Get(typeof(WebServerSuccessResponse), Protocol.Default.Version));
+ authorization.SaveChanges();
+ }
+
+ var request = new WebServerRequest(this.AuthorizationServer) {
+ ClientIdentifier = this.ClientIdentifier,
+ Callback = authorization.Callback,
+ Scope = 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));
+ Contract.Requires<InvalidOperationException>(this.TokenManager != null);
+
+ 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 = this.TokenManager.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.");
+ var success = response as WebServerSuccessResponse;
+ var failure = response as WebServerFailedResponse;
+ ErrorUtilities.VerifyProtocol(success != null || failure != null, MessagingStrings.UnexpectedMessageReceivedOfMany);
+ if (success != null) {
+ var accessTokenRequest = new WebServerAccessTokenRequest(this.AuthorizationServer) {
+ ClientIdentifier = this.ClientIdentifier,
+ ClientSecret = this.ClientSecret,
+ Callback = authorizationState.Callback,
+ VerificationCode = success.VerificationCode,
+ };
+ 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(OAuthWrapStrings.CannotObtainAccessTokenWithReason, error);
+ }
+ } else { // failure
+ Logger.Wrap.Info("User refused to grant the requested authorization at the Authorization Server.");
+ authorizationState.Delete();
+ }
+
+ return authorizationState;
+ }
+
+ return null;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/WrapUtilities.cs b/src/DotNetOpenAuth/OAuthWrap/WrapUtilities.cs
new file mode 100644
index 0000000..8000d02
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/WrapUtilities.cs
@@ -0,0 +1,55 @@
+//-----------------------------------------------------------------------
+// <copyright file="WrapUtilities.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap {
+ 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.OAuth.ChannelElements;
+
+ /// <summary>
+ /// Some common utility methods for OAuth WRAP.
+ /// </summary>
+ internal static class WrapUtilities {
+ /// <summary>
+ /// Authorizes an HTTP request using an OAuth WRAP 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));
+ request.Headers[HttpRequestHeader.Authorization] = string.Format(
+ CultureInfo.InvariantCulture,
+ Protocol.HttpAuthorizationHeaderFormat,
+ Uri.EscapeDataString(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<DotNetOpenAuth.OAuth.ChannelElements.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/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/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 f989260..1545d96 100644
--- a/src/version.txt
+++ b/src/version.txt
@@ -1 +1 @@
-3.4.4
+3.5.0