Owin,在身份validation请求中传递自定义查询参数
我们有自己的OpenID Connect Provider。 我们希望使用Owin中间件在身份validation请求中传递自定义查询参数。 我们无法找到使用Microsoft.Owin.Security.OpenIdConnect程序集实现此方法的方法。 甚至我们也找不到如何向Authentication Request添加标准请求参数(例如“ login_hint parameter”)。
例如,Google有“ login_hint ”和“ hd ”参数( https://developers.google.com/accounts/docs/OAuth2Login#sendauthrequest ),我们希望拥有几乎相同的参数。 但我们甚至无法找到如何使用Owin将这些参数发送给Google。 试过这段代码:
var googleOptions = new GoogleOAuth2AuthenticationOptions() { ClientId = "...", ClientSecret = "...", }; app.UseGoogleAuthentication(googleOptions); ... public ActionResult ExternalLogin(string provider) { var ctx = Request.GetOwinContext(); var properties = new AuthenticationProperties(); properties.Dictionary.Add("login_hint ", "myemail@gmail.com"); properties.Dictionary.Add("hd", "hd"); ctx.Authentication.Challenge(properties, provider); return new HttpUnauthorizedResult(); }
但是,将生成身份validation请求URL,而不会生成“ login_hint ”和“ hd ”参数。
非常感谢任何帮助解决这个问题。
你快到了! 剩下的就是重写内置的GoogleOAuth2AuthenticationProvider
,以下是如何执行此操作的示例:
class CustomGoogleAuthProvider : GoogleOAuth2AuthenticationProvider { public CustomGoogleAuthProvider() { OnApplyRedirect = (GoogleOAuth2ApplyRedirectContext context) => { IDictionary props = context.OwinContext.Authentication.AuthenticationResponseChallenge.Properties.Dictionary; string newRedirectUri = context.RedirectUri; string[] paramertsToPassThrough = new[] { "login_hint", "hd", "anything" }; foreach (var param in paramertsToPassThrough) { if (props.ContainsKey(param)) { newRedirectUri += string.Format("&{0}={1}", param, HttpUtility.UrlEncode(props[param])); } } context.Response.Redirect(newRedirectUri); }; } }
OWIN中间件注册:
app.UseGoogleAuthentication(new Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationOptions() { // other config ... Provider = new CustomGoogleAuthProvider(), });
结果(顺便提一下当前版本(3.0.1)的Google OAuth中间件login_hint会从身份validation参数开箱即用):
所以,在遇到类似问题时,brockallen向我发送了一些代码,这些代码可以让我使用身份服务器3获得所需的代码….
class CustomGoogleAuthProvider : GoogleOAuth2AuthenticationProvider { public CustomGoogleAuthProvider() { OnApplyRedirect = (GoogleOAuth2ApplyRedirectContext context) => { var signinId = context.OwinContext.Request.Query["signin"]; var msg = context.OwinContext.Environment.GetSignInMessage(signinId); var hint = msg.LoginHint; var newRedirectUri = context.RedirectUri; newRedirectUri += string.Format("&login_hint={0}", HttpUtility.UrlEncode(hint)); context.Response.Redirect(newRedirectUri); }; } }