要在ASP.NET Core中实现身份验证并重定向到目标操作,您可以按照以下步骤进行操作:
Startup.cs
文件的ConfigureServices
方法中进行配置:services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.Authority = "https://your-identity-provider";
options.ClientId = "your-client-id";
options.ClientSecret = "your-client-secret";
options.ResponseType = "code";
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("email");
options.GetClaimsFromUserInfoEndpoint = true;
options.SaveTokens = true;
});
注意:您需要根据自己的身份提供商进行相应的配置。
然后,在需要进行身份验证的控制器或操作方法上添加[Authorize]
属性,以确保用户已经登录。
如果用户未登录,身份验证中间件将自动重定向到登录页面。然后,用户将在身份提供商的登录页面上进行身份验证。
要在用户成功登录后重定向到目标操作,您可以在目标操作方法中使用return RedirectToAction("ActionName", "ControllerName");
语句来执行重定向。例如:
[Authorize]
public IActionResult TargetAction()
{
// 执行目标操作
return RedirectToAction("Index", "Home"); // 重定向到主页
}
这将重定向用户到主页(HomeController
的Index
方法)。
请注意,如果用户尚未登录,他们将被重定向到登录页面。一旦登录成功,他们将自动重定向回目标操作。
希望这个示例可以帮助您实现ASP.NET Core身份验证并重定向到目标操作。