Using ASP NET Core 2 Identity with SQLITE

 17-Oct-2017   nityaprakash     ASPNETCORE  IDENTITY    Comments  0

We are going to configure ASPNET membership with ASP.NET Core 2.0 Web API. ASPNET membership provide many inbuilt functionality to manger users in web applications, so we don't need to create our own membership functionality. We are going to to use EntityFramework code first model and using SQLITE to store data permanently. I am using SQLITE here because, I am using Visual Studio for Mac on mac.

Required Packages

We are required to add following packages in the project:

  • Microsoft.AspNetCore.Identity
  • Microsoft.AspNetCore.Identity.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.Sqlite
  • Microsoft.IdentityModel.Tokens

Minimum Classes for Start With

We Need a UserEntity class which will inherit from Microsoft.AspNetCore.Identity.IdentityUser class.



using Microsoft.AspNetCore.Identity;

namespace IdentityDemo.Models
{

    public class UserEntity : IdentityUser
    {
             
    }
}

We are also need to create role class MyUserRole inherited from Microsoft.AspNetCore.Identity.IdentityRole.



using Microsoft.AspNetCore.Identity;

namespace IdentityDemo.Models
{
    public class MyUserRole : IdentityRole
    {

    }
}

Create ApplicationDbContext by inheriting from IdentityDbContext<UserEntity, MyUserRole, string>. IdentityDbContext stores the following Entities to store data related to ASPNET membership.

  • UserClaims
  • User
  • UserLogin
  • UserToken
  • RoleClaim
  • Role
  • UserRole


using IdentityDemo.Models
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace KanbanAPI
{
    public class ApplicationDbContext : IdentityDbContext
    {
        public ApplicationDbContext(DbContextOptions options) : base(options)
        {
            
        }

        protected ApplicationDbContext()
        {
        }
    }

}

Identity Configuration

Now we have to following code in startup.cs file in ConfigurationServices method.



        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddAuthorization(options=>{
                options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
                    .RequireAuthenticatedUser()
                    .Build();
            });

            services.AddAuthentication(o=>{
                o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>{
                options.TokenValidationParameters = new TokenValidationParameters{
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = "test",
                    ValidAudience = "test",
                    IssuerSigningKey = new SymmetricSecurityKey( Encoding.ASCII.GetBytes("secretesecretesecretesecretesecretesecrete"))

                };
            });

            services.AddDbContext( options => options.UseSqlite("Filename=./kanban.db"));

            services.AddIdentity()
            .AddEntityFrameworkStores()
            .AddDefaultTokenProviders();


        }

We have setup Authentication for the application to be able to use Identity in the application. In this case I have setup JWT Token based authentication. In the Configure function of the same class we have to app.UseAuthentication() method to be able to use Identity. As I am writing this code on mac I am using SQLITE to store the data with EntityFramework.

Code First Database Migration

There is command line tool available for .NET core to add migration. There are following commands will be used to do Code first database migration:

  • Add Migrations: dotnet ef migrations add
  • Update Database: dotnet ef database update

Which database to update will be picked up from ConfigurationService method. This too to available through CLI, it has to be added as reference. Add package Microsoft.EntityFrameworkCore.Tools.DotNet.

NOTE: When I was trying to add package/reference in project using Visual Studio for Mac, I was getting error incompatibility issue, and was able to add to the project. However, I manually opened the **.csproj** file and added below line in the file:

<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />

After running all add migration command. it will add a Migration folder in the solution and will add classes to generate ASP Net membership tables.

We are now ready with configuration and start creating Registration etc APIs.


Nitya Prakash Sharma has over 10 years of experience in .NET technology. He is currently working as Senior Consultant in industry. He is always keen to learn new things in Technology and eager to apply wherever is possible. He is also has interest in Photography, sketching and painting.

My Blog
Post Comment

COMMENTS