Click here to Skip to main content
13,707,147 members
Click here to Skip to main content
Add your own
alternative version


6 bookmarked
Posted 19 Nov 2015
Licenced CPOL

Authorization on Self-Hosted SignalR Server with a MySql DB with EntityFramework

, 19 Nov 2015
Rate this:
Please Sign up or sign in to vote.
How to get a claimbased cookie authentication between custom frontend and self hosted SignalR server


Recently, I ran across the problem of authorizing on a self-hosted SignalR console application. When I would ask friends, the first question was: Why not in an ASP.NET environment? Because my console application is more of a daemon than anything else. There isn't much logic behind it but I couldn't get around the login process. I've started to Google quite a bit and I still have not found a public solution available to the initial problem. This is why I am posting this article as there doesn't seem to be much information about it. Not even on the Microsoft SignalR forum.

This article will require some basic knowledge about the environment we are going to use. I will not explain MySQL nor knockoutjs and most certainly not EF. The intention of this article is to get your basic setup going and advance from there!


Setup/Key functions:

  • Entity Framework 6
  • MySQL
  • SignalR Self-hosted (server)
  • Knockoutjs (client)

Using the Code

We will start off by setting up the SignalR server using the simple C# console application template in VS.
Install the following nuget package: 'MySql.Data.Entity'.
This will install the following packages as well:

  • MySql.Data
  • EntityFramework

Then install 'Microsoft.AspNet.SignalR.SelfHost', 'Microsoft.Owin.StaticFiles' and 'Microsoft.Owin.Security.Cookies'.
Quick explanation: We will serve a static authentication file for the login process. A simple form. And save a claims based identity in the cookie.
This will be our basic setup for the serverside.

Next thing we need to do is to set our db connection up with the help of EF. Add a basic user class consisting only of username and password.

public class User
    public Int32 Id { get; set; }
    //loginname and displayname
    public String Username { get; set; }
    public String Password { get; set; }

Then set the context up for EF.

public class GameContext : DbContext
    public GameContext()
        : base("standard")


    public DbSet<user> Users { get; set; }

Prepare a simple user table for the logindata.

-- phpMyAdmin SQL Dump
-- version 4.1.12
-- Host:
-- Erstellungszeit: 19. Nov 2015 um 13:12
-- Server Version: 5.6.16
-- PHP-Version: 5.5.11

SET time_zone = "+00:00";

/*!40101 SET NAMES utf8 */;

-- Datenbank: `database`

-- --------------------------------------------------------

-- Tabellenstruktur für Tabelle `users`

  `username` text NOT NULL,
  `password` text NOT NULL,
  PRIMARY KEY (`id`)

-- Daten für Tabelle `users`

INSERT INTO `users` (`id`, `username`, `password`) VALUES
(1, 'user', 'pass');


Then add the validation process in a UserManager class.

public class UserManager
    private GameContext zGC = new GameContext();

    public User Authenticate(String pUsername, String pPassword)
	//returns null if no user found
        return this.zGC.Users.FirstOrDefault
        (x => x.Username == pUsername && x.Password == pPassword);

Then add the connection string to your app.config file.

<add name="standard" providerName="MySql.Data.MySqlClient.EF6" 

connectionString="Server=localhost;Database=database;Uid=username;Pwd=5FttZWuS6rMnCwLX; />

Add this point we are set to add and retrieve user information. So the next task is to set SignalR up.

To fire up the server, add the following:

string lServerURL = "http://+:19221";
Console.WriteLine("Server launched on => " + lServerURL + "\r\n");

Now, we already get to the interesting part. The configuration.
It'll basically come down to the following:

Add the following code:

public class Startup
    private const String _WebsiteUrl = "Http://";
    private static String _Authpage = File.ReadAllText(Path.Combine
	(Path.Combine(Environment.CurrentDirectory, @"..\.."), @"Auth/Index.html"));

    public void Configuration(IAppBuilder app)
        //So we can actually load the hubs even when we are on a different domain
        string lContentPath = Path.Combine(Environment.CurrentDirectory, @"..\..");
        var fileOptions = new StaticFileOptions
            FileSystem = new PhysicalFileSystem(lContentPath),

        if (!String.IsNullOrEmpty(_Authpage))
            _Authpage = File.ReadAllText(Path.Combine(lContentPath, @"Auth/Index.html"));

        CookieAuthenticationOptions lOptions = new CookieAuthenticationOptions()
            AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
            LoginPath = new PathString("/Auth/Login"),
            LogoutPath = new PathString("/Auth/Logout"),


        app.Use(async (context, next) =>
            var redirectUri = context.Request.Query["ReturnUrl"];

            //If accesses the login path and is not logged in and is a POST request
            if (context.Request.Path.Value.Contains(lOptions.LoginPath.Value) && 
			context.Authentication.User == null)
                if (context.Request.Method == "POST")
                    //Do we have the needed form data to validate the user
                    var lForm = await context.Request.ReadFormAsync();
                    if (!String.IsNullOrEmpty(lForm["input_login"]) && 
                        //Validate him
                        var lAuthenticatedUser = new UserManager().Authenticate(lForm["input_login"], 
                        if (lAuthenticatedUser != null)
                            //If the user exists, set claims
                            ClaimsIdentity lIdentity = new ClaimsIdentity(lOptions.AuthenticationType);
                            lIdentity.AddClaim(new Claim(ClaimTypes.Name, lAuthenticatedUser.Username));

                            //log user in

                            //send user (authorized) to our game site

                            //At this point the user will be able to connect to the hub 
		            //AND access methods with the [Authorize] tag
                    //If not, send him back to the login page
            else if (context.Request.Path.Value.Contains(lOptions.LogoutPath.Value))
            {//If the user is accessing the logout path

                //log him out

                //and send him back to the login screen
            else if (context.Request.Path.Value == "/Auth/")
                //Is the user already logged in, send him to the game site
                if (context.Authentication.User != null)

                context.Response.ContentType = "text/html";
                //Send him the login form
                await context.Response.WriteAsync(_Authpage);
                //If none of the above applies
                await next();


Now if you visit: http://localhost:19221/Auth/, you can successfully login and you will see that a cookie will be set. We are successfully authenticated to our SignalR server.

Let's get a basic hub going which we can connect to by adding a new class and inheriting from 'hub', we will also give it the [Authorize] tag to make sure it's only accessible if logged in.

public class systemHub : Hub
    public void getCurrentDate()
        //we will call the updateCurrentDate function in our javascript
        Clients.Caller.updateCurrentDate("[" + 
        DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + "]");
	// Incase we need to find out if we are logged in
    public Boolean IsAuthenticated(String pCallbackFunc)
        var lLoggedIn = false;
        if (Context.User != null)
            if (Context.User.Identity.IsAuthenticated)
                lLoggedIn = true;

This is pretty much it for our server side. Now we will go ahead and add a new project for our frontend that will connect to our hub and display us the date. For this purpose, we will be using the "ASP.NET Empty Web Application" template. Start it up and add the url to your Startup file.

private const String _WebsiteUrl = "http://localhost:52729/";

Let's finish this project up with a simple ViewModel a connection to our hub and a button to check whether we are connected or not and another button to get the current server time.

<!DOCTYPE html>
<html xmlns="">
        .hidden{display: none;}
    <h1 data-bind='text: loginStatus'>Loading....</h1>
    <h2 data-bind='text: serverDate'></h2>
    <button id="statusButton" class="hidden">getStatus</button>
    <button id="timeButton" class="hidden">getDateTime</button>

    <script src="//"></script>
    <script src=""></script>
    <script src="http://localhost:19221/signalr/hubs"></script>
    <script src="" 

        function ViewModel() {
            var self = this;
            self.loginStatus = ko.observable($('h1').text());
            self.serverDate = ko.observable("");

            self.initSignalr = function(){
                var baseSignalrServerURL = 'http://localhost:19221/';
                $.connection.hub.url = baseSignalrServerURL + 'signalr';
                var lHub = $.connection.systemHub;

                lHub.client.updateCurrentDate = function(pVal){
                lHub.client.updateLoginStatus= function (pVal) {

                //Connect to the hub
                $.connection.hub.start().done(function () {
                    //Once connected, display button

                $('#statusButton').click(function () {

                $('#timeButton').click(function () {

        ko.applyBindings(new ViewModel());

You are now able to browse your frontend and check whether you are logged in or not.

Points of Interest

  • Browse /Auth/Login if you want to log in.
  • Browse /Auth/Logout if you want to log out
  • Set your SignalR app as Startup project, otherwise you won't be able to load the hubs file


  • 19th November, 2015: Initial version


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Dennis Baberich
Germany Germany
<insert stereotypes="" here="">

Just me, just saying.
Message me if you like.

You may also be interested in...


Comments and Discussions

GeneralMy vote of 5 Pin
Anurag Gandhi20-Nov-15 0:09
professionalAnurag Gandhi20-Nov-15 0:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04-2016 | 2.8.180920.1 | Last Updated 19 Nov 2015
Article Copyright 2015 by Dennis Baberich
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid