Migrate from ASP.NET Core 1.x to 2.0

I’ve one project made in .net core 1.1 and recently worked on it to move it to .net core 2.0. For this purpose I follow This link.

I’m using HybridAndClientCredentials on the STS server and openid Connect and cookies on the client. Most of the migration is covered by the above link, but I faced issue where most of my claims are missing.

With the ASP.NET Core 1.x, client would have received the claims: nbf, exp, iss, aud, nonce, iat, c_hash, sid, sub, auth_time, idp, amr.

In Core 2.0 we only get sid, sub and idp. What happened?

Microsoft added a new concept to their OpenID Connect handler called ClaimActions. Claim actions allow modifying how claims from an external provider are mapped (or not) to a claim in your ClaimsPrincipal. Looking at the ctor of the OpenIdConnectOptions, you can see that the handler will now skip the following claims by default:


If you want to “un-skip” a claim, you need to delete a specific claim action when setting up the handler. The following is the very intuitive syntax to get the amr claim back:


Requesting more claims from the OIDC provider

When you are requesting more scopes, e.g. profile or custom scopes that result in more claims, there is another confusing detail to be aware of.

Depending on the response_type in the OIDC protocol, some claims are transferred via the id_token and some via the userinfo endpoint.

So first of all, you need to enable support for the userinfo endpoint in the handler:

options.GetClaimsFromUserInfoEndpoint = true;

In the end you need to add the following class to import all other custom claims

public class MapAllClaimsAction : ClaimAction
        public MapAllClaimsAction() : base(string.Empty, string.Empty)

        public override void Run(JObject userData, ClaimsIdentity identity, string issuer)
            foreach (var claim in identity.Claims)
                // If this claimType is mapped by the JwtSeurityTokenHandler, then this property will be set
                var shortClaimTypeName = claim.Properties.ContainsKey(JwtSecurityTokenHandler.ShortClaimTypeProperty) ?
                    claim.Properties[JwtSecurityTokenHandler.ShortClaimTypeProperty] : string.Empty;

                // checking if claim in the identity (generated from id_token) has the same type as a claim retrieved from userinfo endpoint
                JToken value;
                var isClaimIncluded = userData.TryGetValue(claim.Type, out value) || userData.TryGetValue(shortClaimTypeName, out value);

                // if a same claim exists (matching both type and value) both in id_token identity and userinfo response, remove the json entry from the userinfo response
                if (isClaimIncluded && claim.Value.Equals(value.ToString(), StringComparison.Ordinal))
                    if (!userData.Remove(claim.Type))

            // adding remaining unique claims from userinfo endpoint to the identity
            foreach (var pair in userData)
                JToken value;
                var claimValue = userData.TryGetValue(pair.Key, out value) ? value.ToString() : null;
                identity.AddClaim(new Claim(pair.Key, claimValue, ClaimValueTypes.String, issuer));

In the end add the last ClaimActions in AddOpenIdConnection options list

options.ClaimActions.Add(new MapAllClaimsAction());

Auto redirect to an STS server in an Angular app using oidc Implicit Flow

Excellent npm package for Angular and Identity Server 4 Implicit flow implementation

Software Engineering

This article shows how to implement an auto redirect in an Angular application, if using the OIDC Implicit Flow with an STS server. When a user opens the application, it is sometimes required that the user is automatically redirected to the login page on the STS server. This can be tricky to implement, as you need to know when to redirect and when not. The OIDC client is implemented using the angular-auth-oidc-client npm package.

Code: https://github.com/damienbod/angular-auth-oidc-sample-google-openid

The angular-auth-oidc-client npm package provides an event when the OIDC module is ready to use and also can be configured to emit an event to inform the using component when the callback from the STS server has been processed. These 2 events, can be used to implement the auto redirect to the STS server, when not authorized.

The app.component can subscribe to these 2 events in the constructor.

The onOidcModuleSetup function handles the onModuleSetup…

View original post 189 more words

No executable found matching command dotnet-ef

If you try to run the dotnet ef command from powershell and see the following error.

No executable found matching command dotnet-ef

You need to do the following steps to fix it.

  • Add the Microsoft.EntityFrameworkCore.Tools and/or the Microsoft.EntityFrameworkCore.Tools.DotNet package libraries, depending if you want to use the PowerShell command or the CLI version. I personally do always install both of them.
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="2.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.0" />
    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.0.0" />

it will add PackageReference like this

  • We also need to add the reference as DotNetCliToolReference which will add the following references
   <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
   <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" />
   <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />

Don’t forget to change the version as per your current version of the .net Core

API Versioning in .net Core 2.0 via URL

Version is helpful when we want to roll out new features without breaking the functionality of the existing ones. . It can also help to provide additional functionalities to selected customers. API versioning can be done in different ways like appending the version in the URL or as a query string parameter, via custom header and via Accept-header.

In this post, let’s find how to support multiple version ASP.NET Core Web API by appending the version in URL.

Let’s create an ASP.NET Core web API application and first thing to do is to include the Microsoft.AspNetCore.Mvc.Versioning package (Install the latest package or what is suitable to your project from the nuget.org). At the point of writing this article .net Core 2.0 is out and also the final 2.0.0 version of this nuget package.

Once the package is restored, we need to configure it. Next open Startup.cs, add the highlighted lines of code in ConfigureServices method.

public void ConfigureServices(IServiceCollection services)
  services.AddApiVersioning(option =&gt; {
      option.ReportApiVersions = true;
      option.AssumeDefaultVersionWhenUnspecified = true;
      option.DefaultApiVersion = new ApiVersion(1, 0);

As you can see, there are 3 different options configured.

  • ReportAPIVersions: This is optional. But when set to true, API returns supported versions information in the response header.
  • AssumeDefaultVersionWhenUnspecified: This option will be used to serve the request without a version. The assumed API version by default would be 1.0.
  • DefaultApiVersion: This option is used to specify the default API version to be used when no version is specified in the request. This will default the version to 1.0.

That’s all for the configuration and setup. Now we will see how to access the versions of the API via the URL path segment.

Query string parameters are useful, but it can be painful in case of long URL and other query string parameters. Instead, the better approach would be to add version in the URL path. Like,

  • api/v1/values
  • api/v2/values

So to do this, we need to put the version in the route attribute. Like,

namespace ValuesController
   public class ValuesController : Controller
     public IActionResult Get() => Ok(new string[] { "value1" });

With this change, the API endpoints always need to have the version number. You can navigate to version 1.0 via api/v1/values and to access version 2.0, change the version number in the URL. Simple and looks more clean now.

Deprecated:When multiple API versions are supported, some versions will eventually be deprecated over time. To mark one or more API versions have been deprecated, simply decorate your controller with the deprecated API versions. This doesn’t mean that the API version is not supported. One can still call the endpoint/version. It just a way to make API users aware that following version will be deprecated in future.

[ApiVersion("1.0", Deprecated = true)]

ApiVersionNeutral: attribute defines that this API is version-neutral. This is useful for APIs that behaves the exact same way, regardless of API version or a legacy API that doesn’t support API versioning. So, you can add ApiVersionNeutralattribute to opt out from versioning.

[RoutePrefix( "api/[controller]" )]
public class SharedController : Controller
    public IActionResult Get() => Ok();

MapToApiVersion: attribute allows to map a single API action to any version. In other words, a single controller which supports multiple versions say 1 and 3. The controller may have an API action method supported by version 3 only. In such case, you can use MapToApiVersion. Take a look at below code.

namespace ValuesController
  public class ValuesController : Controller
     public IActionResult Get() => Ok(new string[] { "value1" });

     [HttpGet, MapToApiVersion("2.0")]
     public IActionResult GetV3() => Ok(new string[] { "value2" });

ASP.NET Core logging with NLog and Elasticsearch

Software Engineering

This article shows how to Log to Elasticsearch using NLog in an ASP.NET Core application. NLog is a free open-source logging for .NET.

Code:VS2017 RC3 csproj | VS2015 project.json

2017.02.08 Updated to NLog.Web.AspNetCore 4.3.0 and VS2017 RC3
17.12.2016 Updated to ASP.NET Core 1.1

NLog posts in this series:

  1. ASP.NET Core logging with NLog and Microsoft SQL Server
  2. ASP.NET Core logging with NLog and Elasticsearch
  3. Settings the NLog database connection string in the ASP.NET Core appsettings.json
  4. .NET Core logging to MySQL using NLog
  5. .NET Core logging with NLog and PostgreSQL

NLog.Extensions.Logging is required to use NLog in an ASP.NET Core application. This is added to the dependencies of the project. NLog.Targets.ElasticSearch is also added to the dependencies. This project is at present NOT the NuGet package from ReactiveMarkets, but the source code from ReactiveMarkets and updated to dotnetcore. Thanks to ReactiveMarkets for this library, hopefully the NuGet package will…

View original post 181 more words

Sisense SSO implementation in MVC .net core

We can find a documentation regarding what needs to be done in Sisense BI Elastic cube manager in relation to SSO using JWT.  They also have C# code to use for SSO but one may be scratching his head if he/she wants to use that sample code in MVC .net Core application.

So for that purpose I’ld suggest to make one controller with one action in it, Use that URL of that controller action to configure in Sisense SSO configuration page. The sample code would be


public IActionResult Index([FromQuery]string return_to)
   TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
   int timestamp = (int)t.TotalSeconds;
   var payload = new System.Collections.Generic.Dictionary<string, object>() {
     { "iat", timestamp},
     { "sub", CurrentUser() },
     { "jti", Guid.NewGuid() }
     // Optional properties
     // { "exp", (int)t.Add(TimeSpan.FromMinutes(30)).TotalSeconds } // Expiration time

   string token = Jwt.JsonWebToken.Encode(payload, "secret key from sisense sso                 configuration", Jwt.JwtHashAlgorithm.HS256);
   string redirectUrl = "http://URL_of_your_sisense_web_app_with_port/jwt?jwt=" + token;
   if (return_to != null)
    redirectUrl += "&return_to=" + UrlEncoder.Default.Encode(return_to);
  return Redirect(redirectUrl)

.Net Core 1.0.0 VS 2015 Tooling Preview Installation Issue

If you are trying to install tooling preview for .net Core 1.0.0 particularly or any other version and due to some reasons you are getting errors like you need to reinstall/repair VS 2015 professional with update 3 again, than you are at  the right place

Try running the following command in the command prompt. Don’t forget to go to the directory where the setup is located

NOTE: Change the exe as per your version of the tools

DotNetCore.1.0.0-VS2015Tools.Preview2.exe SKIP_VSU_CHECK=1

Building Single Page Applications using Web API and angularJS (Free e-book)

chsakell's Blog

Single Page Applications are getting more and more attractive nowadays for two basic reasons. Website users have always preferred a fluid user experience than one with page reloads and the incredible growth of several JavaScript frameworks such as angularJS. This growth in conjunction with all the powerful server side frameworks makes Single Page Application development a piece of cake. This post is the online version of the free e-book and describes step by step how to build a production-level SPA using ASP.NET Web API 2 and angularJS. You have two choices. Either grab a coffee and keep going on with this version or simply download the e-book and enjoy it whenever and wherever you want.
There are a lot of stuff to build in this application so I will break this post in the following sections:

View original post 9,862 more words