Monday, October 30, 2017

ASP.NET Core MVC + Web API app with EF Core 2.0 & SQLite

This tutorial uses Visual Studio 2017 and ASP.NET Core 2.0. 

My intention is to give you a practical introduction into developing ASP.NET Core 2.0 MVC and Web API apps with the SQLite database as an alternative to traditional SQL Server.

A useful utility that comes in handy when working with the SQLite database is SQLiteStudio. Download SQLiteStudio from: http://sqlitestudio.pl/?act=download. Extract the ZIP file and place contents in a separate folder. Run SQLiteStudio.exe.

We will build an ASP.NET Core 2.0 app that uses the following Student entity:
image_thumb1

ASP.NET Core 2.0 MVC project

In a working directory, create a folder named SQLiteWeb. Change to the SQLiteWeb directory. Try out some of these important .NET Core 2.0 commands:





  1. dotnet --help – this gives you a list of common commands
  2. dotnet restore – restore dependencies specified in the .NET project
  3. dotnet build - Builds a .NET project
  4. dotnet run --help – provides help information about the run command
  5. dotnet new --help – shows the types of templates that can be scaffolded. At the time of writing these are 18 different templates
  6. dotnet new mvc --help – shows switches that can be used when creating an MVC application
We will create an MVC application that uses "Individual authentication" and the SQLite database. 
Execute the following terminal command from within the SQLite directory: 

dotnet new mvc --auth Individual


A web app is created for you and all Nuget packages are automatically restored. To run the application, 
execute the following command inside the terminal window:

dotnet run

Notice a message similar to the following:

Hosting environment: Production
Content root path: E:\_DEMO\SQLiteWeb
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.



As described in the message, point your browser to http://localhost:5000 and you will see the default 
ASP.NET Core page:


image

This runs your application in a web server called Kestrel that is listening on port 5000. Register a new user.

Stop the web server by hitting I. If you are curious about where the data is saved and the location of the SQLite database, you will find a *.db file located in the bin/Debug/netcoreapp2.0 directory. Have a peek at its contents using the SQLiteStudio utility mentioned earlier in this article.

To open your web application in Visual Studio, start Visual Studio then open the SQLiteWeb.csproj file.

File >> Open >> Project Solution


Hit CTRL + F5 in Visual Studio 2017. This time, the web application will start and will be hosted by IIS Express

When working with ASP.NET Core, you will need to go to the command-line interface frequently. Add a command-prompt extension to make it easier. Click on Tools >> Extensions and Updates

image

Find an extension named “Open Command Line” as shown below.

image

If you have not installed it already, install the above extension.

In solution explorer, right-click on the SQLiteWeb node the choose “Open Command Line” >> “Default (cmd)

image

This opens a regular operating system terminal window. 

The Student class

Inside of the Models folder, add a class file named Student.cs. Use the following code for the class file:

public class Student {
  public int StudentId { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string School { get; set; }
  public DateTime StartDate { get; set; }
}


Add the following property to the ApplicationSbContext.cs class file located in the Data directory.

  public DbSet<Student> Students { get; set; }

Notice the connection string in the appsettings.json file:


{
   "ConnectionStrings": {
      "DefaultConnection": "DataSource=app.db"
   },
   "Logging": {
      "IncludeScopes": false,
      "LogLevel": {
         "Default": "Warning"
      }
   }
}

Migrations

We are now ready to do some migrations: 
  • Compile your application
  • Open a command terminal inside the  main project SQLiteWeb folder
  • Add a migration to the project with the following ef command:
dotnet ef migrations add "First Migration"

Notice that class files are created in the Migrations folder.
  • We will then update the database with the following terminal command:
dotnet ef database update

Seed Data

Before we carry out code first migrations, let us first create some seed data: 
  • In the Models folder, create a class named DummyData.cs.
  • Add the following Initialize() method code inside the DummyData class:
public static void Initialize(ApplicationDbContext db) {
  if (!db.Students.Any()) {
    db.Students.Add(new Student {
      FirstName = "Bob",
      LastName = "Doe",
      School = "Engineering",
      StartDate = Convert.ToDateTime("2015/09/09")
    });
    db.Students.Add(new Student {
      FirstName = "Ann",
      LastName = "Lee",
      School = "Medicine",
      StartDate = Convert.ToDateTime("2014/09/09")
    });
    db.Students.Add(new Student {
      FirstName = "Sue",
      LastName = "Douglas",
      School = "Pharmacy",
      StartDate = Convert.ToDateTime("2016/01/01")
    });
    db.Students.Add(new Student {
      FirstName = "Tom",
      LastName = "Brown",
      School = "Business",
      StartDate = Convert.ToDateTime("2015/09/09")
    });
    db.Students.Add(new Student {
      FirstName = "Joe",
      LastName = "Mason",
      School = "Health",
      StartDate = Convert.ToDateTime("2015/01/01")
    });
    db.SaveChanges();
  }
}

To generate seed data, we will first inject the dependency “ApplicationDbContext context” into the arguments of the Configure() method in Startup.cs. 
Next, we can make a call to seed the data at the bottom of the Configure() method with the following statement:
      
DummyData.Initialize(context);

At this point, data will not have been seeded yet because this happens when the application is actually run.

Creating an MVC UI

Let us seed the data by running your web application in a browser. You should see the same page as we saw earlier. Let us create a UI so that we can see the seeded data.

  • Right-click on the Controllers folder and choose Add >> New Item… >> Controller...
  • Choose "MVC Controller with views, using Entity Framework" then click on Add.
  • Model Class=Student, Data context class=ApplicationDbContext
Click on Add. If you are asked to save the solution file then accept the default location and save it in your project root folder.


You’ll notice that the controller takes a ApplicationDbContext as a constructor parameter. ASP.NET dependency injection will take care of passing an instance of ApplicationDbContext into your controller.

The controller contains an Index action, which displays all students in the database, and a Create action, which inserts a new student into the database.

  • Let us add a link to the Students controller on the main page of our application. Open _Layout.cshtml under Views/Shared.
  • Paste the following markup in the navigation section around line 36:

<li><a asp-area="" asp-controller="Students" asp-action="Index">Students</a></li>


  • Run the application then click on the Students link. You should see the dummy data that we created.

image

  • Add a new student to the database.


The WebAPI Controller


Let us add a Web API Studentsapi controller to our projects. 
  • Right-click on the Controllers folder >> Add > Controller...
  • Select "API Controller with actions, using Entity Framework" then click Add.
  • Model class=Student, Data context class=ApplicationDbContext, Controller name=StudentsapiController
  • Click on Add
  • Hit CTRL-F5 on your keyboard and point your browser to /api/studentapi. You will see the seed data appearing as JSON in the browser:
image_thumb11

Saturday, October 28, 2017

Deploying web apps to Azure using Git

In previous posts, I showed two ways (GitHub & FTP) of deploying web apps to Azure. See the following articles:

Continuous deployment of ASP.NET MVC 5 app to Azure thru GitHub
http://blog.medhat.ca/2016/10/connecting-to-azure-website-with-ftp.html

In this post, I will show you how to deploy a PHP web app to Azure by directly using the Git repository that resides in Azure itself.
The following are prerequisites:
In this example, I am using a PHP app that simply shows some cartoon characters. The output of the PHP app looks like this:

image

Login into portal.azure.com. On the left-side, click on “App Services”.

image

Click on “+ Add”.

image

Click on “Web app”.

image

On the next blade, click on the “Create” button.

image

Enter a unique name for App name. Choose your subscription, select to create a new Resource Group, select an App Service plan/Location then click on Create.

image

The web application will be created for you in less than two minutes. When it is ready, you will see it in the list of your App services.

image

Click on the newly created app service on the first blade. In the above example it is toon. Then, click on Deployment credentials.

image

Enter a unique FTP/deployment username and Password. Note that these credentials can be used for both FTP and Git. Also, these same credentials can be used for this web app as well as other web apps that you may have already created or those that you plan to create in the future. Therefore, it important that you remember these credentials. If you forget the credentials, then you can always create a new pair of username and password.

image

Our next step is to let Azure know that we want to deploy our web app using Git. Click on “Deployment options”.

image

Click on “Choose Source” then select “Local Git Repository”.

image

Afterwards, click on OK.

image

Next, we need to obtain the URL of the remote Git repository on Azure. Click on Overview.

image

Copy the “Git clone url” and save it in a text editor like Notepad. This will later be used to push your code from your computer to Azure. Note that you can conveniently click on a toolbar on the right of the Git URL to copy it.

image

Now, back on your computer, open a terminal window in the working directory of the web application that you wish to deploy. Run the following Git commands:
git init
git add .
git commit –m “first commit”
git remote add azure {the url of the remote Azure Git repository}
git push azure master
Right after you execute the last push command, you will be prompted to authenticate with your deployment credentials in Azure. These are the credentials that you created earlier.

image

Once your credentials are accepted, the push process will commence. When it is all finished, you can verify that your code was accepted by Azure by clicking on “Deployment options” in Azure.You should see a check mark beside your commit.

image

The true test is to go to the website and see whether or not it indeed works. Click on Overview. The website URL is on the right side of the last blade. Click on it.

image

The website should show up in your browser.

image

What next? Make a change to your code and push it to the remote Git repository on Azure. You will soon after notice that the change you made is reflected on your web application.

Thanks for coming this far in my article.

Wednesday, March 29, 2017

Build an ASP.NET Core 1.1 tag helper that consumes Azure Web API RESTful service

In a previous post, I demonstrated how to create an ASP.NET Core 1.0 tag helper. Since ASP.NET 1.1 was released, some of the packages in the previous post are not supported anymore. Therefore, I am hereby updating this article to fix this issue. I am also using Visual Studio 2017 instead of Visual Studio 2015.

Tag Helpers in ASP.NET Core allow you to create your own tags that fulfill a server-side purpose. In this tutorial, I will show you how to create a tag helper <toon> that accesses a Web API service and displays contents in any razor view page.

The Web API service we will consume in this exercise is located at http://cartoonapi.azurewebsites.net/api/cartoon. It delivers the names of cartoon characters and their respective images.

1) To start with, create an ASP.NET Core Web application named ToonTagHelper in Visual Studio 2017.

2) We need to create a class that closely matches the nature of the Web API JSON object. Therefore, add the following Toon class to a Models folder in your project:
public class Toon {
  public string Name { get; set; }
  public string PictureUrl { get; set; }
}
3) Next, we need to install the We API Client libraries. To that end, execute the following commands from within the Package Manager Console window in Visual Studio 2017:
Install-Package Newtonsoft.Json
Install-Package System.Net.Http
Install-Package System.Runtime.Serialization.Xml
Alternatively, you can run the following commands from within a terminal window:
dotnet add package Newtonsoft.Json
dotnet add package System.Net.Http
dotnet add package System.Runtime.Serialization.Xml

This should add the following dependencies to your project.json file:
<PackageReference Include="Newtonsoft.Json" Version="10.0.1" />
<PackageReference Include="System.Net.Http" Version="4.3.1" />
<PackageReference Include="System.Runtime.Serialization.Xml" Version="4.3.0" />
4) Add the following tag to the bottom of Views/Home/About.cshtml:


<toon></toon>

5) Create a folder named TagHelpers and add to it a class file named ToonTag.cs. Have the class inherit from TagHelper and implement the ProcessAsync() method as follows:

public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
}


We could have implemented a method Process() instead. However, in our case, it is appropriate to implement ProcessAsync() instead because we are about to make an async call to a remote service.

6) Add the following instance variable to the ToonTagHelper class:
 private string baseUrl = "http://cartoonapi.azurewebsites.net";

7) Annotate the CartoonCharactersTagHelper class with the following:

[HtmlTargetElement("toon")]
[HtmlTargetElement(Attributes = "toon")]


The first annotation defines the tag <toon> and the second defines the “toon” attribute. This means that we have two different ways to produce the same output on a razor .cshtml view.

8) Add the following method to the ToonTagHelper class:

async Task<IEnumerable<Toon>> GetToonsAsync() {
  HttpClient client = new HttpClient();
  client.BaseAddress = new Uri(baseUrl);
  client.DefaultRequestHeaders.Accept.Clear();
  client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  IEnumerable<Toon> toons = null;
  try {
    // Get all cartoon characters
    HttpResponseMessage response = await client.GetAsync("/api/cartoon");
    if (response.IsSuccessStatusCode)
    {
       string json = await response.Content.ReadAsStringAsync();
      toons = JsonConvert.DeserializeObject<IEnumerable<Toon>>(json);
    }
  } catch (Exception e) {
      System.Diagnostics.Debug.WriteLine(e.ToString());
  }
  return toons;
}



The above code makes a request to the Web API service and returns an IEnumerable<Toon> collection with the results.

9) Add the following code inside the ProcessAsync() method:

IEnumerable<Toon> toons= await GetToonsAsync();
string html = string.Empty;
html += "<table><tr><th>Name</th><th>Picture</th></tr>";
foreach (var item in toons) {
    string photoUrl = baseUrl + "/" + item.PictureUrl;
    html += "<tr>";
    html += "<td>" + item.Name + "</td>";
    html += "<td><img src='" + photoUrl + "' style='width: 50px' /></td>";
    html += "</tr>";
}
html += "</table>";
output.Content.SetHtmlContent(html);


The above code creates a table with the collection of cartoon characters so that it can be displayed wherever the tag helper is used.

11) Register the tag name in the Views/_ViewImports.cshtml file by adding the following to the list of tags that are already there:

@addTagHelper "ToonTagHelper.TagHelpers.ToonTag, ToonTagHelper"

You may need to adjust the above names depending on what you called your app and/or your tag helper class.

11) Compile and run your application, then click on About. You should see the following output:



If you inspect the table in your browser, you will see the following:



The above is using the tag and not the attribute. Edit About.cshtml and comment out “<toon></toon>” and put the following <div> tag with the toon attribute underneath it:
<div toon></div>

Your About.cshtml should now look like this:
@{
    ViewData["Title"] = "About";
}
<h2>@ViewData["Title"].</h2>
<h3>@ViewData["Message"]</h3>

<p>Use this area to provide additional information.</p>
@*<toon></toon>*@
<div toon></div>
When you run your application. you should see the same output as before. However, upon inspection of the HTML source, you will notice that a <div> tag is the primary container for our code rather than a <toon> tag:



This proves to us that you can either use tags or attributes with TagHelpers in ASP.NET Core.

Friday, March 24, 2017

Token authentication with OpenIdDict in ASP.NET Core 1.1

OpenIddict provides a simple solution to implement an OpenID Connect server for any ASP.NET Core 1.1 application.

The official GitHub project is located at https://github.com/openiddict/openiddict-core. In this tutorial, I will show you how to easily implement OpenIdDict with a very basic ASP.NET Core 1.1 MVC/WebAPI project created using the dotnet command line interface. Let’s get started:
Pre-requisites:

Creating web application project in Visual Studio 2015

To ensure that you have the correct version of .NET Core installed on your computer, execute the following command in a terminal window:

dotnet --version

If the number 1.01 appears then you have the correct version. We need to know what templates we can use to generate our ASP.NET application using the dotnet command line interface. Type the following inside your terminal window:

dotnet new --list

At the bottom of the output, you should see this:

Templates                 Short Name      Language      Tags
----------------------------------------------------------------------
Console Application       console         [C#], F#      Common/Console
Class library             classlib        [C#], F#      Common/Library
Unit Test Project         mstest          [C#], F#      Test/MSTest
xUnit Test Project        xunit           [C#], F#      Test/xUnit
ASP.NET Core Empty        web             [C#]          Web/Empty
ASP.NET Core Web App      mvc             [C#], F#      Web/MVCASP.NET Core Web API      webapi          [C#]          Web/WebAPI
Solution File             sln                           Solution


Let us use the MVC template to generate an ASP.NET Core 1.1 application. In your workspace, create a folder named AspToken and go into that folder as follows:
mkdir AspToken
cd AspToken
Use the following command to create an app with individual authentication and SQLite:

dotnet new mvc --auth Individual --framework netcoreapp1.1

In order to run the application, execute the following commands in sequence:
dotnet restore
dotnet ef database update
bower install bootstrap
dotnet run
Point your browser to http://localhost:5000 and you will see a page that looks like this:

image

Click on Register on the top right-side and create a user. I created a user with email = a@a.a and password = P@$$w0rd.

Once you create the user, logout.

Open the root folder of your application in Visual Studio Code (or any other editor you prefer). In Visual Studio Code, it will look like this:

image

Inside the Controllers folder, create a file named ValuesController.cs and add to it the following code:
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
namespace AspToken.Controllers {
  [Produces("application/json")]
  [Route("api/Values")]
  public class ValuesController : Controller {
    // GET: api/Values
    [HttpGet]
    public IEnumerable<string> Get() {
        return new string[] { "value1", "value2" };
    }

    // GET: api/Values/5
    [HttpGet("{id}", Name = "Get")]
    public string Get(int id) {
        return "value";
    }
    // POST: api/Values
    [HttpPost]
    public void Post([FromBody]string value) {
    }
    // PUT: api/Values/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody]string value) {
    }
    // DELETE: api/ApiWithActions/5
    [HttpDelete("{id}")]
    public void Delete(int id) {
    }
  }
}
Stop the web server, execute “dotnet build” followed by “dotnet run”. The route that will be used for this controller is “api/Values”. To view the output from this controller, add /api/values to the localhost address in your browser. The following will be what the API looks like in a browser:

image


To enforce authentication, add the [Authorize] annotation to the ValuesController class. If you run your app again and refresh the page, you will see the following:

image


Obviously, a login dialog is of no use to API services because we need to find a way to send our credentials through API calls by passing tokens rather than using a login form. It is at this juncture that we decide to use the OpenIdDict framework.
Adding OpenIdDict to the web application project
1) Create a file in the main solution directory named NuGet.Config and add to it the following XML markup:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="nuget.org" value="
https://api.nuget.org/v3/index.json" />
    <add key="aspnet-contrib" value="
https://www.myget.org/F/aspnet-contrib/api/v3/index.json" />
  </packageSources>
</configuration>


Contents of your root solution directory will look like this:

image


The NuGet.Config file is needed because OpenIdDict is not yet an official Nuget release at the time of writing this article.

2) Update your .csproj project file with the following dependencies:

<!-- OpenIdDict -->
<PackageReference Include="AspNet.Security.OAuth.Validation" Version="1.0.0-*" />
<PackageReference Include="OpenIddict" Version="1.0.0-*" />
<PackageReference Include="OpenIddict.EntityFrameworkCore" Version="1.0.0-*" />
<PackageReference Include="OpenIddict.Mvc" Version="1.0.0-*" />


3) In the Startup.cs file, make the following changes at the top of ConfigureServices() method:

Replace this:
services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
With this:
services.AddDbContext<ApplicationDbContext>(options =>{
  options.UseSqlite(Configuration.GetConnectionString("DefaultConnection"));
  options.UseOpenIddict();
});
4) Also in the Startup.cs file, add the following code to the ConfigureServices() method right before services AddMvc():

// Configure Identity to use the same JWT claims as OpenIddict instead
// of the legacy WS-Federation claims it uses by default (ClaimTypes),
// which saves you from doing the mapping in your authorization controller.
services.Configure<IdentityOptions>(options =>
{
  options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
  options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
  options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
});


services.AddOpenIddict(options =>
{
  // Register the Entity Framework stores.
  options.AddEntityFrameworkCoreStores<ApplicationDbContext>();
  // Register the ASP.NET Core MVC binder used by OpenIddict.
  // Note: if you don't call this method, you won't be able to
  // bind OpenIdConnectRequest or OpenIdConnectResponse parameters.
  options.AddMvcBinders();
  // Enable the token endpoint.
  options.EnableTokenEndpoint("/connect/token");
  // Enable the password flow.
  options.AllowPasswordFlow();
  // During development, you can disable the HTTPS requirement.
  options.DisableHttpsRequirement();
});

The above code sets up an endpoint for login through token authentication. A controller will be added later that provides an endpoint at /connect/token.

Build your app to ensure there are no syntax or compiler errors.

5) Add the following code to the Configure() method in Startup.cs between app.UseIdentity() and app.UseMvc():
app.UseOAuthValidation();
app.UseOpenIddict();
This adds OpenIddict and the OAuth2 token validation middleware to the ASP.NET Core pipeline.

6) In the Startup.cs file, make the following changes in the Configure() method:

Replace this:
app.UseMvc(routes =>
{
  routes.MapRoute(
      name: "default",
      template: "{controller=Home}/{action=Index}/{id?}");
});
With this:
app.UseMvcWithDefaultRoute();
7) You need to add an authorization controller to provide the endpoint /connect/token. Copy the authorization controller from the OpenIdDict project on GitHub and add it to the Controllers folder. Alternatively, you can instead use the code below for the AuthorizationController class:

/*
 * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
 * See https://github.com/openiddict/openiddict-core for more information concerning
 * the license and the contributors participating to this project.
 */

using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using AspNet.Security.OpenIdConnect.Extensions;
using AspNet.Security.OpenIdConnect.Primitives;
using AspNet.Security.OpenIdConnect.Server;
using AspToken.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using OpenIddict.Core;

namespace AspToken.Controllers
{
    public class AuthorizationController : Controller {
        private readonly IOptions<IdentityOptions> _identityOptions;
        private readonly SignInManager<ApplicationUser> _signInManager;
        private readonly UserManager<ApplicationUser> _userManager;

        public AuthorizationController(
            IOptions<IdentityOptions> identityOptions,
            SignInManager<ApplicationUser> signInManager,
            UserManager<ApplicationUser> userManager) {
            _identityOptions = identityOptions;
            _signInManager = signInManager;
            _userManager = userManager;
        }

        [HttpPost("~/connect/token"), Produces("application/json")]
        public async Task<IActionResult> Exchange(OpenIdConnectRequest request) {
            Debug.Assert(request.IsTokenRequest(),
                "The OpenIddict binder for ASP.NET Core MVC is not registered. " +
                "Make sure services.AddOpenIddict().AddMvcBinders() is correctly called.");

            if (request.IsPasswordGrantType()) {
                var user = await _userManager.FindByNameAsync(request.Username);
                if (user == null)  {
                    return BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The username/password couple is invalid."
                    });
                }

                // Ensure the user is allowed to sign in.
                if (!await _signInManager.CanSignInAsync(user)) {
                    return BadRequest(new OpenIdConnectResponse {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The specified user is not allowed to sign in."
                    });
                }

                // Reject the token request if two-factor authentication has been enabled by the user.
                if (_userManager.SupportsUserTwoFactor && await _userManager.GetTwoFactorEnabledAsync(user)) {
                    return BadRequest(new OpenIdConnectResponse {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The specified user is not allowed to sign in."
                    });
                }

                // Ensure the user is not already locked out.
                if (_userManager.SupportsUserLockout && await _userManager.IsLockedOutAsync(user)) {
                    return BadRequest(new OpenIdConnectResponse {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The username/password couple is invalid."
                    });
                }

                // Ensure the password is valid.
                if (!await _userManager.CheckPasswordAsync(user, request.Password)) {
                    if (_userManager.SupportsUserLockout) {
                        await _userManager.AccessFailedAsync(user);
                    }

                    return BadRequest(new OpenIdConnectResponse {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The username/password couple is invalid."
                    });
                }

                if (_userManager.SupportsUserLockout) {
                    await _userManager.ResetAccessFailedCountAsync(user);
                }

                // Create a new authentication ticket.
                var ticket = await CreateTicketAsync(request, user);

                return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
            } else if (request.IsRefreshTokenGrantType()) {
                // Retrieve the claims principal stored in the refresh token.
                var info = await HttpContext.Authentication.GetAuthenticateInfoAsync(
                    OpenIdConnectServerDefaults.AuthenticationScheme);

                // Retrieve the user profile corresponding to the refresh token.
                // Note: if you want to automatically invalidate the refresh token
                // when the user password/roles change, use the following line instead:
                // var user = _signInManager.ValidateSecurityStampAsync(info.Principal);
                var user = await _userManager.GetUserAsync(info.Principal);
                if (user == null) {
                    return BadRequest(new OpenIdConnectResponse {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The refresh token is no longer valid."
                    });
                }

                // Ensure the user is still allowed to sign in.
                if (!await _signInManager.CanSignInAsync(user)) {
                    return BadRequest(new OpenIdConnectResponse {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The user is no longer allowed to sign in."
                    });
                }

                // Create a new authentication ticket, but reuse the properties stored
                // in the refresh token, including the scopes originally granted.
                var ticket = await CreateTicketAsync(request, user, info.Properties);

                return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
            }

            return BadRequest(new OpenIdConnectResponse {
                Error = OpenIdConnectConstants.Errors.UnsupportedGrantType,
                ErrorDescription = "The specified grant type is not supported."
            });
        }

        private async Task<AuthenticationTicket> CreateTicketAsync(
            OpenIdConnectRequest request, ApplicationUser user,
            AuthenticationProperties properties = null) {
            // Create a new ClaimsPrincipal containing the claims that
            // will be used to create an id_token, a token or a code.
            var principal = await _signInManager.CreateUserPrincipalAsync(user);

            // Create a new authentication ticket holding the user identity.
            var ticket = new AuthenticationTicket(principal, properties,
                OpenIdConnectServerDefaults.AuthenticationScheme);

            if (!request.IsRefreshTokenGrantType()) {
                // Set the list of scopes granted to the client application.
                // Note: the offline_access scope must be granted
                // to allow OpenIddict to return a refresh token.
                ticket.SetScopes(new[] {
                    OpenIdConnectConstants.Scopes.OpenId,
                    OpenIdConnectConstants.Scopes.Email,
                    OpenIdConnectConstants.Scopes.Profile,
                    OpenIdConnectConstants.Scopes.OfflineAccess,
                    OpenIddictConstants.Scopes.Roles
                }.Intersect(request.GetScopes()));
            }
            ticket.SetResources("resource_server");

            // Note: by default, claims are NOT automatically included in the access and identity tokens.
            // To allow OpenIddict to serialize them, you must attach them a destination, that specifies
            // whether they should be included in access tokens, in identity tokens or in both.

            foreach (var claim in ticket.Principal.Claims) {
                // Never include the security stamp in the access and identity tokens, as it's a secret value.
                if (claim.Type == _identityOptions.Value.ClaimsIdentity.SecurityStampClaimType) {
                    continue;
                }

                var destinations = new List<string> {
                    OpenIdConnectConstants.Destinations.AccessToken
                };

                // Only add the iterated claim to the id_token if the corresponding scope was granted to the client application.
                // The other claims will only be added to the access_token, which is encrypted when using the default format.
                if ((claim.Type == OpenIdConnectConstants.Claims.Name && ticket.HasScope(OpenIdConnectConstants.Scopes.Profile)) ||
                    (claim.Type == OpenIdConnectConstants.Claims.Email && ticket.HasScope(OpenIdConnectConstants.Scopes.Email)) ||
                    (claim.Type == OpenIdConnectConstants.Claims.Role && ticket.HasScope(OpenIddictConstants.Claims.Roles)))
                {
                    destinations.Add(OpenIdConnectConstants.Destinations.IdentityToken);
                }
                claim.SetDestinations(destinations);
            }
            return ticket;
        }
    }

}

Make sure your application builds without any errors.
Testing authorization with postman
Before proceeding with testing token authentication, make sure you already created a user with email and password.

There is a handy Google Chrome extension called “postman” that you can install from the Chrome Web Store. The icon of the extension I am referring to looks like this:

image


In Postman, do the following:

image


1) Select POST for the HTTP method.
2) Enter the Web API login endpoint. In the above example, the login endpoint is http://localhost:5000/connect/token/. In your case, you may have to only correct the port number.
3) Click on Body.
4) Click on x-www.form-urlencoded.
5) In entered the following parameter name/value pairs:
username: a@a.a
password: P@$$w0rd
grant_type: password
6) Finally, click on the Send button to initiate the request. The response from the server will look like this:

{
  "resource": "resource_server",
  "token_type": "Bearer",
  "access_token": "CfDJ8AJFDskine9Jhavjj9lbv4Rr7pEocsejCXl24utNyr58SbYfZ6-7gDEnZE6CtTGkGIo7YI6HbTVNfxBpKRGtJsZS--RcukRJ9r5da1kVzWHa_Lx0E1om5LMlxBuq_t-OTuyXi5izZMdGVYLi9ldcyweP1nowKm-xFnq87TzbZtkEfHhTGxaoCA2UP7prT9kpNFHR--svvgk14U6R_uMkuE7alUteTwiFWE9PgzbcwEygZWwAk4AN07QrnBbK565z96TMaoxx2giJakJefs40q8uw8aSlHcNJv7xLmeLoI8sDCYoyqjPeSdyn-cv2g_9ZEhL1JnaUeXx8pl5YuIFH2nJwum1hwSemtARx14cgm0Bb4hFQORtKwNInKRDn8PuFYjibK66JRDUb33a1408JJrJsnmN6nzatWSe4Z8tBpi1mZ58Vht6qooT8gPW_shQleZh_qrmmZdcmXRfyJ-uULnS1kD2ml6h-9v_hydrP1a5dwpT4DPus58Gas3gZJAWPjY-llSYBHaw9X2q0_4pH-lX4SvlRkCFVdfoL37-VYCxW",
  "expires_in": 3600
}


In order to access our ValuesController, we will need to pass the access_token.

You can now add the access_token to your “Authorization” header, with the value prefixed by “Bearer “.  Example:
Authorization: Bearer CfDJ8BNb0JA0Y9lNgKzWkKXsTwf-4RPIpzDaVFES95ETNNIx-q_Qn2hW2PA5he39PPGHPuSCPadHaOeLWYK5hlJe-ZBLZjojcwjZYJTUNP6uhgG3CikaN-ES1tadOyJmEmaOjLe2QeY09AaziWP3SB7quEIPpFOeKyKMieHuOBVx_-R51XyUyVLRMfI7fWEKeEt35PbXMPYOochUybSLaxrNkQL9x1Wuj0l2igspn4hnpmvG76a_VEuRSxyDfZy6VsukPhxfzhlcrd_bvIchg5uMGEiJmbOvbRbIR5c_6Wya2uD6s5yMk8NYyAE6cebLMU_4sZ0pA2Qkzlilun_5sD7GsdlpE9pbzwv3I6liAI0twnsCoB06e4KD5bJUYCTIdTu-qQ2-GTdSlxk3iiCvHNl72R9t3hRvU8VuKld2g4Wc1PWsKzL1IkFbNIG_2CoHWmaAv09OnnpD3rrE-E6BA4gCkvRTUflf6Dc_yvN03InTs_SNOPyybjtVI_MG5o2CKfRClU9ERvFQYHBeqhZlnt2cLm2SBOx0wbexwBYF0nwWjjxLbWBndkodLqVEMtIOrbptRaacJa2MrpfIMbOvax_xvogqPzwZ8vu97BU4IvgTvpGw52HDLj9UZgN4TC_7ZDFd41ZQla7qvBN2Z4o3NjY-sdFJ6K7uXkx0CI9KFivhG_dpSB4VXoXer5ndDc5sExm1iGhjUe5qLJYnf37cm_a_ov7nYSFnkKeWuLgX0mzc2XQOzztFM8UXSfJmdftEBoD9kz_nNQpSWewkhnVQzDRGFl-UhCbkgM7Z78fYIqylT39-
Back in postman, do the following:

image


1) Select GET for the HTTP method.
2) Enter the ValuesController endpoint. In the above example, the login endpoint is http://localhost:5000/api/values/. Again, you may have to only correct the port number.
3) Click on Headers.
4) Enter Authorization for the header parameter.
5) For the Authorization header parameter value, enter the access_token prefixed by the word Bearer followed by a space.
6) Click on the Send button. The response should be the expected Web API output from the ValuesController as follows:

image


You should now be able to secure your Web API data in ASP.NET Core 1.1 so that only those who are authenticated can view the data.
References:
https://github.com/openiddict/openiddict-core
http://overengineer.net/Using-OpenIddict-to-easily-add-token-authentication-to-your-.NET-web-apps
http://kerryritter.com/authorizing-your-net-core-mvc6-api-requests-with-openiddict-and-identity/
http://stackoverflow.com/questions/41122686/the-type-or-namespace-name-openiddictdbcontext-could-not-be-found
https://github.com/openiddict/openiddict-samples/tree/master/samples/RefreshFlow