Monthly Archives: Kwiecień 2017

[EN] How to upgrade Angular 2 project to Angular 4

About a month ago Angular 4 has been released. You may want to ask what about version 3? Well, there’s no Angular 3. We have Angular 4, but I have started to learn Angular 2 and now what? Should I start to learn Angular 4 and forget about version 2? The answer is no. The newest version is backwards compatible with 2.x.x version. It’s just an evolution rather than revolution.

What’s new?
– applications are smaller and faster – the size of the generated code was reduced by around 60 %
– improved *ngIf and *ngFor
– angular universal – project that allows devs to run Angular on a server
– TypeScript 2.1 and 2.2 compatibility
– source maps for templates – when there is an error in a template, source maps are generated
More will come soon with v 4.1.

If Angular 4 has been released, why not to use it in our new project? Let’s see if it is easy to upgrade Angular 2 project to Angular 4.
Open command line tool, go to app folder and type commands as below, then wait a little.


After this we can check version of angular in our app by command

As you see here it is, Hello Angular 4.0.3 🙂


So far it’s good, we will see for some time how it works 😉

[EN] How to populate database in ASP.NET Core Web Api

When we create our app it’s good to have some data in a database at some point, for example test user accounts or other values if we want to test something. How to populate database at the start of application if the database is empty?

First we need to create new class in our project. Let’s see how to do it on example.

I want to seed the database with test user with admin role, because I want to test loging functionality.

Here’s my class with Seed method.

What it does, it just checks if user „TestAdminUser” and role „Admin” exist in the database. If not it adds them and assigns role and claim to the user. If you are wondering what is User class, I have user class defined which is derived from IdentityUser class (Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUser), so it’s IdentityUser class with additional properties.

ELPIdentityInitializer class is not complicated, but we can add here more data. The question is how to load this data and when? As you probably guess, the good place is Startup class and Configure method, because it will be called only once at the start of application. To achieve our goal we need to add another parameter to this method. In my case it will be parameter of type ELPIdentityInitializer. In the body of Configure method, at the end (after UseMvc() method call) we need to execute Seed method from our initializer. This method is awaitable, so we can just wait for completion, because we don’t want to change Configure method to be asynchronous.

Additionally we need to register our initializer class in the service collection, because without it we will see an error while resolving class. To do it let’s add this line of code to the ConfigureServices method in Startup class.

I used AddTransient method here. It means service is created each time it is requested, but it’s not important here. Our service is requested only once at the beginning. BTW Transient lifetime works best for lightweight and stateless services.

After these few steps we should see result of our work which is populated database, in this case Users table.


[EN] How to read data from appsettings.json in ASP.NET Core Web Api

In my previous post about token authentication in ASP.NET Core Web Api I mentioned that is not a good practice to hardcode strings in controller or Startup class, especially if we want to put some sensitive data like key for SigningCredentials or connection string to database or configuration parameters. How to avoid it? We can add all strings to configuration file. In ASP.NET Core we have appsettings.json file which is the right place to put these kind of data. It looks like this by default in Web Api project

ok let’s say we want to add few parameters here, for example data to generate token (in my previous post you can read about generating token) in CreateToken method in one of my Controllers – LoginController.  Here is the method we want to modify.

We want in this case to read issuer and audience from config file, the same with „SuperSecretKey” to generate SymmetricSecurityKey. First we need to add these data to appsettings.json.

Then we need to modify the LoginController where CreateToken method is located.

We need to use IConfigurationRoot object to read data from config file. Let’s add it as private field and inject it in controller.

Now it’s time to replace hardcoded strings in CreteToken method.

Unfortunately that’s not all. It will not work. There’s one step we need to do.  In Startup class we need to register IConfigurationRoot object as a singleton. There’s property called Configuration by default

and we need to add this line of code to ConfigureServices method

That’s all. Since we have known about appsettings.json file it’s good to use it.

[EN] Token authentication in ASP.NET Core Web Api

In the previous post I showed how to implement cookie authentication in ASP.NET Core Web Api, this time I want to show you how to implement token authentication using JWT token. I strongly recommend you to read my previous post about cookie authentication, because it will be simplier to understand, besides source code showed below have some parts described in the previous post.

JWT structure

JWT stands for JSON Web Token. It is small, self-contained JSON. It contains credentials, claims and other information.

JWT consist of header, payload and signature.

Header contains algorithm for JWT and type of token.

Payload contains information that the server can use, e.g. user name, e-mail.

Signature is a secret key generated by server.
The goal is to send token to a client and the client will send it with every request back to the server to guarantee it’s rights. All information in token is encoded in Base64.


Here is a sample of encoded token

Useful web page for decoding JWT tokens is I recommend you to check it.

To better understand token authentication, take a look at the image below.


Client sends credentials, server validates them and returns signed JWT token
to be able to validate it later. Client have to include untouched JWT with every call. It can decode header and payload, but not signature. Only server can decode signature, because the secret is never shared.


We know theory, now it’s time to look into code.
Let’s implement method in controller responsible for generating token, but first it should validate user credentials. In the previous post I used SignInManager class for signin, but this time we don’t want this, because it will generate a cookie. We just want to validate user credentials without a cookie. We can use for it PasswordHasher class. I want to have cleaner code, so I added method for validation in UserService class and UserService is used in LoginController. Here is my UserService with added VerifyHashedPassword method that uses IPasswordHasher

As you can see here are additional methods: GetClaims and GetUserByUsername. GetClaims method will be used to get all information about user and GetUserByUsername finds user by username.
Next it’s time to use these methods in LoginController. Here it is, ready and working create token method.

First we need to find user by username. If the user is found then we can verify password hash. If credentials are good we create the token (BTW we need to add package System.IdentityModel.Tokens.Jwt first).

Then we create claims for user with all necessary informations, key and credentials. Key used to create SymmetricSecurityKey shouldn’t be hardcoded like this. It’s good to move it to configuration file, but I don’t want to complicate this example. Next we create JwtSecurityToken. Issuer and audience is our website that will accept this token. Expires tells how long token is valid.

Now we can test it. Hit f5, open Postman and Send a request.


As you can see we get token in response to our request. It means we did it correctly.

Another thing to do is validating token send by a client.

In Startup class we need to use middleware for security token. Add few lines of code to Configuration method before UserMvc method call. We need to add also Microsoft.AspNetCore.Authentication.JwtBearer package.

TokenValidationParameters should be the same like in create token method. These strings should be also moved to configuration file.

Let’s test it. For example I have EventsController that contains Get method which returns all events, but only for authorized users. If we try to get events we will get 401 Unauthorized error.


In this case we need to get token we generated before while testing create token method and put it in a request header with Key: Authorization and Value: bearer <token>. This time we should get status code 200. It means we have implemented token authentication in ASP.NET Core Web Api successfully.


If you want to take a look at the source code it is available in my Github repo.

[EN] Cookie authentication in ASP.NET Core Web Api

This time I want to focus on user authentication. In APIs we can use different methods for user authentication like:

-cookie Authentication

-basic Authentication (not recommended, slow and insecure)

-token Authentication

In this post I want to show you how to implement cookie authentication in ASP.NET Core Web API.

First make sure you have installed Microsoft.AspNetCore.Identity.EntityFrameworkCore NuGet package in your project. Then let’s modify model a little bit.

Create User class derived from IdentityUser.

Next modify Context class. Our Context should be derived from IdentityDbContext<User> class. If your Context is derived from DbContext class, you need to change it. IdentityContext helps us to create all tables needed for user like Roles, Claims, Tokens, etc.

After these modifications, add another migration via Package Manager Console (type Add-Migration migrationName) and update database by Update-Database command. If you don’t know how to perform code first migrations take a look at one of my previous post.

If we have database ready, we can focus on our API project. In Startup.cs class in ConfigureServices method we need to add identity to services by adding this line of code:

where ELPContext is your app context and User is user class derived from IdentityUser.

That’s not all, we need to add more code, to specify how Identity should work. There’s a small problem with ASP.NET Core WebApi, when you call method that needs authorization you can get 404 Not Found Error instead of 401 Unauthorized. It’s because of default redirection to Account/Login page which can be helpful in ASP.NET MVC project but not in Web API. To handle it we need to set up application cookie events. Events allow us to override things that the IdentitySystem does. Add this code after AddItentity method call.

In the Configure method in Startup class we need to add another line of code before calling app.UseMvc() method:

We have configured our project, so let’s implement controller with register and login methods. I prefer to avoid logic in Controllers and use only services, so first we need to create UserService. This is my UserService for now.

I use UserManager and SigninManager that come from Microsoft.AspNetCore.Identiy namespace. These managers do a lot for us.

When we have service it’s time to use it in Controller.

We have two methods Register and SignIn. It’s time to test it. Hit F5, start your API and open Postman (If you don’t know what is Postman go to my previous post where I mentioned about it).

In Postman pick Post method call, add body which is raw JSON and hit Send. You should see success and status 200 like on image below.


To test Signin method, repeat above steps. You can see in the result in the Cookies tab there’s  cookie provided by ASpNetCore.Identity.Applcation. It contains information about the user. If you close the Postman or browser you have to re-authenticate. The cookie passed back and forth is the thing that going to know what the user is.


Next time I will show you how to implement Token based authentication which is recommended method of authentication 😉

If you want to take a look at the source code it is available in my Github repo.

[EN] Calling ASP.NET Core WebApi from angular app

In the last post I showed how to create service in Angular, now it’s time to try call ASP.NET Core webApi from it.
I created Login controller in my ASP.NET Core WebApi project which contains SignIn method. I want to execute it. I don’t have completed implementation so far, I want only to test if it works. As you see it is HttpPost method and it returns message with current date and status – true.

SignIn method gets UserDto as parameter and it’s important to add [FromBody] attribute, if we want to deserialize json object properly. Let’s start our webApi and try to call it from angular app. It will not work if you didn’t configure WebApi properly to talk with other app. You will see HTTP 415 unsupported media type error everytime you call api. It took me a while to figure it out why it didn’t work, but finally I have found a solution.

Asp.Net Core WebApi configuration

To be able to call our API with success, there is small change in the configuration needed. In Startup class we need to modify a little bit Configure method. Here is default Configure method in ASP.NET Core project

The solution is to configure CORS. There is only one line of code needed. It has to be added before calling UseMvc method.

What is CORS?

It is Cross Origin Resource Sharing. It allows web page to make requests to another domain. We need to enable CORS, because if we have two applications in this case:
– http://localhost:63698/  – backend
– http://localhost:4200/ – frontend
These are two different ports and request doesn’t work correctly without using CORS.
It can be dangerous of course, because we can allow to make requests from another malicious site, but we can specify to use CORS only from the specific origin, from our site, e.g. http://localhost:4200/. In addition CORS builder has a fluent api, so we can add chain of methods, e.g. AllowAnyHeader() or AllowAnyMethod() or we can specify accepted headers. Let’s try to test our app. Here’s my login form. I typed login data and I clicked Login. Let’s see what is in console output.

1 2Yeah it works! This time I used dev console built in Chrome to check result of my request, but there are few other alternatives I want to share with you. For sure there will be a lot of cases when you want to trace your requests in detail during project development. I can recommend you two tools that I use. The first one is Fiddler from Telerik and the second one is Postman. These tools allows you to create requests and inspect them. Let’s take a quick look on Fiddler.


It is desktop application where you can for example use filters to inspect only specific addresses, compose requests and even more.
Postman is desktop application too, but not only. It is also available as extension for Chrome browser. Postman doesn’t scan your network communication. It only allows to create requests and see results, but it is very nice. It allows to save created requests in files.


It is good to know these tools exist, because sooner or later you will find them necessary for daily work.