问题描述
我已经看过ASP.NET的身份和它看起来非常复杂,难以效仿。基本上我想知道的是授权的登录用户因此[授权]数据注解将允许他们通过最简单的方式。
I have looked at ASP.NET Identity and it looks really complex and difficult to follow. Basically what I want to know is the easiest way to authorize a user on login so the [Authorize] data annotation will allow them through.
推荐答案
请按照下列步骤操作:
安装以下的NuGet包
Install the following NuGet packages
- Microsoft.Owin
- Microsoft.Owin.Host.SystemWeb
- Microsoft.Owin.Security
- Microsoft.Owin.Security.Cookies
App_Start文件夹里,添加一个AuthConfig看起来像这样的:
Inside App_Start folder, add a AuthConfig that look like this:
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看起来像这样
In the root path of the project, add a Startup.cs that look like this
[assembly: OwinStartup(typeof(YourPorject.Startup))]
namespace YourPorject
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
AuthConfig.ConfigureAuth(app);
}
}
}
要验证的用户(通常是登录动作中):
To authenticate an user (usually inside a Login Action):
//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授权特定的角色。
You need to add a ClaimTypes.Role to authorize specific roles.
这篇关于MVC认证 - 最简单的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!