コード例 #1
0
        // ====================================================================
        // private メンバー関数
        // ====================================================================

        // --------------------------------------------------------------------
        // ヘッダーの認証トークンからユーザー Id を取得
        // --------------------------------------------------------------------
        private String?GetUserIdFromHeader()
        {
            // Authorization ヘッダーは "Bearer Token" の形式になっている
            HttpContext.Request.Headers.TryGetValue(HEADER_NAME_AUTHORIZATION, out StringValues values);
            if (values.Count == 0)
            {
                return(null);
            }
            String[] split = values[0].Split(' ', StringSplitOptions.RemoveEmptyEntries);
            if (split.Length <= 1)
            {
                return(null);
            }
            String token = split[1];

            // トークン検証
            try
            {
                TokenValidationParameters parameters = ServerCommon.TokenValidationParameters();
                JwtSecurityTokenHandler   jwtSecurityTokenHandler = new();
                ClaimsPrincipal           claims = jwtSecurityTokenHandler.ValidateToken(token, parameters, out SecurityToken validatedToken);
                return(claims.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value);
            }
            catch (Exception)
            {
                // トークンの有効期限切れ等の場合は例外となる
                return(null);
            }
        }
コード例 #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddRazorPages();

            // 秘密鍵準備
            ServerCommon.PrepareTokenSecretKey();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            {
                // 秘密鍵準備後
                options.TokenValidationParameters = ServerCommon.TokenValidationParameters();
            });

            // Server-Sent Events
            services.AddServerSentEvents();
        }