我查看了ASP.NET身份,它看起来非常复杂且难以理解。基本上我想知道的是在登录时授权用户的最简单方法,因此[授权]数据注释将允许他们通过。
答案 0 :(得分:3)
请按照以下步骤操作:
安装以下NuGet包
在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);
}
}
}
验证用户(通常在登录操作中):
//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来授权特定角色。