diff options
Diffstat (limited to 'samples/ServiceProvider/App_Code')
6 files changed, 349 insertions, 349 deletions
diff --git a/samples/ServiceProvider/App_Code/Constants.cs b/samples/ServiceProvider/App_Code/Constants.cs index 4adfd13..7780e96 100644 --- a/samples/ServiceProvider/App_Code/Constants.cs +++ b/samples/ServiceProvider/App_Code/Constants.cs @@ -1,30 +1,30 @@ -using System;
-using DotNetOAuth.Messaging;
-using DotNetOAuth.OAuth;
-using DotNetOAuth.OAuth.ChannelElements;
-
-/// <summary>
-/// Service Provider definitions.
-/// </summary>
-public static class Constants {
- public static Uri WebRootUrl { get; set; }
-
- public static ServiceProviderDescription SelfDescription {
- get {
- ServiceProviderDescription description = new ServiceProviderDescription {
- AccessTokenEndpoint = new MessageReceivingEndpoint(new Uri(WebRootUrl, "/OAuth.ashx"), HttpDeliveryMethods.PostRequest),
- RequestTokenEndpoint = new MessageReceivingEndpoint(new Uri(WebRootUrl, "/OAuth.ashx"), HttpDeliveryMethods.PostRequest),
- UserAuthorizationEndpoint = new MessageReceivingEndpoint(new Uri(WebRootUrl, "/OAuth.ashx"), HttpDeliveryMethods.PostRequest),
- TamperProtectionElements = new ITamperProtectionChannelBindingElement[] {
- new HmacSha1SigningBindingElement(),
- },
- };
-
- return description;
- }
- }
-
- public static ServiceProvider CreateServiceProvider() {
- return new ServiceProvider(SelfDescription, Global.TokenManager);
- }
-}
+using System; +using DotNetOpenAuth.Messaging; +using DotNetOpenAuth.OAuth; +using DotNetOpenAuth.OAuth.ChannelElements; + +/// <summary> +/// Service Provider definitions. +/// </summary> +public static class Constants { + public static Uri WebRootUrl { get; set; } + + public static ServiceProviderDescription SelfDescription { + get { + ServiceProviderDescription description = new ServiceProviderDescription { + AccessTokenEndpoint = new MessageReceivingEndpoint(new Uri(WebRootUrl, "/OAuth.ashx"), HttpDeliveryMethods.PostRequest), + RequestTokenEndpoint = new MessageReceivingEndpoint(new Uri(WebRootUrl, "/OAuth.ashx"), HttpDeliveryMethods.PostRequest), + UserAuthorizationEndpoint = new MessageReceivingEndpoint(new Uri(WebRootUrl, "/OAuth.ashx"), HttpDeliveryMethods.PostRequest), + TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { + new HmacSha1SigningBindingElement(), + }, + }; + + return description; + } + } + + public static ServiceProvider CreateServiceProvider() { + return new ServiceProvider(SelfDescription, Global.TokenManager); + } +} diff --git a/samples/ServiceProvider/App_Code/CustomOAuthTypeProvider.cs b/samples/ServiceProvider/App_Code/CustomOAuthTypeProvider.cs index 7adb808..0fd1ed5 100644 --- a/samples/ServiceProvider/App_Code/CustomOAuthTypeProvider.cs +++ b/samples/ServiceProvider/App_Code/CustomOAuthTypeProvider.cs @@ -1,30 +1,30 @@ -using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Web;
-using DotNetOAuth.OAuth.ChannelElements;
-using DotNetOAuth.OAuth.Messages;
-
-/// <summary>
-/// A custom class that will cause the OAuth library to use our custom message types
-/// where we have them.
-/// </summary>
-public class CustomOAuthTypeProvider : OAuthServiceProviderMessageTypeProvider {
- /// <summary>
- /// Initializes a new instance of the <see cref="CustomOAuthTypeProvider"/> class.
- /// </summary>
- /// <param name="tokenManager">The token manager instance to use.</param>
- public CustomOAuthTypeProvider(ITokenManager tokenManager) : base(tokenManager) {
- }
-
- public override Type GetRequestMessageType(IDictionary<string, string> fields) {
- Type type = base.GetRequestMessageType(fields);
-
- // inject our own type here to replace the standard one
- if (type == typeof(UnauthorizedTokenRequest)) {
- type = typeof(RequestScopedTokenMessage);
- }
-
- return type;
- }
-}
+using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using DotNetOpenAuth.OAuth.ChannelElements; +using DotNetOpenAuth.OAuth.Messages; + +/// <summary> +/// A custom class that will cause the OAuth library to use our custom message types +/// where we have them. +/// </summary> +public class CustomOAuthTypeProvider : OAuthServiceProviderMessageTypeProvider { + /// <summary> + /// Initializes a new instance of the <see cref="CustomOAuthTypeProvider"/> class. + /// </summary> + /// <param name="tokenManager">The token manager instance to use.</param> + public CustomOAuthTypeProvider(ITokenManager tokenManager) : base(tokenManager) { + } + + public override Type GetRequestMessageType(IDictionary<string, string> fields) { + Type type = base.GetRequestMessageType(fields); + + // inject our own type here to replace the standard one + if (type == typeof(UnauthorizedTokenRequest)) { + type = typeof(RequestScopedTokenMessage); + } + + return type; + } +} diff --git a/samples/ServiceProvider/App_Code/DatabaseTokenManager.cs b/samples/ServiceProvider/App_Code/DatabaseTokenManager.cs index 3a567fd..b5d8fdd 100644 --- a/samples/ServiceProvider/App_Code/DatabaseTokenManager.cs +++ b/samples/ServiceProvider/App_Code/DatabaseTokenManager.cs @@ -1,118 +1,118 @@ -//-----------------------------------------------------------------------
-// <copyright file="DatabaseTokenManager.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Linq;
-using DotNetOAuth.OAuth.ChannelElements;
-using DotNetOAuth.OAuth.Messages;
-
-public class DatabaseTokenManager : ITokenManager {
- #region ITokenManager Members
-
- public string GetConsumerSecret(string consumerKey) {
- var consumerRow = Global.DataContext.OAuthConsumers.SingleOrDefault(
- consumerCandidate => consumerCandidate.ConsumerKey == consumerKey);
- if (consumerRow == null) {
- throw new ArgumentException();
- }
-
- return consumerRow.ConsumerSecret;
- }
-
- public string GetTokenSecret(string token) {
- var tokenRow = Global.DataContext.OAuthTokens.SingleOrDefault(
- tokenCandidate => tokenCandidate.Token == token);
- if (tokenRow == null) {
- throw new ArgumentException();
- }
-
- return tokenRow.TokenSecret;
- }
-
- public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response) {
- RequestScopedTokenMessage scopedRequest = (RequestScopedTokenMessage)request;
- var consumer = Global.DataContext.OAuthConsumers.Single(consumerRow => consumerRow.ConsumerKey == request.ConsumerKey);
- string scope = scopedRequest.Scope;
- OAuthToken newToken = new OAuthToken {
- OAuthConsumer = consumer,
- Token = response.Token,
- TokenSecret = response.TokenSecret,
- IssueDate = DateTime.UtcNow,
- Scope = scope,
- };
-
- Global.DataContext.OAuthTokens.InsertOnSubmit(newToken);
- }
-
- /// <summary>
- /// Checks whether a given request token has already been authorized
- /// by some user for use by the Consumer that requested it.
- /// </summary>
- /// <param name="requestToken">The Consumer's request token.</param>
- /// <returns>
- /// True if the request token has already been fully authorized by the user
- /// who owns the relevant protected resources. False if the token has not yet
- /// been authorized, has expired or does not exist.
- /// </returns>
- public bool IsRequestTokenAuthorized(string requestToken) {
- var tokenFound = Global.DataContext.OAuthTokens.SingleOrDefault(
- token => token.Token == requestToken &&
- token.State == TokenAuthorizationState.AuthorizedRequestToken);
- return tokenFound != null;
- }
-
- public void ExpireRequestTokenAndStoreNewAccessToken(string consumerKey, string requestToken, string accessToken, string accessTokenSecret) {
- var data = Global.DataContext;
- var consumerRow = data.OAuthConsumers.Single(consumer => consumer.ConsumerKey == consumerKey);
- var tokenRow = data.OAuthTokens.Single(token => token.Token == requestToken && token.OAuthConsumer == consumerRow);
- Debug.Assert(tokenRow.State == TokenAuthorizationState.AuthorizedRequestToken, "The token should be authorized already!");
-
- // Update the existing row to be an access token.
- tokenRow.IssueDate = DateTime.UtcNow;
- tokenRow.State = TokenAuthorizationState.AccessToken;
- tokenRow.Token = accessToken;
- tokenRow.TokenSecret = accessTokenSecret;
- }
-
- /// <summary>
- /// Classifies a token as a request token or an access token.
- /// </summary>
- /// <param name="token">The token to classify.</param>
- /// <returns>Request or Access token, or invalid if the token is not recognized.</returns>
- public TokenType GetTokenType(string token) {
- var tokenRow = Global.DataContext.OAuthTokens.SingleOrDefault(tokenCandidate => tokenCandidate.Token == token);
- if (tokenRow == null) {
- return TokenType.InvalidToken;
- } else if (tokenRow.State == TokenAuthorizationState.AccessToken) {
- return TokenType.AccessToken;
- } else {
- return TokenType.RequestToken;
- }
- }
-
- #endregion
-
- public void AuthorizeRequestToken(string requestToken, User user) {
- if (requestToken == null) {
- throw new ArgumentNullException("requestToken");
- }
- if (user == null) {
- throw new ArgumentNullException("user");
- }
-
- var tokenRow = Global.DataContext.OAuthTokens.SingleOrDefault(
- tokenCandidate => tokenCandidate.Token == requestToken &&
- tokenCandidate.State == TokenAuthorizationState.UnauthorizedRequestToken);
- if (tokenRow == null) {
- throw new ArgumentException();
- }
-
- tokenRow.State = TokenAuthorizationState.AuthorizedRequestToken;
- tokenRow.User = user;
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="DatabaseTokenManager.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using DotNetOpenAuth.OAuth.ChannelElements; +using DotNetOpenAuth.OAuth.Messages; + +public class DatabaseTokenManager : ITokenManager { + #region ITokenManager Members + + public string GetConsumerSecret(string consumerKey) { + var consumerRow = Global.DataContext.OAuthConsumers.SingleOrDefault( + consumerCandidate => consumerCandidate.ConsumerKey == consumerKey); + if (consumerRow == null) { + throw new ArgumentException(); + } + + return consumerRow.ConsumerSecret; + } + + public string GetTokenSecret(string token) { + var tokenRow = Global.DataContext.OAuthTokens.SingleOrDefault( + tokenCandidate => tokenCandidate.Token == token); + if (tokenRow == null) { + throw new ArgumentException(); + } + + return tokenRow.TokenSecret; + } + + public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response) { + RequestScopedTokenMessage scopedRequest = (RequestScopedTokenMessage)request; + var consumer = Global.DataContext.OAuthConsumers.Single(consumerRow => consumerRow.ConsumerKey == request.ConsumerKey); + string scope = scopedRequest.Scope; + OAuthToken newToken = new OAuthToken { + OAuthConsumer = consumer, + Token = response.Token, + TokenSecret = response.TokenSecret, + IssueDate = DateTime.UtcNow, + Scope = scope, + }; + + Global.DataContext.OAuthTokens.InsertOnSubmit(newToken); + } + + /// <summary> + /// Checks whether a given request token has already been authorized + /// by some user for use by the Consumer that requested it. + /// </summary> + /// <param name="requestToken">The Consumer's request token.</param> + /// <returns> + /// True if the request token has already been fully authorized by the user + /// who owns the relevant protected resources. False if the token has not yet + /// been authorized, has expired or does not exist. + /// </returns> + public bool IsRequestTokenAuthorized(string requestToken) { + var tokenFound = Global.DataContext.OAuthTokens.SingleOrDefault( + token => token.Token == requestToken && + token.State == TokenAuthorizationState.AuthorizedRequestToken); + return tokenFound != null; + } + + public void ExpireRequestTokenAndStoreNewAccessToken(string consumerKey, string requestToken, string accessToken, string accessTokenSecret) { + var data = Global.DataContext; + var consumerRow = data.OAuthConsumers.Single(consumer => consumer.ConsumerKey == consumerKey); + var tokenRow = data.OAuthTokens.Single(token => token.Token == requestToken && token.OAuthConsumer == consumerRow); + Debug.Assert(tokenRow.State == TokenAuthorizationState.AuthorizedRequestToken, "The token should be authorized already!"); + + // Update the existing row to be an access token. + tokenRow.IssueDate = DateTime.UtcNow; + tokenRow.State = TokenAuthorizationState.AccessToken; + tokenRow.Token = accessToken; + tokenRow.TokenSecret = accessTokenSecret; + } + + /// <summary> + /// Classifies a token as a request token or an access token. + /// </summary> + /// <param name="token">The token to classify.</param> + /// <returns>Request or Access token, or invalid if the token is not recognized.</returns> + public TokenType GetTokenType(string token) { + var tokenRow = Global.DataContext.OAuthTokens.SingleOrDefault(tokenCandidate => tokenCandidate.Token == token); + if (tokenRow == null) { + return TokenType.InvalidToken; + } else if (tokenRow.State == TokenAuthorizationState.AccessToken) { + return TokenType.AccessToken; + } else { + return TokenType.RequestToken; + } + } + + #endregion + + public void AuthorizeRequestToken(string requestToken, User user) { + if (requestToken == null) { + throw new ArgumentNullException("requestToken"); + } + if (user == null) { + throw new ArgumentNullException("user"); + } + + var tokenRow = Global.DataContext.OAuthTokens.SingleOrDefault( + tokenCandidate => tokenCandidate.Token == requestToken && + tokenCandidate.State == TokenAuthorizationState.UnauthorizedRequestToken); + if (tokenRow == null) { + throw new ArgumentException(); + } + + tokenRow.State = TokenAuthorizationState.AuthorizedRequestToken; + tokenRow.User = user; + } +} diff --git a/samples/ServiceProvider/App_Code/Global.cs b/samples/ServiceProvider/App_Code/Global.cs index 9ece43c..b343dcd 100644 --- a/samples/ServiceProvider/App_Code/Global.cs +++ b/samples/ServiceProvider/App_Code/Global.cs @@ -1,114 +1,114 @@ -using System;
-using System.Linq;
-using System.ServiceModel;
-using System.Text;
-using System.Web;
-using DotNetOAuth.OAuth.Messages;
-
-/// <summary>
-/// The web application global events and properties.
-/// </summary>
-public class Global : HttpApplication {
- /// <summary>
- /// An application memory cache of recent log messages.
- /// </summary>
- public static StringBuilder LogMessages = new StringBuilder();
-
- /// <summary>
- /// The logger for this sample to use.
- /// </summary>
- public static log4net.ILog Logger = log4net.LogManager.GetLogger("DotNetOAuth.ConsumerSample");
-
- /// <summary>
- /// Gets the transaction-protected database connection for the current request.
- /// </summary>
- public static DataClassesDataContext DataContext {
- get {
- DataClassesDataContext dataContext = dataContextSimple;
- if (dataContext == null) {
- dataContext = new DataClassesDataContext();
- dataContext.Connection.Open();
- dataContext.Transaction = dataContext.Connection.BeginTransaction();
- dataContextSimple = dataContext;
- }
-
- return dataContext;
- }
- }
-
- public static DatabaseTokenManager TokenManager { get; set; }
-
- public static User LoggedInUser {
- get { return Global.DataContext.Users.SingleOrDefault(user => user.OpenIDClaimedIdentifier == HttpContext.Current.User.Identity.Name); }
- }
-
- public static UserAuthorizationRequest PendingOAuthAuthorization {
- get { return HttpContext.Current.Session["authrequest"] as UserAuthorizationRequest; }
- set { HttpContext.Current.Session["authrequest"] = value; }
- }
-
- private static DataClassesDataContext dataContextSimple {
- get {
- if (HttpContext.Current != null) {
- return HttpContext.Current.Items["DataContext"] as DataClassesDataContext;
- } else if (OperationContext.Current != null) {
- object data;
- if (OperationContext.Current.IncomingMessageProperties.TryGetValue("DataContext", out data)) {
- return data as DataClassesDataContext;
- } else {
- return null;
- }
- } else {
- throw new InvalidOperationException();
- }
- }
-
- set {
- if (HttpContext.Current != null) {
- HttpContext.Current.Items["DataContext"] = value;
- } else if (OperationContext.Current != null) {
- OperationContext.Current.IncomingMessageProperties["DataContext"] = value;
- } else {
- throw new InvalidOperationException();
- }
- }
- }
-
- public static void AuthorizePendingRequestToken() {
- ITokenContainingMessage tokenMessage = PendingOAuthAuthorization;
- TokenManager.AuthorizeRequestToken(tokenMessage.Token, LoggedInUser);
- PendingOAuthAuthorization = null;
- }
-
- private static void CommitAndCloseDatabaseIfNecessary() {
- var dataContext = dataContextSimple;
- if (dataContext != null) {
- dataContext.SubmitChanges();
- dataContext.Transaction.Commit();
- dataContext.Connection.Close();
- }
- }
-
- private void Application_Start(object sender, EventArgs e) {
- log4net.Config.XmlConfigurator.Configure();
- Logger.Info("Sample starting...");
- Constants.WebRootUrl = new Uri(HttpContext.Current.Request.Url, "/");
- var tokenManager = new DatabaseTokenManager();
- Global.TokenManager = tokenManager;
- }
-
- private void Application_End(object sender, EventArgs e) {
- Logger.Info("Sample shutting down...");
-
- // this would be automatic, but in partial trust scenarios it is not.
- log4net.LogManager.Shutdown();
- }
-
- private void Application_Error(object sender, EventArgs e) {
- Logger.Error("An unhandled exception occurred in ASP.NET processing: " + Server.GetLastError(), Server.GetLastError());
- }
-
- private void Application_EndRequest(object sender, EventArgs e) {
- CommitAndCloseDatabaseIfNecessary();
- }
-}
+using System; +using System.Linq; +using System.ServiceModel; +using System.Text; +using System.Web; +using DotNetOpenAuth.OAuth.Messages; + +/// <summary> +/// The web application global events and properties. +/// </summary> +public class Global : HttpApplication { + /// <summary> + /// An application memory cache of recent log messages. + /// </summary> + public static StringBuilder LogMessages = new StringBuilder(); + + /// <summary> + /// The logger for this sample to use. + /// </summary> + public static log4net.ILog Logger = log4net.LogManager.GetLogger("DotNetOpenAuth.ConsumerSample"); + + /// <summary> + /// Gets the transaction-protected database connection for the current request. + /// </summary> + public static DataClassesDataContext DataContext { + get { + DataClassesDataContext dataContext = dataContextSimple; + if (dataContext == null) { + dataContext = new DataClassesDataContext(); + dataContext.Connection.Open(); + dataContext.Transaction = dataContext.Connection.BeginTransaction(); + dataContextSimple = dataContext; + } + + return dataContext; + } + } + + public static DatabaseTokenManager TokenManager { get; set; } + + public static User LoggedInUser { + get { return Global.DataContext.Users.SingleOrDefault(user => user.OpenIDClaimedIdentifier == HttpContext.Current.User.Identity.Name); } + } + + public static UserAuthorizationRequest PendingOAuthAuthorization { + get { return HttpContext.Current.Session["authrequest"] as UserAuthorizationRequest; } + set { HttpContext.Current.Session["authrequest"] = value; } + } + + private static DataClassesDataContext dataContextSimple { + get { + if (HttpContext.Current != null) { + return HttpContext.Current.Items["DataContext"] as DataClassesDataContext; + } else if (OperationContext.Current != null) { + object data; + if (OperationContext.Current.IncomingMessageProperties.TryGetValue("DataContext", out data)) { + return data as DataClassesDataContext; + } else { + return null; + } + } else { + throw new InvalidOperationException(); + } + } + + set { + if (HttpContext.Current != null) { + HttpContext.Current.Items["DataContext"] = value; + } else if (OperationContext.Current != null) { + OperationContext.Current.IncomingMessageProperties["DataContext"] = value; + } else { + throw new InvalidOperationException(); + } + } + } + + public static void AuthorizePendingRequestToken() { + ITokenContainingMessage tokenMessage = PendingOAuthAuthorization; + TokenManager.AuthorizeRequestToken(tokenMessage.Token, LoggedInUser); + PendingOAuthAuthorization = null; + } + + private static void CommitAndCloseDatabaseIfNecessary() { + var dataContext = dataContextSimple; + if (dataContext != null) { + dataContext.SubmitChanges(); + dataContext.Transaction.Commit(); + dataContext.Connection.Close(); + } + } + + private void Application_Start(object sender, EventArgs e) { + log4net.Config.XmlConfigurator.Configure(); + Logger.Info("Sample starting..."); + Constants.WebRootUrl = new Uri(HttpContext.Current.Request.Url, "/"); + var tokenManager = new DatabaseTokenManager(); + Global.TokenManager = tokenManager; + } + + private void Application_End(object sender, EventArgs e) { + Logger.Info("Sample shutting down..."); + + // this would be automatic, but in partial trust scenarios it is not. + log4net.LogManager.Shutdown(); + } + + private void Application_Error(object sender, EventArgs e) { + Logger.Error("An unhandled exception occurred in ASP.NET processing: " + Server.GetLastError(), Server.GetLastError()); + } + + private void Application_EndRequest(object sender, EventArgs e) { + CommitAndCloseDatabaseIfNecessary(); + } +} diff --git a/samples/ServiceProvider/App_Code/OAuthAuthorizationManager.cs b/samples/ServiceProvider/App_Code/OAuthAuthorizationManager.cs index 8188c67..fce1ad4 100644 --- a/samples/ServiceProvider/App_Code/OAuthAuthorizationManager.cs +++ b/samples/ServiceProvider/App_Code/OAuthAuthorizationManager.cs @@ -1,37 +1,37 @@ -using System;
-using System.Linq;
-using System.ServiceModel;
-using System.ServiceModel.Channels;
-using DotNetOAuth;
-using DotNetOAuth.OAuth;
-
-/// <summary>
-/// A WCF extension to authenticate incoming messages using OAuth.
-/// </summary>
-public class OAuthAuthorizationManager : ServiceAuthorizationManager {
- public OAuthAuthorizationManager() {
- }
-
- protected override bool CheckAccessCore(OperationContext operationContext) {
- if (!base.CheckAccessCore(operationContext)) {
- return false;
- }
-
- HttpRequestMessageProperty httpDetails = operationContext.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
- Uri requestUri = operationContext.RequestContext.RequestMessage.Properties["OriginalHttpRequestUri"] as Uri;
- ServiceProvider sp = Constants.CreateServiceProvider();
- var auth = sp.ReadProtectedResourceAuthorization(httpDetails, requestUri);
- if (auth != null) {
- var accessToken = Global.DataContext.OAuthTokens.Single(token => token.Token == auth.AccessToken);
-
- // Only allow this method call if the access token scope permits it.
- string[] scopes = accessToken.Scope.Split('|');
- if (scopes.Contains(operationContext.IncomingMessageHeaders.Action)) {
- operationContext.IncomingMessageProperties["OAuthAccessToken"] = accessToken;
- return true;
- }
- }
-
- return false;
- }
-}
+using System; +using System.Linq; +using System.ServiceModel; +using System.ServiceModel.Channels; +using DotNetOpenAuth; +using DotNetOpenAuth.OAuth; + +/// <summary> +/// A WCF extension to authenticate incoming messages using OAuth. +/// </summary> +public class OAuthAuthorizationManager : ServiceAuthorizationManager { + public OAuthAuthorizationManager() { + } + + protected override bool CheckAccessCore(OperationContext operationContext) { + if (!base.CheckAccessCore(operationContext)) { + return false; + } + + HttpRequestMessageProperty httpDetails = operationContext.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty; + Uri requestUri = operationContext.RequestContext.RequestMessage.Properties["OriginalHttpRequestUri"] as Uri; + ServiceProvider sp = Constants.CreateServiceProvider(); + var auth = sp.ReadProtectedResourceAuthorization(httpDetails, requestUri); + if (auth != null) { + var accessToken = Global.DataContext.OAuthTokens.Single(token => token.Token == auth.AccessToken); + + // Only allow this method call if the access token scope permits it. + string[] scopes = accessToken.Scope.Split('|'); + if (scopes.Contains(operationContext.IncomingMessageHeaders.Action)) { + operationContext.IncomingMessageProperties["OAuthAccessToken"] = accessToken; + return true; + } + } + + return false; + } +} diff --git a/samples/ServiceProvider/App_Code/RequestScopedTokenMessage.cs b/samples/ServiceProvider/App_Code/RequestScopedTokenMessage.cs index 7459653..b33a734 100644 --- a/samples/ServiceProvider/App_Code/RequestScopedTokenMessage.cs +++ b/samples/ServiceProvider/App_Code/RequestScopedTokenMessage.cs @@ -1,20 +1,20 @@ -using DotNetOAuth.Messaging;
-using DotNetOAuth.OAuth.Messages;
-
-/// <summary>
-/// A custom web app version of the message sent to request an unauthorized token.
-/// </summary>
-public class RequestScopedTokenMessage : UnauthorizedTokenRequest {
- /// <summary>
- /// Initializes a new instance of the <see cref="RequestScopedTokenMessage"/> class.
- /// </summary>
- /// <param name="endpoint">The endpoint that will receive the message.</param>
- public RequestScopedTokenMessage(MessageReceivingEndpoint endpoint) : base(endpoint) {
- }
-
- /// <summary>
- /// Gets or sets the scope of the access being requested.
- /// </summary>
- [MessagePart("scope", IsRequired = true)]
- public string Scope { get; set; }
-}
+using DotNetOpenAuth.Messaging; +using DotNetOpenAuth.OAuth.Messages; + +/// <summary> +/// A custom web app version of the message sent to request an unauthorized token. +/// </summary> +public class RequestScopedTokenMessage : UnauthorizedTokenRequest { + /// <summary> + /// Initializes a new instance of the <see cref="RequestScopedTokenMessage"/> class. + /// </summary> + /// <param name="endpoint">The endpoint that will receive the message.</param> + public RequestScopedTokenMessage(MessageReceivingEndpoint endpoint) : base(endpoint) { + } + + /// <summary> + /// Gets or sets the scope of the access being requested. + /// </summary> + [MessagePart("scope", IsRequired = true)] + public string Scope { get; set; } +} |