[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.

1

[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.

0

Here is a sample of encoded token

Useful web page for decoding JWT tokens is https://jwt.io/. I recommend you to check it.

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

1a

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.

Implementation

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.

2

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.

3

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.

 4

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.

1

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.

2

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.

4

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.

5

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

[EN] Creating component and service in Angular2

Two posts ago I wrote about Angular2 application and I showed how to add new component and service. This time I want to show you how to implement a service in Angular2 and call webApi from it.

I decided to create login service in angular app which calls SignIn method from webApi (request via http post method).

Ok, let’s start. I have login.component and login.service in my angular app. First we need to make sure if login service is imported in login.module.ts and if it is added to providers list.

Next let’s implement the service.

First we need to import few things. You can ignore app/constants as you can see in my code, it’s just simple typescript class that contains constants. In the constructor we need to create http variable which will be used later.
SignIn function takes two parameters: username and password and returns boolean value. Then we have to construct http request that will be send to webApi. It’s very important to add headers that informs request contains json content, because webApi only accepts jsons. After http.post method there’s another method – map, which transforms the result to whatever we want.

Next is time to implement some code in login.component class. Let’s start from imports, don’t forget to import our service.

I have few variables in my login component, like username, password and 3 others that indicate an error. You can skip it, it’s not needed to achieve our goal from this post. I use it only to check if username and password are valid and show an error message in case they are not valid.

Let’s focus on onLogin() method. After few validations signIn method from login service is called with username and password which are passed as arguments. Subscribe method allows to define operation that we want to execute when result will come. I want to save username in localstorage and navigate to different component – welcome component.

What about login.component.html? It depends from you how you want to design it. There are a lot of samples in bootstrap 😉 Here is mine.

1

Basically you need to create a form.

and add ngSubmit directive that enables binding expressions to onsubmit events. We have onLogin method in login component that will handle it. We need also to bind input controls to our model

It will bind value from this control to _username variable in component class. I have also method binds to keyup event, but it’s only for validating input data. onKeyUp method in the component is responsible for it.

It looks we have all. Our service in Angular2 is ready. Now it’s time to start app and try to call webApi, but we will take a look at it in the next post.

[EN] How to debug angular app in VS Code and Chrome

I have started to develop frontend side of my pet project and yesterday I worked on login service and I had to debug it. I use Visual Studio Code to write app in angular2 and typescript and I thought why not to use VS Code for debugging? Ok, but not so fast. Few steps are required to achieve it.

In VS code open cmd palette with key combination Ctrl+Shift+P and type:

Then type Debugger for Chrome in extensions manager and install it.

1

After installation restart VS code.

Next go to Debugger or press Ctrl+Shift+D and click on the gear icon to create launch.json file.

2

By default it looks like this:

but to be able to debug angular app you need to modify it. My launch.json file looks like this:

Url is default url where angular app is located,  port: 9222 is the port used by Chrome browser.

In this config file there are two configs, one of these is for launching chrome with attached debugger and the second one is for attaching existing chrome instance. Let’s try to launch new chrome window. Click on green start icon.

3

Now you can just put a breakpoint in VS Code, wherever you want and you can debug your angular app 😉

[EN] How to add Autofac container to ASP.NET Core app?

I created few projects in my solution. I have models, services, tests and webApi project. I added LoginController which uses Services, but it uses it by interfaces. I need to use dependency injection to resolve it for me. I decided to add Autofac. It is IoC container which allow us to register all types and it’s implementations, to inject specific types for us. In the last year I wrote post how to add Autofac to ASP.NET MVC app, but post is in Polish and adding Autofac to .NET Core app is slighty different than the last time.

First step to add Autofac to our project is to download nuget package Autofac.Extensions.DependencyInjection.

1

Next step is to register all types from assemblies. We need to do it for each assembly (install Autofac too). For example I have ELP.Model, ELP.Service, ELP.WebApi projects and I want to register all types from them. To do it let’s start from ELP.Service project. I prefer to add new interface to it. Just empty interface to determine assembly.

Add also new class derived from Autofac.Module class and override Load method.

As you see the interface is only to get type info from it to get all assemblies and register it in the container. We need to repeat these steps for each project (in my case ELP.Model, ELP.WebApi). This method is very helpful, because every type will be registered automatically without our attention. When we add new interface and class that implements it, no action is required. Autofac does all for us!

Ok if we have modules, it’s time to modify Startup class a little bit.
Add new property ApplicationContainer of IContainer type. Then Create Container builder in ConfigureServices method and register all modules in it, then build and return result in ApplicationContainer. Take a look at my Startup class below.

That’s it. You can ask what if I have few types that implements one interface? How Autofac handles it? It registers the newest one, but maybe there will be a situation when you want to register specific type, then you can do it like this

If you want to use Autofac in you applications I recommend you to take a look at the documentation, where you can read more about it.

[EN] Angular2 – project structure, changing css to sass, using CLI

Angular2 project structure

Few posts ago I showed how to create new Angular2 project using Angular CLI. Let’s take a look at the project structure. Here we have app folder which contains few items.

post7

Look at the diagram below to better understand this structure.

2

By default we have AppModule and AppComponent which is inside AppModule. This is how Angular2 project structure looks. We can have more components in one module and more modules with components of course.

34

Take a look into code. This is app.module class. It contains few core imports that come from angular library itself. There is also import of app.component class that has to be loaded. Beside it this class is empty for now.

Look at the app.component class. It imports angular/core only, but it has another interesting thing inside component. There is selector ‚app-root’ which will be used in index.html to display component interior, templateUrl which is link to html file with view for this component, styleUrls which is link to css file for our view. Inside class AppComponent we have title – ‚app works!’ which is visible when you run application.

Changing css to sass

Ok, we have css, but what if I want to have sass – css with super powers 😀 Sass is CSS pre-processor and allows you use variables, nested rules and more. It allows to create stylesheets faster. To change css to sass, first we need to download sass with npm

then set default extensions in our project

then we need to change styles from .css to .sass in .angular-cli.json file

and rename file from app.component.css to app.component.sass and rename another file from styles.css to styles.sass. In addition there’s one modification needed in app.component.ts file. StyleUrls should refer to sass file, not css file.

ok project supports sass files now.
Let’s implement something in our project. As I mentiond before about modules and components, every module should be created for one feature.

Using CLI

I want to start from implementing login module, so let’s create module using CLI.
It is so simple. Just type in powershell command

this command will create new module file in folder. Awesome! You don’t need to know best practices for organising your project, CLI does it for you.

5

The same situation is when we want to add component or service. Try it.

After executing these commands app folder looks like this. I created login.service, because it will be a part responsible for communicating with WebApi. Login.component will use this service. Unfortunately login.service is not in login folder. I want to have everything connected with login in one folder for better organisation so I will move it.

6

In official angular cli’s readme , we can see all possibillities that we have to generate files.

7

You can read more here.
Ok, project is ready to start implementation of login component. Maybe I will describe in next post how to connect WebApi. We will see 😉

[EN] Entity Framework Core – Code First migrations

In this post I want to show you how to create new database using Entity Framework Core – Code First migrations approach.

codefirst

I have project ELP.Model in which I defined few entities. I want to create database from it. It is approach called Code First. This is how looks one of my entity

To be able to enable migration and create database, we need to create Context. My Context Class looks like this

We need to install few packages before we start with actual migration.

To do it, open Package Manager Console (In VS Tools-> Nuget Package Manager -> Package Manager Console) set Default Project to your target project and install packages. Make sure to install the newest versions or the same versions for all.

To enable migrations in our project first we need to type in the same console Add-Migration MigrationName

and here is surprise. Not so easy man. I missed something. Yes exactly, we need to add implementation of IDbContextFactory<ELPContext>

1

This class should look like this:

Another Try to Add Migration and … another error…

2

What da… !? It looks like it is an issue in EF Core v 1.1.0. Work around for it is to change version to 1.0 :/ To do it we need to modify TargetFramework in csproj file from netcoreapp1.1 to netcoreapp1.0

3

4

Another try

Uff now everything works fine.

5

Take a look into Solution Explorer. Here we have new classes and Migrations folder.

6

The last step is to execute Update-Database command in Package Manager Console.

Fortunately this time it worked for me in first try. I didn’t expect it will be so easy 😉

To verify it, open SQL Server Object Explorer and check it. It should create new database.

7

Yeah, we have created database, nice. Now we can add something to it 🙂