Example #1
0
        /// <summary>ユーザ情報を取得する</summary>
        /// <param name="authorizationContext">AuthorizationFilterContext</param>
        /// <remarks>awaitするメソッドを追加して呼ぶ可能性も高いのでasyncを付与</remarks>
        private async Task GetUserInfoAsync(AuthorizationFilterContext authorizationContext)
        {
            // Authorization: <type> <credentials>
            if (this.HttpAuthHeader == EnumHttpAuthHeader.None)
            {
                // 認証なし
                return;
            }
            else if (this.HttpAuthHeader.HasFlag(EnumHttpAuthHeader.Basic))
            {
                // Basic認証の認証アルゴリズムを追加
                // Authorization: Basic XXXXXXXXXX
                return;
            }
            else if (this.HttpAuthHeader.HasFlag(EnumHttpAuthHeader.Bearer))
            {
                // Bearer認証の認証アルゴリズムを追加 --------------------------
                // Authorization: Bearer XXXXXXXXXX
                // JWTアサーションを処理し、認証、UserInfoを生成するなど。
                // -------------------------------------------------------------
                List <Claim> claims = null;

                if (authorizationContext.HttpContext.Request.Headers != null)
                {
                    StringValues authHeaders = "";

                    try
                    {
                        if (authorizationContext.HttpContext.Request.Headers.TryGetValue("Authorization", out authHeaders))
                        {
                            string access_token = authHeaders[0].Split(' ')[1];

                            string        sub    = "";
                            List <string> roles  = null;
                            List <string> scopes = null;
                            JObject       jobj   = null;

                            if (AccessToken.Verify(access_token, out sub, out roles, out scopes, out jobj))
                            {
                                // ActionFilterAttributeとApiController間の情報共有はcontext.Principalを使用する。
                                // ★ 必要であれば、他の業務共通引継ぎ情報などをロードする。
                                claims = new List <Claim>()
                                {
                                    new Claim(ClaimTypes.Name, sub),
                                    new Claim(ClaimTypes.Role, string.Join(",", roles)),
                                    new Claim(OAuth2AndOIDCConst.UrnScopesClaim, string.Join(",", scopes)),
                                    new Claim(OAuth2AndOIDCConst.UrnAudienceClaim, (string)jobj[OAuth2AndOIDCConst.aud]),
                                    new Claim("IpAddress", MyBaseAsyncApiController.GetClientIpAddress())
                                };

                                // ClaimsPrincipalを設定
                                MyHttpContext.Current.User = new ClaimsPrincipal(new ClaimsIdentity(claims, "Token"));

                                return;
                            }
                            else
                            {
                                // JWTの内容検証に失敗
                            }
                        }
                        else
                        {
                            // Authorization HeaderがBearerでない。
                        }
                    }
                    catch
                    {
                        // 例外発生 ≒ 未認証扱い。
                    }
                }
                else
                {
                    // Authorization Headerが存在しない。
                }

                #region 未認証状態の場合の扱い

                if (this.HttpAuthHeader.HasFlag(EnumHttpAuthHeader.None))
                {
                    // 未認証状態のclaimsを作成格納
                    claims = new List <Claim>()
                    {
                        new Claim(ClaimTypes.Name, "未認証"),
                        new Claim(ClaimTypes.Role, ""),
                        new Claim(OAuth2AndOIDCConst.UrnScopesClaim, ""),
                        new Claim(OAuth2AndOIDCConst.UrnAudienceClaim, ""),
                        new Claim("IpAddress", MyBaseAsyncApiController.GetClientIpAddress())
                    };

                    MyHttpContext.Current.User.AddIdentity(new ClaimsIdentity(claims, "Token"));
                }
                else
                {
                    // 認証エラーを返す。
                    // ASP.NET Core MVCで403エラーをクライアントへ返す - Living Absurd World
                    // https://blog.hmatoba.net/Article/144
                    authorizationContext.Result = new UnauthorizedResult();
                }

                return;

                #endregion
            }
        }
Example #2
0
        /// <summary>ユーザ情報を取得する</summary>
        /// <param name="authorizationContext">AuthorizationFilterContext</param>
        /// <remarks>awaitするメソッドを追加して呼ぶ可能性も高いのでasyncを付与</remarks>
        private async Task GetUserInfoAsync(AuthorizationFilterContext authorizationContext)
        {
            // カスタム認証処理 --------------------------------------------
            // Authorization: Bearer ヘッダから
            // JWTアサーションを処理し、認証、UserInfoを生成するなど。
            // -------------------------------------------------------------
            List <Claim> claims = null;

            if (authorizationContext.HttpContext.Request.Headers != null)
            {
                StringValues authHeaders = "";

                if (authorizationContext.HttpContext.Request.Headers.TryGetValue("Authorization", out authHeaders))
                {
                    string access_token = authHeaders[0].Split(' ')[1];

                    string        sub    = "";
                    List <string> roles  = null;
                    List <string> scopes = null;
                    JObject       jobj   = null;

                    if (AccessToken.Verify(access_token, out sub, out roles, out scopes, out jobj))
                    {
                        // ActionFilterAttributeとApiController間の情報共有はcontext.Principalを使用する。
                        // ★ 必要であれば、他の業務共通引継ぎ情報などをロードする。
                        claims = new List <Claim>()
                        {
                            new Claim(ClaimTypes.Name, sub),
                            new Claim(ClaimTypes.Role, string.Join(",", roles)),
                            new Claim(OAuth2AndOIDCConst.UrnScopesClaim, string.Join(",", scopes)),
                            new Claim(OAuth2AndOIDCConst.UrnAudienceClaim, (string)jobj[OAuth2AndOIDCConst.aud]),
                            new Claim("IpAddress", MyBaseAsyncApiController.GetClientIpAddress())
                        };

                        // ClaimsPrincipalを設定
                        MyHttpContext.Current.User = new ClaimsPrincipal(new ClaimsIdentity(claims, "Token"));

                        return;
                    }
                    else
                    {
                        // JWTの内容検証に失敗
                    }
                }
                else
                {
                    // Authorization HeaderがBearerでない。
                }
            }
            else
            {
                // Authorization Headerが存在しない。
            }

            #region 未認証状態の場合の扱い

            // The request message contains invalid credential
            //context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request);

            // 未認証状態のclaimsを作成格納
            claims = new List <Claim>()
            {
                new Claim(ClaimTypes.Name, "未認証"),
                new Claim(ClaimTypes.Role, ""),
                new Claim(OAuth2AndOIDCConst.UrnScopesClaim, ""),
                new Claim(OAuth2AndOIDCConst.UrnAudienceClaim, ""),
                new Claim("IpAddress", MyBaseAsyncApiController.GetClientIpAddress())
            };

            // The request message contains valid credential.
            MyHttpContext.Current.User.AddIdentity(new ClaimsIdentity(claims, "Token"));

            return;

            #endregion
        }
Example #3
0
        /// <summary>ユーザ情報を取得する</summary>
        /// <param name="authenticationContext">HttpAuthenticationContext</param>
        private async Task GetUserInfoAsync(HttpAuthenticationContext authenticationContext)
        {
            // Authorization: <type> <credentials>
            if (this.HttpAuthHeader == EnumHttpAuthHeader.None)
            {
                // 認証なし
                return;
            }
            else if (this.HttpAuthHeader.HasFlag(EnumHttpAuthHeader.Basic))
            {
                // Basic認証の認証アルゴリズムを追加
                // Authorization: Basic XXXXXXXXXX
                return;
            }
            else if (this.HttpAuthHeader.HasFlag(EnumHttpAuthHeader.Bearer))
            {
                // Bearer認証の認証アルゴリズムを追加 --------------------------
                // Authorization: Bearer XXXXXXXXXX
                // JWTアサーションを処理し、認証、UserInfoを生成するなど。
                // -------------------------------------------------------------
                List <Claim> claims = null;

                if (authenticationContext.Request.Headers.Authorization != null)
                {
                    try
                    {
                        if (authenticationContext.Request.Headers.Authorization.Scheme.ToLower() == "bearer")
                        {
                            string access_token = authenticationContext.Request.Headers.Authorization.Parameter;

                            string        sub    = "";
                            List <string> roles  = null;
                            List <string> scopes = null;
                            JObject       jobj   = null;

                            if (AccessToken.Verify(access_token, out sub, out roles, out scopes, out jobj))
                            {
                                // ActionFilterAttributeとApiController間の情報共有はcontext.Principalを使用する。
                                // ★ 必要であれば、他の業務共通引継ぎ情報などをロードする。
                                claims = new List <Claim>()
                                {
                                    new Claim(ClaimTypes.Name, sub),
                                    new Claim(ClaimTypes.Role, string.Join(",", roles)),
                                    new Claim(OAuth2AndOIDCConst.UrnScopesClaim, string.Join(",", scopes)),
                                    new Claim(OAuth2AndOIDCConst.UrnAudienceClaim, (string)jobj[OAuth2AndOIDCConst.aud]),
                                    new Claim("IpAddress", MyBaseAsyncApiController.GetClientIpAddress(authenticationContext.Request))
                                };

                                // The request message contains valid credential.
                                authenticationContext.Principal = new ClaimsPrincipal(
                                    new List <ClaimsIdentity> {
                                    new ClaimsIdentity(claims, "Token")
                                });

                                return;
                            }
                            else
                            {
                                // JWTの内容検証に失敗
                            }
                        }
                        else
                        {
                            // Authorization HeaderがBearerでない。
                        }
                    }
                    catch
                    {
                        // 例外発生 ≒ 未認証扱い。
                    }
                }
                else
                {
                    // Authorization Headerが存在しない。
                }

                #region 未認証状態の場合の扱い

                if (this.HttpAuthHeader.HasFlag(EnumHttpAuthHeader.None))
                {
                    // 未認証状態のclaimsを作成格納
                    claims = new List <Claim>()
                    {
                        new Claim(ClaimTypes.Name, "未認証"),
                        new Claim(ClaimTypes.Role, ""),
                        new Claim(OAuth2AndOIDCConst.UrnScopesClaim, ""),
                        new Claim(OAuth2AndOIDCConst.UrnAudienceClaim, ""),
                        new Claim("IpAddress", MyBaseAsyncApiController.GetClientIpAddress(authenticationContext.Request))
                    };

                    authenticationContext.Principal = new ClaimsPrincipal(new List <ClaimsIdentity> {
                        new ClaimsIdentity(claims, "Token")
                    });
                }
                else
                {
                    // 認証エラーを返す。
                    // ASP.NET Web API 2 | Microsoft Docs
                    // https://docs.microsoft.com/ja-jp/aspnet/web-api/overview/security/authentication-filters
                    authenticationContext.ErrorResult = new AuthenticationFailureResult(
                        authenticationContext.Request, "Bearer Credentials is invalid.");
                }

                return;

                #endregion
            }
        }
Example #4
0
        /// <summary>ユーザ情報を取得する</summary>
        /// <param name="authenticationContext">HttpAuthenticationContext</param>
        private async Task GetUserInfoAsync(HttpAuthenticationContext authenticationContext)
        {
            // カスタム認証処理 --------------------------------------------
            // Authorization: Bearer ヘッダから
            // JWTアサーションを処理し、認証、UserInfoを生成するなど。
            // -------------------------------------------------------------
            List <Claim> claims = null;

            if (authenticationContext.Request.Headers.Authorization.Scheme.ToLower() == "bearer")
            {
                string access_token = authenticationContext.Request.Headers.Authorization.Parameter;

                string        sub    = "";
                List <string> roles  = null;
                List <string> scopes = null;
                JObject       jobj   = null;

                if (JwtToken.Verify(access_token, out sub, out roles, out scopes, out jobj))
                {
                    // ActionFilterAttributeとApiController間の情報共有はcontext.Principalを使用する。
                    // ★ 必要であれば、他の業務共通引継ぎ情報などをロードする。
                    claims = new List <Claim>()
                    {
                        new Claim(ClaimTypes.Name, sub),
                        new Claim(ClaimTypes.Role, string.Join(",", roles)),
                        new Claim("Scopes", string.Join(",", scopes)),
                        new Claim("IpAddress", MyBaseAsyncApiController.GetClientIpAddress(authenticationContext.Request))
                    };

                    // The request message contains valid credential
                    authenticationContext.Principal = new ClaimsPrincipal(new List <ClaimsIdentity> {
                        new ClaimsIdentity(claims, "Token")
                    });
                    return;
                }
                else
                {
                    // JWTの内容検証に失敗
                }
            }
            else
            {
                // Authorization: Bearer Headerが存在しない。
            }

            // 未認証状態
            // The request message contains invalid credential
            //context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request);

            claims = new List <Claim>()
            {
                new Claim(ClaimTypes.Name, "未認証"),
                new Claim(ClaimTypes.Role, ""),
                new Claim("Scopes", ""),
                new Claim("IpAddress", MyBaseAsyncApiController.GetClientIpAddress(authenticationContext.Request))
            };

            authenticationContext.Principal = new ClaimsPrincipal(new List <ClaimsIdentity> {
                new ClaimsIdentity(claims, "Token")
            });
            return;
        }