Posts

logo-blog-3-3

React Authentication on ASP.NET Core with OAuth and Identity

React Authentication

In this post I explain how React authentication on ASP.NET Core in the RealTimeWeb.NET application is implemented.

The application supports two ways to authenticate:

  • By registration and entering username and password
  • By connecting to an external login provider like Facebook and Google.

ASP.NET Core supports cookie authentication out-of-the-box. While this is enough to create classic web-application and protect controller view actions, it is not secure enough to protect the API’s used by a Single Page Application (SPA). The recommended way to protect an API is to use authentication tokens. The tokens we use here to are defined by the JWT standard in RFC 7519, JSON Web Tokens.

To generate these tokens we use the AspNet.Security.OpenIdConnect.Server (ASOS). ASOS is an advanced OAuth2/OpenID Connect server framework for ASP.NET Core. The generated tokens are validated by using ASP.NET Jwt Bearer authentication.

Configuration

All authentication configuration is placed in Infrastructure/AuthenticationConfiguration.cs:

It will configure:

  • JWT bearer token authentication for API calls.
  • Cookie authentication for WEB calls.
  • Google and Facebook external authentication providers. These providers are only configured when valid configuration is found in the application configuration.
  • OpenIdConnect.Server that provide us with an authorization and token endpoints. These are used to authenticate from the React client application.

Username/password login

Authentication-UserNamePassword

The flow used for username and password authentication is rather simple:

 

    1. The user enters username and password in a textbox. (source)
    2. The token endpoint is called with the entered credentials. (source)
    3. When the credentials are correct an access_token and refresh_token are returned. Both tokens are stored in the local storage of the browser. (source)
    4. When an API call is made the access_token is added in the header of the HTTP call to authenticate. When a valid access_token is used a valid response is returned with HTTP code 200 (OK). (source)

External provider login

OAuth also support authentication with an external provider. In the example both Google and Facebook are supported. But online you also find adapters for most other providers like GitHub, LinkedIn, … in the AspNet contrib repository.

The flow to authenticate with an external provider is a bit more complex:

Authentication-External-Login-1

 

    1. The user clicks on a specific external provider. (source)
    2. A new window is opened and loads the authorize endpoint: /account/authorize/connect?grant_type=authorization_code. (client and server source)
    3. This request is handled by the registered providers and redirects to the external provider login page.
    4. When the login in successful the external provider redirects back to our authorization complete endpoint: /account/authorize/complete. (source)
    5. When the the authorization is completed we redirect to the authorized enpoind with the generated authorization_code. This additional step is needed to get both an access_token and refresh_token because the authorization endpoint is not allowed to return the refresh_token by the RFC.
    6. The token endpoint is called with the authentication code. (source)
    7. When the authentication code is correct the access_token and refresh_token are returned. Both tokens are stored in the local storage of the browser. (source)
    8. When an API call is made the access_token is added in the header of the HTTP call to authenticate. When a valid access_token is used a valid response is returned with HTTP code 200 (OK). (source)

Using a refresh_token

When a token is requested both an access_token and refresh_token are returned. The validation lifetime of an access_token is much shorter (20 minutes) as the lifetime of the refresh_token (24 hours). The goal is to request a new access_token by providing the refresh_token when the access_token is expired.

Refresh_token are recommended because the user can stay logged-in for a longer period of time without the need to resend the credentials over the wire again. And they can also be revoked by the server. The advantages and disadvantages of the revocation support are explained in this StackOverflow post.

Authentication-Refresh-Token

    1. When the access_token expires the API returns an HTTP 401 response.
    2. When the HTTP 401 response is received the token endpoit is called with the refres_token. (source)
    3. When the refresh_token is not expired the new access_token and refresh_token are returned. Both tokens are stored in the local storage of the browser. (source)
    4. When an API call is made the access_token is added in the header of the HTTP call to authenticate. When a valid access_token is used a valid response is returned with HTTP code 200 (OK). (source)

ASP.NET Identity

To manage users ASP.NET Identity is used in combination with a custom user store that targets PostgreSQL. This will be explained in a future blog post. To be able to run the application locally without the need to install PostgreSQL, an in-memory stored can be used by leaving the connections string empty. For mor information about hot to run the example locally go to the getting started post.

Credits

I like to give credit to Taiseer Joudeh for his AngularJS Token Authentication blog posts. And I also would like to thank Kévin Chalet for the support on getting ASOS to work!

Source code

The source code of the application can be found on github:

https://github.com/tim-cools/RealTimeWeb.NET

Warning!

The application is still work in progress and new features will be added in the next following weeks…

Some of the technologies and frameworks used in this application are pre-release and most likely to change. Currently it is based on RC1 of .NET Core. I try to update the code as soon as possible whenever the final version is released. Ping me on Twitter if you have questions or issues.


RealTimeWeb.NET Blog Posts

This post is part of a blog post series about RealTimeWeb.NET application.

  1. RealTimeWeb.NET – A real time ASP.NET Core application
  2. Getting started with RealTimeWeb.NET
  3. RealTimeWeb.NET Front-end
    1. Creating an ASP.NET Core web application
    2. Single page application in React on ASP.NET Core
    3. React Authentication on ASP.NET Core with OAuth and Identity
    4. Real-time data pushed by web-sockets (SignalR) on ASP.NET Core
    5. Server-side rendering
  4. Real-time back-end
  5. Operations
  6. ...

logo-blog-3-1

ASP.NET Core web application

ASP.NET Core web application

ASP.NET Core is the new Web-development framework developed by Microsoft. The biggest advantages between the previous version of ASP.NET is that it is multi-platform out of the box and is fully open-source. I selected the new ASP.NET Core framework for the development of this sample application because of the multi-platform support. In this post I describe briefly how to create a new ASP.NET Core and the differences between the ASP.NET Framework.

Screenshot

Create a new ASP.NET Core project

There is already a large amount of information available on the web about how to get started with ASP.NET Core so I will not cover this in details again. I will reference to the documentation needed to get started. Click here to view the instruction to install .NET Core on your local machine.

To create a new ASP.NET Core project you can choose between Visual Studio or using yeoman and the command line.
This will create a basic project structure with the necessary configuration and files to start with a web project.

ASP.NET Core Core run-time and frameworks

The new ASP.NET Core framework runs on multiple operation systems out of the box. It leverages this multi-platform support by supporting multiple run-times:

  • The CLR is the original Windows run-time developed by Microsoft. It is a non-open source environment but it prove it’s stability more as 14 years in production environments.
  • Mono is a multi-platform run-time developed by the community. It is more compatible with the original CLR as CoreCLR. This means that it runs most libraries and frameworks without any problem.
  • .NET Core (CoreCLR) is the new multi-platform run-time developed by Microsoft. It is open-source and supports Windows, Mac and Linux. It only supports a subset of the CLR so it is currently not compatible with most CLR libraries.

Each application can run on one or more run-times by specifying the framework(s) it supports. The frameworks are not very well documented for the moment. But at at least following frameworks are available:

  • dnx451 is supported by CLR and Mono.
  • dnx46 targets the .NET framework 4.6. Although mono support many C#6 features, this framework is currently not (yet) supported.
  • dnxcore50 targets only .NET Core (CoreCLR).

Because several libraries I needed for the application does not support Core CLR yet I chose to build and deploy this application in the dnx451 framework. This frameworks is supported on both on the classic CLR as on the Mono run-time.

Project.json

Instead of using a more complicated MS Build file Microsoft decided to put the project definition in a project.json file. This is similar to the node.js packages.json file. This file contains basic project information, the dependencies (NuGet libraries) and the supported frameworks. It also contains one or more commands that can be executed from command line. In this case one command is defined ‘Web’ which starts Kestrel on port 3008. Kestrel is the ASP.NET Core cross platform development web server use to run the web-application.

Click here to view the project.json file specifications. And here for more specific ASP.NET Core project.json configuration

Tooling

One of the great decision they made is to leverage improved command line experience. I like this because this improves productivity and multi-platform support. Instead of running the application from your way-to-heavy Visual Studio you can now run your applications from command line with a single command.

To run dnx a command defined in your project.json you have to call dnx followed by the command you want to run:

.NET Core also supports a command-line .NET Version Manager (dnvm) and a package manager (dnu). Which is great for automating environment setup, builds and deployment.

What is different

Following list describes the main difference between ASP.NET and ASP.NET Core:

  • Web Pages and apis are supported by a single model. Instead of using a different controller from serving Web (MVC) and Api (WebApi) requests there is only one base controller left named Controller. This controller used to implement both scenarios. Here you can see and example of an Api controller and here an example of a Web Page controller.
  • Dependency Injection is now a first class citizen. This is very basic support but it is easy to plug-in your favorite container. Lucky there are already containers that support the new dnx framework like Autofac and StructureMap.
  • All application configuration code is now grouped in a single StartUp.js and the Global.asax is not supported anymore. This class will take care of the container initialization and the web-application configuration. An example of the Startup.cs file can be viewed here.
  • Multiple environments are supported out of the box. Application configuration settings can come now from different sources instead of from a single app.config file. This is a powerful way to differ the configuration for each environment.

Conclusion

Microsoft had a good look at the competing web-development frameworks when they designed the new ASP.NET Core version. This results in my opinion into a modern web-framework adapted to the need of today’s web projects.

Source code

The source code of the application can be found on github:

https://github.com/tim-cools/RealTimeWeb.NET

Warning!

The application is still work in progress and new features will be added in the next following weeks…

Some of the technologies and frameworks used in this application are pre-release and most likely to change. Currently it is based on RC1 of .NET Core. I try to update the code as soon as possible whenever the final version is released. Ping me on Twitter if you have questions or issues.


RealTimeWeb.NET Blog Posts

This post is part of a blog post series about RealTimeWeb.NET application.

  1. RealTimeWeb.NET – A real time ASP.NET Core application
  2. Getting started with RealTimeWeb.NET
  3. RealTimeWeb.NET Front-end
    1. Creating an ASP.NET Core web application
    2. Single page application in React on ASP.NET Core
    3. React Authentication on ASP.NET Core with OAuth and Identity
    4. Real-time data pushed by web-sockets (SignalR) on ASP.NET Core
    5. Server-side rendering
  4. Real-time back-end
  5. Operations
  6. ...

logo-blog-3

RealTimeWeb.NET Front-end

Real-time web application on ASP.NET Core

RealTimeWeb is a real-time web application on ASP.NET Core with two main features:

  • Allow users to become member by registering with username/password or by an external social provider. Currently Google and Facebook authentication is implemented.
  • Display the real-time data of the vehicle monitor received from the Vehicle Monitor service.

Front-End-Components.fw_

Components

The application consist of following parts:

  • ASP.NET Core web application that is responsible to serve the necessary web-page, JavaScript and style-sheet files.
    Read more…
  • The single page application written in React.
    Read more…
  • Authentication and authorization implemented with OAuth and ASP.NET identity.
    Read more…
  • WebSockets to push the real-time data from the vehicle monitor to the user. This is implemented with the usage of SignalR.
    Read more…

Source code

The source code of the application can be found on github:

https://github.com/tim-cools/RealTimeWeb.NET

Warning!

The application is still work in progress and new features will be added in the next following weeks…

Some of the technologies and frameworks used in this application are pre-release and most likely to change. Currently it is based on RC1 of .NET Core. I try to update the code as soon as possible whenever the final version is released. Ping me on Twitter if you have questions or issues.


RealTimeWeb.NET Blog Posts

This post is part of a blog post series about RealTimeWeb.NET application.

  1. RealTimeWeb.NET – A real time ASP.NET Core application
  2. Getting started with RealTimeWeb.NET
  3. RealTimeWeb.NET Front-end
    1. Creating an ASP.NET Core web application
    2. Single page application in React on ASP.NET Core
    3. React Authentication on ASP.NET Core with OAuth and Identity
    4. Real-time data pushed by web-sockets (SignalR) on ASP.NET Core
    5. Server-side rendering
  4. Real-time back-end
  5. Operations
  6. ...

logo-blog-2

Getting started with RealTimeWeb.NET

Getting started

In order to be able to run the application locally you need to perform following steps:

  • Install PostgreSQL 9.5
  • Install RabbitMQ
  • Configure application for the external providers: Google and Facebook

The first time that the application runs it will ask you to enter all configuration values. When the settings are saved a configuration file appsettings.private.json is created in web folder. The configuration file is .ignored by git. If you need to change the configuration in the future you can:

  • Set “general:configured” to false in the appsettings.private.json in web folder.
    When the application is restarted this installation screen is shown again. (RECOMMENDED)
  • Edit the files manually.
  • Remove the file en restart the web application to start from scratch

The web application should be restarted in order to reload the configuration and make the changes active.

Web-installation

All these values are optional and the application will run without them. When no connection string is defined the application will use an in-memory data store. This means that the data will only be kept in memory as long as the application runs.

Source code

The source code of the application can be found on github:

https://github.com/tim-cools/RealTimeWeb.NET

Warning!

The application is still work in progress and new features will be added in the next following weeks…

Some of the technologies and frameworks used in this application are pre-release and most likely to change. Currently it is based on RC1 of .NET Core. I try to update the code as soon as possible whenever the final version is released. Ping me on Twitter if you have questions or issues.


RealTimeWeb.NET Blog Posts

This post is part of a blog post series about RealTimeWeb.NET application.

  1. RealTimeWeb.NET – A real time ASP.NET Core application
  2. Getting started with RealTimeWeb.NET
  3. RealTimeWeb.NET Front-end
    1. Creating an ASP.NET Core web application
    2. Single page application in React on ASP.NET Core
    3. React Authentication on ASP.NET Core with OAuth and Identity
    4. Real-time data pushed by web-sockets (SignalR) on ASP.NET Core
    5. Server-side rendering
  4. Real-time back-end
  5. Operations
  6. ...

Marten

Marten, PostgreSQL as document db for .NET

Marten, PostgreSQL as document db for .NET

Since they include the JSONB column type a while ago I was thinking about using PostgreSQL as document database. But I had no time to implement something like this myself yet. So I was happily surprised when I stumbled upon Marten a few weeks ago. Marten is a new persistence library for .NET that provide document db functionality on top of a PostgreSQL database. This was exactly what I was thinking about. It is created by Jeremy Miller the creator of SturctureMap and the Fubu stack. And tough it is still in an early stage, the supported features look already promising:

  • Schema-less document persistence with ACID support
  • Linq support for querying
  • Unit of work with Identity Map and optional dirty checks
  • Optimized batch udpates
  • Compatibility with  RavenDB client API (or close to)
  • EventStore on top of PostgreSQL with sycn and async projections

What is a Marten

A Marten is a cute animal living in many parts of the world. Check it out yourself:

14674805776_b9180bf828_o-300x214
Source: Flickpicpete

Why PostgreSQL

Since PostgreSQL version 9.2 they started to include more and more features to support a JSON column type. This allow you to store and retrieve schema-less documents in the database. And since 9.4 they included a binary JSON (jsonb) column type that support indexing on fields in the json data. Besides that PostgreSQL also support all traditional database features like ACID support, while many Document database lack this. This makes the database a good candidate for many software projects that need the productivity of storing schema-less documents combined with the advantages of traditional databases (eg multi document transactions).

PostgreSQL also has a huge supporting open source community and there are many tools and extensions. Some examples of these extensions are:

    References

    I will probably blog more about this topic later as I started contributing to the OSS project. And I hope to be able to contribute more on this awesome project in the future.
    In meanwhile you ca find more info here:

    Event Store Rest API Basics (Node.js)

    Event Store Node.js client

    I recently finished my first project written in Node.js with EventStore as data-store. I published the some of the code used to access the EventStore to github, feel free to play with it. The official documentation can be found the the EventStore web-site.

    The code to load/save the events is coded in a repository and contains 3 methods:

    Have a look at the implementation on github. And at jasmine test file for the full examples.

    Loading the events of an aggregate

    The load method loads all events of a stream to be able to replay them on an aggregate. The events are loaded in batch. (In this example per 5)

    The load method returns the current version of the stream and all stored events:

    When the stream doesn’t exists, the load methods returns an empty event array with -1 as version. -1 should be used as version to save events to a new streams.

    Load the last event of a stream

    To get the state of an projection the last event of a stream is loaded. This is done by requesting the head of the stream.

    The loadLast method returns the version of the stream, and the name and the body of the last event.

    Saving the events of an aggregate

    The save methods appends to specified event to the stream. It also performs a concurrency check based on the version. When the version is not correct the callback returns with an error.

    What’s next

    In the next posts I describe how I managed projections and applied event-sourcing on an aggregate in JavaScript.

    Source code

    A working project for these examples can be found on github: https://github.com/tim-cools/EventStore-Node-Examples

    Event Store Projections by Example

    This post is part of a series:

    1. EventStore Client API Basics (C#)
    2. Counting events of a specific type
    3. Partition events based on data found in previous events
    4. Calculating an average per day
    5. The irresponsible gambler
    6. Distribute events to other streams
    7. Temporal Projection to generate alarms
    8. Projection in C#