ASP.NET Core Identity with Cosmos DB (MongoDB) Part2: ASP.NET Core Code
Hello and welcome back to this tutorial if you remember in the part 1: "ASP.NET Core Identity with Cosmos DB (MongoDB) Part1: Database Configuration" we configured our database services local and remote to store our identity service now in this part we will configure a simple Identity service with 3 endpoints.
- Retrieve User Data
In this tutorial we will use the latests stable ASP.NET Core 2.1 using Visual Studio for Mac you can either use Visual Studio for Mac, Visual Studio for Windows, Visual Studio Code or compile the project using console.
Lets start creating a new ASP.NET Core Web Api following next steps:
Select .NET Core 2.1 as target framework
Set a project name
If everything goes well you'll see the project structure as follow
let's analyze our project structure
- Dependencies: Display and manage all project references such nuget packages, core target framework and/or any project or dll references.
- Controllers: This folder contains our controllers definitions
- Properties: This folder contains the "launchSettings.json" which allow us to configure any specific configuration of our project like startup path, enviroment vars etc.
- wwwroot: Contains all the public files used by our web app.
- appsettings.json: This file contains all release settings.
- appsettings.Development.json: This file contains all development settings.
- Program.cs: Code that create the ASP.NET Core service
- Startup.cs: Code that initilize our Web App service
Once we get familiarized with the project structure we can start with our ASP.NET Core Web Api by adding the nuget package that will allow us to configure Identity using MongoDB "AspNetCore.Identity.Mongo" by performing double click under Dependencies/NuGet and searching for it in the Add Packages Window.
This will add all package dependencies required for our web api now is time to setup our mongodb connection string into the appsettings.json files as I mentioned previously we have to appsettings.json files one for development and one for release in this case we will add the local connection string to the appsettings.Development.json file and the cosmosdb connection string into the appsettings.json file.
In order to configure our connection string we will need to add a new key with the name "ConnectionStrings" with a key and value for our connection string in this key we will use the following name "MongoDbDatabase", also in order to enable a security JWT config we will add 3 new keys "JwtKey" (Key Used to Encript Token), "JwtIssuer" (Token Issuer) & "JwtExpireDays" (Expire value in days), after complete the process in both files you'll see the next file structure:
Now is time to start adding some code in our project, we will add a custom User and Role entities just in case that you want to add a custom field into your app roles and users, the files structure will be the next:
After add both files into our project now we can configure our Identity MongoDB service into the Startup.cs -> ConfigureServices method by adding services.AddMongoIdentityProvider<TUser, TRole>(stringConnection, optionsConfigCallback); in the optionsConfigCallback we can set common identity settings for User, Password, SignIn and many others configuration items.
Also in this method we will need to add the JWT Security Authentication config the Startup.cs -> ConfigureServices will be something similar as the following code:
Now we're able to start creating a few entities to transfer json client request/responses into C# objects and manipulate then usen the annotations standard helpers and avoid extra manual validation we need 3 for responses and 2 for requests using the next structure:
After that we will be able to create our main controller to expose 3 main endpoints 1 for register, 1 for login and 1 for retrieve user data we can re-use the default values controller under Controllers folder or just create a new one under the Controllers folder(right-click -> Add -> New File)
Your controller need to have the base class and router configuration
"api/v1/" - will be the default path for out endpoint as a good practice you can use versioning for your endpoints is not mandatory but I'll help to manage different versions of your endpoints.
"[controller]/" - this will take the name of your controller if you use standard naming for controller like this examples "User-Controller" controllertype + "Controller" in this case the api will take the controllertype name "user" "api/v1/user".
"[action]" - this will take by default the name of the method as the name of the action in this case "userdata", "register" & "login".
you'll noticed that 2 endpoints doesn't need to be protected since we will recibe only info to register/login but for the "userdata" we will add an standard authentication validation using a Bearer token that one will be provide over the json reponse of regiser and login endpoints the final code for UserController will be the next
After this now we're able to test our endpoints in any client library like postman since we have a self signed ssl certificate for localhost make sure that your client allow to consume that kind of services.
The config will be the next for requests.
1) Request Headers:
/api/v1/user/register & /api/v1/user/login
Authorization: Bearer yourToken
2) Request Type
/api/v1/user/register - POST
/api/v1/user/login - POST
/api/v1/user/userdata - GET
If you want to publish your service to azure is very easy using the visual studio tool and follow the steps there:
We just completed our api service code now we need to create a client to consume our service in the final part I'll show you how to create a very fast Mobile App using Xamarin.Forms to consume our rest services.
GITHUB COMPLETE CODE: https://github.com/AlejandroRuiz/CosmosDBTutorial
HAPPY CODE :)