我试图在用户尝试登录时将自定义标头值(无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();
}
IdentityServer> AccountControlelr:
[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);
}
自定义标头值永远不会到达任何登录端点。想知道是否有人曾经遇到过这个问题,并且对如何使其工作有任何想法?非常感谢
答案 0 :(得分:0)
您可以将自定义参数传递给授权端点。如果您使用的是OpenID Connect中间件,则可以将值添加到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);
};
});
然后在登录页面中,您可以轻松获取querString:
[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();
}