diff options
author | Andrew Arnott <andrewarnott@gmail.com> | 2011-07-01 16:49:44 -0700 |
---|---|---|
committer | Andrew Arnott <andrewarnott@gmail.com> | 2011-07-01 16:49:44 -0700 |
commit | b6f7a18b949acb4346754ae47fb07424076a3cd0 (patch) | |
tree | 4c23cb2b8174f3288cb0b787cff4c6ac432c6bef /src/DotNetOpenAuth.OAuth2/OAuth2 | |
parent | f16525005555b86151b7a1c741aa29550635108a (diff) | |
download | DotNetOpenAuth-b6f7a18b949acb4346754ae47fb07424076a3cd0.zip DotNetOpenAuth-b6f7a18b949acb4346754ae47fb07424076a3cd0.tar.gz DotNetOpenAuth-b6f7a18b949acb4346754ae47fb07424076a3cd0.tar.bz2 |
First pass at dividing DotNetOpenAuth features into separate assemblies.
Nothing compiles at this point.
Diffstat (limited to 'src/DotNetOpenAuth.OAuth2/OAuth2')
61 files changed, 6229 insertions, 0 deletions
diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/AuthorizationServer.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/AuthorizationServer.cs new file mode 100644 index 0000000..ad40fa5 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/AuthorizationServer.cs @@ -0,0 +1,258 @@ +//----------------------------------------------------------------------- +// <copyright file="AuthorizationServer.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2 { + using System; + using System.Collections.Generic; + using System.Diagnostics.Contracts; + using System.Linq; + using System.Security.Cryptography; + using System.Text; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth2.ChannelElements; + using DotNetOpenAuth.OAuth2.Messages; + + /// <summary> + /// Authorization Server supporting the web server flow. + /// </summary> + public class AuthorizationServer { + /// <summary> + /// Initializes a new instance of the <see cref="AuthorizationServer"/> class. + /// </summary> + /// <param name="authorizationServer">The authorization server.</param> + public AuthorizationServer(IAuthorizationServer authorizationServer) { + Contract.Requires<ArgumentNullException>(authorizationServer != null); + this.OAuthChannel = new OAuth2AuthorizationServerChannel(authorizationServer); + } + + /// <summary> + /// Gets the channel. + /// </summary> + /// <value>The channel.</value> + public Channel Channel { + get { return this.OAuthChannel; } + } + + /// <summary> + /// Gets the authorization server. + /// </summary> + /// <value>The authorization server.</value> + public IAuthorizationServer AuthorizationServerServices { + get { return this.OAuthChannel.AuthorizationServer; } + } + + /// <summary> + /// Gets the channel. + /// </summary> + internal OAuth2AuthorizationServerChannel OAuthChannel { get; private set; } + + /// <summary> + /// Reads in a client's request for the Authorization Server to obtain permission from + /// the user to authorize the Client's access of some protected resource(s). + /// </summary> + /// <param name="request">The HTTP request to read from.</param> + /// <returns>The incoming request, or null if no OAuth message was attached.</returns> + /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception> + public EndUserAuthorizationRequest ReadAuthorizationRequest(HttpRequestInfo request = null) { + if (request == null) { + request = this.Channel.GetRequestFromContext(); + } + + EndUserAuthorizationRequest message; + if (this.Channel.TryReadFromRequest(request, out message)) { + if (message.ResponseType == EndUserAuthorizationResponseType.AuthorizationCode) { + // Clients with no secrets can only request implicit grant types. + var client = this.AuthorizationServerServices.GetClientOrThrow(message.ClientIdentifier); + ErrorUtilities.VerifyProtocol(!String.IsNullOrEmpty(client.Secret), Protocol.unauthorized_client); + } + } + + return message; + } + + /// <summary> + /// Approves an authorization request and sends an HTTP response to the user agent to redirect the user back to the Client. + /// </summary> + /// <param name="authorizationRequest">The authorization request to approve.</param> + /// <param name="userName">The username of the account that approved the request (or whose data will be accessed by the client).</param> + /// <param name="scopes">The scope of access the client should be granted. If <c>null</c>, all scopes in the original request will be granted.</param> + /// <param name="callback">The Client callback URL to use when formulating the redirect to send the user agent back to the Client.</param> + public void ApproveAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, string userName, IEnumerable<string> scopes = null, Uri callback = null) { + Contract.Requires<ArgumentNullException>(authorizationRequest != null); + + var response = this.PrepareApproveAuthorizationRequest(authorizationRequest, userName, scopes, callback); + this.Channel.Respond(response); + } + + /// <summary> + /// Rejects an authorization request and sends an HTTP response to the user agent to redirect the user back to the Client. + /// </summary> + /// <param name="authorizationRequest">The authorization request to disapprove.</param> + /// <param name="callback">The Client callback URL to use when formulating the redirect to send the user agent back to the Client.</param> + public void RejectAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, Uri callback = null) { + Contract.Requires<ArgumentNullException>(authorizationRequest != null); + + var response = this.PrepareRejectAuthorizationRequest(authorizationRequest, callback); + this.Channel.Respond(response); + } + + /// <summary> + /// Checks the incoming HTTP request for an access token request and prepares a response if the request message was found. + /// </summary> + /// <param name="response">The formulated response, or <c>null</c> if the request was not found..</param> + /// <returns>A value indicating whether any access token request was found in the HTTP request.</returns> + /// <remarks> + /// This method assumes that the authorization server and the resource server are the same and that they share a single + /// asymmetric key for signing and encrypting the access token. If this is not true, use the <see cref="ReadAccessTokenRequest"/> method instead. + /// </remarks> + public bool TryPrepareAccessTokenResponse(out IDirectResponseProtocolMessage response) { + return this.TryPrepareAccessTokenResponse(this.Channel.GetRequestFromContext(), out response); + } + + /// <summary> + /// Checks the incoming HTTP request for an access token request and prepares a response if the request message was found. + /// </summary> + /// <param name="httpRequestInfo">The HTTP request info.</param> + /// <param name="response">The formulated response, or <c>null</c> if the request was not found..</param> + /// <returns>A value indicating whether any access token request was found in the HTTP request.</returns> + /// <remarks> + /// This method assumes that the authorization server and the resource server are the same and that they share a single + /// asymmetric key for signing and encrypting the access token. If this is not true, use the <see cref="ReadAccessTokenRequest"/> method instead. + /// </remarks> + public bool TryPrepareAccessTokenResponse(HttpRequestInfo httpRequestInfo, out IDirectResponseProtocolMessage response) { + Contract.Requires<ArgumentNullException>(httpRequestInfo != null); + Contract.Ensures(Contract.Result<bool>() == (Contract.ValueAtReturn<IDirectResponseProtocolMessage>(out response) != null)); + + var request = this.ReadAccessTokenRequest(httpRequestInfo); + if (request != null) { + response = this.PrepareAccessTokenResponse(request); + return true; + } + + response = null; + return false; + } + + /// <summary> + /// Reads the access token request. + /// </summary> + /// <param name="requestInfo">The request info.</param> + /// <returns>The Client's request for an access token; or <c>null</c> if no such message was found in the request.</returns> + public AccessTokenRequestBase ReadAccessTokenRequest(HttpRequestInfo requestInfo = null) { + if (requestInfo == null) { + requestInfo = this.Channel.GetRequestFromContext(); + } + + AccessTokenRequestBase request; + this.Channel.TryReadFromRequest(requestInfo, out request); + return request; + } + + /// <summary> + /// Prepares a response to inform the Client that the user has rejected the Client's authorization request. + /// </summary> + /// <param name="authorizationRequest">The authorization request.</param> + /// <param name="callback">The Client callback URL to use when formulating the redirect to send the user agent back to the Client.</param> + /// <returns>The authorization response message to send to the Client.</returns> + public EndUserAuthorizationFailedResponse PrepareRejectAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, Uri callback = null) { + Contract.Requires<ArgumentNullException>(authorizationRequest != null); + Contract.Ensures(Contract.Result<EndUserAuthorizationFailedResponse>() != null); + + if (callback == null) { + callback = this.GetCallback(authorizationRequest); + } + + var response = new EndUserAuthorizationFailedResponse(callback, authorizationRequest); + return response; + } + + /// <summary> + /// Approves an authorization request. + /// </summary> + /// <param name="authorizationRequest">The authorization request to approve.</param> + /// <param name="userName">The username of the account that approved the request (or whose data will be accessed by the client).</param> + /// <param name="scopes">The scope of access the client should be granted. If <c>null</c>, all scopes in the original request will be granted.</param> + /// <param name="callback">The Client callback URL to use when formulating the redirect to send the user agent back to the Client.</param> + /// <returns>The authorization response message to send to the Client.</returns> + public EndUserAuthorizationSuccessResponseBase PrepareApproveAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, string userName, IEnumerable<string> scopes = null, Uri callback = null) { + Contract.Requires<ArgumentNullException>(authorizationRequest != null); + Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(userName)); + Contract.Ensures(Contract.Result<EndUserAuthorizationSuccessResponseBase>() != null); + + if (callback == null) { + callback = this.GetCallback(authorizationRequest); + } + + var client = this.AuthorizationServerServices.GetClientOrThrow(authorizationRequest.ClientIdentifier); + EndUserAuthorizationSuccessResponseBase response; + switch (authorizationRequest.ResponseType) { + case EndUserAuthorizationResponseType.AccessToken: + var accessTokenResponse = new EndUserAuthorizationSuccessAccessTokenResponse(callback, authorizationRequest); + accessTokenResponse.Lifetime = this.AuthorizationServerServices.GetAccessTokenLifetime(authorizationRequest); + response = accessTokenResponse; + break; + case EndUserAuthorizationResponseType.AuthorizationCode: + response = new EndUserAuthorizationSuccessAuthCodeResponse(callback, authorizationRequest); + break; + default: + throw ErrorUtilities.ThrowInternal("Unexpected response type."); + } + + response.AuthorizingUsername = userName; + + // Customize the approved scope if the authorization server has decided to do so. + if (scopes != null) { + response.Scope.ResetContents(scopes); + } + + return response; + } + + /// <summary> + /// Prepares the response to an access token request. + /// </summary> + /// <param name="request">The request for an access token.</param> + /// <param name="includeRefreshToken">If set to <c>true</c>, the response will include a long-lived refresh token.</param> + /// <returns>The response message to send to the client.</returns> + public virtual IDirectResponseProtocolMessage PrepareAccessTokenResponse(AccessTokenRequestBase request, bool includeRefreshToken = true) { + Contract.Requires<ArgumentNullException>(request != null); + + var tokenRequest = (IAuthorizationCarryingRequest)request; + var response = new AccessTokenSuccessResponse(request) { + Lifetime = this.AuthorizationServerServices.GetAccessTokenLifetime(request), + HasRefreshToken = includeRefreshToken, + }; + response.Scope.ResetContents(tokenRequest.AuthorizationDescription.Scope); + return response; + } + + /// <summary> + /// Gets the redirect URL to use for a particular authorization request. + /// </summary> + /// <param name="authorizationRequest">The authorization request.</param> + /// <returns>The URL to redirect to. Never <c>null</c>.</returns> + /// <exception cref="ProtocolException">Thrown if no callback URL could be determined.</exception> + protected Uri GetCallback(EndUserAuthorizationRequest authorizationRequest) { + Contract.Requires<ArgumentNullException>(authorizationRequest != null); + Contract.Ensures(Contract.Result<Uri>() != null); + + var client = this.AuthorizationServerServices.GetClientOrThrow(authorizationRequest.ClientIdentifier); + + // Prefer a request-specific callback to the pre-registered one (if any). + if (authorizationRequest.Callback != null) { + // The OAuth channel has already validated the callback parameter against + // the authorization server's whitelist for this client. + return authorizationRequest.Callback; + } + + // Since the request didn't include a callback URL, look up the callback from + // the client's preregistration with this authorization server. + Uri defaultCallback = client.DefaultCallback; + ErrorUtilities.VerifyProtocol(defaultCallback != null, OAuthStrings.NoCallback); + return defaultCallback; + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/AuthorizationServerDescription.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/AuthorizationServerDescription.cs new file mode 100644 index 0000000..bbad27c --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/AuthorizationServerDescription.cs @@ -0,0 +1,62 @@ +//----------------------------------------------------------------------- +// <copyright file="AuthorizationServerDescription.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2 { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + + /// <summary> + /// A description of an OAuth Authorization Server as seen by an OAuth Client. + /// </summary> + public class AuthorizationServerDescription { + /// <summary> + /// Initializes a new instance of the <see cref="AuthorizationServerDescription"/> class. + /// </summary> + public AuthorizationServerDescription() { + this.ProtocolVersion = Protocol.Default.ProtocolVersion; + } + + /// <summary> + /// Gets or sets the Authorization Server URL from which an Access Token is requested by the Client. + /// </summary> + /// <value>An HTTPS URL.</value> + /// <remarks> + /// <para>After obtaining authorization from the resource owner, clients request an access token from the authorization server's token endpoint.</para> + /// <para>The URI of the token endpoint can be found in the service documentation, or can be obtained by the client by making an unauthorized protected resource request (from the WWW-Authenticate response header token-uri (The 'authorization-uri' Attribute) attribute).</para> + /// <para>The token endpoint advertised by the resource server MAY include a query component as defined by [RFC3986] (Berners-Lee, T., Fielding, R., and L. Masinter, “Uniform Resource Identifier (URI): Generic Syntax,” January 2005.) section 3.</para> + /// <para>Since requests to the token endpoint result in the transmission of plain text credentials in the HTTP request and response, the authorization server MUST require the use of a transport-layer mechanism such as TLS/SSL (or a secure channel with equivalent protections) when sending requests to the token endpoints. </para> + /// </remarks> + public Uri TokenEndpoint { get; set; } + + /// <summary> + /// Gets or sets the Authorization Server URL where the Client (re)directs the User + /// to make an authorization request. + /// </summary> + /// <value>An HTTPS URL.</value> + /// <remarks> + /// <para>Clients direct the resource owner to the authorization endpoint to approve their access request. Before granting access, the resource owner first authenticates with the authorization server. The way in which the authorization server authenticates the end-user (e.g. username and password login, OpenID, session cookies) and in which the authorization server obtains the end-user's authorization, including whether it uses a secure channel such as TLS/SSL, is beyond the scope of this specification. However, the authorization server MUST first verify the identity of the end-user.</para> + /// <para>The URI of the authorization endpoint can be found in the service documentation, or can be obtained by the client by making an unauthorized protected resource request (from the WWW-Authenticate response header auth-uri (The 'authorization-uri' Attribute) attribute).</para> + /// <para>The authorization endpoint advertised by the resource server MAY include a query component as defined by [RFC3986] (Berners-Lee, T., Fielding, R., and L. Masinter, “Uniform Resource Identifier (URI): Generic Syntax,” January 2005.) section 3.</para> + /// <para>Since requests to the authorization endpoint result in user authentication and the transmission of sensitive values, the authorization server SHOULD require the use of a transport-layer mechanism such as TLS/SSL (or a secure channel with equivalent protections) when sending requests to the authorization endpoints.</para> + /// </remarks> + public Uri AuthorizationEndpoint { get; set; } + + /// <summary> + /// Gets or sets the OAuth version supported by the Authorization Server. + /// </summary> + public ProtocolVersion ProtocolVersion { get; set; } + + /// <summary> + /// Gets the version of the OAuth protocol to use with this Authorization Server. + /// </summary> + /// <value>The version.</value> + internal Version Version { + get { return Protocol.Lookup(this.ProtocolVersion).Version; } + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/AuthorizationState.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/AuthorizationState.cs new file mode 100644 index 0000000..bfc33aa --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/AuthorizationState.cs @@ -0,0 +1,93 @@ +//----------------------------------------------------------------------- +// <copyright file="AuthorizationState.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2 { + using System; + using System.Collections.Generic; + + using DotNetOpenAuth.Messaging; + + /// <summary> + /// A simple in-memory copy of an authorization state. + /// </summary> + [Serializable] + public class AuthorizationState : IAuthorizationState { + /// <summary> + /// Initializes a new instance of the <see cref="AuthorizationState"/> class. + /// </summary> + /// <param name="scopes">The scopes of access being requested or that was obtained.</param> + public AuthorizationState(IEnumerable<string> scopes = null) { + this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer); + if (scopes != null) { + this.Scope.AddRange(scopes); + } + } + + /// <summary> + /// Gets or sets the callback URL used to obtain authorization. + /// </summary> + /// <value>The callback URL.</value> + public Uri Callback { get; set; } + + /// <summary> + /// Gets or sets the long-lived token used to renew the short-lived <see cref="AccessToken"/>. + /// </summary> + /// <value>The refresh token.</value> + public string RefreshToken { get; set; } + + /// <summary> + /// Gets or sets the access token. + /// </summary> + /// <value>The access token.</value> + public string AccessToken { get; set; } + + /// <summary> + /// Gets or sets the access token UTC expiration date. + /// </summary> + /// <value></value> + public DateTime? AccessTokenExpirationUtc { get; set; } + + /// <summary> + /// Gets or sets the access token issue date UTC. + /// </summary> + /// <value>The access token issue date UTC.</value> + public DateTime? AccessTokenIssueDateUtc { get; set; } + + /// <summary> + /// Gets the scope the token is (to be) authorized for. + /// </summary> + /// <value>The scope.</value> + public HashSet<string> Scope { get; private set; } + + /// <summary> + /// Gets or sets a value indicating whether this instance is deleted. + /// </summary> + /// <value> + /// <c>true</c> if this instance is deleted; otherwise, <c>false</c>. + /// </value> + public bool IsDeleted { get; set; } + + /// <summary> + /// Deletes this authorization, including access token and refresh token where applicable. + /// </summary> + /// <remarks> + /// This method is invoked when an authorization attempt fails, is rejected, is revoked, or + /// expires and cannot be renewed. + /// </remarks> + public virtual void Delete() { + this.IsDeleted = true; + } + + /// <summary> + /// Saves any changes made to this authorization object's properties. + /// </summary> + /// <remarks> + /// This method is invoked after DotNetOpenAuth changes any property. + /// </remarks> + public virtual void SaveChanges() { + } + } +}
\ No newline at end of file diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AccessRequestBindingElement.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AccessRequestBindingElement.cs new file mode 100644 index 0000000..b86f5dd --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AccessRequestBindingElement.cs @@ -0,0 +1,158 @@ +//----------------------------------------------------------------------- +// <copyright file="AccessRequestBindingElement.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.ChannelElements { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Security.Cryptography; + using System.Text; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; + using DotNetOpenAuth.OAuth2.Messages; + + /// <summary> + /// Decodes verification codes, refresh tokens and access tokens on incoming messages. + /// </summary> + /// <remarks> + /// This binding element also ensures that the code/token coming in is issued to + /// the same client that is sending the code/token and that the authorization has + /// not been revoked and that an access token has not expired. + /// </remarks> + internal class AccessRequestBindingElement : AuthServerBindingElementBase { + /// <summary> + /// Initializes a new instance of the <see cref="AccessRequestBindingElement"/> class. + /// </summary> + internal AccessRequestBindingElement() { + } + + /// <summary> + /// Gets the protection commonly offered (if any) by this binding element. + /// </summary> + /// <value></value> + /// <remarks> + /// This value is used to assist in sorting binding elements in the channel stack. + /// </remarks> + public override MessageProtections Protection { + get { return MessageProtections.None; } + } + + /// <summary> + /// Prepares a message for sending based on the rules of this channel binding element. + /// </summary> + /// <param name="message">The message to prepare for sending.</param> + /// <returns> + /// The protections (if any) that this binding element applied to the message. + /// Null if this binding element did not even apply to this binding element. + /// </returns> + /// <remarks> + /// Implementations that provide message protection must honor the + /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. + /// </remarks> + public override MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) { + var response = message as IAuthorizationCarryingRequest; + if (response != null) { + switch (response.CodeOrTokenType) { + case CodeOrTokenType.AuthorizationCode: + var codeFormatter = AuthorizationCode.CreateFormatter(this.AuthorizationServer); + var code = (AuthorizationCode)response.AuthorizationDescription; + response.CodeOrToken = codeFormatter.Serialize(code); + break; + case CodeOrTokenType.AccessToken: + var responseWithOriginatingRequest = (IDirectResponseProtocolMessage)message; + var request = (IAccessTokenRequest)responseWithOriginatingRequest.OriginatingRequest; + + using (var resourceServerKey = this.AuthorizationServer.GetResourceServerEncryptionKey(request)) { + var tokenFormatter = AccessToken.CreateFormatter(this.AuthorizationServer.AccessTokenSigningKey, resourceServerKey); + var token = (AccessToken)response.AuthorizationDescription; + response.CodeOrToken = tokenFormatter.Serialize(token); + break; + } + default: + throw ErrorUtilities.ThrowInternal(string.Format(CultureInfo.CurrentCulture, "Unexpected outgoing code or token type: {0}", response.CodeOrTokenType)); + } + + return MessageProtections.None; + } + + var accessTokenResponse = message as AccessTokenSuccessResponse; + if (accessTokenResponse != null) { + var directResponseMessage = (IDirectResponseProtocolMessage)accessTokenResponse; + var accessTokenRequest = (AccessTokenRequestBase)directResponseMessage.OriginatingRequest; + ErrorUtilities.VerifyProtocol(accessTokenRequest.GrantType != GrantType.ClientCredentials || accessTokenResponse.RefreshToken == null, OAuthStrings.NoGrantNoRefreshToken); + } + + return null; + } + + /// <summary> + /// Performs any transformation on an incoming message that may be necessary and/or + /// validates an incoming message based on the rules of this channel binding element. + /// </summary> + /// <param name="message">The incoming message to process.</param> + /// <returns> + /// The protections (if any) that this binding element applied to the message. + /// Null if this binding element did not even apply to this binding element. + /// </returns> + /// <exception cref="ProtocolException"> + /// Thrown when the binding element rules indicate that this message is invalid and should + /// NOT be processed. + /// </exception> + /// <remarks> + /// Implementations that provide message protection must honor the + /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. + /// </remarks> + public override MessageProtections? ProcessIncomingMessage(IProtocolMessage message) { + var tokenRequest = message as IAuthorizationCarryingRequest; + if (tokenRequest != null) { + try { + switch (tokenRequest.CodeOrTokenType) { + case CodeOrTokenType.AuthorizationCode: + var verificationCodeFormatter = AuthorizationCode.CreateFormatter(this.AuthorizationServer); + var verificationCode = verificationCodeFormatter.Deserialize(message, tokenRequest.CodeOrToken); + tokenRequest.AuthorizationDescription = verificationCode; + break; + case CodeOrTokenType.RefreshToken: + var refreshTokenFormatter = RefreshToken.CreateFormatter(this.AuthorizationServer.CryptoKeyStore); + var refreshToken = refreshTokenFormatter.Deserialize(message, tokenRequest.CodeOrToken); + tokenRequest.AuthorizationDescription = refreshToken; + break; + default: + throw ErrorUtilities.ThrowInternal("Unexpected value for CodeOrTokenType: " + tokenRequest.CodeOrTokenType); + } + } catch (ExpiredMessageException ex) { + throw ErrorUtilities.Wrap(ex, Protocol.authorization_expired); + } + + var accessRequest = tokenRequest as AccessTokenRequestBase; + if (accessRequest != null) { + // Make sure the client sending us this token is the client we issued the token to. + ErrorUtilities.VerifyProtocol(string.Equals(accessRequest.ClientIdentifier, tokenRequest.AuthorizationDescription.ClientIdentifier, StringComparison.Ordinal), Protocol.incorrect_client_credentials); + + // Check that the client secret is correct. + var client = this.AuthorizationServer.GetClientOrThrow(accessRequest.ClientIdentifier); + string secret = client.Secret; + ErrorUtilities.VerifyProtocol(!String.IsNullOrEmpty(secret), Protocol.unauthorized_client); // an empty secret is not allowed for client authenticated calls. + ErrorUtilities.VerifyProtocol(MessagingUtilities.EqualsConstantTime(secret, accessRequest.ClientSecret), Protocol.incorrect_client_credentials); + + var scopedAccessRequest = accessRequest as ScopedAccessTokenRequest; + if (scopedAccessRequest != null) { + // Make sure the scope the client is requesting does not exceed the scope in the grant. + ErrorUtilities.VerifyProtocol(scopedAccessRequest.Scope.IsSubsetOf(tokenRequest.AuthorizationDescription.Scope), OAuthStrings.AccessScopeExceedsGrantScope, scopedAccessRequest.Scope, tokenRequest.AuthorizationDescription.Scope); + } + } + + // Make sure the authorization this token represents hasn't already been revoked. + ErrorUtilities.VerifyProtocol(this.AuthorizationServer.IsAuthorizationValid(tokenRequest.AuthorizationDescription), Protocol.authorization_expired); + + return MessageProtections.None; + } + + return null; + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AccessToken.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AccessToken.cs new file mode 100644 index 0000000..6278828 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AccessToken.cs @@ -0,0 +1,102 @@ +//----------------------------------------------------------------------- +// <copyright file="AccessToken.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.ChannelElements { + using System; + using System.Collections.Generic; + using System.Diagnostics.Contracts; + using System.Security.Cryptography; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; + + /// <summary> + /// A short-lived token that accompanies HTTP requests to protected data to authorize the request. + /// </summary> + internal class AccessToken : AuthorizationDataBag { + /// <summary> + /// Initializes a new instance of the <see cref="AccessToken"/> class. + /// </summary> + public AccessToken() { + } + + /// <summary> + /// Initializes a new instance of the <see cref="AccessToken"/> class. + /// </summary> + /// <param name="authorization">The authorization to be described by the access token.</param> + /// <param name="lifetime">The lifetime of the access token.</param> + internal AccessToken(IAuthorizationDescription authorization, TimeSpan? lifetime) { + Contract.Requires<ArgumentNullException>(authorization != null); + + this.ClientIdentifier = authorization.ClientIdentifier; + this.UtcCreationDate = authorization.UtcIssued; + this.User = authorization.User; + this.Scope.ResetContents(authorization.Scope); + this.Lifetime = lifetime; + } + + /// <summary> + /// Initializes a new instance of the <see cref="AccessToken"/> class. + /// </summary> + /// <param name="clientIdentifier">The client identifier.</param> + /// <param name="scopes">The scopes.</param> + /// <param name="username">The username of the account that authorized this token.</param> + /// <param name="lifetime">The lifetime for this access token.</param> + internal AccessToken(string clientIdentifier, IEnumerable<string> scopes, string username, TimeSpan? lifetime) { + Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(clientIdentifier)); + + this.ClientIdentifier = clientIdentifier; + this.Scope.ResetContents(scopes); + this.User = username; + this.Lifetime = lifetime; + this.UtcCreationDate = DateTime.UtcNow; + } + + /// <summary> + /// Gets or sets the lifetime of the access token. + /// </summary> + /// <value>The lifetime.</value> + [MessagePart(Encoder = typeof(TimespanSecondsEncoder))] + internal TimeSpan? Lifetime { get; set; } + + /// <summary> + /// Creates a formatter capable of serializing/deserializing an access token. + /// </summary> + /// <param name="signingKey">The crypto service provider with the authorization server's private key used to asymmetrically sign the access token.</param> + /// <param name="encryptingKey">The crypto service provider with the resource server's public key used to encrypt the access token.</param> + /// <returns>An access token serializer.</returns> + internal static IDataBagFormatter<AccessToken> CreateFormatter(RSACryptoServiceProvider signingKey, RSACryptoServiceProvider encryptingKey) { + Contract.Requires(signingKey != null || !signingKey.PublicOnly); + Contract.Requires(encryptingKey != null); + Contract.Ensures(Contract.Result<IDataBagFormatter<AccessToken>>() != null); + + return new UriStyleMessageFormatter<AccessToken>(signingKey, encryptingKey); + } + + /// <summary> + /// Checks the message state for conformity to the protocol specification + /// and throws an exception if the message is invalid. + /// </summary> + /// <remarks> + /// <para>Some messages have required fields, or combinations of fields that must relate to each other + /// in specialized ways. After deserializing a message, this method checks the state of the + /// message to see if it conforms to the protocol.</para> + /// <para>Note that this property should <i>not</i> check signatures or perform any state checks + /// outside this scope of this particular message.</para> + /// </remarks> + /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception> + protected override void EnsureValidMessage() { + base.EnsureValidMessage(); + + // Has this token expired? + if (this.Lifetime.HasValue) { + DateTime expirationDate = this.UtcCreationDate + this.Lifetime.Value; + if (expirationDate < DateTime.UtcNow) { + throw new ExpiredMessageException(expirationDate, this.ContainingMessage); + } + } + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AccessTokenBindingElement.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AccessTokenBindingElement.cs new file mode 100644 index 0000000..3a709b6 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AccessTokenBindingElement.cs @@ -0,0 +1,93 @@ +//----------------------------------------------------------------------- +// <copyright file="AccessTokenBindingElement.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.ChannelElements { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Security.Cryptography; + using System.Text; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth2.Messages; + + /// <summary> + /// Serializes access tokens inside an outgoing message. + /// </summary> + internal class AccessTokenBindingElement : AuthServerBindingElementBase { + /// <summary> + /// Initializes a new instance of the <see cref="AccessTokenBindingElement"/> class. + /// </summary> + internal AccessTokenBindingElement() { + } + + /// <summary> + /// Gets the protection commonly offered (if any) by this binding element. + /// </summary> + /// <value>Always <c>MessageProtections.None</c></value> + /// <remarks> + /// This value is used to assist in sorting binding elements in the channel stack. + /// </remarks> + public override MessageProtections Protection { + get { return MessageProtections.None; } + } + + /// <summary> + /// Prepares a message for sending based on the rules of this channel binding element. + /// </summary> + /// <param name="message">The message to prepare for sending.</param> + /// <returns> + /// The protections (if any) that this binding element applied to the message. + /// Null if this binding element did not even apply to this binding element. + /// </returns> + public override MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) { + var directResponse = message as IDirectResponseProtocolMessage; + IAccessTokenRequest request = directResponse != null ? directResponse.OriginatingRequest as IAccessTokenRequest : null; + + var implicitGrantResponse = message as EndUserAuthorizationSuccessAccessTokenResponse; + if (implicitGrantResponse != null) { + IAuthorizationCarryingRequest tokenCarryingResponse = implicitGrantResponse; + tokenCarryingResponse.AuthorizationDescription = new AccessToken(request.ClientIdentifier, implicitGrantResponse.Scope, implicitGrantResponse.AuthorizingUsername, implicitGrantResponse.Lifetime); + + return MessageProtections.None; + } + + var accessTokenResponse = message as AccessTokenSuccessResponse; + if (accessTokenResponse != null) { + var authCarryingRequest = (IAuthorizationCarryingRequest)request; + var accessToken = new AccessToken(authCarryingRequest.AuthorizationDescription, accessTokenResponse.Lifetime); + using (var resourceServerEncryptionKey = this.AuthorizationServer.GetResourceServerEncryptionKey(request)) { + var accessTokenFormatter = AccessToken.CreateFormatter(this.AuthorizationServer.AccessTokenSigningKey, resourceServerEncryptionKey); + accessTokenResponse.AccessToken = accessTokenFormatter.Serialize(accessToken); + } + + if (accessTokenResponse.HasRefreshToken) { + var refreshToken = new RefreshToken(authCarryingRequest.AuthorizationDescription); + var refreshTokenFormatter = RefreshToken.CreateFormatter(this.AuthorizationServer.CryptoKeyStore); + accessTokenResponse.RefreshToken = refreshTokenFormatter.Serialize(refreshToken); + } + } + + return null; + } + + /// <summary> + /// Performs any transformation on an incoming message that may be necessary and/or + /// validates an incoming message based on the rules of this channel binding element. + /// </summary> + /// <param name="message">The incoming message to process.</param> + /// <returns> + /// The protections (if any) that this binding element applied to the message. + /// Null if this binding element did not even apply to this binding element. + /// </returns> + /// <exception cref="ProtocolException"> + /// Thrown when the binding element rules indicate that this message is invalid and should + /// NOT be processed. + /// </exception> + public override MessageProtections? ProcessIncomingMessage(IProtocolMessage message) { + return null; + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthServerAllFlowsBindingElement.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthServerAllFlowsBindingElement.cs new file mode 100644 index 0000000..bc464e2 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthServerAllFlowsBindingElement.cs @@ -0,0 +1,83 @@ +//----------------------------------------------------------------------- +// <copyright file="AuthServerAllFlowsBindingElement.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.ChannelElements { + using System; + using System.Collections.Generic; + using System.Diagnostics.Contracts; + using System.Linq; + using System.Text; + using DotNetOpenAuth.OAuth2.Messages; + using Messaging; + + /// <summary> + /// A binding element that should be applied for authorization server channels regardless of which flows + /// are supported. + /// </summary> + internal class AuthServerAllFlowsBindingElement : AuthServerBindingElementBase { + /// <summary> + /// Initializes a new instance of the <see cref="AuthServerAllFlowsBindingElement"/> class. + /// </summary> + internal AuthServerAllFlowsBindingElement() { + } + + /// <summary> + /// Gets the protection commonly offered (if any) by this binding element. + /// </summary> + /// <remarks> + /// This value is used to assist in sorting binding elements in the channel stack. + /// </remarks> + public override MessageProtections Protection { + get { return MessageProtections.None; } + } + + /// <summary> + /// Prepares a message for sending based on the rules of this channel binding element. + /// </summary> + /// <param name="message">The message to prepare for sending.</param> + /// <returns> + /// The protections (if any) that this binding element applied to the message. + /// Null if this binding element did not even apply to this binding element. + /// </returns> + /// <remarks> + /// Implementations that provide message protection must honor the + /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. + /// </remarks> + public override MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) { + return null; + } + + /// <summary> + /// Performs any transformation on an incoming message that may be necessary and/or + /// validates an incoming message based on the rules of this channel binding element. + /// </summary> + /// <param name="message">The incoming message to process.</param> + /// <returns> + /// The protections (if any) that this binding element applied to the message. + /// Null if this binding element did not even apply to this binding element. + /// </returns> + /// <exception cref="ProtocolException"> + /// Thrown when the binding element rules indicate that this message is invalid and should + /// NOT be processed. + /// </exception> + /// <remarks> + /// Implementations that provide message protection must honor the + /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. + /// </remarks> + public override MessageProtections? ProcessIncomingMessage(IProtocolMessage message) { + var authorizationRequest = message as EndUserAuthorizationRequest; + if (authorizationRequest != null) { + var client = this.AuthorizationServer.GetClientOrThrow(authorizationRequest.ClientIdentifier); + ErrorUtilities.VerifyProtocol(authorizationRequest.Callback == null || client.IsCallbackAllowed(authorizationRequest.Callback), OAuthStrings.ClientCallbackDisallowed, authorizationRequest.Callback); + ErrorUtilities.VerifyProtocol(authorizationRequest.Callback != null || client.DefaultCallback != null, OAuthStrings.NoCallback); + + return MessageProtections.None; + } + + return null; + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthServerBindingElementBase.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthServerBindingElementBase.cs new file mode 100644 index 0000000..9d3e78f --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthServerBindingElementBase.cs @@ -0,0 +1,92 @@ +//----------------------------------------------------------------------- +// <copyright file="AuthServerBindingElementBase.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.ChannelElements { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using Messaging; + + /// <summary> + /// The base class for any authorization server channel binding element. + /// </summary> + internal abstract class AuthServerBindingElementBase : IChannelBindingElement { + /// <summary> + /// Initializes a new instance of the <see cref="AuthServerBindingElementBase"/> class. + /// </summary> + protected AuthServerBindingElementBase() + { + } + + /// <summary> + /// Gets or sets the channel that this binding element belongs to. + /// </summary> + /// <remarks> + /// This property is set by the channel when it is first constructed. + /// </remarks> + public Channel Channel { get; set; } + + /// <summary> + /// Gets the protection commonly offered (if any) by this binding element. + /// </summary> + /// <remarks> + /// This value is used to assist in sorting binding elements in the channel stack. + /// </remarks> + public abstract MessageProtections Protection { get; } + + /// <summary> + /// Gets the channel that this binding element belongs to. + /// </summary> + /// <remarks> + /// This property is set by the channel when it is first constructed. + /// </remarks> + protected OAuth2AuthorizationServerChannel OAuthChannel { + get { return (OAuth2AuthorizationServerChannel)this.Channel; } + } + + /// <summary> + /// Gets the authorization server hosting this channel. + /// </summary> + /// <value>The authorization server.</value> + protected IAuthorizationServer AuthorizationServer { + get { return this.OAuthChannel.AuthorizationServer; } + } + + /// <summary> + /// Prepares a message for sending based on the rules of this channel binding element. + /// </summary> + /// <param name="message">The message to prepare for sending.</param> + /// <returns> + /// The protections (if any) that this binding element applied to the message. + /// Null if this binding element did not even apply to this binding element. + /// </returns> + /// <remarks> + /// Implementations that provide message protection must honor the + /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. + /// </remarks> + public abstract MessageProtections? ProcessOutgoingMessage(IProtocolMessage message); + + /// <summary> + /// Performs any transformation on an incoming message that may be necessary and/or + /// validates an incoming message based on the rules of this channel binding element. + /// </summary> + /// <param name="message">The incoming message to process.</param> + /// <returns> + /// The protections (if any) that this binding element applied to the message. + /// Null if this binding element did not even apply to this binding element. + /// </returns> + /// <exception cref="ProtocolException"> + /// Thrown when the binding element rules indicate that this message is invalid and should + /// NOT be processed. + /// </exception> + /// <remarks> + /// Implementations that provide message protection must honor the + /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. + /// </remarks> + public abstract MessageProtections? ProcessIncomingMessage(IProtocolMessage message); + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthorizationCode.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthorizationCode.cs new file mode 100644 index 0000000..03732bb --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthorizationCode.cs @@ -0,0 +1,100 @@ +//----------------------------------------------------------------------- +// <copyright file="AuthorizationCode.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.ChannelElements { + using System; + using System.Collections.Generic; + using System.Diagnostics.Contracts; + using System.Security.Cryptography; + using System.Text; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// Represents the authorization code created when a user approves authorization that + /// allows the client to request an access/refresh token. + /// </summary> + internal class AuthorizationCode : AuthorizationDataBag { + /// <summary> + /// The name of the bucket for symmetric keys used to sign authorization codes. + /// </summary> + internal const string AuthorizationCodeKeyBucket = "https://localhost/dnoa/oauth_authorization_code"; + + /// <summary> + /// Initializes a new instance of the <see cref="AuthorizationCode"/> class. + /// </summary> + public AuthorizationCode() { + } + + /// <summary> + /// Initializes a new instance of the <see cref="AuthorizationCode"/> class. + /// </summary> + /// <param name="clientIdentifier">The client identifier.</param> + /// <param name="callback">The callback the client used to obtain authorization.</param> + /// <param name="scopes">The authorized scopes.</param> + /// <param name="username">The name on the account that authorized access.</param> + internal AuthorizationCode(string clientIdentifier, Uri callback, IEnumerable<string> scopes, string username) { + Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(clientIdentifier)); + Contract.Requires<ArgumentNullException>(callback != null); + + this.ClientIdentifier = clientIdentifier; + this.CallbackHash = CalculateCallbackHash(callback); + this.Scope.ResetContents(scopes); + this.User = username; + this.UtcCreationDate = DateTime.UtcNow; + } + + /// <summary> + /// Gets or sets the hash of the callback URL. + /// </summary> + [MessagePart("cb")] + private byte[] CallbackHash { get; set; } + + /// <summary> + /// Creates a serializer/deserializer for this type. + /// </summary> + /// <param name="authorizationServer">The authorization server that will be serializing/deserializing this authorization code. Must not be null.</param> + /// <returns>A DataBag formatter.</returns> + internal static IDataBagFormatter<AuthorizationCode> CreateFormatter(IAuthorizationServer authorizationServer) { + Contract.Requires<ArgumentNullException>(authorizationServer != null); + Contract.Ensures(Contract.Result<IDataBagFormatter<AuthorizationCode>>() != null); + + return new UriStyleMessageFormatter<AuthorizationCode>( + authorizationServer.CryptoKeyStore, + AuthorizationCodeKeyBucket, + signed: true, + encrypted: true, + compressed: false, + maximumAge: AuthorizationCodeBindingElement.MaximumMessageAge, + decodeOnceOnly: authorizationServer.VerificationCodeNonceStore); + } + + /// <summary> + /// Verifies the the given callback URL matches the callback originally given in the authorization request. + /// </summary> + /// <param name="callback">The callback.</param> + /// <remarks> + /// This method serves to verify that the callback URL given in the original authorization request + /// and the callback URL given in the access token request match. + /// </remarks> + /// <exception cref="ProtocolException">Thrown when the callback URLs do not match.</exception> + internal void VerifyCallback(Uri callback) { + ErrorUtilities.VerifyProtocol(MessagingUtilities.AreEquivalent(this.CallbackHash, CalculateCallbackHash(callback)), Protocol.redirect_uri_mismatch); + } + + /// <summary> + /// Calculates the hash of the callback URL. + /// </summary> + /// <param name="callback">The callback whose hash should be calculated.</param> + /// <returns> + /// A base64 encoding of the hash of the URL. + /// </returns> + private static byte[] CalculateCallbackHash(Uri callback) { + using (var hasher = new SHA256Managed()) { + return hasher.ComputeHash(Encoding.UTF8.GetBytes(callback.AbsoluteUri)); + } + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthorizationCodeBindingElement.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthorizationCodeBindingElement.cs new file mode 100644 index 0000000..4569c93 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthorizationCodeBindingElement.cs @@ -0,0 +1,101 @@ +//----------------------------------------------------------------------- +// <copyright file="AuthorizationCodeBindingElement.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.ChannelElements { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using Messages; + using Messaging; + using Messaging.Bindings; + + /// <summary> + /// A binding element for OAuth 2.0 authorization servers that create/verify + /// issued authorization codes as part of obtaining access/refresh tokens. + /// </summary> + internal class AuthorizationCodeBindingElement : AuthServerBindingElementBase { + /// <summary> + /// Initializes a new instance of the <see cref="AuthorizationCodeBindingElement"/> class. + /// </summary> + internal AuthorizationCodeBindingElement() { + } + + /// <summary> + /// Gets the protection commonly offered (if any) by this binding element. + /// </summary> + /// <value>Always <c>MessageProtections.None</c></value> + /// <remarks> + /// This value is used to assist in sorting binding elements in the channel stack. + /// </remarks> + public override MessageProtections Protection { + get { return MessageProtections.None; } + } + + /// <summary> + /// Gets the maximum message age from the standard expiration binding element. + /// </summary> + /// <value>This interval need not account for clock skew because it is only compared within a single authorization server or farm of servers.</value> + internal static TimeSpan MaximumMessageAge { + get { return Configuration.DotNetOpenAuthSection.Configuration.Messaging.MaximumMessageLifetimeNoSkew; } + } + + /// <summary> + /// Prepares a message for sending based on the rules of this channel binding element. + /// </summary> + /// <param name="message">The message to prepare for sending.</param> + /// <returns> + /// The protections (if any) that this binding element applied to the message. + /// Null if this binding element did not even apply to this binding element. + /// </returns> + /// <remarks> + /// Implementations that provide message protection must honor the + /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. + /// </remarks> + public override MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) { + var response = message as EndUserAuthorizationSuccessAuthCodeResponse; + if (response != null) { + var directResponse = (IDirectResponseProtocolMessage)response; + var request = (EndUserAuthorizationRequest)directResponse.OriginatingRequest; + IAuthorizationCarryingRequest tokenCarryingResponse = response; + tokenCarryingResponse.AuthorizationDescription = new AuthorizationCode(request.ClientIdentifier, request.Callback, response.Scope, response.AuthorizingUsername); + + return MessageProtections.None; + } + + return null; + } + + /// <summary> + /// Performs any transformation on an incoming message that may be necessary and/or + /// validates an incoming message based on the rules of this channel binding element. + /// </summary> + /// <param name="message">The incoming message to process.</param> + /// <returns> + /// The protections (if any) that this binding element applied to the message. + /// Null if this binding element did not even apply to this binding element. + /// </returns> + /// <exception cref="ProtocolException"> + /// Thrown when the binding element rules indicate that this message is invalid and should + /// NOT be processed. + /// </exception> + /// <remarks> + /// Implementations that provide message protection must honor the + /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. + /// </remarks> + public override MessageProtections? ProcessIncomingMessage(IProtocolMessage message) { + var request = message as AccessTokenAuthorizationCodeRequest; + if (request != null) { + IAuthorizationCarryingRequest tokenRequest = request; + ((AuthorizationCode)tokenRequest.AuthorizationDescription).VerifyCallback(request.Callback); + + return MessageProtections.None; + } + + return null; + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthorizationDataBag.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthorizationDataBag.cs new file mode 100644 index 0000000..8f1d983 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthorizationDataBag.cs @@ -0,0 +1,51 @@ +//----------------------------------------------------------------------- +// <copyright file="AuthorizationDataBag.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.ChannelElements { + using System; + using System.Collections.Generic; + + using DotNetOpenAuth.Messaging; + + /// <summary> + /// A data bag that stores authorization data. + /// </summary> + internal abstract class AuthorizationDataBag : DataBag, IAuthorizationDescription { + /// <summary> + /// Initializes a new instance of the <see cref="AuthorizationDataBag"/> class. + /// </summary> + protected AuthorizationDataBag() { + this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer); + } + + /// <summary> + /// Gets or sets the identifier of the client authorized to access protected data. + /// </summary> + /// <value></value> + [MessagePart] + public string ClientIdentifier { get; set; } + + /// <summary> + /// Gets the date this authorization was established or the token was issued. + /// </summary> + /// <value>A date/time expressed in UTC.</value> + public DateTime UtcIssued { + get { return this.UtcCreationDate; } + } + + /// <summary> + /// Gets or sets the name on the account whose data on the resource server is accessible using this authorization. + /// </summary> + [MessagePart] + public string User { get; set; } + + /// <summary> + /// Gets the scope of operations the client is allowed to invoke. + /// </summary> + [MessagePart(Encoder = typeof(ScopeEncoder))] + public HashSet<string> Scope { get; private set; } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/EndUserAuthorizationResponseTypeEncoder.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/EndUserAuthorizationResponseTypeEncoder.cs new file mode 100644 index 0000000..139025d --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/EndUserAuthorizationResponseTypeEncoder.cs @@ -0,0 +1,66 @@ +//----------------------------------------------------------------------- +// <copyright file="EndUserAuthorizationResponseTypeEncoder.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.ChannelElements { + using System; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Reflection; + using DotNetOpenAuth.OAuth2.Messages; + + /// <summary> + /// Encodes/decodes the OAuth 2.0 response_type argument. + /// </summary> + internal class EndUserAuthorizationResponseTypeEncoder : IMessagePartEncoder { + /// <summary> + /// Initializes a new instance of the <see cref="EndUserAuthorizationResponseTypeEncoder"/> class. + /// </summary> + public EndUserAuthorizationResponseTypeEncoder() { + } + + #region IMessagePartEncoder Members + + /// <summary> + /// Encodes the specified value. + /// </summary> + /// <param name="value">The value. Guaranteed to never be null.</param> + /// <returns> + /// The <paramref name="value"/> in string form, ready for message transport. + /// </returns> + public string Encode(object value) { + var responseType = (EndUserAuthorizationResponseType)value; + switch (responseType) + { + case EndUserAuthorizationResponseType.AccessToken: + return Protocol.ResponseTypes.Token; + case EndUserAuthorizationResponseType.AuthorizationCode: + return Protocol.ResponseTypes.Code; + default: + throw ErrorUtilities.ThrowFormat(MessagingStrings.UnexpectedMessagePartValue, Protocol.response_type, value); + } + } + + /// <summary> + /// Decodes the specified value. + /// </summary> + /// <param name="value">The string value carried by the transport. Guaranteed to never be null, although it may be empty.</param> + /// <returns> + /// The deserialized form of the given string. + /// </returns> + /// <exception cref="FormatException">Thrown when the string value given cannot be decoded into the required object type.</exception> + public object Decode(string value) { + switch (value) { + case Protocol.ResponseTypes.Token: + return EndUserAuthorizationResponseType.AccessToken; + case Protocol.ResponseTypes.Code: + return EndUserAuthorizationResponseType.AuthorizationCode; + default: + throw ErrorUtilities.ThrowFormat(MessagingStrings.UnexpectedMessagePartValue, Protocol.response_type, value); + } + } + + #endregion + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/GrantTypeEncoder.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/GrantTypeEncoder.cs new file mode 100644 index 0000000..78ed975 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/GrantTypeEncoder.cs @@ -0,0 +1,78 @@ +//----------------------------------------------------------------------- +// <copyright file="GrantTypeEncoder.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.ChannelElements { + using System; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Reflection; + using DotNetOpenAuth.OAuth2.Messages; + + /// <summary> + /// Encodes/decodes the OAuth 2.0 grant_type argument. + /// </summary> + internal class GrantTypeEncoder : IMessagePartEncoder { + /// <summary> + /// Initializes a new instance of the <see cref="GrantTypeEncoder"/> class. + /// </summary> + public GrantTypeEncoder() { + } + + #region IMessagePartEncoder Members + + /// <summary> + /// Encodes the specified value. + /// </summary> + /// <param name="value">The value. Guaranteed to never be null.</param> + /// <returns> + /// The <paramref name="value"/> in string form, ready for message transport. + /// </returns> + public string Encode(object value) { + var responseType = (GrantType)value; + switch (responseType) + { + case GrantType.ClientCredentials: + return Protocol.GrantTypes.ClientCredentials; + case GrantType.AuthorizationCode: + return Protocol.GrantTypes.AuthorizationCode; + case GrantType.RefreshToken: + return Protocol.GrantTypes.RefreshToken; + case GrantType.Password: + return Protocol.GrantTypes.Password; + case GrantType.Assertion: + return Protocol.GrantTypes.Assertion; + default: + throw ErrorUtilities.ThrowFormat(MessagingStrings.UnexpectedMessagePartValue, Protocol.grant_type, value); + } + } + + /// <summary> + /// Decodes the specified value. + /// </summary> + /// <param name="value">The string value carried by the transport. Guaranteed to never be null, although it may be empty.</param> + /// <returns> + /// The deserialized form of the given string. + /// </returns> + /// <exception cref="FormatException">Thrown when the string value given cannot be decoded into the required object type.</exception> + public object Decode(string value) { + switch (value) { + case Protocol.GrantTypes.ClientCredentials: + return GrantType.ClientCredentials; + case Protocol.GrantTypes.Assertion: + return GrantType.Assertion; + case Protocol.GrantTypes.Password: + return GrantType.Password; + case Protocol.GrantTypes.RefreshToken: + return GrantType.RefreshToken; + case Protocol.GrantTypes.AuthorizationCode: + return GrantType.AuthorizationCode; + default: + throw ErrorUtilities.ThrowFormat(MessagingStrings.UnexpectedMessagePartValue, Protocol.grant_type, value); + } + } + + #endregion + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/IAuthorizationCarryingRequest.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/IAuthorizationCarryingRequest.cs new file mode 100644 index 0000000..e450131 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/IAuthorizationCarryingRequest.cs @@ -0,0 +1,54 @@ +//----------------------------------------------------------------------- +// <copyright file="IAuthorizationCarryingRequest.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.ChannelElements { + using System.Security.Cryptography; + + using Messaging; + + /// <summary> + /// The various types of tokens created by the authorization server. + /// </summary> + internal enum CodeOrTokenType { + /// <summary> + /// The code issued to the client after the user has approved authorization. + /// </summary> + AuthorizationCode, + + /// <summary> + /// The long-lived token issued to the client that enables it to obtain + /// short-lived access tokens later. + /// </summary> + RefreshToken, + + /// <summary> + /// A (typically) short-lived token. + /// </summary> + AccessToken, + } + + /// <summary> + /// A message that carries some kind of token from the client to the authorization or resource server. + /// </summary> + internal interface IAuthorizationCarryingRequest : IDirectedProtocolMessage { + /// <summary> + /// Gets or sets the verification code or refresh/access token. + /// </summary> + /// <value>The code or token.</value> + string CodeOrToken { get; set; } + + /// <summary> + /// Gets the type of the code or token. + /// </summary> + /// <value>The type of the code or token.</value> + CodeOrTokenType CodeOrTokenType { get; } + + /// <summary> + /// Gets or sets the authorization that the token describes. + /// </summary> + IAuthorizationDescription AuthorizationDescription { get; set; } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/IAuthorizationDescription.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/IAuthorizationDescription.cs new file mode 100644 index 0000000..2b3a9ce --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/IAuthorizationDescription.cs @@ -0,0 +1,90 @@ +//----------------------------------------------------------------------- +// <copyright file="IAuthorizationDescription.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.ChannelElements { + using System; + using System.Collections.Generic; + using System.Diagnostics.Contracts; + using System.Linq; + using System.Text; + + /// <summary> + /// Describes a delegated authorization between a resource server, a client, and a user. + /// </summary> + [ContractClass(typeof(IAuthorizationDescriptionContract))] + public interface IAuthorizationDescription { + /// <summary> + /// Gets the identifier of the client authorized to access protected data. + /// </summary> + string ClientIdentifier { get; } + + /// <summary> + /// Gets the date this authorization was established or the token was issued. + /// </summary> + /// <value>A date/time expressed in UTC.</value> + DateTime UtcIssued { get; } + + /// <summary> + /// Gets the name on the account whose data on the resource server is accessible using this authorization. + /// </summary> + string User { get; } + + /// <summary> + /// Gets the scope of operations the client is allowed to invoke. + /// </summary> + HashSet<string> Scope { get; } + } + + /// <summary> + /// Code contract for the <see cref="IAuthorizationDescription"/> interface. + /// </summary> + [ContractClassFor(typeof(IAuthorizationDescription))] + internal abstract class IAuthorizationDescriptionContract : IAuthorizationDescription { + /// <summary> + /// Prevents a default instance of the <see cref="IAuthorizationDescriptionContract"/> class from being created. + /// </summary> + private IAuthorizationDescriptionContract() { + } + + /// <summary> + /// Gets the identifier of the client authorized to access protected data. + /// </summary> + string IAuthorizationDescription.ClientIdentifier { + get { + Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>())); + throw new NotImplementedException(); + } + } + + /// <summary> + /// Gets the date this authorization was established or the token was issued. + /// </summary> + /// <value>A date/time expressed in UTC.</value> + DateTime IAuthorizationDescription.UtcIssued { + get { throw new NotImplementedException(); } + } + + /// <summary> + /// Gets the name on the account whose data on the resource server is accessible using this authorization. + /// </summary> + string IAuthorizationDescription.User { + get { + Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>())); + throw new NotImplementedException(); + } + } + + /// <summary> + /// Gets the scope of operations the client is allowed to invoke. + /// </summary> + HashSet<string> IAuthorizationDescription.Scope { + get { + Contract.Ensures(Contract.Result<HashSet<string>>() != null); + throw new NotImplementedException(); + } + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2AuthorizationServerChannel.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2AuthorizationServerChannel.cs new file mode 100644 index 0000000..888830e --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2AuthorizationServerChannel.cs @@ -0,0 +1,108 @@ +//----------------------------------------------------------------------- +// <copyright file="OAuth2AuthorizationServerChannel.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.ChannelElements { + using System; + using System.Collections.Generic; + using System.Diagnostics.Contracts; + using System.Net.Mime; + using System.Web; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// The channel for the OAuth protocol. + /// </summary> + internal class OAuth2AuthorizationServerChannel : OAuth2ChannelBase { + /// <summary> + /// Initializes a new instance of the <see cref="OAuth2AuthorizationServerChannel"/> class. + /// </summary> + /// <param name="authorizationServer">The authorization server.</param> + protected internal OAuth2AuthorizationServerChannel(IAuthorizationServer authorizationServer) + : base(InitializeBindingElements(authorizationServer)) { + Contract.Requires<ArgumentNullException>(authorizationServer != null); + this.AuthorizationServer = authorizationServer; + } + + /// <summary> + /// Gets the authorization server. + /// </summary> + /// <value>The authorization server.</value> + public IAuthorizationServer AuthorizationServer { get; private set; } + + /// <summary> + /// Gets the protocol message that may be in the given HTTP response. + /// </summary> + /// <param name="response">The response that is anticipated to contain an protocol message.</param> + /// <returns> + /// The deserialized message parts, if found. Null otherwise. + /// </returns> + /// <exception cref="ProtocolException">Thrown when the response is not valid.</exception> + protected override IDictionary<string, string> ReadFromResponseCore(IncomingWebResponse response) { + throw new NotImplementedException(); + } + + /// <summary> + /// Queues a message for sending in the response stream. + /// </summary> + /// <param name="response">The message to send as a response.</param> + /// <returns> + /// The pending user agent redirect based message to be sent as an HttpResponse. + /// </returns> + /// <remarks> + /// This method implements spec OAuth V1.0 section 5.3. + /// </remarks> + protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) { + var webResponse = new OutgoingWebResponse(); + string json = this.SerializeAsJson(response); + webResponse.SetResponse(json, new ContentType(JsonEncoded)); + return webResponse; + } + + /// <summary> + /// Gets the protocol message that may be embedded in the given HTTP request. + /// </summary> + /// <param name="request">The request to search for an embedded message.</param> + /// <returns> + /// The deserialized message, if one is found. Null otherwise. + /// </returns> + protected override IDirectedProtocolMessage ReadFromRequestCore(HttpRequestInfo request) { + if (!string.IsNullOrEmpty(request.Url.Fragment)) { + var fields = HttpUtility.ParseQueryString(request.Url.Fragment.Substring(1)).ToDictionary(); + + MessageReceivingEndpoint recipient; + try { + recipient = request.GetRecipient(); + } catch (ArgumentException ex) { + Logger.Messaging.WarnFormat("Unrecognized HTTP request: " + ex.ToString()); + return null; + } + + return (IDirectedProtocolMessage)this.Receive(fields, recipient); + } + + return base.ReadFromRequestCore(request); + } + + /// <summary> + /// Initializes the binding elements for the OAuth channel. + /// </summary> + /// <param name="authorizationServer">The authorization server.</param> + /// <returns> + /// An array of binding elements used to initialize the channel. + /// </returns> + private static IChannelBindingElement[] InitializeBindingElements(IAuthorizationServer authorizationServer) { + Contract.Requires<ArgumentNullException>(authorizationServer != null); + var bindingElements = new List<IChannelBindingElement>(); + + bindingElements.Add(new AuthServerAllFlowsBindingElement()); + bindingElements.Add(new AuthorizationCodeBindingElement()); + bindingElements.Add(new AccessTokenBindingElement()); + bindingElements.Add(new AccessRequestBindingElement()); + + return bindingElements.ToArray(); + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2ChannelBase.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2ChannelBase.cs new file mode 100644 index 0000000..a646f51 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2ChannelBase.cs @@ -0,0 +1,69 @@ +//----------------------------------------------------------------------- +// <copyright file="OAuth2ChannelBase.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.ChannelElements { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth2.Messages; + + /// <summary> + /// The base messaging channel used by OAuth 2.0 parties. + /// </summary> + internal abstract class OAuth2ChannelBase : StandardMessageFactoryChannel { + /// <summary> + /// The messages receivable by this channel. + /// </summary> + private static readonly Type[] MessageTypes = new Type[] { + typeof(AccessTokenRefreshRequest), + typeof(AccessTokenAuthorizationCodeRequest), + typeof(AccessTokenResourceOwnerPasswordCredentialsRequest), + typeof(AccessTokenClientCredentialsRequest), + typeof(AccessTokenSuccessResponse), + typeof(AccessTokenFailedResponse), + typeof(EndUserAuthorizationRequest), + typeof(EndUserAuthorizationSuccessAuthCodeResponse), + typeof(EndUserAuthorizationSuccessAccessTokenResponse), + typeof(EndUserAuthorizationFailedResponse), + typeof(UnauthorizedResponse), + }; + + /// <summary> + /// The protocol versions supported by this channel. + /// </summary> + private static readonly Version[] Versions = Protocol.AllVersions.Select(v => v.Version).ToArray(); + + /// <summary> + /// Initializes a new instance of the <see cref="OAuth2ChannelBase"/> class. + /// </summary> + /// <param name="channelBindingElements">The channel binding elements.</param> + internal OAuth2ChannelBase(params IChannelBindingElement[] channelBindingElements) + : base(MessageTypes, Versions, channelBindingElements) { + } + + /// <summary> + /// Allows preprocessing and validation of message data before an appropriate message type is + /// selected or deserialized. + /// </summary> + /// <param name="fields">The received message data.</param> + protected override void FilterReceivedFields(IDictionary<string, string> fields) { + base.FilterReceivedFields(fields); + + // Apply the OAuth 2.0 section 2.1 requirement: + // Parameters sent without a value MUST be treated as if they were omitted from the request. + // The authorization server SHOULD ignore unrecognized request parameters. + var emptyKeys = from pair in fields + where String.IsNullOrEmpty(pair.Value) + select pair.Key; + foreach (string emptyKey in emptyKeys.ToList()) { + fields.Remove(emptyKey); + } + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2ClientChannel.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2ClientChannel.cs new file mode 100644 index 0000000..e4a9afd --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2ClientChannel.cs @@ -0,0 +1,122 @@ +//----------------------------------------------------------------------- +// <copyright file="OAuth2ClientChannel.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.ChannelElements { + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Diagnostics.Contracts; + using System.Net; + using System.Web; + + using DotNetOpenAuth.Messaging; + + /// <summary> + /// The messaging channel used by OAuth 2.0 Clients. + /// </summary> + internal class OAuth2ClientChannel : OAuth2ChannelBase { + /// <summary> + /// Initializes a new instance of the <see cref="OAuth2ClientChannel"/> class. + /// </summary> + internal OAuth2ClientChannel() { + } + + /// <summary> + /// Prepares an HTTP request that carries a given message. + /// </summary> + /// <param name="request">The message to send.</param> + /// <returns> + /// The <see cref="HttpWebRequest"/> prepared to send the request. + /// </returns> + /// <remarks> + /// This method must be overridden by a derived class, unless the <see cref="Channel.RequestCore"/> method + /// is overridden and does not require this method. + /// </remarks> + protected override HttpWebRequest CreateHttpRequest(IDirectedProtocolMessage request) { + HttpWebRequest httpRequest; + if ((request.HttpMethods & HttpDeliveryMethods.GetRequest) != 0) { + httpRequest = InitializeRequestAsGet(request); + } else if ((request.HttpMethods & HttpDeliveryMethods.PostRequest) != 0) { + httpRequest = InitializeRequestAsPost(request); + } else { + throw new NotSupportedException(); + } + + return httpRequest; + } + + /// <summary> + /// Gets the protocol message that may be in the given HTTP response. + /// </summary> + /// <param name="response">The response that is anticipated to contain an protocol message.</param> + /// <returns> + /// The deserialized message parts, if found. Null otherwise. + /// </returns> + /// <exception cref="ProtocolException">Thrown when the response is not valid.</exception> + protected override IDictionary<string, string> ReadFromResponseCore(IncomingWebResponse response) { + // The spec says direct responses should be JSON objects, but Facebook uses HttpFormUrlEncoded instead, calling it text/plain + // Others return text/javascript. Again bad. + string body = response.GetResponseReader().ReadToEnd(); + if (response.ContentType.MediaType == JsonEncoded || response.ContentType.MediaType == JsonTextEncoded) { + return this.DeserializeFromJson(body); + } else if (response.ContentType.MediaType == HttpFormUrlEncoded || response.ContentType.MediaType == PlainTextEncoded) { + return HttpUtility.ParseQueryString(body).ToDictionary(); + } else { + throw ErrorUtilities.ThrowProtocol("Unexpected response Content-Type {0}", response.ContentType.MediaType); + } + } + + /// <summary> + /// Gets the protocol message that may be embedded in the given HTTP request. + /// </summary> + /// <param name="request">The request to search for an embedded message.</param> + /// <returns> + /// The deserialized message, if one is found. Null otherwise. + /// </returns> + protected override IDirectedProtocolMessage ReadFromRequestCore(HttpRequestInfo request) { + Logger.Channel.DebugFormat("Incoming HTTP request: {0} {1}", request.HttpMethod, request.UrlBeforeRewriting.AbsoluteUri); + + var fields = request.QueryStringBeforeRewriting.ToDictionary(); + + // Also read parameters from the fragment, if it's available. + // Typically the fragment is not available because the browser doesn't send it to a web server + // but this request may have been fabricated by an installed desktop app, in which case + // the fragment is available. + string fragment = request.UrlBeforeRewriting.Fragment; + if (!string.IsNullOrEmpty(fragment)) { + foreach (var pair in HttpUtility.ParseQueryString(fragment.Substring(1)).ToDictionary()) { + fields.Add(pair.Key, pair.Value); + } + } + + MessageReceivingEndpoint recipient; + try { + recipient = request.GetRecipient(); + } catch (ArgumentException ex) { + Logger.Messaging.WarnFormat("Unrecognized HTTP request: ", ex); + return null; + } + + return (IDirectedProtocolMessage)this.Receive(fields, recipient); + } + + /// <summary> + /// Queues a message for sending in the response stream where the fields + /// are sent in the response stream in querystring style. + /// </summary> + /// <param name="response">The message to send as a response.</param> + /// <returns> + /// The pending user agent redirect based message to be sent as an HttpResponse. + /// </returns> + /// <remarks> + /// This method implements spec OAuth V1.0 section 5.3. + /// </remarks> + protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) { + // Clients don't ever send direct responses. + throw new NotImplementedException(); + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2ResourceServerChannel.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2ResourceServerChannel.cs new file mode 100644 index 0000000..94df1a8 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2ResourceServerChannel.cs @@ -0,0 +1,153 @@ +//----------------------------------------------------------------------- +// <copyright file="OAuth2ResourceServerChannel.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.ChannelElements { + using System; + using System.Collections.Generic; + using System.Diagnostics.Contracts; + using System.Linq; + using System.Net; + using System.Net.Mime; + using System.Text; + using System.Web; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Reflection; + using DotNetOpenAuth.OAuth2.Messages; + + /// <summary> + /// The channel for the OAuth protocol. + /// </summary> + internal class OAuth2ResourceServerChannel : StandardMessageFactoryChannel { + /// <summary> + /// The messages receivable by this channel. + /// </summary> + private static readonly Type[] MessageTypes = new Type[] { + typeof(Messages.AccessProtectedResourceRequest), + }; + + /// <summary> + /// The protocol versions supported by this channel. + /// </summary> + private static readonly Version[] Versions = Protocol.AllVersions.Select(v => v.Version).ToArray(); + + /// <summary> + /// Initializes a new instance of the <see cref="OAuth2ResourceServerChannel"/> class. + /// </summary> + protected internal OAuth2ResourceServerChannel() + : base(MessageTypes, Versions) { + // TODO: add signing (authenticated request) binding element. + } + + /// <summary> + /// Gets the protocol message that may be embedded in the given HTTP request. + /// </summary> + /// <param name="request">The request to search for an embedded message.</param> + /// <returns> + /// The deserialized message, if one is found. Null otherwise. + /// </returns> + protected override IDirectedProtocolMessage ReadFromRequestCore(HttpRequestInfo request) { + var fields = new Dictionary<string, string>(); + string accessToken; + if ((accessToken = SearchForBearerAccessTokenInRequest(request)) != null) { + fields["token_type"] = Protocol.AccessTokenTypes.Bearer; + fields["access_token"] = accessToken; + } + + if (fields.Count > 0) { + MessageReceivingEndpoint recipient; + try { + recipient = request.GetRecipient(); + } catch (ArgumentException ex) { + Logger.OAuth.WarnFormat("Unrecognized HTTP request: " + ex.ToString()); + return null; + } + + // Deserialize the message using all the data we've collected. + var message = (IDirectedProtocolMessage)this.Receive(fields, recipient); + return message; + } + + return null; + } + + /// <summary> + /// Gets the protocol message that may be in the given HTTP response. + /// </summary> + /// <param name="response">The response that is anticipated to contain an protocol message.</param> + /// <returns> + /// The deserialized message parts, if found. Null otherwise. + /// </returns> + /// <exception cref="ProtocolException">Thrown when the response is not valid.</exception> + protected override IDictionary<string, string> ReadFromResponseCore(IncomingWebResponse response) { + // We never expect resource servers to send out direct requests, + // and therefore won't have direct responses. + throw new NotImplementedException(); + } + + /// <summary> + /// Queues a message for sending in the response stream where the fields + /// are sent in the response stream in querystring style. + /// </summary> + /// <param name="response">The message to send as a response.</param> + /// <returns> + /// The pending user agent redirect based message to be sent as an HttpResponse. + /// </returns> + /// <remarks> + /// This method implements spec OAuth V1.0 section 5.3. + /// </remarks> + protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) { + var webResponse = new OutgoingWebResponse(); + + // The only direct response from a resource server is a 401 Unauthorized error. + var unauthorizedResponse = response as UnauthorizedResponse; + ErrorUtilities.VerifyInternal(unauthorizedResponse != null, "Only unauthorized responses are expected."); + + // First initialize based on the specifics within the message. + var httpResponse = response as IHttpDirectResponse; + webResponse.Status = httpResponse != null ? httpResponse.HttpStatusCode : HttpStatusCode.Unauthorized; + foreach (string headerName in httpResponse.Headers) { + webResponse.Headers.Add(headerName, httpResponse.Headers[headerName]); + } + + // Now serialize all the message parts into the WWW-Authenticate header. + var fields = this.MessageDescriptions.GetAccessor(response); + webResponse.Headers[HttpResponseHeader.WwwAuthenticate] = MessagingUtilities.AssembleAuthorizationHeader(Protocol.BearerHttpAuthorizationScheme, fields); + return webResponse; + } + + /// <summary> + /// Searches for a bearer access token in the request. + /// </summary> + /// <param name="request">The request.</param> + /// <returns>The bearer access token, if one exists. Otherwise <c>null</c>.</returns> + private static string SearchForBearerAccessTokenInRequest(HttpRequestInfo request) { + Contract.Requires<ArgumentNullException>(request != null, "request"); + + // First search the authorization header. + string authorizationHeader = request.Headers[HttpRequestHeader.Authorization]; + if (!string.IsNullOrEmpty(authorizationHeader) && authorizationHeader.StartsWith(Protocol.BearerHttpAuthorizationSchemeWithTrailingSpace, StringComparison.OrdinalIgnoreCase)) { + return authorizationHeader.Substring(Protocol.BearerHttpAuthorizationSchemeWithTrailingSpace.Length); + } + + // Failing that, scan the entity + if (!string.IsNullOrEmpty(request.Headers[HttpRequestHeader.ContentType])) { + var contentType = new ContentType(request.Headers[HttpRequestHeader.ContentType]); + if (string.Equals(contentType.MediaType, HttpFormUrlEncoded, StringComparison.Ordinal)) { + if (request.Form[Protocol.BearerTokenEncodedUrlParameterName] != null) { + return request.Form[Protocol.BearerTokenEncodedUrlParameterName]; + } + } + } + + // Finally, check the least desirable location: the query string + if (!String.IsNullOrEmpty(request.QueryStringBeforeRewriting[Protocol.BearerTokenEncodedUrlParameterName])) { + return request.QueryStringBeforeRewriting[Protocol.BearerTokenEncodedUrlParameterName]; + } + + return null; + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/RefreshToken.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/RefreshToken.cs new file mode 100644 index 0000000..9fe54c5 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/RefreshToken.cs @@ -0,0 +1,56 @@ +//----------------------------------------------------------------------- +// <copyright file="RefreshToken.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.ChannelElements { + using System; + using System.Diagnostics.Contracts; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; + + /// <summary> + /// The refresh token issued to a client by an authorization server that allows the client + /// to periodically obtain new short-lived access tokens. + /// </summary> + internal class RefreshToken : AuthorizationDataBag { + /// <summary> + /// The name of the bucket for symmetric keys used to sign refresh tokens. + /// </summary> + internal const string RefreshTokenKeyBucket = "https://localhost/dnoa/oauth_refresh_token"; + + /// <summary> + /// Initializes a new instance of the <see cref="RefreshToken"/> class. + /// </summary> + public RefreshToken() { + } + + /// <summary> + /// Initializes a new instance of the <see cref="RefreshToken"/> class. + /// </summary> + /// <param name="authorization">The authorization this refresh token should describe.</param> + internal RefreshToken(IAuthorizationDescription authorization) { + Contract.Requires<ArgumentNullException>(authorization != null); + + this.ClientIdentifier = authorization.ClientIdentifier; + this.UtcCreationDate = authorization.UtcIssued; + this.User = authorization.User; + this.Scope.ResetContents(authorization.Scope); + } + + /// <summary> + /// Creates a formatter capable of serializing/deserializing a refresh token. + /// </summary> + /// <param name="cryptoKeyStore">The crypto key store.</param> + /// <returns> + /// A DataBag formatter. Never null. + /// </returns> + internal static IDataBagFormatter<RefreshToken> CreateFormatter(ICryptoKeyStore cryptoKeyStore) { + Contract.Requires<ArgumentNullException>(cryptoKeyStore != null); + Contract.Ensures(Contract.Result<IDataBagFormatter<RefreshToken>>() != null); + + return new UriStyleMessageFormatter<RefreshToken>(cryptoKeyStore, RefreshTokenKeyBucket, signed: true, encrypted: true); + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/ScopeEncoder.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/ScopeEncoder.cs new file mode 100644 index 0000000..7ae5fbf --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/ScopeEncoder.cs @@ -0,0 +1,51 @@ +//----------------------------------------------------------------------- +// <copyright file="ScopeEncoder.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.ChannelElements { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Reflection; + + /// <summary> + /// Encodes or decodes a set of scopes into the OAuth 2.0 scope message part. + /// </summary> + internal class ScopeEncoder : IMessagePartEncoder { + /// <summary> + /// Initializes a new instance of the <see cref="ScopeEncoder"/> class. + /// </summary> + public ScopeEncoder() { + } + + /// <summary> + /// Encodes the specified value. + /// </summary> + /// <param name="value">The value. Guaranteed to never be null.</param> + /// <returns> + /// The <paramref name="value"/> in string form, ready for message transport. + /// </returns> + public string Encode(object value) { + var scopes = (IEnumerable<string>)value; + ErrorUtilities.VerifyProtocol(!scopes.Any(scope => scope.Contains(" ")), OAuthStrings.ScopesMayNotContainSpaces); + return (scopes != null && scopes.Any()) ? string.Join(" ", scopes.ToArray()) : null; + } + + /// <summary> + /// Decodes the specified value. + /// </summary> + /// <param name="value">The string value carried by the transport. Guaranteed to never be null, although it may be empty.</param> + /// <returns> + /// The deserialized form of the given string. + /// </returns> + /// <exception cref="FormatException">Thrown when the string value given cannot be decoded into the required object type.</exception> + public object Decode(string value) { + return OAuthUtilities.SplitScopes(value); + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ClientAuthorizationView.Designer.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ClientAuthorizationView.Designer.cs new file mode 100644 index 0000000..c05a4b8 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ClientAuthorizationView.Designer.cs @@ -0,0 +1,56 @@ +namespace DotNetOpenAuth.OAuth2 { + partial class ClientAuthorizationView { + /// <summary> + /// Required designer variable. + /// </summary> + private System.ComponentModel.IContainer components = null; + + /// <summary> + /// Clean up any resources being used. + /// </summary> + /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> + protected override void Dispose(bool disposing) { + if (disposing && (components != null)) { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Component Designer generated code + + /// <summary> + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// </summary> + private void InitializeComponent() { + this.webBrowser1 = new System.Windows.Forms.WebBrowser(); + this.SuspendLayout(); + // + // webBrowser1 + // + this.webBrowser1.AllowWebBrowserDrop = false; + this.webBrowser1.Dock = System.Windows.Forms.DockStyle.Fill; + this.webBrowser1.IsWebBrowserContextMenuEnabled = false; + this.webBrowser1.Location = new System.Drawing.Point(0, 0); + this.webBrowser1.Name = "webBrowser1"; + this.webBrowser1.Size = new System.Drawing.Size(150, 150); + this.webBrowser1.TabIndex = 0; + this.webBrowser1.Navigated += new System.Windows.Forms.WebBrowserNavigatedEventHandler(this.WebBrowser1_Navigated); + this.webBrowser1.Navigating += new System.Windows.Forms.WebBrowserNavigatingEventHandler(this.WebBrowser1_Navigating); + this.webBrowser1.LocationChanged += new System.EventHandler(this.WebBrowser1_LocationChanged); + // + // ClientAuthorizationView + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.Controls.Add(this.webBrowser1); + this.Name = "ClientAuthorizationView"; + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.WebBrowser webBrowser1; + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ClientAuthorizationView.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ClientAuthorizationView.cs new file mode 100644 index 0000000..ffa217b --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ClientAuthorizationView.cs @@ -0,0 +1,192 @@ +//----------------------------------------------------------------------- +// <copyright file="ClientAuthorizationView.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2 { + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.Data; + using System.Diagnostics.Contracts; + using System.Drawing; + using System.Linq; + using System.Text; + using System.Windows.Forms; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// A WinForms control that hosts a mini-browser for hosting by native applications to + /// allow the user to authorize the client without leaving the application. + /// </summary> + public partial class ClientAuthorizationView : UserControl { + /// <summary> + /// Initializes a new instance of the <see cref="ClientAuthorizationView"/> class. + /// </summary> + public ClientAuthorizationView() { + this.InitializeComponent(); + + this.Authorization = new AuthorizationState(); + } + + /// <summary> + /// Occurs when the authorization flow has completed. + /// </summary> + public event EventHandler<ClientAuthorizationCompleteEventArgs> Completed; + + /// <summary> + /// Gets the authorization tracking object. + /// </summary> + public IAuthorizationState Authorization { get; private set; } + + /// <summary> + /// Gets or sets the client used to coordinate the authorization flow. + /// </summary> + public UserAgentClient Client { get; set; } + + /// <summary> + /// Gets the set of scopes that describe the requested level of access. + /// </summary> + public HashSet<string> Scope { + get { return this.Authorization.Scope; } + } + + /// <summary> + /// Gets or sets the callback URL used to indicate the flow has completed. + /// </summary> + public Uri Callback { + get { return this.Authorization.Callback; } + set { this.Authorization.Callback = value; } + } + + /// <summary> + /// Gets a value indicating whether the authorization flow has been completed. + /// </summary> + public bool IsCompleted { + get { return this.Authorization == null || this.Authorization.AccessToken != null; } + } + + /// <summary> + /// Gets a value indicating whether authorization has been granted. + /// </summary> + /// <value>Null if <see cref="IsCompleted"/> is <c>false</c></value> + public bool? IsGranted { + get { + if (this.Authorization == null) { + return false; + } + + return this.Authorization.AccessToken != null ? (bool?)true : null; + } + } + + /// <summary> + /// Gets a value indicating whether authorization has been rejected. + /// </summary> + /// <value>Null if <see cref="IsCompleted"/> is <c>false</c></value> + public bool? IsRejected { + get { + bool? granted = this.IsGranted; + return granted.HasValue ? (bool?)(!granted.Value) : null; + } + } + + /// <summary> + /// Called when the authorization flow has been completed. + /// </summary> + protected virtual void OnCompleted() { + var completed = this.Completed; + if (completed != null) { + completed(this, new ClientAuthorizationCompleteEventArgs(this.Authorization)); + } + } + + /// <summary> + /// Raises the <see cref="E:System.Windows.Forms.UserControl.Load"/> event. + /// </summary> + /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param> + protected override void OnLoad(EventArgs e) { + base.OnLoad(e); + + Uri authorizationUrl = this.Client.RequestUserAuthorization(this.Authorization); + this.webBrowser1.Navigate(authorizationUrl.AbsoluteUri); // use AbsoluteUri to workaround bug in WebBrowser that calls Uri.ToString instead of Uri.AbsoluteUri leading to escaping errors. + } + + /// <summary> + /// Tests whether two URLs are equal for purposes of detecting the conclusion of authorization. + /// </summary> + /// <param name="location1">The first location.</param> + /// <param name="location2">The second location.</param> + /// <param name="components">The components to compare.</param> + /// <returns><c>true</c> if the given components are equal.</returns> + private static bool SignificantlyEqual(Uri location1, Uri location2, UriComponents components) { + string value1 = location1.GetComponents(components, UriFormat.Unescaped); + string value2 = location2.GetComponents(components, UriFormat.Unescaped); + return string.Equals(value1, value2, StringComparison.Ordinal); + } + + /// <summary> + /// Handles the Navigating event of the webBrowser1 control. + /// </summary> + /// <param name="sender">The source of the event.</param> + /// <param name="e">The <see cref="System.Windows.Forms.WebBrowserNavigatingEventArgs"/> instance containing the event data.</param> + private void WebBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e) { + this.ProcessLocationChanged(e.Url); + } + + /// <summary> + /// Processes changes in the URL the browser has navigated to. + /// </summary> + /// <param name="location">The location.</param> + private void ProcessLocationChanged(Uri location) { + if (SignificantlyEqual(location, this.Authorization.Callback, UriComponents.SchemeAndServer | UriComponents.Path)) { + try { + this.Client.ProcessUserAuthorization(location, this.Authorization); + } catch (ProtocolException ex) { + MessageBox.Show(ex.ToStringDescriptive()); + } finally { + this.OnCompleted(); + } + } + } + + /// <summary> + /// Handles the Navigated event of the webBrowser1 control. + /// </summary> + /// <param name="sender">The source of the event.</param> + /// <param name="e">The <see cref="System.Windows.Forms.WebBrowserNavigatedEventArgs"/> instance containing the event data.</param> + private void WebBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e) { + this.ProcessLocationChanged(e.Url); + } + + /// <summary> + /// Handles the LocationChanged event of the webBrowser1 control. + /// </summary> + /// <param name="sender">The source of the event.</param> + /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> + private void WebBrowser1_LocationChanged(object sender, EventArgs e) { + this.ProcessLocationChanged(this.webBrowser1.Url); + } + + /// <summary> + /// Describes the results of a completed authorization flow. + /// </summary> + public class ClientAuthorizationCompleteEventArgs : EventArgs { + /// <summary> + /// Initializes a new instance of the <see cref="ClientAuthorizationCompleteEventArgs"/> class. + /// </summary> + /// <param name="authorization">The authorization.</param> + public ClientAuthorizationCompleteEventArgs(IAuthorizationState authorization) { + Contract.Requires<ArgumentNullException>(authorization != null); + this.Authorization = authorization; + } + + /// <summary> + /// Gets the authorization tracking object. + /// </summary> + /// <value>Null if authorization was rejected by the user.</value> + public IAuthorizationState Authorization { get; private set; } + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ClientAuthorizationView.resx b/src/DotNetOpenAuth.OAuth2/OAuth2/ClientAuthorizationView.resx new file mode 100644 index 0000000..7080a7d --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ClientAuthorizationView.resx @@ -0,0 +1,120 @@ +<?xml version="1.0" encoding="utf-8"?> +<root> + <!-- + Microsoft ResX Schema + + Version 2.0 + + The primary goals of this format is to allow a simple XML format + that is mostly human readable. The generation and parsing of the + various data types are done through the TypeConverter classes + associated with the data types. + + Example: + + ... ado.net/XML headers & schema ... + <resheader name="resmimetype">text/microsoft-resx</resheader> + <resheader name="version">2.0</resheader> + <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> + <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> + <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> + <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> + <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> + <value>[base64 mime encoded serialized .NET Framework object]</value> + </data> + <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> + <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> + <comment>This is a comment</comment> + </data> + + There are any number of "resheader" rows that contain simple + name/value pairs. + + Each data row contains a name, and value. The row also contains a + type or mimetype. Type corresponds to a .NET class that support + text/value conversion through the TypeConverter architecture. + Classes that don't support this are serialized and stored with the + mimetype set. + + The mimetype is used for serialized objects, and tells the + ResXResourceReader how to depersist the object. This is currently not + extensible. For a given mimetype the value must be set accordingly: + + Note - application/x-microsoft.net.object.binary.base64 is the format + that the ResXResourceWriter will generate, however the reader can + read any of the formats listed below. + + mimetype: application/x-microsoft.net.object.binary.base64 + value : The object must be serialized with + : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter + : and then encoded with base64 encoding. + + mimetype: application/x-microsoft.net.object.soap.base64 + value : The object must be serialized with + : System.Runtime.Serialization.Formatters.Soap.SoapFormatter + : and then encoded with base64 encoding. + + mimetype: application/x-microsoft.net.object.bytearray.base64 + value : The object must be serialized into a byte array + : using a System.ComponentModel.TypeConverter + : and then encoded with base64 encoding. + --> + <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> + <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> + <xsd:element name="root" msdata:IsDataSet="true"> + <xsd:complexType> + <xsd:choice maxOccurs="unbounded"> + <xsd:element name="metadata"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" /> + </xsd:sequence> + <xsd:attribute name="name" use="required" type="xsd:string" /> + <xsd:attribute name="type" type="xsd:string" /> + <xsd:attribute name="mimetype" type="xsd:string" /> + <xsd:attribute ref="xml:space" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="assembly"> + <xsd:complexType> + <xsd:attribute name="alias" type="xsd:string" /> + <xsd:attribute name="name" type="xsd:string" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="data"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> + <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> + <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> + <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> + <xsd:attribute ref="xml:space" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="resheader"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" use="required" /> + </xsd:complexType> + </xsd:element> + </xsd:choice> + </xsd:complexType> + </xsd:element> + </xsd:schema> + <resheader name="resmimetype"> + <value>text/microsoft-resx</value> + </resheader> + <resheader name="version"> + <value>2.0</value> + </resheader> + <resheader name="reader"> + <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> + </resheader> + <resheader name="writer"> + <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> + </resheader> +</root>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ClientBase.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ClientBase.cs new file mode 100644 index 0000000..51aac39 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ClientBase.cs @@ -0,0 +1,256 @@ +//----------------------------------------------------------------------- +// <copyright file="ClientBase.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2 { + using System; + using System.Collections.Generic; + using System.Diagnostics.Contracts; + using System.Globalization; + using System.Linq; + using System.Net; + using System.Text; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth2.ChannelElements; + using DotNetOpenAuth.OAuth2.Messages; + + /// <summary> + /// A base class for common OAuth Client behaviors. + /// </summary> + public class ClientBase { + /// <summary> + /// Initializes a new instance of the <see cref="ClientBase"/> class. + /// </summary> + /// <param name="authorizationServer">The token issuer.</param> + /// <param name="clientIdentifier">The client identifier.</param> + /// <param name="clientSecret">The client secret.</param> + protected ClientBase(AuthorizationServerDescription authorizationServer, string clientIdentifier = null, string clientSecret = null) { + Contract.Requires<ArgumentNullException>(authorizationServer != null); + this.AuthorizationServer = authorizationServer; + this.Channel = new OAuth2ClientChannel(); + this.ClientIdentifier = clientIdentifier; + this.ClientSecret = clientSecret; + } + + /// <summary> + /// Gets the token issuer. + /// </summary> + /// <value>The token issuer.</value> + public AuthorizationServerDescription AuthorizationServer { get; private set; } + + /// <summary> + /// Gets the OAuth channel. + /// </summary> + /// <value>The channel.</value> + public Channel Channel { get; private set; } + + /// <summary> + /// Gets or sets the identifier by which this client is known to the Authorization Server. + /// </summary> + public string ClientIdentifier { get; set; } + + /// <summary> + /// Gets or sets the client secret shared with the Authorization Server. + /// </summary> + public string ClientSecret { get; set; } + + /// <summary> + /// Adds the necessary HTTP Authorization header to an HTTP request for protected resources + /// so that the Service Provider will allow the request through. + /// </summary> + /// <param name="request">The request for protected resources from the service provider.</param> + /// <param name="accessToken">The access token previously obtained from the Authorization Server.</param> + public static void AuthorizeRequest(HttpWebRequest request, string accessToken) { + Contract.Requires<ArgumentNullException>(request != null); + Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(accessToken)); + + OAuthUtilities.AuthorizeWithBearerToken(request, accessToken); + } + + /// <summary> + /// Adds the OAuth authorization token to an outgoing HTTP request, renewing a + /// (nearly) expired access token if necessary. + /// </summary> + /// <param name="request">The request for protected resources from the service provider.</param> + /// <param name="authorization">The authorization for this request previously obtained via OAuth.</param> + public void AuthorizeRequest(HttpWebRequest request, IAuthorizationState authorization) { + 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.RefreshAuthorization(authorization); + } + + AuthorizeRequest(request, authorization.AccessToken); + } + + /// <summary> + /// Refreshes a short-lived access token using a longer-lived refresh token + /// with a new access token that has the same scope as the refresh token. + /// The refresh token itself may also be refreshed. + /// </summary> + /// <param name="authorization">The authorization to update.</param> + /// <param name="skipIfUsefulLifeExceeds">If given, the access token will <em>not</em> be refreshed if its remaining lifetime exceeds this value.</param> + /// <returns>A value indicating whether the access token was actually renewed; <c>true</c> if it was renewed, or <c>false</c> if it still had useful life remaining.</returns> + /// <remarks> + /// This method may modify the value of the <see cref="IAuthorizationState.RefreshToken"/> property on + /// the <paramref name="authorization"/> parameter if the authorization server has cycled out your refresh token. + /// If the parameter value was updated, this method calls <see cref="IAuthorizationState.SaveChanges"/> on that instance. + /// </remarks> + public bool RefreshAuthorization(IAuthorizationState authorization, TimeSpan? skipIfUsefulLifeExceeds = null) { + Contract.Requires<ArgumentNullException>(authorization != null); + Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(authorization.RefreshToken)); + + if (skipIfUsefulLifeExceeds.HasValue && authorization.AccessTokenExpirationUtc.HasValue) { + TimeSpan usefulLifeRemaining = authorization.AccessTokenExpirationUtc.Value - DateTime.UtcNow; + if (usefulLifeRemaining > skipIfUsefulLifeExceeds.Value) { + // There is useful life remaining in the access token. Don't refresh. + Logger.OAuth.DebugFormat("Skipping token refresh step because access token's remaining life is {0}, which exceeds {1}.", usefulLifeRemaining, skipIfUsefulLifeExceeds.Value); + return false; + } + } + + var request = new AccessTokenRefreshRequest(this.AuthorizationServer) { + ClientIdentifier = this.ClientIdentifier, + ClientSecret = this.ClientSecret, + RefreshToken = authorization.RefreshToken, + }; + + var response = this.Channel.Request<AccessTokenSuccessResponse>(request); + UpdateAuthorizationWithResponse(authorization, response); + return true; + } + + /// <summary> + /// Gets an access token that may be used for only a subset of the scope for which a given + /// refresh token is authorized. + /// </summary> + /// <param name="refreshToken">The refresh token.</param> + /// <param name="scope">The scope subset desired in the access token.</param> + /// <returns>A description of the obtained access token, and possibly a new refresh token.</returns> + /// <remarks> + /// If the return value includes a new refresh token, the old refresh token should be discarded and + /// replaced with the new one. + /// </remarks> + public IAuthorizationState GetScopedAccessToken(string refreshToken, HashSet<string> scope) { + Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(refreshToken)); + Contract.Requires<ArgumentNullException>(scope != null); + Contract.Ensures(Contract.Result<IAuthorizationState>() != null); + + var request = new AccessTokenRefreshRequest(this.AuthorizationServer) { + ClientIdentifier = this.ClientIdentifier, + ClientSecret = this.ClientSecret, + RefreshToken = refreshToken, + }; + + var response = this.Channel.Request<AccessTokenSuccessResponse>(request); + var authorization = new AuthorizationState(); + UpdateAuthorizationWithResponse(authorization, response); + + return authorization; + } + + /// <summary> + /// Updates the authorization state maintained by the client with the content of an outgoing response. + /// </summary> + /// <param name="authorizationState">The authorization state maintained by the client.</param> + /// <param name="accessTokenSuccess">The access token containing response message.</param> + internal static void UpdateAuthorizationWithResponse(IAuthorizationState authorizationState, AccessTokenSuccessResponse accessTokenSuccess) { + Contract.Requires<ArgumentNullException>(authorizationState != null); + Contract.Requires<ArgumentNullException>(accessTokenSuccess != null); + + authorizationState.AccessToken = accessTokenSuccess.AccessToken; + authorizationState.AccessTokenExpirationUtc = DateTime.UtcNow + accessTokenSuccess.Lifetime; + authorizationState.AccessTokenIssueDateUtc = DateTime.UtcNow; + + // The authorization server MAY choose to renew the refresh token itself. + if (accessTokenSuccess.RefreshToken != null) { + authorizationState.RefreshToken = accessTokenSuccess.RefreshToken; + } + + // An included scope parameter in the response only describes the access token's scope. + // Don't update the whole authorization state object with that scope because that represents + // the refresh token's original scope. + if ((authorizationState.Scope == null || authorizationState.Scope.Count == 0) && accessTokenSuccess.Scope != null) { + authorizationState.Scope.ResetContents(accessTokenSuccess.Scope); + } + + authorizationState.SaveChanges(); + } + + /// <summary> + /// Updates the authorization state maintained by the client with the content of an outgoing response. + /// </summary> + /// <param name="authorizationState">The authorization state maintained by the client.</param> + /// <param name="accessTokenSuccess">The access token containing response message.</param> + internal static void UpdateAuthorizationWithResponse(IAuthorizationState authorizationState, EndUserAuthorizationSuccessAccessTokenResponse accessTokenSuccess) { + Contract.Requires<ArgumentNullException>(authorizationState != null); + Contract.Requires<ArgumentNullException>(accessTokenSuccess != null); + + authorizationState.AccessToken = accessTokenSuccess.AccessToken; + authorizationState.AccessTokenExpirationUtc = DateTime.UtcNow + accessTokenSuccess.Lifetime; + authorizationState.AccessTokenIssueDateUtc = DateTime.UtcNow; + if (accessTokenSuccess.Scope != null && accessTokenSuccess.Scope != authorizationState.Scope) { + if (authorizationState.Scope != null) { + Logger.OAuth.InfoFormat( + "Requested scope of \"{0}\" changed to \"{1}\" by authorization server.", + authorizationState.Scope, + accessTokenSuccess.Scope); + } + + authorizationState.Scope.ResetContents(accessTokenSuccess.Scope); + } + + authorizationState.SaveChanges(); + } + + /// <summary> + /// Updates authorization state with a success response from the Authorization Server. + /// </summary> + /// <param name="authorizationState">The authorization state to update.</param> + /// <param name="authorizationSuccess">The authorization success message obtained from the authorization server.</param> + internal void UpdateAuthorizationWithResponse(IAuthorizationState authorizationState, EndUserAuthorizationSuccessAuthCodeResponse authorizationSuccess) { + Contract.Requires<ArgumentNullException>(authorizationState != null); + Contract.Requires<ArgumentNullException>(authorizationSuccess != null); + + var accessTokenRequest = new AccessTokenAuthorizationCodeRequest(this.AuthorizationServer) { + ClientIdentifier = this.ClientIdentifier, + ClientSecret = this.ClientSecret, + Callback = authorizationState.Callback, + AuthorizationCode = authorizationSuccess.AuthorizationCode, + }; + IProtocolMessage accessTokenResponse = this.Channel.Request(accessTokenRequest); + var accessTokenSuccess = accessTokenResponse as AccessTokenSuccessResponse; + var failedAccessTokenResponse = accessTokenResponse as AccessTokenFailedResponse; + if (accessTokenSuccess != null) { + UpdateAuthorizationWithResponse(authorizationState, accessTokenSuccess); + } else { + authorizationState.Delete(); + string error = failedAccessTokenResponse != null ? failedAccessTokenResponse.Error : "(unknown)"; + ErrorUtilities.ThrowProtocol(OAuthStrings.CannotObtainAccessTokenWithReason, error); + } + } + + /// <summary> + /// Calculates the fraction of life remaining in an access token. + /// </summary> + /// <param name="authorization">The authorization to measure.</param> + /// <returns>A fractional number no greater than 1. Could be negative if the access token has already expired.</returns> + private static double ProportionalLifeRemaining(IAuthorizationState authorization) { + Contract.Requires<ArgumentNullException>(authorization != null); + Contract.Requires<ArgumentException>(authorization.AccessTokenIssueDateUtc.HasValue); + Contract.Requires<ArgumentException>(authorization.AccessTokenExpirationUtc.HasValue); + + // Calculate what % of the total life this access token has left. + TimeSpan totalLifetime = authorization.AccessTokenExpirationUtc.Value - authorization.AccessTokenIssueDateUtc.Value; + TimeSpan elapsedLifetime = DateTime.UtcNow - authorization.AccessTokenIssueDateUtc.Value; + double proportionLifetimeRemaining = 1 - (elapsedLifetime.TotalSeconds / totalLifetime.TotalSeconds); + return proportionLifetimeRemaining; + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/IAccessTokenAnalyzer.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/IAccessTokenAnalyzer.cs new file mode 100644 index 0000000..74b8ebb --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/IAccessTokenAnalyzer.cs @@ -0,0 +1,64 @@ +//----------------------------------------------------------------------- +// <copyright file="IAccessTokenAnalyzer.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2 { + using System; + using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; + using System.Diagnostics.Contracts; + using System.Linq; + using System.Text; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// An interface that resource server hosts should implement if they accept access tokens + /// issued by non-DotNetOpenAuth authorization servers. + /// </summary> + [ContractClass((typeof(IAccessTokenAnalyzerContract)))] + public interface IAccessTokenAnalyzer { + /// <summary> + /// Reads an access token to find out what data it authorizes access to. + /// </summary> + /// <param name="message">The message carrying the access token.</param> + /// <param name="accessToken">The access token.</param> + /// <param name="user">The user whose data is accessible with this access token.</param> + /// <param name="scope">The scope of access authorized by this access token.</param> + /// <returns>A value indicating whether this access token is valid.</returns> + [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#", Justification = "Try pattern")] + [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification = "Try pattern")] + bool TryValidateAccessToken(IDirectedProtocolMessage message, string accessToken, out string user, out HashSet<string> scope); + } + + /// <summary> + /// Code contract for the <see cref="IAccessTokenAnalyzer"/> interface. + /// </summary> + [ContractClassFor(typeof(IAccessTokenAnalyzer))] + internal abstract class IAccessTokenAnalyzerContract : IAccessTokenAnalyzer { + /// <summary> + /// Prevents a default instance of the <see cref="IAccessTokenAnalyzerContract"/> class from being created. + /// </summary> + private IAccessTokenAnalyzerContract() { + } + + /// <summary> + /// Reads an access token to find out what data it authorizes access to. + /// </summary> + /// <param name="message">The message carrying the access token.</param> + /// <param name="accessToken">The access token.</param> + /// <param name="user">The user whose data is accessible with this access token.</param> + /// <param name="scope">The scope of access authorized by this access token.</param> + /// <returns> + /// A value indicating whether this access token is valid. + /// </returns> + bool IAccessTokenAnalyzer.TryValidateAccessToken(IDirectedProtocolMessage message, string accessToken, out string user, out HashSet<string> scope) { + Contract.Requires<ArgumentNullException>(message != null); + Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(accessToken)); + Contract.Ensures(Contract.Result<bool>() == (Contract.ValueAtReturn<string>(out user) != null)); + + throw new NotImplementedException(); + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/IAuthorizationServer.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/IAuthorizationServer.cs new file mode 100644 index 0000000..883f40c --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/IAuthorizationServer.cs @@ -0,0 +1,238 @@ +//----------------------------------------------------------------------- +// <copyright file="IAuthorizationServer.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2 { + using System; + using System.Collections.Generic; + using System.Diagnostics.Contracts; + using System.Linq; + using System.Security.Cryptography; + using System.Text; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; + using DotNetOpenAuth.OAuth2.ChannelElements; + using DotNetOpenAuth.OAuth2.Messages; + + /// <summary> + /// Provides host-specific authorization server services needed by this library. + /// </summary> + [ContractClass(typeof(IAuthorizationServerContract))] + public interface IAuthorizationServer { + /// <summary> + /// Gets the store for storeing crypto keys used to symmetrically encrypt and sign authorization codes and refresh tokens. + /// </summary> + /// <remarks> + /// This store should be kept strictly confidential in the authorization server(s) + /// and NOT shared with the resource server. Anyone with these secrets can mint + /// tokens to essentially grant themselves access to anything they want. + /// </remarks> + ICryptoKeyStore CryptoKeyStore { get; } + + /// <summary> + /// Gets the authorization code nonce store to use to ensure that authorization codes can only be used once. + /// </summary> + /// <value>The authorization code nonce store.</value> + INonceStore VerificationCodeNonceStore { get; } + + /// <summary> + /// Gets the crypto service provider with the asymmetric private key to use for signing access tokens. + /// </summary> + /// <returns>A crypto service provider instance that contains the private key.</returns> + /// <value>Must not be null, and must contain the private key.</value> + /// <remarks> + /// The public key in the private/public key pair will be used by the resource + /// servers to validate that the access token is minted by a trusted authorization server. + /// </remarks> + RSACryptoServiceProvider AccessTokenSigningKey { get; } + + /// <summary> + /// Obtains the lifetime for a new access token. + /// </summary> + /// <param name="accessTokenRequestMessage"> + /// Details regarding the resources that the access token will grant access to, and the identity of the client + /// that will receive that access. + /// Based on this information the receiving resource server can be determined and the lifetime of the access + /// token can be set based on the sensitivity of the resources. + /// </param> + /// <returns> + /// Receives the lifetime for this access token. Note that within this lifetime, authorization <i>may</i> not be revokable. + /// Short lifetimes are recommended (i.e. one hour), particularly when the client is not authenticated or + /// the resources to which access is being granted are sensitive. + /// </returns> + TimeSpan GetAccessTokenLifetime(IAccessTokenRequest accessTokenRequestMessage); + + /// <summary> + /// Obtains the encryption key for an access token being created. + /// </summary> + /// <param name="accessTokenRequestMessage"> + /// Details regarding the resources that the access token will grant access to, and the identity of the client + /// that will receive that access. + /// Based on this information the receiving resource server can be determined and the lifetime of the access + /// token can be set based on the sensitivity of the resources. + /// </param> + /// <returns> + /// The crypto service provider with the asymmetric public key to use for encrypting access tokens for a specific resource server. + /// The caller is responsible to dispose of this value. + /// </returns> + /// <remarks> + /// The caller is responsible to dispose of the returned value. + /// </remarks> + RSACryptoServiceProvider GetResourceServerEncryptionKey(IAccessTokenRequest accessTokenRequestMessage); + + /// <summary> + /// Gets the client with a given identifier. + /// </summary> + /// <param name="clientIdentifier">The client identifier.</param> + /// <returns>The client registration. Never null.</returns> + /// <exception cref="ArgumentException">Thrown when no client with the given identifier is registered with this authorization server.</exception> + IConsumerDescription GetClient(string clientIdentifier); + + /// <summary> + /// Determines whether a described authorization is (still) valid. + /// </summary> + /// <param name="authorization">The authorization.</param> + /// <returns> + /// <c>true</c> if the original authorization is still valid; otherwise, <c>false</c>. + /// </returns> + /// <remarks> + /// <para>When establishing that an authorization is still valid, + /// it's very important to only match on recorded authorizations that + /// meet these criteria:</para> + /// 1) The client identifier matches. + /// 2) The user account matches. + /// 3) The scope on the recorded authorization must include all scopes in the given authorization. + /// 4) The date the recorded authorization was issued must be <em>no later</em> that the date the given authorization was issued. + /// <para>One possible scenario is where the user authorized a client, later revoked authorization, + /// and even later reinstated authorization. This subsequent recorded authorization + /// would not satisfy requirement #4 in the above list. This is important because the revocation + /// the user went through should invalidate all previously issued tokens as a matter of + /// security in the event the user was revoking access in order to sever authorization on a stolen + /// account or piece of hardware in which the tokens were stored. </para> + /// </remarks> + bool IsAuthorizationValid(IAuthorizationDescription authorization); + } + + /// <summary> + /// Code Contract for the <see cref="IAuthorizationServer"/> interface. + /// </summary> + [ContractClassFor(typeof(IAuthorizationServer))] + internal abstract class IAuthorizationServerContract : IAuthorizationServer { + /// <summary> + /// Prevents a default instance of the <see cref="IAuthorizationServerContract"/> class from being created. + /// </summary> + private IAuthorizationServerContract() { + } + + /// <summary> + /// Gets the store for storeing crypto keys used to symmetrically encrypt and sign authorization codes and refresh tokens. + /// </summary> + ICryptoKeyStore IAuthorizationServer.CryptoKeyStore { + get { + Contract.Ensures(Contract.Result<ICryptoKeyStore>() != null); + throw new NotImplementedException(); + } + } + + /// <summary> + /// Gets the authorization code nonce store to use to ensure that authorization codes can only be used once. + /// </summary> + /// <value>The authorization code nonce store.</value> + INonceStore IAuthorizationServer.VerificationCodeNonceStore { + get { + Contract.Ensures(Contract.Result<INonceStore>() != null); + throw new NotImplementedException(); + } + } + + /// <summary> + /// Gets the crypto service provider with the asymmetric private key to use for signing access tokens. + /// </summary> + /// <value> + /// Must not be null, and must contain the private key. + /// </value> + /// <returns>A crypto service provider instance that contains the private key.</returns> + RSACryptoServiceProvider IAuthorizationServer.AccessTokenSigningKey { + get { + Contract.Ensures(Contract.Result<RSACryptoServiceProvider>() != null); + Contract.Ensures(!Contract.Result<RSACryptoServiceProvider>().PublicOnly); + throw new NotImplementedException(); + } + } + + /// <summary> + /// Obtains the lifetime for a new access token. + /// </summary> + /// <param name="accessTokenRequestMessage">Details regarding the resources that the access token will grant access to, and the identity of the client + /// that will receive that access. + /// Based on this information the receiving resource server can be determined and the lifetime of the access + /// token can be set based on the sensitivity of the resources.</param> + /// <returns> + /// Receives the lifetime for this access token. Note that within this lifetime, authorization <i>may</i> not be revokable. + /// Short lifetimes are recommended (i.e. one hour), particularly when the client is not authenticated or + /// the resources to which access is being granted are sensitive. + /// </returns> + TimeSpan IAuthorizationServer.GetAccessTokenLifetime(IAccessTokenRequest accessTokenRequestMessage) { + Contract.Requires<ArgumentNullException>(accessTokenRequestMessage != null); + throw new NotImplementedException(); + } + + /// <summary> + /// Obtains the encryption key for an access token being created. + /// </summary> + /// <param name="accessTokenRequestMessage">Details regarding the resources that the access token will grant access to, and the identity of the client + /// that will receive that access. + /// Based on this information the receiving resource server can be determined and the lifetime of the access + /// token can be set based on the sensitivity of the resources.</param> + /// <returns> + /// The crypto service provider with the asymmetric public key to use for encrypting access tokens for a specific resource server. + /// The caller is responsible to dispose of this value. + /// </returns> + RSACryptoServiceProvider IAuthorizationServer.GetResourceServerEncryptionKey(IAccessTokenRequest accessTokenRequestMessage) { + Contract.Requires<ArgumentNullException>(accessTokenRequestMessage != null); + Contract.Ensures(Contract.Result<RSACryptoServiceProvider>() != null); + throw new NotImplementedException(); + } + + /// <summary> + /// Gets the client with a given identifier. + /// </summary> + /// <param name="clientIdentifier">The client identifier.</param> + /// <returns>The client registration. Never null.</returns> + /// <exception cref="ArgumentException">Thrown when no client with the given identifier is registered with this authorization server.</exception> + IConsumerDescription IAuthorizationServer.GetClient(string clientIdentifier) { + 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); + throw new NotImplementedException(); + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/IAuthorizationState.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/IAuthorizationState.cs new file mode 100644 index 0000000..39437ac --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/IAuthorizationState.cs @@ -0,0 +1,67 @@ +//----------------------------------------------------------------------- +// <copyright file="IAuthorizationState.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2 { + using System; + using System.Collections.Generic; + + /// <summary> + /// Provides access to a persistent object that tracks the state of an authorization. + /// </summary> + public interface IAuthorizationState { + /// <summary> + /// Gets or sets the callback URL used to obtain authorization. + /// </summary> + /// <value>The callback URL.</value> + Uri Callback { get; set; } + + /// <summary> + /// Gets or sets the long-lived token used to renew the short-lived <see cref="AccessToken"/>. + /// </summary> + /// <value>The refresh token.</value> + string RefreshToken { get; set; } + + /// <summary> + /// Gets or sets the access token. + /// </summary> + /// <value>The access token.</value> + string AccessToken { get; set; } + + /// <summary> + /// Gets or sets the access token issue date UTC. + /// </summary> + /// <value>The access token issue date UTC.</value> + DateTime? AccessTokenIssueDateUtc { get; set; } + + /// <summary> + /// Gets or sets the access token UTC expiration date. + /// </summary> + DateTime? AccessTokenExpirationUtc { get; set; } + + /// <summary> + /// Gets the scope the token is (to be) authorized for. + /// </summary> + /// <value>The scope.</value> + HashSet<string> Scope { get; } + + /// <summary> + /// Deletes this authorization, including access token and refresh token where applicable. + /// </summary> + /// <remarks> + /// This method is invoked when an authorization attempt fails, is rejected, is revoked, or + /// expires and cannot be renewed. + /// </remarks> + void Delete(); + + /// <summary> + /// Saves any changes made to this authorization object's properties. + /// </summary> + /// <remarks> + /// This method is invoked after DotNetOpenAuth changes any property. + /// </remarks> + void SaveChanges(); + } +}
\ No newline at end of file diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/IClientAuthorizationTracker.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/IClientAuthorizationTracker.cs new file mode 100644 index 0000000..97294e6 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/IClientAuthorizationTracker.cs @@ -0,0 +1,53 @@ +//----------------------------------------------------------------------- +// <copyright file="IClientAuthorizationTracker.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2 { + using System; + using System.Diagnostics.Contracts; + + /// <summary> + /// A token manager implemented by some clients to assist in tracking authorization state. + /// </summary> + [ContractClass(typeof(IClientAuthorizationTrackerContract))] + public interface IClientAuthorizationTracker { + /// <summary> + /// Gets the state of the authorization for a given callback URL and client state. + /// </summary> + /// <param name="callbackUrl">The callback URL.</param> + /// <param name="clientState">State of the client stored at the beginning of an authorization request.</param> + /// <returns>The authorization state; may be <c>null</c> if no authorization state matches.</returns> + IAuthorizationState GetAuthorizationState(Uri callbackUrl, string clientState); + } + + /// <summary> + /// Contract class for the <see cref="IClientAuthorizationTracker"/> interface. + /// </summary> + [ContractClassFor(typeof(IClientAuthorizationTracker))] + internal abstract class IClientAuthorizationTrackerContract : IClientAuthorizationTracker { + /// <summary> + /// Prevents a default instance of the <see cref="IClientAuthorizationTrackerContract"/> class from being created. + /// </summary> + private IClientAuthorizationTrackerContract() { + } + + #region IClientTokenManager Members + + /// <summary> + /// Gets the state of the authorization for a given callback URL and client state. + /// </summary> + /// <param name="callbackUrl">The callback URL.</param> + /// <param name="clientState">State of the client stored at the beginning of an authorization request.</param> + /// <returns> + /// The authorization state; may be <c>null</c> if no authorization state matches. + /// </returns> + IAuthorizationState IClientAuthorizationTracker.GetAuthorizationState(Uri callbackUrl, string clientState) { + Contract.Requires<ArgumentNullException>(callbackUrl != null); + throw new NotImplementedException(); + } + + #endregion + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/IConsumerDescription.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/IConsumerDescription.cs new file mode 100644 index 0000000..14f3523 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/IConsumerDescription.cs @@ -0,0 +1,101 @@ +//----------------------------------------------------------------------- +// <copyright file="IConsumerDescription.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2 { + using System; + using System.Collections.Generic; + using System.Diagnostics.Contracts; + + /// <summary> + /// A description of a client from an Authorization Server's point of view. + /// </summary> + [ContractClass(typeof(IConsumerDescriptionContract))] + public interface IConsumerDescription { + /// <summary> + /// Gets the client secret. + /// </summary> + string Secret { get; } + + /// <summary> + /// Gets the callback to use when an individual authorization request + /// does not include an explicit callback URI. + /// </summary> + /// <value>An absolute URL; or <c>null</c> if none is registered.</value> + Uri DefaultCallback { get; } + + /// <summary> + /// Determines whether a callback URI included in a client's authorization request + /// is among those allowed callbacks for the registered client. + /// </summary> + /// <param name="callback">The absolute URI the client has requested the authorization result be received at.</param> + /// <returns> + /// <c>true</c> if the callback URL is allowable for this client; otherwise, <c>false</c>. + /// </returns> + /// <remarks> + /// <para> + /// At the point this method is invoked, the identity of the client has <em>not</em> + /// been confirmed. To avoid open redirector attacks, the alleged client's identity + /// is used to lookup a list of allowable callback URLs to make sure that the callback URL + /// the actual client is requesting is one of the expected ones. + /// </para> + /// <para> + /// From OAuth 2.0 section 2.1: + /// The authorization server SHOULD require the client to pre-register + /// their redirection URI or at least certain components such as the + /// scheme, host, port and path. If a redirection URI was registered, + /// the authorization server MUST compare any redirection URI received at + /// the authorization endpoint with the registered URI. + /// </para> + /// </remarks> + bool IsCallbackAllowed(Uri callback); + } + + /// <summary> + /// Contract class for the <see cref="IConsumerDescription"/> interface. + /// </summary> + [ContractClassFor(typeof(IConsumerDescription))] + internal abstract class IConsumerDescriptionContract : IConsumerDescription { + #region IConsumerDescription Members + + /// <summary> + /// Gets the client secret. + /// </summary> + /// <value></value> + string IConsumerDescription.Secret { + get { throw new NotImplementedException(); } + } + + /// <summary> + /// Gets the callback to use when an individual authorization request + /// does not include an explicit callback URI. + /// </summary> + /// <value> + /// An absolute URL; or <c>null</c> if none is registered. + /// </value> + Uri IConsumerDescription.DefaultCallback { + get { + Contract.Ensures(Contract.Result<Uri>() == null || Contract.Result<Uri>().IsAbsoluteUri); + throw new NotImplementedException(); + } + } + + /// <summary> + /// Determines whether a callback URI included in a client's authorization request + /// is among those allowed callbacks for the registered client. + /// </summary> + /// <param name="callback">The requested callback URI.</param> + /// <returns> + /// <c>true</c> if the callback is allowed; otherwise, <c>false</c>. + /// </returns> + bool IConsumerDescription.IsCallbackAllowed(Uri callback) { + Contract.Requires<ArgumentNullException>(callback != null); + Contract.Requires<ArgumentException>(callback.IsAbsoluteUri); + throw new NotImplementedException(); + } + + #endregion + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessProtectedResourceRequest.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessProtectedResourceRequest.cs new file mode 100644 index 0000000..2e94156 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessProtectedResourceRequest.cs @@ -0,0 +1,73 @@ +//----------------------------------------------------------------------- +// <copyright file="AccessProtectedResourceRequest.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.Messages { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using ChannelElements; + using Messaging; + + /// <summary> + /// A message that accompanies an HTTP request to a resource server that provides authorization. + /// </summary> + /// <remarks> + /// In its current form, this class only accepts bearer access tokens. + /// When support for additional access token types is added, this class should probably be refactored + /// into derived types, where each derived type supports a particular access token type. + /// </remarks> + internal class AccessProtectedResourceRequest : MessageBase, IAuthorizationCarryingRequest { + /// <summary> + /// Initializes a new instance of the <see cref="AccessProtectedResourceRequest"/> class. + /// </summary> + /// <param name="recipient">The recipient.</param> + /// <param name="version">The version.</param> + internal AccessProtectedResourceRequest(Uri recipient, Version version) + : base(version, MessageTransport.Direct, recipient) { + } + + /// <summary> + /// Gets the type of the code or token. + /// </summary> + /// <value>The type of the code or token.</value> + CodeOrTokenType IAuthorizationCarryingRequest.CodeOrTokenType { + get { return CodeOrTokenType.AccessToken; } + } + + /// <summary> + /// Gets or sets the verification code or refresh/access token. + /// </summary> + /// <value>The code or token.</value> + string IAuthorizationCarryingRequest.CodeOrToken { + get { return this.AccessToken; } + set { this.AccessToken = value; } + } + + /// <summary> + /// Gets or sets the authorization that the token describes. + /// </summary> + IAuthorizationDescription IAuthorizationCarryingRequest.AuthorizationDescription { get; set; } + + /// <summary> + /// Gets the type of the access token. + /// </summary> + /// <value> + /// Always "bearer". + /// </value> + [MessagePart("token_type", IsRequired = true)] + internal string TokenType { + get { return Protocol.AccessTokenTypes.Bearer; } + } + + /// <summary> + /// Gets or sets the access token. + /// </summary> + /// <value>The access token.</value> + [MessagePart("access_token", IsRequired = true)] + internal string AccessToken { get; set; } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenAuthorizationCodeRequest.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenAuthorizationCodeRequest.cs new file mode 100644 index 0000000..22dad1d --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenAuthorizationCodeRequest.cs @@ -0,0 +1,94 @@ +//----------------------------------------------------------------------- +// <copyright file="AccessTokenAuthorizationCodeRequest.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.Messages { + using System; + using System.Collections.Generic; + using System.Diagnostics.Contracts; + using System.Linq; + using System.Text; + + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth2.ChannelElements; + + /// <summary> + /// A request from a Client to an Authorization Server to exchange an authorization code for an access token, + /// and (at the authorization server's option) a refresh token. + /// </summary> + internal class AccessTokenAuthorizationCodeRequest : AccessTokenRequestBase, IAuthorizationCarryingRequest { + /// <summary> + /// Initializes a new instance of the <see cref="AccessTokenAuthorizationCodeRequest"/> class. + /// </summary> + /// <param name="tokenEndpoint">The Authorization Server's access token endpoint URL.</param> + /// <param name="version">The version.</param> + internal AccessTokenAuthorizationCodeRequest(Uri tokenEndpoint, Version version) + : base(tokenEndpoint, version) { + } + + /// <summary> + /// Initializes a new instance of the <see cref="AccessTokenAuthorizationCodeRequest"/> class. + /// </summary> + /// <param name="authorizationServer">The authorization server.</param> + internal AccessTokenAuthorizationCodeRequest(AuthorizationServerDescription authorizationServer) + : this(authorizationServer.TokenEndpoint, authorizationServer.Version) { + Contract.Requires<ArgumentNullException>(authorizationServer != null); + } + + /// <summary> + /// Gets the type of the code or token. + /// </summary> + /// <value>The type of the code or token.</value> + CodeOrTokenType IAuthorizationCarryingRequest.CodeOrTokenType { + get { return CodeOrTokenType.AuthorizationCode; } + } + + /// <summary> + /// Gets or sets the verification code or refresh/access token. + /// </summary> + /// <value>The code or token.</value> + string IAuthorizationCarryingRequest.CodeOrToken { + get { return this.AuthorizationCode; } + set { this.AuthorizationCode = value; } + } + + /// <summary> + /// Gets or sets the authorization that the token describes. + /// </summary> + IAuthorizationDescription IAuthorizationCarryingRequest.AuthorizationDescription { get; set; } + + /// <summary> + /// Gets the type of the grant. + /// </summary> + /// <value>The type of the grant.</value> + internal override GrantType GrantType { + get { return Messages.GrantType.AuthorizationCode; } + } + + /// <summary> + /// Gets or sets the verification code previously communicated to the Client + /// in <see cref="EndUserAuthorizationSuccessAuthCodeResponse.AuthorizationCode"/>. + /// </summary> + /// <value>The verification code received from the authorization server.</value> + [MessagePart(Protocol.code, IsRequired = true)] + internal string AuthorizationCode { get; set; } + + /// <summary> + /// Gets or sets the callback URL used in <see cref="EndUserAuthorizationRequest.Callback"/> + /// </summary> + /// <value> + /// The Callback URL used to obtain the Verification Code. + /// </value> + [MessagePart(Protocol.redirect_uri, IsRequired = true)] + internal Uri Callback { get; set; } + + /// <summary> + /// Gets the scope of operations the client is allowed to invoke. + /// </summary> + protected override HashSet<string> RequestedScope { + get { return ((IAuthorizationCarryingRequest)this).AuthorizationDescription.Scope; } + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenClientCredentialsRequest.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenClientCredentialsRequest.cs new file mode 100644 index 0000000..01e1633 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenClientCredentialsRequest.cs @@ -0,0 +1,41 @@ +//----------------------------------------------------------------------- +// <copyright file="AccessTokenClientCredentialsRequest.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.Messages { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth2.ChannelElements; + + /// <summary> + /// A request for an access token for a client application that has its + /// own (non-user affiliated) client name and password. + /// </summary> + /// <remarks> + /// This is somewhat analogous to 2-legged OAuth. + /// </remarks> + internal class AccessTokenClientCredentialsRequest : ScopedAccessTokenRequest { + /// <summary> + /// Initializes a new instance of the <see cref="AccessTokenClientCredentialsRequest"/> class. + /// </summary> + /// <param name="tokenEndpoint">The authorization server.</param> + /// <param name="version">The version.</param> + internal AccessTokenClientCredentialsRequest(Uri tokenEndpoint, Version version) + : base(tokenEndpoint, version) { + this.HttpMethods = HttpDeliveryMethods.PostRequest; + } + + /// <summary> + /// Gets the type of the grant. + /// </summary> + /// <value>The type of the grant.</value> + internal override GrantType GrantType { + get { return Messages.GrantType.ClientCredentials; } + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenFailedResponse.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenFailedResponse.cs new file mode 100644 index 0000000..82de341 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenFailedResponse.cs @@ -0,0 +1,86 @@ +//----------------------------------------------------------------------- +// <copyright file="AccessTokenFailedResponse.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.Messages { + using System; + using System.Net; + + using Messaging; + + /// <summary> + /// A response from the Authorization Server to the Client to indicate that a + /// request for an access token renewal failed, probably due to an invalid + /// refresh token. + /// </summary> + /// <remarks> + /// This message type is shared by the Web App, Rich App, and Username/Password profiles. + /// </remarks> + internal class AccessTokenFailedResponse : MessageBase, IHttpDirectResponse { + /// <summary> + /// A value indicating whether this error response is in result to a request that had invalid client credentials which were supplied in the HTTP Authorization header. + /// </summary> + private readonly bool invalidClientCredentialsInAuthorizationHeader; + + /// <summary> + /// Initializes a new instance of the <see cref="AccessTokenFailedResponse"/> class. + /// </summary> + /// <param name="request">The faulty request.</param> + internal AccessTokenFailedResponse(AccessTokenRequestBase request) + : base(request) { + } + + /// <summary> + /// Initializes a new instance of the <see cref="AccessTokenFailedResponse"/> class. + /// </summary> + /// <param name="request">The faulty request.</param> + /// <param name="invalidClientCredentialsInAuthorizationHeader">A value indicating whether this error response is in result to a request that had invalid client credentials which were supplied in the HTTP Authorization header.</param> + internal AccessTokenFailedResponse(AccessTokenRequestBase request, bool invalidClientCredentialsInAuthorizationHeader) + : base(request) + { + this.invalidClientCredentialsInAuthorizationHeader = invalidClientCredentialsInAuthorizationHeader; + } + + #region IHttpDirectResponse Members + + /// <summary> + /// Gets the HTTP status code that the direct response should be sent with. + /// </summary> + HttpStatusCode IHttpDirectResponse.HttpStatusCode { + get { return this.invalidClientCredentialsInAuthorizationHeader ? HttpStatusCode.Unauthorized : HttpStatusCode.BadRequest; } + } + + /// <summary> + /// Gets the HTTP headers to add to the response. + /// </summary> + /// <value>May be an empty collection, but must not be <c>null</c>.</value> + WebHeaderCollection IHttpDirectResponse.Headers { + get { return new WebHeaderCollection(); } + } + + #endregion + + /// <summary> + /// Gets or sets the error. + /// </summary> + /// <value>One of the values given in <see cref="Protocol.AccessTokenRequestErrorCodes"/>.</value> + [MessagePart(Protocol.error, IsRequired = true)] + internal string Error { get; set; } + + /// <summary> + /// Gets or sets a human readable description of the error. + /// </summary> + /// <value>Human-readable text providing additional information, used to assist in the understanding and resolution of the error that occurred.</value> + [MessagePart(Protocol.error_description, IsRequired = false)] + internal string ErrorDescription { get; set; } + + /// <summary> + /// Gets or sets the location of the web page that describes the error and possible resolution. + /// </summary> + /// <value>A URI identifying a human-readable web page with information about the error, used to provide the end-user with additional information about the error.</value> + [MessagePart(Protocol.error_uri, IsRequired = false)] + internal Uri ErrorUri { get; set; } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenRefreshRequest.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenRefreshRequest.cs new file mode 100644 index 0000000..22354e4 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenRefreshRequest.cs @@ -0,0 +1,75 @@ +//----------------------------------------------------------------------- +// <copyright file="AccessTokenRefreshRequest.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.Messages { + using System; + using System.Collections.Generic; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth2.ChannelElements; + + /// <summary> + /// A request from the client to the token endpoint for a new access token + /// in exchange for a refresh token that the client has previously obtained. + /// </summary> + internal class AccessTokenRefreshRequest : ScopedAccessTokenRequest, IAuthorizationCarryingRequest { + /// <summary> + /// Initializes a new instance of the <see cref="AccessTokenRefreshRequest"/> class. + /// </summary> + /// <param name="tokenEndpoint">The token endpoint.</param> + /// <param name="version">The version.</param> + internal AccessTokenRefreshRequest(Uri tokenEndpoint, Version version) + : base(tokenEndpoint, version) { + } + + /// <summary> + /// Initializes a new instance of the <see cref="AccessTokenRefreshRequest"/> class. + /// </summary> + /// <param name="authorizationServer">The authorization server.</param> + internal AccessTokenRefreshRequest(AuthorizationServerDescription authorizationServer) + : this(authorizationServer.TokenEndpoint, authorizationServer.Version) { + } + + /// <summary> + /// Gets the type of the code or token. + /// </summary> + /// <value>The type of the code or token.</value> + CodeOrTokenType IAuthorizationCarryingRequest.CodeOrTokenType { + get { return CodeOrTokenType.RefreshToken; } + } + + /// <summary> + /// Gets or sets the verification code or refresh/access token. + /// </summary> + /// <value>The code or token.</value> + string IAuthorizationCarryingRequest.CodeOrToken { + get { return this.RefreshToken; } + set { this.RefreshToken = value; } + } + + /// <summary> + /// Gets or sets the authorization that the token describes. + /// </summary> + IAuthorizationDescription IAuthorizationCarryingRequest.AuthorizationDescription { get; set; } + + /// <summary> + /// Gets or sets the refresh token. + /// </summary> + /// <value>The refresh token.</value> + /// <remarks> + /// REQUIRED. The refresh token associated with the access token to be refreshed. + /// </remarks> + [MessagePart(Protocol.refresh_token, IsRequired = true)] + internal string RefreshToken { get; set; } + + /// <summary> + /// Gets the type of the grant. + /// </summary> + /// <value>The type of the grant.</value> + internal override GrantType GrantType { + get { return Messages.GrantType.RefreshToken; } + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenRequestBase.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenRequestBase.cs new file mode 100644 index 0000000..10dc231 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenRequestBase.cs @@ -0,0 +1,78 @@ +//----------------------------------------------------------------------- +// <copyright file="AccessTokenRequestBase.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.Messages { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using DotNetOpenAuth.Configuration; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth2.ChannelElements; + + /// <summary> + /// A message sent from the client to the authorization server to exchange a previously obtained grant for an access token. + /// </summary> + public abstract class AccessTokenRequestBase : AuthenticatedClientRequestBase, IAccessTokenRequest { + /// <summary> + /// Initializes a new instance of the <see cref="AccessTokenRequestBase"/> class. + /// </summary> + /// <param name="tokenEndpoint">The Authorization Server's access token endpoint URL.</param> + /// <param name="version">The version.</param> + protected AccessTokenRequestBase(Uri tokenEndpoint, Version version) + : base(tokenEndpoint, version) { + this.HttpMethods = HttpDeliveryMethods.PostRequest; + } + + /// <summary> + /// Gets the scope of operations the client is allowed to invoke. + /// </summary> + HashSet<string> IAccessTokenRequest.Scope { + get { return this.RequestedScope; } + } + + /// <summary> + /// Gets a value indicating whether the client requesting the access token has authenticated itself. + /// </summary> + /// <value> + /// Always true, because of our base class. + /// </value> + bool IAccessTokenRequest.ClientAuthenticated { + get { return true; } + } + + /// <summary> + /// Gets the type of the grant. + /// </summary> + /// <value>The type of the grant.</value> + [MessagePart(Protocol.grant_type, IsRequired = true, Encoder = typeof(GrantTypeEncoder))] + internal abstract GrantType GrantType { get; } + + /// <summary> + /// Gets the scope of operations the client is allowed to invoke. + /// </summary> + protected abstract HashSet<string> RequestedScope { get; } + + /// <summary> + /// Checks the message state for conformity to the protocol specification + /// and throws an exception if the message is invalid. + /// </summary> + /// <remarks> + /// <para>Some messages have required fields, or combinations of fields that must relate to each other + /// in specialized ways. After deserializing a message, this method checks the state of the + /// message to see if it conforms to the protocol.</para> + /// <para>Note that this property should <i>not</i> check signatures or perform any state checks + /// outside this scope of this particular message.</para> + /// </remarks> + /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception> + protected override void EnsureValidMessage() { + base.EnsureValidMessage(); + ErrorUtilities.VerifyProtocol( + DotNetOpenAuthSection.Configuration.Messaging.RelaxSslRequirements || this.Recipient.IsTransportSecure(), + OAuthStrings.HttpsRequired); + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenResourceOwnerPasswordCredentialsRequest.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenResourceOwnerPasswordCredentialsRequest.cs new file mode 100644 index 0000000..82febe9 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenResourceOwnerPasswordCredentialsRequest.cs @@ -0,0 +1,50 @@ +//----------------------------------------------------------------------- +// <copyright file="AccessTokenResourceOwnerPasswordCredentialsRequest.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.Messages { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + + using DotNetOpenAuth.Messaging; + + /// <summary> + /// A request from a Client to an Authorization Server to exchange the user's username and password for an access token. + /// </summary> + internal class AccessTokenResourceOwnerPasswordCredentialsRequest : ScopedAccessTokenRequest { + /// <summary> + /// Initializes a new instance of the <see cref="AccessTokenResourceOwnerPasswordCredentialsRequest"/> class. + /// </summary> + /// <param name="accessTokenEndpoint">The access token endpoint.</param> + /// <param name="version">The protocol version.</param> + internal AccessTokenResourceOwnerPasswordCredentialsRequest(Uri accessTokenEndpoint, Version version) + : base(accessTokenEndpoint, version) { + } + + /// <summary> + /// Gets the type of the grant. + /// </summary> + /// <value>The type of the grant.</value> + internal override GrantType GrantType { + get { return Messages.GrantType.Password; } + } + + /// <summary> + /// Gets or sets the user's account username. + /// </summary> + /// <value>The username on the user's account.</value> + [MessagePart(Protocol.username, IsRequired = true)] + internal string UserName { get; set; } + + /// <summary> + /// Gets or sets the user's password. + /// </summary> + /// <value>The password.</value> + [MessagePart(Protocol.password, IsRequired = true)] + internal string Password { get; set; } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenSuccessResponse.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenSuccessResponse.cs new file mode 100644 index 0000000..5682bf7 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenSuccessResponse.cs @@ -0,0 +1,99 @@ +//----------------------------------------------------------------------- +// <copyright file="AccessTokenSuccessResponse.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.Messages { + using System; + using System.Collections.Generic; + using System.Net; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth2.ChannelElements; + + /// <summary> + /// A response from the Authorization Server to the Client containing a delegation code + /// that the Client should use to obtain an access token. + /// </summary> + /// <remarks> + /// This message type is shared by the Web App, Rich App, and Username/Password profiles. + /// </remarks> + internal class AccessTokenSuccessResponse : MessageBase, IHttpDirectResponse { + /// <summary> + /// Initializes a new instance of the <see cref="AccessTokenSuccessResponse"/> class. + /// </summary> + /// <param name="request">The request.</param> + internal AccessTokenSuccessResponse(AccessTokenRequestBase request) + : base(request) { + this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer); + this.TokenType = Protocol.AccessTokenTypes.Bearer; + } + + /// <summary> + /// Gets the HTTP status code that the direct response should be sent with. + /// </summary> + /// <value>Always HttpStatusCode.OK</value> + HttpStatusCode IHttpDirectResponse.HttpStatusCode { + get { return HttpStatusCode.OK; } + } + + /// <summary> + /// Gets the HTTP headers to add to the response. + /// </summary> + /// <value>May be an empty collection, but must not be <c>null</c>.</value> + WebHeaderCollection IHttpDirectResponse.Headers { + get { + return new WebHeaderCollection + { + { HttpResponseHeader.CacheControl, "no-store" }, + }; + } + } + + /// <summary> + /// Gets or sets the access token. + /// </summary> + /// <value>The access token.</value> + [MessagePart(Protocol.access_token, IsRequired = true)] + public string AccessToken { get; internal set; } + + /// <summary> + /// Gets or sets the token type. + /// </summary> + /// <value>Usually "bearer".</value> + /// <remarks> + /// Described in OAuth 2.0 section 7.1. + /// </remarks> + [MessagePart(Protocol.token_type, IsRequired = true)] + public string TokenType { get; internal set; } + + /// <summary> + /// Gets or sets the lifetime of the access token. + /// </summary> + /// <value>The lifetime.</value> + [MessagePart(Protocol.expires_in, IsRequired = false, Encoder = typeof(TimespanSecondsEncoder))] + public TimeSpan? Lifetime { get; internal set; } + + /// <summary> + /// Gets or sets the refresh token. + /// </summary> + /// <value>The refresh token.</value> + /// <remarks> + /// OPTIONAL. The refresh token used to obtain new access tokens using the same end-user access grant as described in Section 6 (Refreshing an Access Token). + /// </remarks> + [MessagePart(Protocol.refresh_token, IsRequired = false)] + public string RefreshToken { get; internal set; } + + /// <summary> + /// Gets the scope of access being requested. + /// </summary> + /// <value>The scope of the access request expressed as a list of space-delimited strings. The value of the scope parameter is defined by the authorization server. If the value contains multiple space-delimited strings, their order does not matter, and each string adds an additional access range to the requested scope.</value> + [MessagePart(Protocol.scope, IsRequired = false, Encoder = typeof(ScopeEncoder))] + public HashSet<string> Scope { get; private set; } + + /// <summary> + /// Gets or sets a value indicating whether a refresh token is or should be included in the response. + /// </summary> + internal bool HasRefreshToken { get; set; } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AuthenticatedClientRequestBase.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AuthenticatedClientRequestBase.cs new file mode 100644 index 0000000..22f7461 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AuthenticatedClientRequestBase.cs @@ -0,0 +1,42 @@ +//----------------------------------------------------------------------- +// <copyright file="AuthenticatedClientRequestBase.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.Messages { + using System; + + using DotNetOpenAuth.Messaging; + + /// <summary> + /// A direct message from the client to the authorization server that includes the client's credentials. + /// </summary> + public abstract class AuthenticatedClientRequestBase : MessageBase { + /// <summary> + /// Initializes a new instance of the <see cref="AuthenticatedClientRequestBase"/> class. + /// </summary> + /// <param name="tokenEndpoint">The Authorization Server's access token endpoint URL.</param> + /// <param name="version">The version.</param> + protected AuthenticatedClientRequestBase(Uri tokenEndpoint, Version version) + : base(version, MessageTransport.Direct, tokenEndpoint) { + } + + /// <summary> + /// Gets the client identifier previously obtained from the Authorization Server. + /// </summary> + /// <value>The client identifier.</value> + [MessagePart(Protocol.client_id, IsRequired = true)] + public string ClientIdentifier { get; internal set; } + + /// <summary> + /// Gets the client secret. + /// </summary> + /// <value>The client secret.</value> + /// <remarks> + /// REQUIRED. The client secret as described in Section 2.1 (Client Credentials). OPTIONAL if no client secret was issued. + /// </remarks> + [MessagePart(Protocol.client_secret, IsRequired = false)] + public string ClientSecret { get; internal set; } + } +}
\ No newline at end of file diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationFailedResponse.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationFailedResponse.cs new file mode 100644 index 0000000..5497e1b --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationFailedResponse.cs @@ -0,0 +1,81 @@ +//----------------------------------------------------------------------- +// <copyright file="EndUserAuthorizationFailedResponse.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.Messages { + using System; + using System.Collections.Generic; + using System.Diagnostics.Contracts; + using System.Linq; + using System.Runtime.Remoting.Messaging; + using System.Text; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// The message that an Authorization Server responds to a Client with when the user denies a user authorization request. + /// </summary> + public class EndUserAuthorizationFailedResponse : MessageBase, IMessageWithClientState { + /// <summary> + /// Initializes a new instance of the <see cref="EndUserAuthorizationFailedResponse"/> class. + /// </summary> + /// <param name="clientCallback">The URL to redirect to so the client receives the message. This may not be built into the request message if the client pre-registered the URL with the authorization server.</param> + /// <param name="version">The protocol version.</param> + internal EndUserAuthorizationFailedResponse(Uri clientCallback, Version version) + : base(version, MessageTransport.Indirect, clientCallback) { + Contract.Requires<ArgumentNullException>(version != null); + Contract.Requires<ArgumentNullException>(clientCallback != null); + } + + /// <summary> + /// Initializes a new instance of the <see cref="EndUserAuthorizationFailedResponse"/> class. + /// </summary> + /// <param name="clientCallback">The URL to redirect to so the client receives the message. This may not be built into the request message if the client pre-registered the URL with the authorization server.</param> + /// <param name="request">The authorization request from the user agent on behalf of the client.</param> + internal EndUserAuthorizationFailedResponse(Uri clientCallback, EndUserAuthorizationRequest request) + : base(((IProtocolMessage)request).Version, MessageTransport.Indirect, clientCallback) { + Contract.Requires<ArgumentNullException>(request != null); + ((IMessageWithClientState)this).ClientState = request.ClientState; + } + + /// <summary> + /// Gets or sets the error. + /// </summary> + /// <value> + /// One of the values given in <see cref="Protocol.EndUserAuthorizationRequestErrorCodes"/>. + /// OR a numerical HTTP status code from the 4xx or 5xx + /// range, with the exception of the 400 (Bad Request) and + /// 401 (Unauthorized) status codes. For example, if the + /// service is temporarily unavailable, the authorization + /// server MAY return an error response with "error" set to + /// "503". + /// </value> + [MessagePart(Protocol.error, IsRequired = true)] + public string Error { get; set; } + + /// <summary> + /// Gets or sets a human readable description of the error. + /// </summary> + /// <value>Human-readable text providing additional information, used to assist in the understanding and resolution of the error that occurred.</value> + [MessagePart(Protocol.error_description, IsRequired = false)] + public string ErrorDescription { get; set; } + + /// <summary> + /// Gets or sets the location of the web page that describes the error and possible resolution. + /// </summary> + /// <value>A URI identifying a human-readable web page with information about the error, used to provide the end-user with additional information about the error.</value> + [MessagePart(Protocol.error_uri, IsRequired = false)] + public Uri ErrorUri { get; set; } + + /// <summary> + /// Gets or sets some state as provided by the client in the authorization request. + /// </summary> + /// <value>An opaque value defined by the client.</value> + /// <remarks> + /// REQUIRED if the Client sent the value in the <see cref="EndUserAuthorizationRequest"/>. + /// </remarks> + [MessagePart(Protocol.state, IsRequired = false)] + string IMessageWithClientState.ClientState { get; set; } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationRequest.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationRequest.cs new file mode 100644 index 0000000..856fe22 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationRequest.cs @@ -0,0 +1,118 @@ +//----------------------------------------------------------------------- +// <copyright file="EndUserAuthorizationRequest.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.Messages { + using System; + using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; + using System.Diagnostics.Contracts; + using DotNetOpenAuth.Configuration; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth2.ChannelElements; + + /// <summary> + /// A message sent by a web application Client to the AuthorizationServer + /// via the user agent to obtain authorization from the user and prepare + /// to issue an access token to the Consumer if permission is granted. + /// </summary> + [Serializable] + public class EndUserAuthorizationRequest : MessageBase, IAccessTokenRequest { + /// <summary> + /// Initializes a new instance of the <see cref="EndUserAuthorizationRequest"/> class. + /// </summary> + /// <param name="authorizationEndpoint">The Authorization Server's user authorization URL to direct the user to.</param> + /// <param name="version">The protocol version.</param> + internal EndUserAuthorizationRequest(Uri authorizationEndpoint, Version version) + : base(version, MessageTransport.Indirect, authorizationEndpoint) { + Contract.Requires<ArgumentNullException>(authorizationEndpoint != null); + Contract.Requires<ArgumentNullException>(version != null); + this.HttpMethods = HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.PostRequest; + this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer); + this.ResponseType = EndUserAuthorizationResponseType.AuthorizationCode; + } + + /// <summary> + /// Initializes a new instance of the <see cref="EndUserAuthorizationRequest"/> class. + /// </summary> + /// <param name="authorizationServer">The authorization server.</param> + internal EndUserAuthorizationRequest(AuthorizationServerDescription authorizationServer) + : this(authorizationServer.AuthorizationEndpoint, authorizationServer.Version) { + Contract.Requires<ArgumentNullException>(authorizationServer != null); + Contract.Requires<ArgumentException>(authorizationServer.Version != null); + Contract.Requires<ArgumentException>(authorizationServer.AuthorizationEndpoint != null); + } + + /// <summary> + /// Gets or sets the grant type that the client expects of the authorization server. + /// </summary> + /// <value>Always <see cref="EndUserAuthorizationResponseType.AuthorizationCode"/>. Other response types are not supported.</value> + [MessagePart(Protocol.response_type, IsRequired = true, Encoder = typeof(EndUserAuthorizationResponseTypeEncoder))] + public EndUserAuthorizationResponseType ResponseType { get; set; } + + /// <summary> + /// Gets or sets the identifier by which this client is known to the Authorization Server. + /// </summary> + [MessagePart(Protocol.client_id, IsRequired = true)] + public string ClientIdentifier { get; set; } + + /// <summary> + /// Gets a value indicating whether the client requesting the access token has authenticated itself. + /// </summary> + /// <value> + /// Always false because authorization requests only include the client_id, without a secret. + /// </value> + bool IAccessTokenRequest.ClientAuthenticated { + get { return false; } + } + + /// <summary> + /// Gets or sets the callback URL. + /// </summary> + /// <value> + /// An absolute URL to which the Authorization Server will redirect the User back after + /// the user has approved the authorization request. + /// </value> + /// <remarks> + /// REQUIRED unless a redirection URI has been established between the client and authorization server via other means. An absolute URI to which the authorization server will redirect the user-agent to when the end-user authorization step is completed. The authorization server MAY require the client to pre-register their redirection URI. The redirection URI MUST NOT include a query component as defined by [RFC3986] (Berners-Lee, T., Fielding, R., and L. Masinter, “Uniform Resource Identifier (URI): Generic Syntax,” January 2005.) section 3 if the state parameter is present. + /// </remarks> + [MessagePart(Protocol.redirect_uri, IsRequired = false)] + public Uri Callback { get; set; } + + /// <summary> + /// Gets or sets state of the client that should be sent back with the authorization response. + /// </summary> + /// <value> + /// An opaque value that Clients can use to maintain state associated with this request. + /// </value> + /// <remarks> + /// This data is proprietary to the client and should be considered an opaque string to the + /// authorization server. + /// </remarks> + [MessagePart(Protocol.state, IsRequired = false)] + public string ClientState { get; set; } + + /// <summary> + /// Gets the scope of access being requested. + /// </summary> + /// <value>The scope of the access request expressed as a list of space-delimited strings. The value of the scope parameter is defined by the authorization server. If the value contains multiple space-delimited strings, their order does not matter, and each string adds an additional access range to the requested scope.</value> + [MessagePart(Protocol.scope, IsRequired = false, Encoder = typeof(ScopeEncoder))] + public HashSet<string> Scope { get; private set; } + + /// <summary> + /// Checks the message state for conformity to the protocol specification + /// and throws an exception if the message is invalid. + /// </summary> + /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception> + protected override void EnsureValidMessage() { + base.EnsureValidMessage(); + + ErrorUtilities.VerifyProtocol( + DotNetOpenAuthSection.Configuration.Messaging.RelaxSslRequirements || this.Recipient.IsTransportSecure(), + OAuthStrings.HttpsRequired); + ErrorUtilities.VerifyProtocol(this.Callback == null || this.Callback.IsAbsoluteUri, this, OAuthStrings.AbsoluteUriRequired, Protocol.redirect_uri); + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationResponseType.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationResponseType.cs new file mode 100644 index 0000000..815fef6 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationResponseType.cs @@ -0,0 +1,25 @@ +//----------------------------------------------------------------------- +// <copyright file="EndUserAuthorizationResponseType.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.Messages { + using System; + + /// <summary> + /// An indication of what kind of response the client is requesting from the authorization server + /// after the user has granted authorized access. + /// </summary> + public enum EndUserAuthorizationResponseType { + /// <summary> + /// An access token should be returned immediately. + /// </summary> + AccessToken, + + /// <summary> + /// An authorization code should be returned, which can later be exchanged for refresh and access tokens. + /// </summary> + AuthorizationCode, + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessAccessTokenResponse.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessAccessTokenResponse.cs new file mode 100644 index 0000000..c9373eb --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessAccessTokenResponse.cs @@ -0,0 +1,121 @@ +//----------------------------------------------------------------------- +// <copyright file="EndUserAuthorizationSuccessAccessTokenResponse.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.Messages { + using System; + using System.Collections.Generic; + using System.Diagnostics.Contracts; + using System.Linq; + using System.Text; + + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth2.ChannelElements; + + /// <summary> + /// The message sent by the Authorization Server to the Client via the user agent + /// to indicate that user authorization was granted, carrying only an access token, + /// and to return the user to the Client where they started their experience. + /// </summary> + internal class EndUserAuthorizationSuccessAccessTokenResponse : EndUserAuthorizationSuccessResponseBase, IAuthorizationCarryingRequest, IHttpIndirectResponse { + /// <summary> + /// Initializes a new instance of the <see cref="EndUserAuthorizationSuccessAccessTokenResponse"/> class. + /// </summary> + /// <param name="clientCallback">The URL to redirect to so the client receives the message. This may not be built into the request message if the client pre-registered the URL with the authorization server.</param> + /// <param name="version">The protocol version.</param> + internal EndUserAuthorizationSuccessAccessTokenResponse(Uri clientCallback, Version version) + : base(clientCallback, version) { + Contract.Requires<ArgumentNullException>(version != null); + Contract.Requires<ArgumentNullException>(clientCallback != null); + this.TokenType = Protocol.AccessTokenTypes.Bearer; + } + + /// <summary> + /// Initializes a new instance of the <see cref="EndUserAuthorizationSuccessAccessTokenResponse"/> class. + /// </summary> + /// <param name="clientCallback">The URL to redirect to so the client receives the message. This may not be built into the request message if the client pre-registered the URL with the authorization server.</param> + /// <param name="request">The authorization request from the user agent on behalf of the client.</param> + internal EndUserAuthorizationSuccessAccessTokenResponse(Uri clientCallback, EndUserAuthorizationRequest request) + : base(clientCallback, request) { + Contract.Requires<ArgumentNullException>(clientCallback != null); + Contract.Requires<ArgumentNullException>(request != null); + ((IMessageWithClientState)this).ClientState = request.ClientState; + this.TokenType = Protocol.AccessTokenTypes.Bearer; + } + + #region IAuthorizationCarryingRequest Members + + /// <summary> + /// Gets or sets the verification code or refresh/access token. + /// </summary> + /// <value>The code or token.</value> + string IAuthorizationCarryingRequest.CodeOrToken { + get { return this.AccessToken; } + set { this.AccessToken = value; } + } + + /// <summary> + /// Gets the type of the code or token. + /// </summary> + /// <value>The type of the code or token.</value> + CodeOrTokenType IAuthorizationCarryingRequest.CodeOrTokenType { + get { return CodeOrTokenType.AccessToken; } + } + + /// <summary> + /// Gets or sets the authorization that the token describes. + /// </summary> + /// <value></value> + IAuthorizationDescription IAuthorizationCarryingRequest.AuthorizationDescription { get; set; } + + #endregion + + #region IHttpIndirectResponse Members + + /// <summary> + /// Gets a value indicating whether the payload for the message should be included + /// in the redirect fragment instead of the query string or POST entity. + /// </summary> + bool IHttpIndirectResponse.Include301RedirectPayloadInFragment { + get { return true; } + } + + #endregion + + /// <summary> + /// Gets or sets the token type. + /// </summary> + /// <value>Usually "bearer".</value> + /// <remarks> + /// Described in OAuth 2.0 section 7.1. + /// </remarks> + [MessagePart(Protocol.token_type, IsRequired = true)] + public string TokenType { get; internal set; } + + /// <summary> + /// Gets or sets the access token. + /// </summary> + /// <value>The access token.</value> + [MessagePart(Protocol.access_token, IsRequired = true)] + public string AccessToken { get; set; } + + /// <summary> + /// Gets or sets the scope of the <see cref="AccessToken"/> if one is given; otherwise the scope of the authorization code. + /// </summary> + /// <value>The scope.</value> + [MessagePart(Protocol.scope, IsRequired = false, Encoder = typeof(ScopeEncoder))] + public new ICollection<string> Scope { + get { return base.Scope; } + protected set { base.Scope = value; } + } + + /// <summary> + /// Gets or sets the lifetime of the authorization. + /// </summary> + /// <value>The lifetime.</value> + [MessagePart(Protocol.expires_in, IsRequired = false, Encoder = typeof(TimespanSecondsEncoder))] + internal TimeSpan? Lifetime { get; set; } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessAuthCodeResponse.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessAuthCodeResponse.cs new file mode 100644 index 0000000..65965ef --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessAuthCodeResponse.cs @@ -0,0 +1,76 @@ +//----------------------------------------------------------------------- +// <copyright file="EndUserAuthorizationSuccessAuthCodeResponse.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.Messages { + using System; + using System.Diagnostics.Contracts; + + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth2.ChannelElements; + + /// <summary> + /// The message sent by the Authorization Server to the Client via the user agent + /// to indicate that user authorization was granted, carrying an authorization code and possibly an access token, + /// and to return the user to the Client where they started their experience. + /// </summary> + internal class EndUserAuthorizationSuccessAuthCodeResponse : EndUserAuthorizationSuccessResponseBase, IAuthorizationCarryingRequest { + /// <summary> + /// Initializes a new instance of the <see cref="EndUserAuthorizationSuccessAuthCodeResponse"/> class. + /// </summary> + /// <param name="clientCallback">The URL to redirect to so the client receives the message. This may not be built into the request message if the client pre-registered the URL with the authorization server.</param> + /// <param name="version">The protocol version.</param> + internal EndUserAuthorizationSuccessAuthCodeResponse(Uri clientCallback, Version version) + : base(clientCallback, version) { + Contract.Requires<ArgumentNullException>(version != null); + Contract.Requires<ArgumentNullException>(clientCallback != null); + } + + /// <summary> + /// Initializes a new instance of the <see cref="EndUserAuthorizationSuccessAuthCodeResponse"/> class. + /// </summary> + /// <param name="clientCallback">The URL to redirect to so the client receives the message. This may not be built into the request message if the client pre-registered the URL with the authorization server.</param> + /// <param name="request">The authorization request from the user agent on behalf of the client.</param> + internal EndUserAuthorizationSuccessAuthCodeResponse(Uri clientCallback, EndUserAuthorizationRequest request) + : base(clientCallback, request) { + Contract.Requires<ArgumentNullException>(clientCallback != null); + Contract.Requires<ArgumentNullException>(request != null); + ((IMessageWithClientState)this).ClientState = request.ClientState; + } + + #region IAuthorizationCarryingRequest Members + + /// <summary> + /// Gets or sets the verification code or refresh/access token. + /// </summary> + /// <value>The code or token.</value> + string IAuthorizationCarryingRequest.CodeOrToken { + get { return this.AuthorizationCode; } + set { this.AuthorizationCode = value; } + } + + /// <summary> + /// Gets the type of the code or token. + /// </summary> + /// <value>The type of the code or token.</value> + CodeOrTokenType IAuthorizationCarryingRequest.CodeOrTokenType { + get { return CodeOrTokenType.AuthorizationCode; } + } + + /// <summary> + /// Gets or sets the authorization that the token describes. + /// </summary> + IAuthorizationDescription IAuthorizationCarryingRequest.AuthorizationDescription { get; set; } + + #endregion + + /// <summary> + /// Gets or sets the authorization code. + /// </summary> + /// <value>The authorization code.</value> + [MessagePart(Protocol.code, IsRequired = true)] + internal string AuthorizationCode { get; set; } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessResponseBase.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessResponseBase.cs new file mode 100644 index 0000000..d3c32e8 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessResponseBase.cs @@ -0,0 +1,69 @@ +//----------------------------------------------------------------------- +// <copyright file="EndUserAuthorizationSuccessResponseBase.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.Messages { + using System; + using System.Collections.Generic; + using System.Diagnostics.Contracts; + using System.Security.Cryptography; + + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth2.ChannelElements; + + /// <summary> + /// The message sent by the Authorization Server to the Client via the user agent + /// to indicate that user authorization was granted, and to return the user + /// to the Client where they started their experience. + /// </summary> + public abstract class EndUserAuthorizationSuccessResponseBase : MessageBase, IMessageWithClientState { + /// <summary> + /// Initializes a new instance of the <see cref="EndUserAuthorizationSuccessResponseBase"/> class. + /// </summary> + /// <param name="clientCallback">The URL to redirect to so the client receives the message. This may not be built into the request message if the client pre-registered the URL with the authorization server.</param> + /// <param name="version">The protocol version.</param> + internal EndUserAuthorizationSuccessResponseBase(Uri clientCallback, Version version) + : base(version, MessageTransport.Indirect, clientCallback) { + Contract.Requires<ArgumentNullException>(version != null); + Contract.Requires<ArgumentNullException>(clientCallback != null); + this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer); + } + + /// <summary> + /// Initializes a new instance of the <see cref="EndUserAuthorizationSuccessResponseBase"/> class. + /// </summary> + /// <param name="clientCallback">The URL to redirect to so the client receives the message. This may not be built into the request message if the client pre-registered the URL with the authorization server.</param> + /// <param name="request">The authorization request from the user agent on behalf of the client.</param> + internal EndUserAuthorizationSuccessResponseBase(Uri clientCallback, EndUserAuthorizationRequest request) + : base(request, clientCallback) { + Contract.Requires<ArgumentNullException>(clientCallback != null); + Contract.Requires<ArgumentNullException>(request != null); + ((IMessageWithClientState)this).ClientState = request.ClientState; + this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer); + this.Scope.ResetContents(request.Scope); + } + + /// <summary> + /// Gets or sets some state as provided by the client in the authorization request. + /// </summary> + /// <value>An opaque value defined by the client.</value> + /// <remarks> + /// REQUIRED if the Client sent the value in the <see cref="EndUserAuthorizationRequest"/>. + /// </remarks> + [MessagePart(Protocol.state, IsRequired = false)] + string IMessageWithClientState.ClientState { get; set; } + + /// <summary> + /// Gets or sets the scope of the <see cref="AccessToken"/> if one is given; otherwise the scope of the authorization code. + /// </summary> + /// <value>The scope.</value> + public ICollection<string> Scope { get; protected set; } + + /// <summary> + /// Gets or sets the authorizing user's account name. + /// </summary> + internal string AuthorizingUsername { get; set; } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/GrantType.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/GrantType.cs new file mode 100644 index 0000000..4580a7f --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/GrantType.cs @@ -0,0 +1,42 @@ +//----------------------------------------------------------------------- +// <copyright file="GrantType.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.Messages { + /// <summary> + /// The types of authorizations that a client can use to obtain + /// a refresh token and/or an access token. + /// </summary> + internal enum GrantType { + /// <summary> + /// The client is providing the authorization code previously obtained from an end user authorization response. + /// </summary> + AuthorizationCode, + + /// <summary> + /// The client is providing the end user's username and password to the authorization server. + /// </summary> + Password, + + /// <summary> + /// The client is providing an assertion it obtained from another source. + /// </summary> + Assertion, + + /// <summary> + /// The client is providing a refresh token. + /// </summary> + RefreshToken, + + /// <summary> + /// No authorization to access a user's data has been given. The client is requesting + /// an access token authorized for its own private data. This fits the classic OAuth 1.0(a) "2-legged OAuth" scenario. + /// </summary> + /// <remarks> + /// When requesting an access token using the none access grant type (no access grant is included), the client is requesting access to the protected resources under its control, or those of another resource owner which has been previously arranged with the authorization server (the method of which is beyond the scope of this specification). + /// </remarks> + ClientCredentials, + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/IAccessTokenRequest.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/IAccessTokenRequest.cs new file mode 100644 index 0000000..7246beb --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/IAccessTokenRequest.cs @@ -0,0 +1,37 @@ +//----------------------------------------------------------------------- +// <copyright file="IAccessTokenRequest.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.Messages { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth2.ChannelElements; + + /// <summary> + /// A request from a client that should be responded to directly with an access token. + /// </summary> + public interface IAccessTokenRequest : IMessage { + /// <summary> + /// Gets a value indicating whether the client requesting the access token has authenticated itself. + /// </summary> + /// <value> + /// <c>false</c> for implicit grant requests; otherwise, <c>true</c>. + /// </value> + bool ClientAuthenticated { get; } + + /// <summary> + /// Gets the identifier of the client authorized to access protected data. + /// </summary> + string ClientIdentifier { get; } + + /// <summary> + /// Gets the scope of operations the client is allowed to invoke. + /// </summary> + HashSet<string> Scope { get; } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/IMessageWithClientState.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/IMessageWithClientState.cs new file mode 100644 index 0000000..fa371ae --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/IMessageWithClientState.cs @@ -0,0 +1,21 @@ +//----------------------------------------------------------------------- +// <copyright file="IMessageWithClientState.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.Messages { + using DotNetOpenAuth.Messaging; + + /// <summary> + /// A message carrying client state the authorization server should preserve on behalf of the client + /// during an authorization. + /// </summary> + internal interface IMessageWithClientState : IProtocolMessage { + /// <summary> + /// Gets or sets the state of the client. + /// </summary> + /// <value>The state of the client.</value> + string ClientState { get; set; } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/MessageBase.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/MessageBase.cs new file mode 100644 index 0000000..e390d6e --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/MessageBase.cs @@ -0,0 +1,239 @@ +//----------------------------------------------------------------------- +// <copyright file="MessageBase.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.Messages { + using System; + using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; + using System.Diagnostics.Contracts; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// A common message base class for OAuth messages. + /// </summary> + [Serializable] + public class MessageBase : IDirectedProtocolMessage, IDirectResponseProtocolMessage { + /// <summary> + /// A dictionary to contain extra message data. + /// </summary> + private Dictionary<string, string> extraData = new Dictionary<string, string>(); + + /// <summary> + /// The originating request. + /// </summary> + private IDirectedProtocolMessage originatingRequest; + + /// <summary> + /// The backing field for the <see cref="IMessage.Version"/> property. + /// </summary> + private Version version; + + /// <summary> + /// A value indicating whether this message is a direct or indirect message. + /// </summary> + private MessageTransport messageTransport; + + /// <summary> + /// Initializes a new instance of the <see cref="MessageBase"/> class + /// that is used for direct response messages. + /// </summary> + /// <param name="version">The version.</param> + protected MessageBase(Version version) { + 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 RequiredProtection; } + } + + /// <summary> + /// Gets a value indicating whether this is a direct or indirect message. + /// </summary> + /// <value></value> + MessageTransport IProtocolMessage.Transport { + get { return this.Transport; } + } + + #endregion + + #region IDirectedProtocolMessage Members + + /// <summary> + /// Gets the preferred method of transport for the message. + /// </summary> + /// <remarks> + /// For indirect messages this will likely be GET+POST, which both can be simulated in the user agent: + /// the GET with a simple 301 Redirect, and the POST with an HTML form in the response with javascript + /// to automate submission. + /// </remarks> + HttpDeliveryMethods IDirectedProtocolMessage.HttpMethods { + get { return this.HttpMethods; } + } + + /// <summary> + /// Gets the URL of the intended receiver of this message. + /// </summary> + Uri IDirectedProtocolMessage.Recipient { + get { return this.Recipient; } + } + + #endregion + + #region IDirectResponseProtocolMessage Members + + /// <summary> + /// Gets the originating request message that caused this response to be formed. + /// </summary> + IDirectedProtocolMessage IDirectResponseProtocolMessage.OriginatingRequest { + get { return this.OriginatingRequest; } + } + + #endregion + + /// <summary> + /// Gets the level of protection this message requires. + /// </summary> + protected static MessageProtections RequiredProtection { + get { return MessageProtections.None; } + } + + /// <summary> + /// Gets a value indicating whether this is a direct or indirect message. + /// </summary> + protected MessageTransport Transport { + get { return this.messageTransport; } + } + + /// <summary> + /// Gets the version of the protocol or extension this message is prepared to implement. + /// </summary> + protected Version Version { + get { return this.version; } + } + + /// <summary> + /// Gets or sets the preferred method of transport for the message. + /// </summary> + /// <remarks> + /// For indirect messages this will likely be GET+POST, which both can be simulated in the user agent: + /// the GET with a simple 301 Redirect, and the POST with an HTML form in the response with javascript + /// to automate submission. + /// </remarks> + protected HttpDeliveryMethods HttpMethods { get; set; } + + /// <summary> + /// Gets the originating request message that caused this response to be formed. + /// </summary> + protected IDirectedProtocolMessage OriginatingRequest { + get { return this.originatingRequest; } + } + + /// <summary> + /// Gets the URL of the intended receiver of this message. + /// </summary> + protected Uri Recipient { get; private set; } + + #region IMessage Methods + + /// <summary> + /// Checks the message state for conformity to the protocol specification + /// and throws an exception if the message is invalid. + /// </summary> + /// <remarks> + /// <para>Some messages have required fields, or combinations of fields that must relate to each other + /// in specialized ways. After deserializing a message, this method checks the state of the + /// message to see if it conforms to the protocol.</para> + /// <para>Note that this property should <i>not</i> check signatures or perform any state checks + /// outside this scope of this particular message.</para> + /// </remarks> + /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception> + void IMessage.EnsureValidMessage() { + this.EnsureValidMessage(); + } + + #endregion + + /// <summary> + /// Checks the message state for conformity to the protocol specification + /// and throws an exception if the message is invalid. + /// </summary> + /// <remarks> + /// <para>Some messages have required fields, or combinations of fields that must relate to each other + /// in specialized ways. After deserializing a message, this method checks the state of the + /// message to see if it conforms to the protocol.</para> + /// <para>Note that this property should <i>not</i> check signatures or perform any state checks + /// outside this scope of this particular message.</para> + /// </remarks> + /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception> + protected virtual void EnsureValidMessage() { + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/OAuth 2 Messages.cd b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/OAuth 2 Messages.cd new file mode 100644 index 0000000..05e3ad9 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/OAuth 2 Messages.cd @@ -0,0 +1,164 @@ +<?xml version="1.0" encoding="utf-8"?> +<ClassDiagram MajorVersion="1" MinorVersion="1"> + <Class Name="DotNetOpenAuth.OAuth2.Messages.MessageBase" Collapsed="true"> + <Position X="0.5" Y="0.5" Width="1.5" /> + <TypeIdentifier> + <HashCode>IAAMACQAQAAAgAkAAAAIAAYACgAAIAAAIACAACAAAIA=</HashCode> + <FileName>OAuth2\Messages\MessageBase.cs</FileName> + </TypeIdentifier> + <Lollipop Position="0.2" /> + </Class> + <Class Name="DotNetOpenAuth.OAuth2.Messages.AccessTokenAuthorizationCodeRequest" Collapsed="true"> + <Position X="8.5" Y="6.75" Width="3" /> + <TypeIdentifier> + <HashCode>ACAAEAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAgAAAATAA=</HashCode> + <FileName>OAuth2\Messages\AccessTokenAuthorizationCodeRequest.cs</FileName> + </TypeIdentifier> + <Lollipop Position="0.2" /> + </Class> + <Class Name="DotNetOpenAuth.OAuth2.Messages.AccessTokenClientCredentialsRequest" Collapsed="true"> + <Position X="8.5" Y="8.75" Width="2.75" /> + <TypeIdentifier> + <HashCode>AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA=</HashCode> + <FileName>OAuth2\Messages\AccessTokenClientCredentialsRequest.cs</FileName> + </TypeIdentifier> + </Class> + <Class Name="DotNetOpenAuth.OAuth2.Messages.AccessTokenFailedResponse" Collapsed="true"> + <Position X="3.25" Y="8.5" Width="2.25" /> + <TypeIdentifier> + <HashCode>AAAAAIAAAAAAAQAAAABAAAQAAAAAAAEQAAAAAAAAAAA=</HashCode> + <FileName>OAuth2\Messages\AccessTokenFailedResponse.cs</FileName> + </TypeIdentifier> + <Lollipop Position="0.2" /> + </Class> + <Class Name="DotNetOpenAuth.OAuth2.Messages.AccessTokenRefreshRequest" Collapsed="true"> + <Position X="8.5" Y="9.75" Width="2.25" /> + <TypeIdentifier> + <HashCode>AAAAEAAAQAAAAAAAAAAAAAAQAAAAAAAAAAAgAAAABAA=</HashCode> + <FileName>OAuth2\Messages\AccessTokenRefreshRequest.cs</FileName> + </TypeIdentifier> + <Lollipop Position="0.2" /> + </Class> + <Class Name="DotNetOpenAuth.OAuth2.Messages.AccessTokenRequestBase" Collapsed="true"> + <Position X="5.75" Y="5.75" Width="2" /> + <TypeIdentifier> + <HashCode>AAAAAAAAQABAAAAAAAAAAAAQAAAAAAAAAAAAAAAACAA=</HashCode> + <FileName>OAuth2\Messages\AccessTokenRequestBase.cs</FileName> + </TypeIdentifier> + <Lollipop Position="0.2" /> + </Class> + <Class Name="DotNetOpenAuth.OAuth2.Messages.AccessTokenResourceOwnerPasswordCredentialsRequest" Collapsed="true"> + <Position X="8.5" Y="10.5" Width="4" /> + <TypeIdentifier> + <HashCode>AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAACAQAAAAAAAAA=</HashCode> + <FileName>OAuth2\Messages\AccessTokenResourceOwnerPasswordCredentialsRequest.cs</FileName> + </TypeIdentifier> + </Class> + <Class Name="DotNetOpenAuth.OAuth2.Messages.AccessTokenSuccessResponse" Collapsed="true"> + <Position X="3.25" Y="7.5" Width="2.25" /> + <TypeIdentifier> + <HashCode>AAAAAAAAQAAAACAAAAAAAAQAEAAAAAAQAEAAAAAAAgA=</HashCode> + <FileName>OAuth2\Messages\AccessTokenSuccessResponse.cs</FileName> + </TypeIdentifier> + <Lollipop Position="0.2" /> + </Class> + <Class Name="DotNetOpenAuth.OAuth2.Messages.AuthenticatedClientRequestBase" Collapsed="true"> + <Position X="3.25" Y="5.25" Width="2.25" /> + <TypeIdentifier> + <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAA=</HashCode> + <FileName>OAuth2\Messages\AuthenticatedClientRequestBase.cs</FileName> + </TypeIdentifier> + </Class> + <Class Name="DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationFailedResponse" Collapsed="true"> + <Position X="3.25" Y="4.5" Width="2.75" /> + <TypeIdentifier> + <HashCode>AAAAAIAAAAAAAQAAAAAAAAgAAAAAAAEAAAAAAAAAAAA=</HashCode> + <FileName>OAuth2\Messages\EndUserAuthorizationFailedResponse.cs</FileName> + </TypeIdentifier> + <Lollipop Position="0.2" /> + </Class> + <Class Name="DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationRequest" Collapsed="true"> + <Position X="3.25" Y="0.5" Width="2.25" /> + <TypeIdentifier> + <HashCode>AAAAAAAAQABAACAAAAAAAACAAAQAAAQAAAAAAAAAQAA=</HashCode> + <FileName>OAuth2\Messages\EndUserAuthorizationRequest.cs</FileName> + </TypeIdentifier> + <Lollipop Position="0.2" /> + </Class> + <Class Name="DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationSuccessAccessTokenResponse" Collapsed="true"> + <Position X="6.25" Y="3.75" Width="3.75" /> + <TypeIdentifier> + <HashCode>AAAAEAAAAAAAAAAAAAAAAAACEAAAAAAAAAAgAAAABgA=</HashCode> + <FileName>OAuth2\Messages\EndUserAuthorizationSuccessAccessTokenResponse.cs</FileName> + </TypeIdentifier> + <Lollipop Position="0.2" /> + </Class> + <Class Name="DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationSuccessAuthCodeResponse" Collapsed="true"> + <Position X="6.25" Y="2.5" Width="3.5" /> + <TypeIdentifier> + <HashCode>ACAAEAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAgAAAABAA=</HashCode> + <FileName>OAuth2\Messages\EndUserAuthorizationSuccessAuthCodeResponse.cs</FileName> + </TypeIdentifier> + <Lollipop Position="0.2" /> + </Class> + <Class Name="DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationSuccessResponseBase" Collapsed="true"> + <Position X="3.25" Y="1.5" Width="2.75" /> + <TypeIdentifier> + <HashCode>AAACAAAAAAAAACAAAAAAAAgAAAAAAAAAAEAAAAAAAAA=</HashCode> + <FileName>OAuth2\Messages\EndUserAuthorizationSuccessResponseBase.cs</FileName> + </TypeIdentifier> + <Lollipop Position="0.2" /> + </Class> + <Class Name="DotNetOpenAuth.OAuth2.Messages.AccessProtectedResourceRequest" Collapsed="true"> + <Position X="3.25" Y="9.75" Width="2.5" /> + <TypeIdentifier> + <HashCode>AAAAEAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAgAAAABgA=</HashCode> + <FileName>OAuth2\Messages\AccessProtectedResourceRequest.cs</FileName> + </TypeIdentifier> + <Lollipop Position="0.2" /> + </Class> + <Class Name="DotNetOpenAuth.OAuth2.Messages.UnauthorizedResponse" Collapsed="true"> + <Position X="3.25" Y="10.75" Width="2" /> + <TypeIdentifier> + <HashCode>AUABAAAAAAAAACAAAAAAAAQIAAAAAAAQAAAAAAAAABA=</HashCode> + <FileName>OAuth2\Messages\UnauthorizedResponse.cs</FileName> + </TypeIdentifier> + <Lollipop Position="0.2" /> + </Class> + <Class Name="DotNetOpenAuth.OAuth2.Messages.ScopedAccessTokenRequest" Collapsed="true"> + <Position X="6.75" Y="7.75" Width="2.25" /> + <TypeIdentifier> + <HashCode>AAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAACAA=</HashCode> + <FileName>OAuth2\Messages\ScopedAccessTokenRequest.cs</FileName> + </TypeIdentifier> + </Class> + <Interface Name="DotNetOpenAuth.OAuth2.Messages.IMessageWithClientState"> + <Position X="11.5" Y="0.5" Width="2" /> + <TypeIdentifier> + <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAA=</HashCode> + <FileName>OAuth2\Messages\IMessageWithClientState.cs</FileName> + </TypeIdentifier> + </Interface> + <Interface Name="DotNetOpenAuth.OAuth2.ChannelElements.IAuthorizationCarryingRequest"> + <Position X="11.75" Y="2" Width="2.5" /> + <TypeIdentifier> + <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAEAAAAA=</HashCode> + <FileName>OAuth2\ChannelElements\IAuthorizationCarryingRequest.cs</FileName> + </TypeIdentifier> + </Interface> + <Enum Name="DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationResponseType"> + <Position X="8" Y="0.5" Width="3" /> + <TypeIdentifier> + <HashCode>ACAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAA=</HashCode> + <FileName>OAuth2\Messages\EndUserAuthorizationResponseType.cs</FileName> + </TypeIdentifier> + </Enum> + <Enum Name="DotNetOpenAuth.OAuth2.Messages.GrantType"> + <Position X="6.25" Y="0.5" Width="1.5" /> + <TypeIdentifier> + <HashCode>ACAAAAAAQAAAAAQAAgAAAAAAAAAAAAACAAAAAAAAAAA=</HashCode> + <FileName>OAuth2\Messages\GrantType.cs</FileName> + </TypeIdentifier> + </Enum> + <Font Name="Segoe UI" Size="9" /> +</ClassDiagram>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/ScopedAccessTokenRequest.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/ScopedAccessTokenRequest.cs new file mode 100644 index 0000000..5568b1c --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/ScopedAccessTokenRequest.cs @@ -0,0 +1,41 @@ +//----------------------------------------------------------------------- +// <copyright file="ScopedAccessTokenRequest.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.Messages { + using System; + using System.Collections.Generic; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth2.ChannelElements; + + /// <summary> + /// An access token request that includes a scope parameter. + /// </summary> + internal abstract class ScopedAccessTokenRequest : AccessTokenRequestBase { + /// <summary> + /// Initializes a new instance of the <see cref="ScopedAccessTokenRequest"/> class. + /// </summary> + /// <param name="tokenEndpoint">The Authorization Server's access token endpoint URL.</param> + /// <param name="version">The version.</param> + internal ScopedAccessTokenRequest(Uri tokenEndpoint, Version version) + : base(tokenEndpoint, version) { + this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer); + } + + /// <summary> + /// Gets the set of scopes the Client would like the access token to provide access to. + /// </summary> + /// <value>A set of scopes. Never null.</value> + [MessagePart(Protocol.scope, IsRequired = false, Encoder = typeof(ScopeEncoder))] + internal HashSet<string> Scope { get; private set; } + + /// <summary> + /// Gets the scope of operations the client is allowed to invoke. + /// </summary> + protected override HashSet<string> RequestedScope { + get { return this.Scope; } + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/UnauthorizedResponse.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/UnauthorizedResponse.cs new file mode 100644 index 0000000..d79c00b --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/UnauthorizedResponse.cs @@ -0,0 +1,115 @@ +//----------------------------------------------------------------------- +// <copyright file="UnauthorizedResponse.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2.Messages { + using System; + using System.Diagnostics.Contracts; + using System.Net; + using System.Text; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// A direct response that is simply a 401 Unauthorized with an + /// WWW-Authenticate: OAuth header. + /// </summary> + internal class UnauthorizedResponse : MessageBase, IHttpDirectResponse { + /// <summary> + /// Initializes a new instance of the <see cref="UnauthorizedResponse"/> class. + /// </summary> + /// <param name="exception">The exception.</param> + /// <param name="version">The protocol version.</param> + internal UnauthorizedResponse(ProtocolException exception, Version version = null) + : base(version ?? Protocol.Default.Version) { + Contract.Requires<ArgumentNullException>(exception != null); + this.ErrorMessage = exception.Message; + } + + /// <summary> + /// Initializes a new instance of the <see cref="UnauthorizedResponse"/> class. + /// </summary> + /// <param name="request">The request.</param> + internal UnauthorizedResponse(IDirectedProtocolMessage request) + : base(request) { + this.Realm = "Service"; + } + + /// <summary> + /// Initializes a new instance of the <see cref="UnauthorizedResponse"/> class. + /// </summary> + /// <param name="request">The request.</param> + /// <param name="exception">The exception.</param> + internal UnauthorizedResponse(IDirectedProtocolMessage request, ProtocolException exception) + : this(request) { + Contract.Requires<ArgumentNullException>(exception != null); + this.ErrorMessage = exception.Message; + } + + #region IHttpDirectResponse Members + + /// <summary> + /// Gets the HTTP status code that the direct response should be sent with. + /// </summary> + HttpStatusCode IHttpDirectResponse.HttpStatusCode { + get { return HttpStatusCode.Unauthorized; } + } + + /// <summary> + /// Gets the HTTP headers to add to the response. + /// </summary> + /// <value>May be an empty collection, but must not be <c>null</c>.</value> + WebHeaderCollection IHttpDirectResponse.Headers { + get { + return new WebHeaderCollection() { + { HttpResponseHeader.WwwAuthenticate, Protocol.BearerHttpAuthorizationScheme }, + }; + } + } + + #endregion + + /// <summary> + /// Gets or sets the error message. + /// </summary> + /// <value>The error message.</value> + [MessagePart("error")] + internal string ErrorMessage { get; set; } + + /// <summary> + /// Gets or sets the realm. + /// </summary> + /// <value>The realm.</value> + [MessagePart("realm")] + internal string Realm { get; set; } + + /// <summary> + /// Gets or sets the scope. + /// </summary> + /// <value>The scope.</value> + [MessagePart("scope")] + internal string Scope { get; set; } + + /// <summary> + /// Gets or sets the algorithms. + /// </summary> + /// <value>The algorithms.</value> + [MessagePart("algorithms")] + internal string Algorithms { get; set; } + + /// <summary> + /// Gets or sets the user endpoint. + /// </summary> + /// <value>The user endpoint.</value> + [MessagePart("user-uri")] + internal Uri UserEndpoint { get; set; } + + /// <summary> + /// Gets or sets the token endpoint. + /// </summary> + /// <value>The token endpoint.</value> + [MessagePart("token-uri")] + internal Uri TokenEndpoint { get; set; } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/OAuth 2 client facades.cd b/src/DotNetOpenAuth.OAuth2/OAuth2/OAuth 2 client facades.cd new file mode 100644 index 0000000..97bf2eb --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/OAuth 2 client facades.cd @@ -0,0 +1,31 @@ +<?xml version="1.0" encoding="utf-8"?> +<ClassDiagram MajorVersion="1" MinorVersion="1"> + <Class Name="DotNetOpenAuth.OAuth2.ClientBase"> + <Position X="0.5" Y="0.5" Width="3.5" /> + <TypeIdentifier> + <HashCode>AAACAAAwAEAAAAAAAgAAAIEAAAwAAAAAAAAAAAAAAAA=</HashCode> + <FileName>OAuth2\ClientBase.cs</FileName> + </TypeIdentifier> + </Class> + <Class Name="DotNetOpenAuth.OAuth2.WebServerClient"> + <Position X="4.5" Y="0.5" Width="3.5" /> + <TypeIdentifier> + <HashCode>AAAAAQAAAAAAEAAAAAAABAAAAAAAAAAAAAAAAAABAAA=</HashCode> + <FileName>OAuth2\WebServerClient.cs</FileName> + </TypeIdentifier> + </Class> + <Class Name="DotNetOpenAuth.OAuth2.UserAgentClient"> + <Position X="4.5" Y="3" Width="3.5" /> + <InheritanceLine Type="DotNetOpenAuth.OAuth2.ClientBase" FixedFromPoint="true"> + <Path> + <Point X="4" Y="3.166" /> + <Point X="4.5" Y="3.166" /> + </Path> + </InheritanceLine> + <TypeIdentifier> + <HashCode>AAAAAAAAAAAAEAAAAAAABAAAAAAAAAAAAAAAAAAAAAA=</HashCode> + <FileName>OAuth2\UserAgentClient.cs</FileName> + </TypeIdentifier> + </Class> + <Font Name="Segoe UI" Size="9" /> +</ClassDiagram>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthStrings.Designer.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthStrings.Designer.cs new file mode 100644 index 0000000..9ea12ab --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthStrings.Designer.cs @@ -0,0 +1,144 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by a tool. +// Runtime Version:4.0.30319.225 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// </auto-generated> +//------------------------------------------------------------------------------ + +namespace DotNetOpenAuth.OAuth2 { + using System; + + + /// <summary> + /// A strongly-typed resource class, for looking up localized strings, etc. + /// </summary> + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class OAuthStrings { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal OAuthStrings() { + } + + /// <summary> + /// Returns the cached ResourceManager instance used by this class. + /// </summary> + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DotNetOpenAuth.OAuth2.OAuthStrings", typeof(OAuthStrings).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// <summary> + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// </summary> + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// <summary> + /// Looks up a localized string similar to The value for message part "{0}" must be an absolute URI.. + /// </summary> + internal static string AbsoluteUriRequired { + get { + return ResourceManager.GetString("AbsoluteUriRequired", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to The requested access scope ("{0}") exceeds the grant scope ("{1}").. + /// </summary> + internal static string AccessScopeExceedsGrantScope { + get { + return ResourceManager.GetString("AccessScopeExceedsGrantScope", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to Failed to obtain access token. Authorization Server reports reason: {0}. + /// </summary> + internal static string CannotObtainAccessTokenWithReason { + get { + return ResourceManager.GetString("CannotObtainAccessTokenWithReason", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to The callback URL ({0}) is not allowed for this client.. + /// </summary> + internal static string ClientCallbackDisallowed { + get { + return ResourceManager.GetString("ClientCallbackDisallowed", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to This message can only be sent over HTTPS.. + /// </summary> + internal static string HttpsRequired { + get { + return ResourceManager.GetString("HttpsRequired", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to Failed to obtain access token due to invalid Client Identifier or Client Secret.. + /// </summary> + internal static string InvalidClientCredentials { + get { + return ResourceManager.GetString("InvalidClientCredentials", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to No callback URI was available for this request.. + /// </summary> + internal static string NoCallback { + get { + return ResourceManager.GetString("NoCallback", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to Refresh tokens should not be granted without the request including an access grant.. + /// </summary> + internal static string NoGrantNoRefreshToken { + get { + return ResourceManager.GetString("NoGrantNoRefreshToken", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to Individual scopes may not contain spaces.. + /// </summary> + internal static string ScopesMayNotContainSpaces { + get { + return ResourceManager.GetString("ScopesMayNotContainSpaces", resourceCulture); + } + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthStrings.resx b/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthStrings.resx new file mode 100644 index 0000000..fc2f2d2 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthStrings.resx @@ -0,0 +1,147 @@ +<?xml version="1.0" encoding="utf-8"?> +<root> + <!-- + Microsoft ResX Schema + + Version 2.0 + + The primary goals of this format is to allow a simple XML format + that is mostly human readable. The generation and parsing of the + various data types are done through the TypeConverter classes + associated with the data types. + + Example: + + ... ado.net/XML headers & schema ... + <resheader name="resmimetype">text/microsoft-resx</resheader> + <resheader name="version">2.0</resheader> + <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> + <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> + <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> + <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> + <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> + <value>[base64 mime encoded serialized .NET Framework object]</value> + </data> + <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> + <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> + <comment>This is a comment</comment> + </data> + + There are any number of "resheader" rows that contain simple + name/value pairs. + + Each data row contains a name, and value. The row also contains a + type or mimetype. Type corresponds to a .NET class that support + text/value conversion through the TypeConverter architecture. + Classes that don't support this are serialized and stored with the + mimetype set. + + The mimetype is used for serialized objects, and tells the + ResXResourceReader how to depersist the object. This is currently not + extensible. For a given mimetype the value must be set accordingly: + + Note - application/x-microsoft.net.object.binary.base64 is the format + that the ResXResourceWriter will generate, however the reader can + read any of the formats listed below. + + mimetype: application/x-microsoft.net.object.binary.base64 + value : The object must be serialized with + : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter + : and then encoded with base64 encoding. + + mimetype: application/x-microsoft.net.object.soap.base64 + value : The object must be serialized with + : System.Runtime.Serialization.Formatters.Soap.SoapFormatter + : and then encoded with base64 encoding. + + mimetype: application/x-microsoft.net.object.bytearray.base64 + value : The object must be serialized into a byte array + : using a System.ComponentModel.TypeConverter + : and then encoded with base64 encoding. + --> + <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> + <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> + <xsd:element name="root" msdata:IsDataSet="true"> + <xsd:complexType> + <xsd:choice maxOccurs="unbounded"> + <xsd:element name="metadata"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" /> + </xsd:sequence> + <xsd:attribute name="name" use="required" type="xsd:string" /> + <xsd:attribute name="type" type="xsd:string" /> + <xsd:attribute name="mimetype" type="xsd:string" /> + <xsd:attribute ref="xml:space" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="assembly"> + <xsd:complexType> + <xsd:attribute name="alias" type="xsd:string" /> + <xsd:attribute name="name" type="xsd:string" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="data"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> + <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> + <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> + <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> + <xsd:attribute ref="xml:space" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="resheader"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" use="required" /> + </xsd:complexType> + </xsd:element> + </xsd:choice> + </xsd:complexType> + </xsd:element> + </xsd:schema> + <resheader name="resmimetype"> + <value>text/microsoft-resx</value> + </resheader> + <resheader name="version"> + <value>2.0</value> + </resheader> + <resheader name="reader"> + <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> + </resheader> + <resheader name="writer"> + <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> + </resheader> + <data name="AbsoluteUriRequired" xml:space="preserve"> + <value>The value for message part "{0}" must be an absolute URI.</value> + </data> + <data name="AccessScopeExceedsGrantScope" xml:space="preserve"> + <value>The requested access scope ("{0}") exceeds the grant scope ("{1}").</value> + </data> + <data name="CannotObtainAccessTokenWithReason" xml:space="preserve"> + <value>Failed to obtain access token. Authorization Server reports reason: {0}</value> + </data> + <data name="ClientCallbackDisallowed" xml:space="preserve"> + <value>The callback URL ({0}) is not allowed for this client.</value> + </data> + <data name="HttpsRequired" xml:space="preserve"> + <value>This message can only be sent over HTTPS.</value> + </data> + <data name="InvalidClientCredentials" xml:space="preserve"> + <value>Failed to obtain access token due to invalid Client Identifier or Client Secret.</value> + </data> + <data name="NoCallback" xml:space="preserve"> + <value>No callback URI was available for this request.</value> + </data> + <data name="NoGrantNoRefreshToken" xml:space="preserve"> + <value>Refresh tokens should not be granted without the request including an access grant.</value> + </data> + <data name="ScopesMayNotContainSpaces" xml:space="preserve"> + <value>Individual scopes may not contain spaces.</value> + </data> +</root>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthUtilities.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthUtilities.cs new file mode 100644 index 0000000..c2b2f5f --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthUtilities.cs @@ -0,0 +1,123 @@ +//----------------------------------------------------------------------- +// <copyright file="OAuthUtilities.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2 { + using System; + using System.Collections.Generic; + using System.Diagnostics.Contracts; + using System.Globalization; + using System.Linq; + using System.Net; + using System.Text; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// Some common utility methods for OAuth 2.0. + /// </summary> + public static class OAuthUtilities { + /// <summary> + /// The <see cref="StringComparer"/> instance to use when comparing scope equivalence. + /// </summary> + public static readonly StringComparer ScopeStringComparer = StringComparer.Ordinal; + + /// <summary> + /// The delimiter between scope elements. + /// </summary> + private static char[] scopeDelimiter = new char[] { ' ' }; + + /// <summary> + /// The characters that may appear in an access token that is included in an HTTP Authorization header. + /// </summary> + /// <remarks> + /// This is defined in OAuth 2.0 DRAFT 10, section 5.1.1. (http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#authz-header) + /// </remarks> + private static string accessTokenAuthorizationHeaderAllowedCharacters = MessagingUtilities.UppercaseLetters + + MessagingUtilities.LowercaseLetters + + MessagingUtilities.Digits + + @"!#$%&'()*+-./:<=>?@[]^_`{|}~\,;"; + + /// <summary> + /// Determines whether one given scope is a subset of another scope. + /// </summary> + /// <param name="requestedScope">The requested scope, which may be a subset of <paramref name="grantedScope"/>.</param> + /// <param name="grantedScope">The granted scope, the suspected superset.</param> + /// <returns> + /// <c>true</c> if all the elements that appear in <paramref name="requestedScope"/> also appear in <paramref name="grantedScope"/>; + /// <c>false</c> otherwise. + /// </returns> + public static bool IsScopeSubset(string requestedScope, string grantedScope) { + if (string.IsNullOrEmpty(requestedScope)) { + return true; + } + + if (string.IsNullOrEmpty(grantedScope)) { + return false; + } + + var requestedScopes = new HashSet<string>(requestedScope.Split(scopeDelimiter, StringSplitOptions.RemoveEmptyEntries)); + var grantedScopes = new HashSet<string>(grantedScope.Split(scopeDelimiter, StringSplitOptions.RemoveEmptyEntries)); + return requestedScopes.IsSubsetOf(grantedScopes); + } + + /// <summary> + /// Identifies individual scope elements + /// </summary> + /// <param name="scope">The space-delimited list of scopes.</param> + /// <returns>A set of individual scopes, with any duplicates removed.</returns> + public static HashSet<string> SplitScopes(string scope) { + if (string.IsNullOrEmpty(scope)) { + return new HashSet<string>(); + } + + return new HashSet<string>(scope.Split(scopeDelimiter, StringSplitOptions.RemoveEmptyEntries), ScopeStringComparer); + } + + /// <summary> + /// Serializes a set of scopes as a space-delimited list. + /// </summary> + /// <param name="scopes">The scopes to serialize.</param> + /// <returns>A space-delimited list.</returns> + public static string JoinScopes(HashSet<string> scopes) { + Contract.Requires<ArgumentNullException>(scopes != null); + return string.Join(" ", scopes.ToArray()); + } + + /// <summary> + /// Authorizes an HTTP request using an OAuth 2.0 access token in an HTTP Authorization header. + /// </summary> + /// <param name="request">The request to authorize.</param> + /// <param name="accessToken">The access token previously obtained from the Authorization Server.</param> + internal static void AuthorizeWithBearerToken(this HttpWebRequest request, string accessToken) { + Contract.Requires<ArgumentNullException>(request != null); + Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(accessToken)); + ErrorUtilities.VerifyProtocol(accessToken.All(ch => accessTokenAuthorizationHeaderAllowedCharacters.IndexOf(ch) >= 0), "The access token contains characters that must not appear in the HTTP Authorization header."); + + request.Headers[HttpRequestHeader.Authorization] = string.Format( + CultureInfo.InvariantCulture, + Protocol.BearerHttpAuthorizationHeaderFormat, + accessToken); + } + + /// <summary> + /// Gets information about the client with a given identifier. + /// </summary> + /// <param name="authorizationServer">The authorization server.</param> + /// <param name="clientIdentifier">The client identifier.</param> + /// <returns>The client information. Never null.</returns> + internal static IConsumerDescription GetClientOrThrow(this IAuthorizationServer authorizationServer, string clientIdentifier) { + Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(clientIdentifier)); + Contract.Ensures(Contract.Result<IConsumerDescription>() != null); + + try { + return authorizationServer.GetClient(clientIdentifier); + } catch (KeyNotFoundException ex) { + throw ErrorUtilities.Wrap(ex, OAuth.OAuthStrings.ConsumerOrTokenSecretNotFound); + } catch (ArgumentException ex) { + throw ErrorUtilities.Wrap(ex, OAuth.OAuthStrings.ConsumerOrTokenSecretNotFound); + } + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Protocol.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Protocol.cs new file mode 100644 index 0000000..3cb8253 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Protocol.cs @@ -0,0 +1,355 @@ +// <auto-generated/> // disable StyleCop on this file +//----------------------------------------------------------------------- +// <copyright file="Protocol.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2 { + using System; + using System.Collections.Generic; + + /// <summary> + /// An enumeration of the OAuth protocol versions supported by this library. + /// </summary> + public enum ProtocolVersion { + /// <summary> + /// The OAuth 2.0 specification. + /// </summary> + V20, + } + + /// <summary> + /// Protocol constants for OAuth 2.0. + /// </summary> + internal class Protocol { + /// <summary> + /// The HTTP authorization scheme "Bearer"; + /// </summary> + internal const string BearerHttpAuthorizationScheme = "Bearer"; + + /// <summary> + /// The HTTP authorization scheme "Bearer "; + /// </summary> + internal const string BearerHttpAuthorizationSchemeWithTrailingSpace = BearerHttpAuthorizationScheme + " "; + + /// <summary> + /// The format of the HTTP Authorization header value that authorizes OAuth 2.0 requests using bearer access tokens. + /// </summary> + internal const string BearerHttpAuthorizationHeaderFormat = BearerHttpAuthorizationSchemeWithTrailingSpace + "{0}"; + + /// <summary> + /// The name of the parameter whose value is an OAuth 2.0 bearer access token, as it is defined + /// in a URL-encoded POST entity or URL query string. + /// </summary> + internal const string BearerTokenEncodedUrlParameterName = "access_token"; + + /// <summary> + /// The "type" string. + /// </summary> + internal const string type = "type"; + + /// <summary> + /// The "state" string. + /// </summary> + internal const string state = "state"; + + /// <summary> + /// The "redirect_uri_mismatch" string. + /// </summary> + internal const string redirect_uri_mismatch = "redirect_uri_mismatch"; + + /// <summary> + /// The "bad_verification_code" string. + /// </summary> + internal const string bad_verification_code = "bad_verification_code"; + + /// <summary> + /// The "incorrect_client_credentials" string. + /// </summary> + internal const string incorrect_client_credentials = "incorrect_client_credentials"; + + /// <summary> + /// The "unauthorized_client" string. + /// </summary> + internal const string unauthorized_client = "unauthorized_client"; + + /// <summary> + /// The "authorization_expired" string. + /// </summary> + internal const string authorization_expired = "authorization_expired"; + + /// <summary> + /// The "redirect_uri" string. + /// </summary> + internal const string redirect_uri = "redirect_uri"; + + /// <summary> + /// The "client_id" string. + /// </summary> + internal const string client_id = "client_id"; + + /// <summary> + /// The "scope" string. + /// </summary> + internal const string scope = "scope"; + + /// <summary> + /// The "immediate" string. + /// </summary> + internal const string immediate = "immediate"; + + /// <summary> + /// The "client_secret" string. + /// </summary> + internal const string client_secret = "client_secret"; + + /// <summary> + /// The "code" string. + /// </summary> + internal const string code = "code"; + + /// <summary> + /// The "user_code" string. + /// </summary> + internal const string user_code = "user_code"; + + /// <summary> + /// The "verification_uri" string. + /// </summary> + internal const string verification_uri = "verification_uri"; + + /// <summary> + /// The "interval" string. + /// </summary> + internal const string interval = "interval"; + + /// <summary> + /// The "error" string. + /// </summary> + internal const string error = "error"; + + /// <summary> + /// The "access_token" string. + /// </summary> + internal const string access_token = "access_token"; + + /// <summary> + /// The "access_token_secret" string. + /// </summary> + internal const string access_token_secret = "access_token_secret"; + + /// <summary> + /// The "token_type" string. + /// </summary> + internal const string token_type = "token_type"; + + /// <summary> + /// The "refresh_token" string. + /// </summary> + internal const string refresh_token = "refresh_token"; + + /// <summary> + /// The "expires_in" string. + /// </summary> + internal const string expires_in = "expires_in"; + + /// <summary> + /// The "expired_delegation_code" string. + /// </summary> + internal const string expired_delegation_code = "expired_delegation_code"; + + /// <summary> + /// The "username" string. + /// </summary> + internal const string username = "username"; + + /// <summary> + /// The "password" string. + /// </summary> + internal const string password = "password"; + + /// <summary> + /// The "format" string. + /// </summary> + internal const string format = "format"; + + /// <summary> + /// The "assertion" string. + /// </summary> + internal const string assertion = "assertion"; + + /// <summary> + /// The "assertion_type" string. + /// </summary> + internal const string assertion_type = "assertion_type"; + + /// <summary> + /// The "user_denied" string. + /// </summary> + internal const string user_denied = "user_denied"; + + /// <summary> + /// Gets the <see cref="Protocol"/> instance with values initialized for V1.0 of the protocol. + /// </summary> + internal static readonly Protocol V20 = new Protocol { + Version = new Version(2, 0), + ProtocolVersion = ProtocolVersion.V20, + }; + + /// <summary> + /// A list of all supported OAuth versions, in order starting from newest version. + /// </summary> + internal static readonly List<Protocol> AllVersions = new List<Protocol>() { V20 }; + + /// <summary> + /// The default (or most recent) supported version of the OpenID protocol. + /// </summary> + internal static readonly Protocol Default = AllVersions[0]; + + /// <summary> + /// The "error_uri" string. + /// </summary> + public const string error_uri = "error_uri"; + + /// <summary> + /// The "error_description" string. + /// </summary> + internal const string error_description = "error_description"; + + /// <summary> + /// The "response_type" string. + /// </summary> + internal const string response_type = "response_type"; + + /// <summary> + /// The "grant_type" string. + /// </summary> + internal const string grant_type = "grant_type"; + + /// <summary> + /// Gets or sets the OAuth 2.0 version represented by this instance. + /// </summary> + /// <value>The version.</value> + internal Version Version { get; private set; } + + /// <summary> + /// Gets or sets the OAuth 2.0 version represented by this instance. + /// </summary> + /// <value>The protocol version.</value> + internal ProtocolVersion ProtocolVersion { get; private set; } + + /// <summary> + /// Gets the OAuth Protocol instance to use for the given version. + /// </summary> + /// <param name="version">The OAuth version to get.</param> + /// <returns>A matching <see cref="Protocol"/> instance.</returns> + public static Protocol Lookup(ProtocolVersion version) { + switch (version) { + case ProtocolVersion.V20: return Protocol.V20; + default: throw new ArgumentOutOfRangeException("version"); + } + } + + /// <summary> + /// Values for the "response_type" parameter. + /// </summary> + internal static class ResponseTypes + { + /// <summary> + /// The string "code". + /// </summary> + internal const string Code = "code"; + + /// <summary> + /// The string "token". + /// </summary> + internal const string Token = "token"; + } + + internal static class GrantTypes + { + internal const string AuthorizationCode = "authorization_code"; + + internal const string Password = "password"; + + internal const string Assertion = "assertion"; + + internal const string RefreshToken = "refresh_token"; + + internal const string ClientCredentials = "client_credentials"; + } + + /// <summary> + /// Error codes that an authorization server can return to a client in response to a malformed or unsupported access token request. + /// </summary> + internal static class AccessTokenRequestErrorCodes + { + /// <summary> + /// The request is missing a required parameter, includes an unknown parameter or parameter value, repeats a parameter, includes multiple credentials, utilizes more than one mechanism for authenticating the client, or is otherwise malformed. + /// </summary> + internal const string InvalidRequest = "invalid_request"; + + /// <summary> + /// The client is not authorized to use the access grant type provided. + /// </summary> + internal const string UnauthorizedClient = "unauthorized_client"; + + /// <summary> + /// The resource owner or authorization server denied the request. + /// </summary> + internal const string AccessDenied = "access_denied"; + + /// <summary> + /// The authorization server does not support obtaining an access token using this method. + /// </summary> + internal const string UnsupportedGrantType = "unsupported_response_type"; + + /// <summary> + /// The requested scope is invalid, unknown, malformed, or exceeds the previously granted scope. + /// </summary> + internal const string InvalidScope = "invalid_scope"; + } + + /// <summary> + /// Error codes that an authorization server can return to a client in response to a malformed or unsupported end user authorization request. + /// </summary> + internal static class EndUserAuthorizationRequestErrorCodes + { + /// <summary> + /// The request is missing a required parameter, includes an unknown parameter or parameter value, or is otherwise malformed. + /// </summary> + internal const string InvalidRequest = "invalid_request"; + + /// <summary> + /// The client is not authorized to use the requested response type. + /// </summary> + internal const string UnauthorizedClient = "unauthorized_client"; + + /// <summary> + /// The end-user or authorization server denied the request. + /// </summary> + internal const string AccessDenied = "access_denied"; + + /// <summary> + /// The requested response type is not supported by the authorization server. + /// </summary> + internal const string UnsupportedResponseType = "unsupported_response_type"; + + /// <summary> + /// The requested scope is invalid, unknown, or malformed. + /// </summary> + internal const string InvalidScope = "invalid_scope"; + } + + /// <summary> + /// Recognized access token types. + /// </summary> + internal static class AccessTokenTypes { + /// <summary> + /// The "bearer" token type. + /// </summary> + internal const string Bearer = "bearer"; + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ResourceServer.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ResourceServer.cs new file mode 100644 index 0000000..a5baef0 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ResourceServer.cs @@ -0,0 +1,136 @@ +//----------------------------------------------------------------------- +// <copyright file="ResourceServer.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2 { + using System; + using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; + using System.Diagnostics.Contracts; + using System.Linq; + using System.Net; + using System.Security.Principal; + using System.ServiceModel.Channels; + using System.Text; + using System.Text.RegularExpressions; + using System.Web; + using ChannelElements; + using Messages; + using Messaging; + + /// <summary> + /// Provides services for validating OAuth access tokens. + /// </summary> + public class ResourceServer { + /// <summary> + /// Initializes a new instance of the <see cref="ResourceServer"/> class. + /// </summary> + /// <param name="accessTokenAnalyzer">The access token analyzer.</param> + public ResourceServer(IAccessTokenAnalyzer accessTokenAnalyzer) { + Contract.Requires<ArgumentNullException>(accessTokenAnalyzer != null); + + this.AccessTokenAnalyzer = accessTokenAnalyzer; + this.Channel = new OAuth2ResourceServerChannel(); + } + + /// <summary> + /// Gets the access token analyzer. + /// </summary> + /// <value>The access token analyzer.</value> + public IAccessTokenAnalyzer AccessTokenAnalyzer { get; private set; } + + /// <summary> + /// Gets the channel. + /// </summary> + /// <value>The channel.</value> + internal OAuth2ResourceServerChannel Channel { get; private set; } + + /// <summary> + /// Discovers what access the client should have considering the access token in the current request. + /// </summary> + /// <param name="userName">The name on the account the client has access to.</param> + /// <param name="scope">The set of operations the client is authorized for.</param> + /// <returns>An error to return to the client if access is not authorized; <c>null</c> if access is granted.</returns> + [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Try pattern")] + [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#", Justification = "Try pattern")] + public OutgoingWebResponse VerifyAccess(out string userName, out HashSet<string> scope) { + return this.VerifyAccess(this.Channel.GetRequestFromContext(), out userName, out scope); + } + + /// <summary> + /// Discovers what access the client should have considering the access token in the current request. + /// </summary> + /// <param name="httpRequestInfo">The HTTP request info.</param> + /// <param name="userName">The name on the account the client has access to.</param> + /// <param name="scope">The set of operations the client is authorized for.</param> + /// <returns> + /// An error to return to the client if access is not authorized; <c>null</c> if access is granted. + /// </returns> + [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#", Justification = "Try pattern")] + [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification = "Try pattern")] + public virtual OutgoingWebResponse VerifyAccess(HttpRequestInfo httpRequestInfo, out string userName, out HashSet<string> scope) { + Contract.Requires<ArgumentNullException>(httpRequestInfo != null); + + AccessProtectedResourceRequest request = null; + try { + if (this.Channel.TryReadFromRequest<AccessProtectedResourceRequest>(httpRequestInfo, out request)) { + if (this.AccessTokenAnalyzer.TryValidateAccessToken(request, request.AccessToken, out userName, out scope)) { + // No errors to return. + return null; + } + + throw ErrorUtilities.ThrowProtocol("Bad access token"); + } else { + var response = new UnauthorizedResponse(new ProtocolException("Missing access token")); + + userName = null; + scope = null; + return this.Channel.PrepareResponse(response); + } + } catch (ProtocolException ex) { + var response = request != null ? new UnauthorizedResponse(request, ex) : new UnauthorizedResponse(ex); + + userName = null; + scope = null; + return this.Channel.PrepareResponse(response); + } + } + + /// <summary> + /// Discovers what access the client should have considering the access token in the current request. + /// </summary> + /// <param name="httpRequestInfo">The HTTP request info.</param> + /// <param name="principal">The principal that contains the user and roles that the access token is authorized for.</param> + /// <returns> + /// An error to return to the client if access is not authorized; <c>null</c> if access is granted. + /// </returns> + [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#", Justification = "Try pattern")] + public virtual OutgoingWebResponse VerifyAccess(HttpRequestInfo httpRequestInfo, out IPrincipal principal) { + string username; + HashSet<string> scope; + var result = this.VerifyAccess(httpRequestInfo, out username, out scope); + principal = result == null ? new OAuth.ChannelElements.OAuthPrincipal(username, scope != null ? scope.ToArray() : new string[0]) : null; + return result; + } + + /// <summary> + /// Discovers what access the client should have considering the access token in the current request. + /// </summary> + /// <param name="request">HTTP details from an incoming WCF message.</param> + /// <param name="requestUri">The URI of the WCF service endpoint.</param> + /// <param name="principal">The principal that contains the user and roles that the access token is authorized for.</param> + /// <returns> + /// An error to return to the client if access is not authorized; <c>null</c> if access is granted. + /// </returns> + [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#", Justification = "Try pattern")] + [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification = "Try pattern")] + public virtual OutgoingWebResponse VerifyAccess(HttpRequestMessageProperty request, Uri requestUri, out IPrincipal principal) { + Contract.Requires<ArgumentNullException>(request != null); + Contract.Requires<ArgumentNullException>(requestUri != null); + + return this.VerifyAccess(new HttpRequestInfo(request, requestUri), out principal); + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/StandardAccessTokenAnalyzer.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/StandardAccessTokenAnalyzer.cs new file mode 100644 index 0000000..1f59e52 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/StandardAccessTokenAnalyzer.cs @@ -0,0 +1,66 @@ +//----------------------------------------------------------------------- +// <copyright file="StandardAccessTokenAnalyzer.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2 { + using System; + using System.Collections.Generic; + using System.Diagnostics.Contracts; + using System.Security.Cryptography; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth2.ChannelElements; + + /// <summary> + /// An access token reader that understands DotNetOpenAuth authorization server issued tokens. + /// </summary> + public class StandardAccessTokenAnalyzer : IAccessTokenAnalyzer { + /// <summary> + /// Initializes a new instance of the <see cref="StandardAccessTokenAnalyzer"/> class. + /// </summary> + /// <param name="authorizationServerPublicSigningKey">The crypto service provider with the authorization server public signing key.</param> + /// <param name="resourceServerPrivateEncryptionKey">The crypto service provider with the resource server private encryption key.</param> + public StandardAccessTokenAnalyzer(RSACryptoServiceProvider authorizationServerPublicSigningKey, RSACryptoServiceProvider resourceServerPrivateEncryptionKey) { + Contract.Requires<ArgumentNullException>(authorizationServerPublicSigningKey != null); + Contract.Requires<ArgumentNullException>(resourceServerPrivateEncryptionKey != null); + Contract.Requires<ArgumentException>(!resourceServerPrivateEncryptionKey.PublicOnly); + this.AuthorizationServerPublicSigningKey = authorizationServerPublicSigningKey; + this.ResourceServerPrivateEncryptionKey = resourceServerPrivateEncryptionKey; + } + + /// <summary> + /// Gets the authorization server public signing key. + /// </summary> + /// <value>The authorization server public signing key.</value> + public RSACryptoServiceProvider AuthorizationServerPublicSigningKey { get; private set; } + + /// <summary> + /// Gets the resource server private encryption key. + /// </summary> + /// <value>The resource server private encryption key.</value> + public RSACryptoServiceProvider ResourceServerPrivateEncryptionKey { get; private set; } + + /// <summary> + /// Reads an access token to find out what data it authorizes access to. + /// </summary> + /// <param name="message">The message carrying the access token.</param> + /// <param name="accessToken">The access token.</param> + /// <param name="user">The user whose data is accessible with this access token.</param> + /// <param name="scope">The scope of access authorized by this access token.</param> + /// <returns> + /// A value indicating whether this access token is valid. + /// </returns> + /// <remarks> + /// This method also responsible to throw a <see cref="ProtocolException"/> or return + /// <c>false</c> when the access token is expired, invalid, or from an untrusted authorization server. + /// </remarks> + public virtual bool TryValidateAccessToken(IDirectedProtocolMessage message, string accessToken, out string user, out HashSet<string> scope) { + var accessTokenFormatter = AccessToken.CreateFormatter(this.AuthorizationServerPublicSigningKey, this.ResourceServerPrivateEncryptionKey); + var token = accessTokenFormatter.Deserialize(message, accessToken); + user = token.User; + scope = new HashSet<string>(token.Scope, OAuthUtilities.ScopeStringComparer); + return true; + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/UserAgentClient.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/UserAgentClient.cs new file mode 100644 index 0000000..e23eca4 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/UserAgentClient.cs @@ -0,0 +1,123 @@ +//----------------------------------------------------------------------- +// <copyright file="UserAgentClient.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2 { + using System; + using System.Collections.Generic; + using System.Diagnostics.Contracts; + using System.Linq; + using System.Text; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth2.Messages; + + /// <summary> + /// The OAuth client for the user-agent flow, providing services for installed apps + /// and in-browser Javascript widgets. + /// </summary> + public class UserAgentClient : ClientBase { + /// <summary> + /// Initializes a new instance of the <see cref="UserAgentClient"/> class. + /// </summary> + /// <param name="authorizationServer">The token issuer.</param> + /// <param name="clientIdentifier">The client identifier.</param> + /// <param name="clientSecret">The client secret.</param> + public UserAgentClient(AuthorizationServerDescription authorizationServer, string clientIdentifier = null, string clientSecret = null) + : base(authorizationServer, clientIdentifier, clientSecret) { + } + + /// <summary> + /// Initializes a new instance of the <see cref="UserAgentClient"/> class. + /// </summary> + /// <param name="authorizationEndpoint">The authorization endpoint.</param> + /// <param name="tokenEndpoint">The token endpoint.</param> + /// <param name="clientIdentifier">The client identifier.</param> + /// <param name="clientSecret">The client secret.</param> + public UserAgentClient(Uri authorizationEndpoint, Uri tokenEndpoint, string clientIdentifier = null, string clientSecret = null) + : this(new AuthorizationServerDescription { AuthorizationEndpoint = authorizationEndpoint, TokenEndpoint = tokenEndpoint }, clientIdentifier, clientSecret) { + Contract.Requires<ArgumentNullException>(authorizationEndpoint != null); + Contract.Requires<ArgumentNullException>(tokenEndpoint != null); + } + + /// <summary> + /// Generates a URL that the user's browser can be directed to in order to authorize + /// this client to access protected data at some resource server. + /// </summary> + /// <param name="scope">The scope of authorized access requested.</param> + /// <param name="state">The client state that should be returned with the authorization response.</param> + /// <param name="returnTo">The URL that the authorization response should be sent to via a user-agent redirect.</param> + /// <returns> + /// A fully-qualified URL suitable to initiate the authorization flow. + /// </returns> + public Uri RequestUserAuthorization(IEnumerable<string> scope = null, string state = null, Uri returnTo = null) { + var authorization = new AuthorizationState(scope) { + Callback = returnTo, + }; + + return this.RequestUserAuthorization(authorization); + } + + /// <summary> + /// Generates a URL that the user's browser can be directed to in order to authorize + /// this client to access protected data at some resource server. + /// </summary> + /// <param name="authorization">The authorization state that is tracking this particular request. Optional.</param> + /// <param name="state">The client state that should be returned with the authorization response.</param> + /// <returns> + /// A fully-qualified URL suitable to initiate the authorization flow. + /// </returns> + public Uri RequestUserAuthorization(IAuthorizationState authorization, string state = null) { + Contract.Requires<ArgumentNullException>(authorization != null); + Contract.Requires<InvalidOperationException>(!string.IsNullOrEmpty(this.ClientIdentifier)); + + if (authorization.Callback == null) { + authorization.Callback = new Uri("http://localhost/"); + } + + var request = new EndUserAuthorizationRequest(this.AuthorizationServer) { + ClientIdentifier = this.ClientIdentifier, + Callback = authorization.Callback, + ClientState = state, + }; + request.Scope.ResetContents(authorization.Scope); + + return this.Channel.PrepareResponse(request).GetDirectUriRequest(this.Channel); + } + + /// <summary> + /// Scans the incoming request for an authorization response message. + /// </summary> + /// <param name="actualRedirectUrl">The actual URL of the incoming HTTP request.</param> + /// <param name="authorizationState">The authorization.</param> + /// <returns>The granted authorization, or <c>null</c> if the incoming HTTP request did not contain an authorization server response or authorization was rejected.</returns> + public IAuthorizationState ProcessUserAuthorization(Uri actualRedirectUrl, IAuthorizationState authorizationState = null) { + Contract.Requires<ArgumentNullException>(actualRedirectUrl != null); + + if (authorizationState == null) { + authorizationState = new AuthorizationState(); + } + + var carrier = new HttpRequestInfo("GET", actualRedirectUrl, actualRedirectUrl.PathAndQuery, new System.Net.WebHeaderCollection(), null); + IDirectedProtocolMessage response = this.Channel.ReadFromRequest(carrier); + if (response == null) { + return null; + } + + EndUserAuthorizationSuccessAccessTokenResponse accessTokenSuccess; + EndUserAuthorizationSuccessAuthCodeResponse authCodeSuccess; + EndUserAuthorizationFailedResponse failure; + if ((accessTokenSuccess = response as EndUserAuthorizationSuccessAccessTokenResponse) != null) { + UpdateAuthorizationWithResponse(authorizationState, accessTokenSuccess); + } else if ((authCodeSuccess = response as EndUserAuthorizationSuccessAuthCodeResponse) != null) { + this.UpdateAuthorizationWithResponse(authorizationState, authCodeSuccess); + } else if ((failure = response as EndUserAuthorizationFailedResponse) != null) { + authorizationState.Delete(); + return null; + } + + return authorizationState; + } + } +} diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/WebServerClient.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/WebServerClient.cs new file mode 100644 index 0000000..a6fae13 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/WebServerClient.cs @@ -0,0 +1,130 @@ +//----------------------------------------------------------------------- +// <copyright file="WebServerClient.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth2 { + using System; + using System.Collections.Generic; + using System.Diagnostics.Contracts; + using System.Linq; + using System.Net; + using System.Text; + using System.Web; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth2.Messages; + + /// <summary> + /// An OAuth 2.0 consumer designed for web applications. + /// </summary> + public class WebServerClient : ClientBase { + /// <summary> + /// Initializes a new instance of the <see cref="WebServerClient"/> class. + /// </summary> + /// <param name="authorizationServer">The authorization server.</param> + /// <param name="clientIdentifier">The client identifier.</param> + /// <param name="clientSecret">The client secret.</param> + public WebServerClient(AuthorizationServerDescription authorizationServer, string clientIdentifier = null, string clientSecret = null) + : base(authorizationServer, clientIdentifier, clientSecret) { + } + + /// <summary> + /// Gets or sets an optional component that gives you greater control to record and influence the authorization process. + /// </summary> + /// <value>The authorization tracker.</value> + public IClientAuthorizationTracker AuthorizationTracker { get; set; } + + /// <summary> + /// Prepares a request for user authorization from an authorization server. + /// </summary> + /// <param name="scope">The scope of authorized access requested.</param> + /// <param name="state">The state of the client that should be sent back with the authorization response.</param> + /// <param name="returnTo">The URL the authorization server should redirect the browser (typically on this site) to when the authorization is completed. If null, the current request's URL will be used.</param> + public void RequestUserAuthorization(IEnumerable<string> scope = null, string state = null, Uri returnTo = null) { + var authorizationState = new AuthorizationState(scope) { + Callback = returnTo, + }; + this.PrepareRequestUserAuthorization(authorizationState, state).Respond(); + } + + /// <summary> + /// Prepares a request for user authorization from an authorization server. + /// </summary> + /// <param name="scopes">The scope of authorized access requested.</param> + /// <param name="state">The state of the client that should be sent back with the authorization response.</param> + /// <returns>The authorization request.</returns> + public OutgoingWebResponse PrepareRequestUserAuthorization(IEnumerable<string> scopes = null, string state = null) { + var authorizationState = new AuthorizationState(scopes); + return this.PrepareRequestUserAuthorization(authorizationState, state); + } + + /// <summary> + /// Prepares a request for user authorization from an authorization server. + /// </summary> + /// <param name="authorization">The authorization state to associate with this particular request.</param> + /// <param name="state">The state of the client that should be sent back with the authorization response.</param> + /// <returns>The authorization request.</returns> + public OutgoingWebResponse PrepareRequestUserAuthorization(IAuthorizationState authorization, string state = null) { + 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<OutgoingWebResponse>() != null); + + if (authorization.Callback == null) { + authorization.Callback = this.Channel.GetRequestFromContext().UrlBeforeRewriting + .StripMessagePartsFromQueryString(this.Channel.MessageDescriptions.Get(typeof(EndUserAuthorizationSuccessResponseBase), Protocol.Default.Version)) + .StripMessagePartsFromQueryString(this.Channel.MessageDescriptions.Get(typeof(EndUserAuthorizationFailedResponse), Protocol.Default.Version)); + authorization.SaveChanges(); + } + + var request = new EndUserAuthorizationRequest(this.AuthorizationServer) { + ClientIdentifier = this.ClientIdentifier, + Callback = authorization.Callback, + ClientState = state, + }; + request.Scope.ResetContents(authorization.Scope); + + return this.Channel.PrepareResponse(request); + } + + /// <summary> + /// Processes the authorization response from an authorization server, if available. + /// </summary> + /// <param name="request">The incoming HTTP request that may carry an authorization response.</param> + /// <returns>The authorization state that contains the details of the authorization.</returns> + public IAuthorizationState ProcessUserAuthorization(HttpRequestInfo request = null) { + Contract.Requires<InvalidOperationException>(!string.IsNullOrEmpty(this.ClientIdentifier)); + Contract.Requires<InvalidOperationException>(!string.IsNullOrEmpty(this.ClientSecret)); + + if (request == null) { + request = this.Channel.GetRequestFromContext(); + } + + IMessageWithClientState response; + if (this.Channel.TryReadFromRequest<IMessageWithClientState>(request, out response)) { + Uri callback = MessagingUtilities.StripMessagePartsFromQueryString(request.UrlBeforeRewriting, this.Channel.MessageDescriptions.Get(response)); + IAuthorizationState authorizationState; + if (this.AuthorizationTracker != null) { + authorizationState = this.AuthorizationTracker.GetAuthorizationState(callback, response.ClientState); + ErrorUtilities.VerifyProtocol(authorizationState != null, "Unexpected OAuth authorization response received with callback and client state that does not match an expected value."); + } else { + authorizationState = new AuthorizationState { Callback = callback }; + } + var success = response as EndUserAuthorizationSuccessAuthCodeResponse; + var failure = response as EndUserAuthorizationFailedResponse; + ErrorUtilities.VerifyProtocol(success != null || failure != null, MessagingStrings.UnexpectedMessageReceivedOfMany); + if (success != null) { + this.UpdateAuthorizationWithResponse(authorizationState, success); + } else { // failure + Logger.OAuth.Info("User refused to grant the requested authorization at the Authorization Server."); + authorizationState.Delete(); + } + + return authorizationState; + } + + return null; + } + } +} |