Xamarin.Tips – Sending Authorized SignalR Requests

In my last post, I talked about creating a CookieProvider for handling OAuth Bearer Tokens from an HTTP Cookie. Now that we have this capability, we can make a secure connection to SignalR using a Cookie store rather than adding our tokens to the Authorization HTTP Header.

By using cookies instead of the HTTP Header, we can now use a full Websocket connection rather than being forced into long polling. Using websockets increases speed of messages received and messages sent.

So here’s the quick bit of code for making a secure SignalR Websocket connection:

SignalRConnectionService.cs

    public class SignalRConnectionService
    {
        private HubConnection _connection;
        public IHubProxy AppHubProxy { get; set; }

        public SignalRConnectionService()
        {
            _connection = new HubConnection(YOUR_SIGNALR_URL);
            AppHubProxy = _connection.CreateHubProxy("AppHub");
        }

        public async Task StartAsync()
        {
            try
            {
                if(_connection.State != ConnectionState.Disconnected)
                {
                    _connection.Stop();
                }
                _connection.CookieContainer = new CookieContainer();
                _connection.CookieContainer.Add(new Uri(THE_BASE_URL_OF_YOUR_SERVER), new Cookie("BearerToken", YOUR_ACCESS_TOKEN));
                await _connection.Start();
               
        }
        public void Stop()
        {
            _connection.Stop();
        }
    }

Now we have the full speed of websockets enabled in our Xamarin, Mac, and Windows applications!

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

ASP.NET.Tips – Consuming Bearer Tokens as a Cookie

A while ago, I talked about creating a super basic OAuth Bearer and Refresh Token System in your ASP.NET web applications: Adding a Simple Refresh Token to OAuth Bearer Tokens

Now, almost two years later, we will expand on this by creating a Cookie provider that consumes your bearer tokens to make Authorization easier. One reason to consider doing this is if you are using SignalR or any other socket service with your OAuth tokens. You can add your Bearer token in your Authorization header of your requests to SignalR, however, doing this will force your client to use LongPolling rather than actually using WebSockets as it is intended.

So, let’s create our provider:

OAuthCookieProvider.cs

 public class OAuthCookieProvider : OAuthBearerAuthenticationProvider
    {
        public override Task RequestToken(OAuthRequestTokenContext context)
        {
            if (context == null) throw new ArgumentException("context");
            var tokenCookie = context.OwinContext.Request.Cookies["BearerToken"];
            if (!string.IsNullOrEmpty(tokenCookie))
            {
                context.Token = tokenCookie;
                return Task.FromResult<object>(null);
            }
            return base.RequestToken(context);
        }
    }

And now let’s get that registered with Owin:

Startup.cs

...
public void Configuration(IAppBuilder app)
{
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
    {
        Provider = new OAuthCookieProvider()
    });
}
...

Now we can send requests with our HTTP cookie with the key of BearerToken and make it through the built in Authorize attribute without having to write anything custom.

Next, we will look at taking advantage of this CookieProvider in a .NET Signalr Client to use the full power and speed of web socket connections.

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Organized Architecture for a Cross-Platform SignalR Application

SignalR is a great tool for keeping not only your web applications synced in real-time, but with it’s easy to use APIs for clients, it is perfect for use in your mobile applications.

I have some previous posts that are going to help in designing the of an architecture for a cross-platform implementation with SignalR. Take a look at these:

In this scenario, we are going to focus on two major layers of separation within our applications, although you can always add more layers of abstraction if that is your style or preference. Our two layers are the Portable Class Library and Native Client Libraries. This example is going to be using one PCL with all of our shared code, and then individual projects for Windows Phone 8.1, Windows 8.1, Xamarin.iOS, and Xamarin.Android.

The Portable Class Library

In this architecture, we want to focus on sharing as much code as possible. This implies that the only code that should not be in our PCL is code that includes the UI (Note we are not using Xamarin.Forms), updates the UI, or accesses the device’s native features (cameras, location, etc). This would include things such as ViewModels if you’re using the MVVM pattern (this example is using MVVM Light), Models, Web Request Logic, and even our SignalR Managers.
With that in mind, here are some nuget packages to consider for your PCL:

So let’s get started with a simple BaseHubManager to manage our connections. I’m going to follow a basic Inheritance pattern for these managers so that we can share as much of our SignalR code in our Base Manager as possible.

BaseHubManager:

  public class BaseHubManager
    {
        public HubConnection Connection{ get; set; }
        public IHubProxy Proxy { get; set; }

        // The empty constructor should only be used for a basic connection with no specific Hub
        public BaseHubManager()
        {
            Connection= new HubConnection(Constants.BaseUrl);
        }

        // Connect to specific Hub
        public BaseHubManager(string hubProxy)
        {
            Connection= new HubConnection(Constants.BaseUrl);
            Connection.Headers.Add(&quot;Authorization&quot;, string.Format(&quot;Bearer {0}&quot;, App.CurrentUser.TokenInfo.AccessToken)); //add access token to authorize
            Proxy = Connection.CreateHubProxy(hubProxy);
        }

        public async Task Start()
        {
            await _connection.Start(new LongPollingTransport());
            //Add additional shared Start logic
        }

        public void Stop()
        {
             _connection.Stop();
             //Add additional shared Stop logic
        }

        public virtual async void Connect()
        {
            await this.Start();
            //Add additional shared Connect logic
        }
    }

Now that we have a solid base, we can easily spin up individual Hub managers to connect to specific Hubs. Below is an example of a HubManager that would connect to the “ChatHub” on your server.

ChatHubManager:

 public class ChatHubManager : BaseHubManager
    {
        public ObservableCollection&lt;string&gt; Messages{ get; set; }

        public ChatHubManager ()
            : base(&quot;ChatHub&quot;)
        {
            this.Connect();
        }
        // Send new message to ChatHub
        public async Task&lt;string&gt; Create(string newMessage)
        {
            //establish connection
            await this.Start();

            var message= await Proxy.Invoke&lt;string&gt;(&quot;Create&quot;, newMessage);

            return message;
        }

        // Get all messages from ChatHub
        public async Task&lt;IEnumerable&lt;string&gt;&gt; Get()
        {
            //establish connection
            await this.Start();

            var messages = await Proxy.Invoke&lt;IEnumerable&lt;string&gt;&gt;(&quot;Get&quot;));

            Messages = new ObservableCollection&lt;string&gt;(messages);
            return messages;

        }

    }

Expanding new HubManagers like this one make it very easy to call server-side methods from our client by simply creating an instance of our Manager and calling our Invoking methods:

var manager = new ChatManager();
var messages = await manager.Get();

Now what about the other side of SignalR – Client methods? There are some things to consider. Most importantly, will your client end points update anything in the UI? This also includes updating ViewModel properties that will cause updates in the UI.
The problem is that the client end point listeners don’t stem from any sort of UI action the way that calling a server method might. Thus, it can’t run on the UI thread by itself and you would likely run into some sort of Threading Exception.

If you don’t need to update the UI at any point from your client listener, consider adding your listeners in your manager with something like this:

public ChatHubManager ()
    : base(&quot;ChatHub&quot;)
{
        this.Connect();
        Proxy.On&lt;string&gt;(&quot;newMessage&quot;, async data =&gt;
        {
            //Do something that is NOT on the UI thread
        }
}

One thing that SignalR does wonderfully is give you the ability to add these listeners from anywhere. That includes from your individual client projects that reference your PCL. So, let’s look at how to add these kind of requests to our client projects so we can update our UIs.

The Individual Client Projects

Let’s use a Windows Phone 8.1 project as our example, although the same logic can be applied to any type of project. So we need to add our client listener like we did above, but we also need it to make changes to our UI, which will require tapping into our UI thread. For this case, let’s add a ChatSignalingManager to our Windows Phone project that contains a reference to our ChatHubManager in our PCL above:

 public class ChatSignalingManager
    {
        private ChatHubManager _hubManager;
        private CoreDispatcher _dispatcher;
        public ChatSignalingManager (CoreDispatcher dispatcher)
        {
            _hubManager= new ChatHubManager ();
            _dispatcher = dispatcher;
            InitializeChatEndpoints();
        }

       //Add client end points for the ChatHubManager
        private void InitializeChatEndpoints()
        {
            var newMessage = _hubManager.Proxy.On&lt;string&gt;(&quot;newMessage&quot;, async data =&gt;
            {
                await _dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =&gt;
                    {
                        // process your UI changes here
                    });
            });

           // Add additional end points for the ChatHub here
        }

    }

Notice the biggest difference in how we handle our end point in our client project versus our PCL. The Dispatcher. In this case, we can pass Windows CoreDispatcher to our constructor, and by calling _dispatcher.RunAsync we are able to execute our process on our UI thread to successfully run code against our UI.

Here is an example of constructing the ChatSignalingManager from the MainPage of a Windows Phone app:

public sealed partial class MainPage : Page
{

    private ChatSignalingManager _signalingManager;
    public MainPage()
    {
        this.InitializeComponent();

        this.NavigationCacheMode = NavigationCacheMode.Required;
        _signalingManager = new ChatSignalingManager (Dispatcher);

    }

}

Hopefully that is enough code to get you started, but feel free to ask more questions in the comments. Just remember to share as much code as possible in your PCL and use your Client Projects to handle updates to your UI and also to utilize SignalR’s flexibility and versatility.

Connecting to an Authorized SignalR Hub from a .NET Client

In a previous post, I talked about adding Access and Refresh tokens to your Web Application using OAuth Bearer Tokens. In this post, we are going to be using this same logic to authorize external clients from an external .NET client application such as Windows Store apps, Xamarin.iOS, Xamarin.Android, etc.

Assuming we have our access token (and refresh token) stored locally on our client, we can use it to authorize our requests to our SignalR Hub. Let’s put together a basic Hub:

[Authorize]
public class SimpleHub : Hub
{
    public string AuthorizedString()
    {
        return "You are successfully Authorized";
    }

}

This is obviously and extremely simple example, and we aren’t going to get into calling client methods from the server with our authorized user as I will be covering that in a later post.
Now that we have our server-side Hub, let’s put together a client-side manager to connect to this Hub and make our request to AuthorizedString()

public class SimpleHubManager
{
    private HubConnection _connection;
    private IHubProxy _proxy;
    public SimpleHubManager()
    {
        _connection = new HubConnection("http://YOUR_DOMAIN/"); //connect to SignalR on your server
        _connection.Headers.Add("Authorization", string.format("Bearer {0}", YOUR_ACCESS_TOKEN)); //THIS IS WHERE YOU ADD YOUR ACCESS TOKEN MENTIONED ABOVE
        _proxy = _connection.CreateHubProxy("SimpleHub"); //connect to Hub from above
    }

    public async Task<string> GetAuthorizedString()
    {
        await _connection.Start(); //start connection
        var authorizedString = await _proxy.Invoke<string>("AuthorizedString"); //Invoke server side method and return value
        return authorizedString;
    }
}

As long as the Access Token being used by the client has not expired and is added to the Authorization Http Header, then we will be able to bypass the [Authorization] on the server.
So now, from our client, if we call:

var manager = new SimpleHubManager();
var authString = await manager.GetAuthorizedString(); //"You are successfully Authorized"

We see our string is exactly what we expect.

Stay tuned for some more advanced SignalR work in the future!