当用户尝试登录时,我尝试将自定义标头值(无 cookie)传递给 IdentityServer4。这是所有设置的方式。
自定义身份验证属性:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class CustomAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
private readonly string _customId;
public CustomAuthorizeAttribute(string customId)
{
_customId = customId;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
context.HttpContext.Request.Headers.Add("X-CustomId", _customId);
}
}
控制器:
[CustomAuthorize("0123456789")]
public IActionResult Secure()
{
ViewData["Message"] = "Secure Page.";
return View();
}
身份服务器 > 帐户控制:
[HttpGet]
public async Task<IActionResult> Login(string returnUrl)
{
var customId = _httpContextAccessor.HttpContext.Request.Headers["X-CustomId"];
// build a model so we know what to show on the login page
var vm = await BuildLoginViewModelAsync(returnUrl);
if (vm.IsExternalLoginOnly)
{
// we only have one option for logging in and it's an external provider
return await ExternalLogin(vm.ExternalLoginScheme, returnUrl);
}
return View(vm);
}
自定义标头值永远不会到达任何登录端点。想知道是否有人以前遇到过这个问题并且有任何想法如何让它发挥作用?非常感谢
您可以将自定义参数传递给授权端点。如果您使用的是 OpenID Connect Middleware ,您可以将该值添加到授权请求的查询字符串中OnRedirectToIdentityProvider
功能 :
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
//hybrid flow
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies";
options.Authority = "http://localhost:62888/";
options.RequireHttpsMetadata = false;
options.ClientId = "mvc2";
options.ClientSecret = "secret";
options.ResponseType = "code id_token";
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Add("api1");
options.Scope.Add("offline_access");
options.Events.OnRedirectToIdentityProvider = async n =>
{
var headerValue = n.HttpContext.Request.Headers["X-CustomId"];
n.ProtocolMessage.SetParameter("X-CustomId", headerValue.ToString());
await Task.FromResult(0);
};
});
然后在登录页面,您可以轻松获取查询字符串:
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> Login(string returnUrl = null)
{
var queryString = HttpContext.Request.Query["returnUrl"].ToString();
// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
ViewData["ReturnUrl"] = returnUrl;
return View();
}
Then prase the queryString
to get value of X-CustomId:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)