gpt4 book ai didi

c# - 在 Asp Mvc 上使用 OWIN 进行自定义身份验证

转载 作者:太空狗 更新时间:2023-10-30 01:15:34 25 4
gpt4 key购买 nike

我正在尝试在 Asp MVC 上使用 owin 创建登录屏幕。这是 Controller 中的代码。

我什至尝试对这些值进行硬编码,但在登录后尝试进入仪表板时,我仍然收到 401。

 [HttpPost]
public ActionResult Login(string username, string password)
{
int userId = 0;
string role = string.Empty;

if (new UserManager().IsValid(username, password, ref userId, ref role))
{
var ident = new ClaimsIdentity(
new[] {
// adding following 2 claim just for supporting default antiforgery provider
new Claim(ClaimTypes.NameIdentifier, userId.ToString()),
new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),

new Claim(ClaimTypes.Name,username),

// optionally you could add roles if any
new Claim(ClaimTypes.Role, role)

},
DefaultAuthenticationTypes.ApplicationCookie);

HttpContext.GetOwinContext().Authentication.SignIn(
new AuthenticationProperties { IsPersistent = false }, ident);
return RedirectToAction("Dashboard"); // auth succeed
}
// invalid username or password
ModelState.AddModelError("", "invalid username or password");
return View("Index", "_LayoutUnAuthorised");
}

[Authorize(Roles = "Default")]
public ActionResult Dashboard()
{



return View();
}

我的启动文件是空的,我是不是遗漏了什么

public class Startup
{
public void Configuration(IAppBuilder app)
{

}
}

最佳答案

是的,您错过了 Owin Cookie Configuration on Startup 类:

public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AuthenticationType = "ApplicationCookie",
LoginPath = new PathString("/Account/LogOn"),
});
}

安装 Nuget 包 Microsoft.Owin.Security.Cookies 然后就可以了

关于c# - 在 Asp Mvc 上使用 OWIN 进行自定义身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37705290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com