Azureの小ネタ (改)

~Azureネタを中心に、色々とその他の技術的なことなどを~

ASP.NET Core 2.0 で Web APIの認証

ASP.NET Core 2.0 ベースの Web APIで認証をかける方法を知りたかったので、サンプル作って挙動を確認してみたメモ。

最近HDDに埋もれてしまうので、Githubに置くのがよいのかなと思ったり。

m-moris/asp-netcore-jwt-validation

検証

Startup.cs にて、JWTの設定をする。いくつか書き方はあるみたいなんだけども以下。

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    // for debug.
                    options.RequireHttpsMetadata = false; 

                    options.Audience = Config.Audience;
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateAudience = true,
                        ValidateIssuerSigningKey = true,
                        ValidateIssuer = true,
                        ValidIssuer = Config.Issuer,
                        IssuerSigningKey = KeyStore.GetSymmetricSecurityKey()
                    };
                });

            services.AddSingleton<Users, Users>();
            services.AddMvc();
        }

JWTの生成は、JwtSecurityToken クラスを使う。署名は適当。

JwtSecurityToken CreateJwtSecurityToken(User user)
        {
            var claims = new List<Claim>()
            {
                new Claim(JwtRegisteredClaimNames.Jti, Config.Id),
                new Claim(JwtRegisteredClaimNames.Sub, user.Name),
                new Claim(ClaimTypes.Sid, Config.Id),
                new Claim(ClaimTypes.Name , user.Name),
                new Claim(ClaimTypes.Role, user.Role)
            };

            var token = new JwtSecurityToken(
                issuer: Config.Issuer,
                audience: Config.Audience,
                claims: claims,
                expires: DateTime.UtcNow.AddDays(7),
                signingCredentials: new SigningCredentials(KeyStore.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)
            );

            return token;
        }

API側は属性ベース。

        [Authorize]
        [Route("api/values/user")]
        [HttpGet]
        public ActionResult Get() {
            ...
        }

発行されたTokenは、以下のサイトで簡単でデコードしてくれる。

jwt.io

感想

  • 簡単にできる。Startup.cs JWTの設定を追加して設定すればOK。あとはAPI側に属性つければOK。
  • JWTのクレームにロールを含めれば、ロールベースの認証もできる。
  • ASP.NET Core 1.1 -> 2.0 で少し変わったみたいで、マイグレ方法はこのあたりに書いてある。 Migrating Auth and Identity to ASP.NET Core 2.0 | Microsoft Docs
  • 各種Validationの設定があるけれど、true -> falseにしても変化がないのがよくわからなかった(検証をSkipしてくれるわけではないのか)
  • いろいろ調べていて、ぱっと見で、ASP.NET Core 1.1なのか2.0の話なのか区別がつかない。

参考