MVC身份validation – 最简单的方法

我看过ASP.NET身份,它看起来非常复杂,难以理解。 基本上我想知道的是在登录时授权用户的最简单方法,因此[授权]数据注释将允许他们通过。

跟着这些步骤:

安装以下NuGet包

  • Microsoft.Owin
  • Microsoft.Owin.Host.SystemWeb
  • Microsoft.Owin.Security
  • Microsoft.Owin.Security.Cookies

在App_Start文件夹中,添加如下所示的AuthConfig:

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); } } } 

要对用户进行身份validation(通常在登录操作中):

 //user = the user that is loggin on, retrieved from database List claims = new List { 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来授权特定角色。