C# MVC身份验证-最简单的方法
我看过ASP.NET标识,它看起来非常复杂,很难理解。基本上,我想知道的是在登录时授权用户的最简单方法,因此[authorize]数据注释将允许他们通过。遵循以下步骤: 安装以下NuGet软件包 Microsoft.Owin Microsoft.Owin.Host.SystemWeb Microsoft.Owin.Security Microsoft.Owin.Security.Cookies 在App_Start文件夹中,添加一个AuthConfig,如下所示:C# MVC身份验证-最简单的方法,c#,asp.net-mvc,C#,Asp.net Mvc,我看过ASP.NET标识,它看起来非常复杂,很难理解。基本上,我想知道的是在登录时授权用户的最简单方法,因此[authorize]数据注释将允许他们通过。遵循以下步骤: 安装以下NuGet软件包 Microsoft.Owin Microsoft.Owin.Host.SystemWeb Microsoft.Owin.Security Microsoft.Owin.Security.Cookies 在App_Start文件夹中,添加一个AuthConfig,如下所示: public static c
public static class AuthConfig
{
public const string DefaultAuthType = "DefaultAppCookie"; //example
public const string LoginPath = "System/SignIn"; //example
public static void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthType,
LoginPath = new PathString(LoginPath)
});
}
}
在项目的根路径中,添加如下所示的Startup.cs
[assembly: OwinStartup(typeof(YourPorject.Startup))]
namespace YourPorject
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
AuthConfig.ConfigureAuth(app);
}
}
}
要对登录操作中的用户进行身份验证,请执行以下操作:
//user = the user that is loggin on, retrieved from database
List<Claim> claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.Name),
new Claim(ClaimTypes.Email, user.Email),
//some other claims
};
ClaimsIdentity identity = new ClaimsIdentity(claims, AuthConfig.DefaultAuthType);
IAuthenticationManager authManager = Request.GetOwinContext().Authentication;
authManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
您需要添加ClaimTypes.Role以授权特定角色。查看此链接。它解释了表单身份验证。试着按照下面的操作:谢谢你的帖子。一个简单的问题,DefaultAuthType需要什么?ThanksIt只是一个常量字符串,用于登录操作。。。由于ClaimSideEntity对象中使用的身份验证类型的名称必须与AuthConfig匹配,因此很难找到在没有asp.net标识的情况下持久化声明和角色的完整示例。非常感谢。