谷歌oauth的HD参数使用dotnet core 2.0

时间:2017-11-29 00:20:20

标签: c# oauth google-api .net-core

我想将hosting domain parameter添加到我的OAuth工作流程中以限制对我的应用程序的登录访问,但我没有找到任何关于它的dotnet核心文档。

到目前为止,这就是我所做的:

services.AddAuthentication().AddGoogle(g =>
{
    g.ClientId = Configuration["google-client-id"];
    g.ClientSecret = Configuration["google-client-secret"];
    g.ClaimActions.MapJsonSubKey(PlatformKeys.GoogleAuthImageUrl, "image", "url");
});

如何将该参数添加到配置中?
这是自定义索赔吗?

1 个答案:

答案 0 :(得分:0)

我已根据OAuthHandler

创建了自定义Google处理程序
public class CustomGoogleHandler : OAuthHandler<CustomGoogleOptions>
    {
        public CustomGoogleHandler(IOptionsMonitor<CustomGoogleOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
            : base(options, logger, encoder, clock)
        {
        }

        protected override async Task<AuthenticationTicket> CreateTicketAsync(ClaimsIdentity identity, AuthenticationProperties properties, OAuthTokenResponse tokens)
        {
            // code omited for simplicity
        }

        protected override string BuildChallengeUrl(AuthenticationProperties properties, string redirectUri)
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
            {
                {"response_type", "code"},
                {"client_id", Options.ClientId},
                {"redirect_uri", redirectUri}
            };
            AddQueryString(dictionary, properties, "scope", FormatScope());
            AddQueryString(dictionary, properties, "access_type", Options.AccessType);
            AddQueryString(dictionary, properties, "hd", Options.HostedDomain);
            AddQueryString(dictionary, properties, "approval_prompt");
            AddQueryString(dictionary, properties, "prompt");
            AddQueryString(dictionary, properties, "login_hint");
            AddQueryString(dictionary, properties, "include_granted_scopes");
            string str = Options.StateDataFormat.Protect(properties);
            dictionary.Add("state", str);
            return QueryHelpers.AddQueryString(Options.AuthorizationEndpoint, dictionary);
        }

        private static void AddQueryString(IDictionary<string, string> queryStrings, AuthenticationProperties properties, string name, string defaultValue = null)
        {
            // code omited for simplicity
        }
    }

我刚刚将自定义域属性添加到我的自定义google选项中,如下所示:

public class CustomGoogleOptions : GoogleOptions
    {

        /// <summary>
        /// Support for HostedDomain option
        /// https://developers.google.com/identity/protocols/OpenIDConnect#hd-param
        /// </summary>
        public string HostedDomain { get; set; }        

    }

我希望这有帮助!