OAuth in C# as a client - c#

I've been given 6 bits of information to access some data from a website:
Website Json Url (eg: http://somesite.com/items/list.json)
OAuth Authorization Url (eg: http://somesite.com/oauth/authorization)
OAuth Request Url (eg: http://somesite.com/oauth/request)
OAuth Access Url (eg: http://somesite.com/oauth/access)
Client Key (eg: 12345678)
Client Secret (eg: abcdefghijklmnop)
Now, I've looked at DotNetOpenAuth and OAuth.NET libraries, and while I'm sure they are very capable of doing what I need, I just can't figure out how to use either in this way.
Could someone post some sample code of how to consume the Url (Point 1.) in either library (or any other way that may work just as well)?
Thanks!

I also just started working with OAuth a month ago and was also confused by all these libraries. One thing I realized about these libraries is that they're quite complicated (as you have found out). Another thing that makes it hard is that there wasn't a lot of example (it was worse in my case because I was trying to implement a Provider and not a Client).
Originally, I wanted to use the latest OAuth 2.0 but the only .NET library out there that implements it is DotNetOpenAuth. It's probably one of the most complete .NET OAuth library out there but it'll take too long for me to understand (due to not knowing WCF, MVC, etc). I have since downgraded to OAuth 1.0a because I found these examples for DevDefined OAuth. I don't know about you but I found it easier to learn from examples.
It looks like you only want to implement a Client so make sure to look at the Consumer examples. Try to compile the examples and ignore the Provider examples because you don't need them and it'll make you more confused. Be patient. If you're still confused, it might be a good idea to look at some of the libraries made for other languages as they might have easier to understand documentations.

OK, I know your last post was months ago, but in case you were still working on this (or for people like me who would have loved to see an answer to this question), here's some information regarding the NullReferenceException you encountered creating the OAuth request:
The null reference comes from the IServiceLocator that is used to resolve dependencies. If you don't explicitly pass one into the constructor, it uses the static property ServiceLocator.Current in the Microsoft.Practices.ServiceLocation namespace.
This is one of the many pitfalls of using static methods and global state, is you hide issues like this from the consumer of your API. So if you haven't specified a default service locator, then null is returned, resulting in the NullReferenceException.
So to fix this issue, I wired up an implementation of IServiceLocator that uses StructureMap (one of the many IoC containers available) as the container. Lastly, you will need to register instances for two interfaces: ISigningProvider and INonceProvider. Luckily, several standard implementations exist in the OAuth.Net.Components assembly, such as GuidNonceProvider and HmacSha1SigningProvider.
The resulting code looks like something like this:
var container = new Container();
container.Configure(a => a.For<INonceProvider>().Use<GuidNonceProvider>());
container.Configure(a => a.For<ISigningProvider>()
.Use<HmacSha1SigningProvider>()
.Named("signing.provider:HMAC-SHA1"));
var locator = new StructureMapAdapter(container);
ServiceLocator.SetLocatorProvider(delegate { return locator; });
I realize this isn't the final solution to your original question (I'm still working on getting it working myself), but I hope it gets you a few steps further. And if you've long abandoned this implementation altogether... well, happy coding anyway!

For OAuth 2.0:
I learned that it's easiest to just put up the authentication page in an HTML window then trap the returned access_token. You can then do that using in client-side web browser.
For example, in MonoTouch it would be:
//
// Present the authentication page to the user
//
var authUrl = "http://www.example.com/authenticate";
_borwser.LoadRequest (new NSUrlRequest (new NSUrl (authUrl)));
//
// The user logged in an we have gotten an access_token
//
void Success(string access_token) {
_web.RemoveFromSuperview();
var url = "http://www.example.com/data?access_token=" + access_token;
// FETCH the URL as needed
}
//
// Watch for the login
//
class Del : UIWebViewDelegate
{
public override void LoadingFinished (UIWebView webView)
{
try {
var url = webView.Request.Url.AbsoluteString;
var ci = url.LastIndexOf ("access_token=");
if (ci > 0) {
var code = url.Substring (ci + "access_token=".Length);
_ui.Success (code);
}
} catch (Exception error) {
Log.Error (error);
}
}
}

Related

Where is the dictionary key "MS_HttpContext" defined for HttpRequestMessage.Properties?

I've searched everywhere and nowhere does it mention where this key is defined, or similar ones such as HTTP_X_FORWARDED_FOR, REMOTE_ADDR etc.
MSDN documentation doesn't mention anything useful. The only thing close to useful I came about was some stackoverflow questions (this and this), along with this short blog post.
None of these sadly address my current question - from where does all these dictionary keys come from? Where is their specification, so that one knows they exist and learn to utilize them, by seeing the contents they hold?
EDIT: I'm using .NET Framework 4.6.0, where System.Net.Http's version is 4.0.0.0.
To get the client IP, I'm doing the following:
public string GetSomeIp(HttpRequestMessage request)
{
HttpContextWrapper context =
request.Properties["MS_HttpContext"] as HttpContextWrapper;
return (context == null) ?
string.Empty : (context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
?? context.Request.ServerVariables["REMOTE_ADDR"]).Split(',')[0].Trim();
}
I'd like to find the documentation, which explains what MS_HttpContext does/holds in detail, as well as REMOTE_ADDR, HTTP_X_FORWADED_FOR, and where they are defined, so I can see all the other keys and more in detail of their implementation/proper usage.
I'm aware of the following server variables, but the keys used here are not mentioned there. (except REMOTE_ADDR)
I'd like to find the documentation, which explains what MS_HttpContext does/holds in detail
The System.Web.Http.* assemblies seem not described on the https://referencesource.microsoft.com/.
However, all these projects are now hosted on the GitHub as Open? Source https://github.com/aspnet/AspNetWebStack.
So far, I assume that this constant/key is used within a routine that assigns the System.Web -> HttpContext to System.Web.Http -> Request.
https://github.com/aspnet/AspNetWebStack/blob/master/src/System.Web.Http.WebHost/HttpRequestMessageExtensions.cs#L11-L44
Another occurrences are related to CORS and Tests. You can clone this repo and search for the "MS_HttpContext" occurrences in depth in you are looking for details. However, I am not sure about its documentation.
where this key is defined, or similar ones such as HTTP_X_FORWARDED_FOR, REMOTE_ADDR etc.
from where does all these dictionary keys come from?
These request's properties (aka Server Variables) are created (almost duplicated) from the corresponding headers sent by a client here (applicable for HttpContext - ASP.NET WebForms/MVC):
https://referencesource.microsoft.com/#System.Web/HttpRequest.cs,dc76880a3cfd0009
https://referencesource.microsoft.com/#System.Web/HttpRequest.cs,639
By the way, there are no more such properties in the HttpRequest for ASP.NET Core (headers only).
If you need to grab the client IP information, use any approach from the aforementioned (yours or suggested) links.
If you need to retrieve the familiar HttpContext instance (for example, outside the ApiController, for example, DelegatingHandler/aka middleware), use any of the approaches illustrated in this (already mentioned as well).
If you need to retrieve it inside the ApiController, it may be even easier (don't forget about required null ref checks and self-hosted WebAPI solutions):
public class YourApiController : ApiController {
public HttpResponseMessage YourActionName() {
var request = new HttpContextWrapper(CurrentContext).Request;
...
}
}
public class YourAuditHandler : DelegatingHandler {
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
string ipAddress = HttpContext.Current != null ? HttpContext.Current.Request.UserHostAddress : "0.0.0.0";
...
}
}

get application path in asp.net vnext

I've been trying to open a file in asp.net 5 and have not been having a lot of success.
In the past you used Server.MapPath or HostingEnvironment.ApplicationPhysicalPath. They are both gone in the OWIN based framework.
There is a HostingEnvironment class but it's in the System.Aspnet but it needs to be initialized by the hosting environment (it no longer has a static member for ApplicationPhysicalPath but I'm guessing the WebRoot member does that now. The problem is I can't find a reference to it anywhere.
I've also looked at Context.GetFeature<> but it doesn't seem to have any feature that would show the application path, just request and response related info. The code listing the features can be found here.
<snark>Is the ability to work with files a discontinued feature in ASP.NET?</snark>
There is also the possibility that I can't brain very well right now and missed something.
You can get it from the ApplicationBasePath property of Microsoft.Framework.Runtime.IApplicationEnvironment serivce.
Example: https://github.com/aspnet/Mvc/blob/9f1cb655f6bb1fa0ce1c1e3782c43a2d45ca4e37/test/WebSites/FilesWebSite/Controllers/DownloadFilesController.cs#L28
There are two approaches now:
using Microsoft.Extensions.PlatformAbstractions;
public Startup(IApplicationEnvironment appEnv)
{
// approach 1
var path01 = PlatformServices.Default.Application.ApplicationBasePath;
// approach 2
var path02 = appEnv.ApplicationBasePath;
}

CefSharp1: Custom HTTP SchemeHandler with fallback to default

I'm writing an application where I need to override both the HTTP and HTTPS schemes with my own handler. However, I need to let any requests that are not handled fallback to the default handler and be processed normally. I thought I could just return "false" from ProcessRequestAsync but that doesn't work. Any insight would be appreciated. I'd rather not have to build my own "fallback" as it seems that it would be problematic.
I'm currently using 1.25.7 of CefSharp, however I did upgrade to version 37 and got the same results.
Here's the code to my SchemeHandler:
public bool ProcessRequestAsync(IRequest request, SchemeHandlerResponse response, OnRequestCompletedHandler requestCompletedCallback)
{
Uri uri = new Uri(request.Url);
foreach (IUriInterceptor interceptor in _interceptors)
{
if (interceptor.canHandle(uri))
{
interceptor.handleRequest(request, response);
requestCompletedCallback.Invoke();
return true;
}
}
return false;
}
IUriInterceptor is my own class. I made it to better organize my custom handlers.
This isn't currently supported by CefSharp.
The underlying CEF library does allow it in CefSchemeHandlerFactory.Create():
Return a new resource handler instance to handle the request or an empty reference to allow default handling of the request.
http://magpcss.org/ceforum/apidocs3/projects/(default)/CefSchemeHandlerFactory.html
However the C++ implementation in CefSharp always expects a handler to be returned, and so you can never tell CEF to allow default handling:
CefRefPtr<CefResourceHandler> SchemeHandlerFactoryWrapper::Create(
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
const CefString& scheme_name,
CefRefPtr<CefRequest> request)
{
ISchemeHandler^ handler = _factory->Create();
CefRefPtr<SchemeHandlerWrapper> wrapper = new SchemeHandlerWrapper(handler);
return static_cast<CefRefPtr<CefResourceHandler>>(wrapper);
}
https://github.com/cefsharp/CefSharp/blob/00b25f5e3fac20b94b3022019fdeefbac6f9e271/CefSharp.Core/SchemeHandlerFactoryWrapper.cpp#L19-L21
The source code of CefSharp would need to be changed for this to work. They are very happy to guide contributors and to accept contributions to the project (remember, it's open source and free!).
Another alternative is to use the CefGlue project, which is a minimal wrapper around CEF that uses pinvoke, so it probably works out of the box there. However, integrating CefGlue into your WinForms or WPF app may be more difficult than CefSharp.

Retrieving HttpContext in a Custom NLog Target

I may me missing something basic here - but is it possible to retrieve the HttpContext.Current in a custom NLog event?
I am trying to give each request a unique Guid so that I can correlate logging messages to a single event (i.e, tie together each log event for a single request). So, I want to store this Guid in HttpContext.Current.Items, then retrieve it in the NLog target and include it in the log message.
Here is my example target where I'd like to access HttpContext.Current:
[Target("AzureTableTarget")]
public class AzureTableTarget : TargetWithLayout
{
public AzureTableTarget()
{
_appSettings = IoCResolver.Get<IAppSettings>();
}
protected override void Write(LogEventInfo logEvent)
{
var correlationId = HttpContext.Current; //This is always null
var batchOperation = new TableBatchOperation();
CxLogEventBuilder.Build(_appSettings, logEvent).ForEach(batchOperation.Insert);
_loggingTable.ExecuteBatchAsync(batchOperation);
}
}
Nowadays it's easier to retrieve the HTTP Context in a NLog target (works for ASP.NET and ASP.NET Core)
Install NLog.Web (ASP.NET) or NLog.Web.AspNetCore (ASP.NET Core) package
For ASP.NET core, follow the ASP.NET Core - NLog setup
Inherit from AspNetLayoutRendererBase (namespace NLog.Web.LayoutRenderers)
Get the request by calling var context = HttpContextAccessor.HttpContext;
Example:
[LayoutRenderer("aspnet-sessionid")]
[ThreadSafe]
public class AspNetSessionIdLayoutRenderer : AspNetLayoutRendererBase
{
protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent)
{
var context = HttpContextAccessor.HttpContext;
var contextSession = context?.Session();
if (contextSession == null)
{
InternalLogger.Debug("HttpContext Session Lookup returned null");
return;
}
builder.Append(contextSession.SessionID); // ASP.NET Core: contextSession.Id
}
}
PS: there are currently many predefined renderers for ASP.NET (Core): https://nlog-project.org/config/?tab=layout-renderers&search=aspnet
If your custom target should capture one (or more) context-specific values, then I recommend that your target inherits from TargetWithContext (or AsyncTaskTarget).
It gives the ability to setup and capture contextproperty-items. Where the Layout can be assigned to capture context-details. Examples of possible context-details easily available from HttpContext:
https://nlog-project.org/config/?tab=layout-renderers&search=package:nlog.web.aspnetcore
For more details about writing custom-targets:
https://github.com/NLog/NLog/wiki/How-to-write-a-custom-target-for-structured-logging
https://github.com/NLog/NLog/wiki/How-to-write-a-custom-async-target
Btw. there already exists this custom target that nicely inherits from AsyncTaskTarget:
https://www.nuget.org/packages/NLog.Extensions.AzureCosmosTable/
This article about Working with HttpContext.Current might help. The key, for you, might be that when control passes from one thread to another HttpContext.Current in the new thread can be null.
Here is another question/answer from here on SO that describes HttpContext.Current being null in the context of a web service. The accepted answer suggests turning on ASP.Net compatibility in your web.config file.
I don't know of either of these will help, but they might. I found them by googling for "HttpContext.Current is null", which yielded quite a number of hits. I have done very little ASP.NET development, so I can't really comment on HttpContext.Current from my own personal experience.
Given your use case, I would suggest that you look into System.Diagnostics.CorrelationManager.ActivityId.
One nice feature of ActivityId is that it is "flowed" from parent threads to child threads (including thread pool threads). I think that it works well with Tasks and Parallel operations. Works well meaning that the ActivityId, as set in a parent thread, has the expected value in a child thread.
There is not a LayoutRenderer for ActivityId, but it easy enough to write one. See an example (written against NLog 1.0) here:
Most useful NLog configurations
I'm pretty sure that the "EstimatedBufferSize" stuff is no longer needed, so something like will probably work:
[LayoutRenderer("ActivityId")]
class ActivityIdLayoutRenderer : LayoutRenderer
{
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
builder.Append(Trace.CorrelationManager.ActivityId);
}
}
If you go this route, you might consider adding a Format property to the ActivityIdLayoutRenderer to allow you to specify the guid format. See this answer (from me). It contains a lot of useful information about working with guids.
NewGuid vs System.Guid.NewGuid().ToString("D");
See this source file (in NLog's git repository) for an example of how you can implement and use such a Format property:
https://github.com/NLog/NLog/blob/master/src/NLog/LayoutRenderers/GuidLayoutRenderer.cs

SignalR multiple hubs on different paths in same application?

I have an application which contains multiple hubs all on unique paths, so when calling the default :
routes.MapHubs("path", new HubConfiguration(...));
It blows up saying that the signalr.hubs is already defined (as mentioned here MapHubs not needed in SignalR 1.01?).
Now I can understand that it should only be called once, but then you will only get 1 path, so is there any way to handle a path per hub scenario? like how with MVC you specify the controller and action? so something like:
routes.MapHub<SomeHub>("path", new HubConfiguration(...));
== Edit for more info ==
It is mentioned often that you should never need to call this map hubs more than once, and in most scenarios I can agree, however I would not say that this is going to be the case for all applications.
In this scenario it is a website which at runtime loads any plugins which are available, each plugin is exposed the dependency injection framework to include its dependencies and the route table to include its routes. The hubs may have nothing to do with each other (other than the fact that they are both hub objects). So the hubs are not all known up front and are only known after the plugins are loaded, and yes I could wait until after this and try binding the hubs there, however then how do I have custom routes for each one then?
This seems to be a case of SignalR trying to abstract a little too much, as I dont see it being a bad idea to have custom routes rather than the default "/signalr", and as the routes all have different responsibilities it seems bad to have one entry route for them all.
So anyway I think the question still stands, as I dont see this as being a bad use case or bad design it just seems to be that I want to be able to have a route with a hub applied to it, much like in mvc you apply a controller and action to a route.
You shouldn't need more than the signalr.hubs route. If you point your browser to that route, you will see it automatically finds all public types assignable to IHub and creates a JavaScript proxy for them. You can interact with different hubs by name from JavaScript, i.e. if you have the following Hub:
public class GameHub : Hub
You can connect to that specific hub by doing:
var gameHubProxy = $.connection.gameHub;
You can also explicitly specify a name for your hub by adding the HubNameAttribute to the class:
[HubName("AwesomeHub")]
public class GameHub : Hub
You can then retrieve the specific proxy by doing
var awesomeHubProxy = $.connection.awesomeHub;
UPDATE:
I'm not sure whether SignalR will be able to run on multiple paths in the same application. It could potentially mess things up and the default assembly locator won't be able to pick up hubs loaded at runtime anyway.
However, there is a solution where you can implement your own IAssemblyLocator that will pick up hubs from your plugin assemblies:
public class PluginAssemblyLocator : DefaultAssemblyLocator
{
private readonly IEnumerable<Assembly> _pluginAssemblies;
public PluginAssemblyLocator(IEnumerable<Assembly> pluginAssemblies)
{
_pluginAssemblies = pluginAssemblies;
}
public override IList<Assembly> GetAssemblies()
{
return base.GetAssemblies().Union(_pluginAssemblies).ToList();
}
}
After you've loaded your plugins, you should call MapHubs and register an override of SignalRs IAssemblyLocator service:
protected void Application_Start(object sender, EventArgs e)
{
// Load plugins and let them specify their own routes (but not for hubs).
var pluginAssemblies = LoadPlugins(RouteTable.Routes);
RouteTable.Routes.MapHubs();
GlobalHost.DependencyResolver.Register(typeof(IAssemblyLocator), () => new PluginAssemblyLocator(pluginAssemblies));
}
NOTE: Register the IAssemblyLocator AFTER you've called MapHubs because it will also override it.
Now, there are issues with this approach. If you're using the static JavaScript proxy, it won't be re-generated every time it's accessed. This means that if your /signalr/hubs proxy is accessed before all plugins/hubs has been loaded, they won't be picked up. You can get around this by either making sure that all hubs are loaded by the time you map the route or by not using the static proxy at all.
This solution still requires you to get a reference to your plugin assemblies, I hope that's feasible...

Categories