我已经看过ASP.NET Identity,它看起来确实很复杂,很难遵循。基本上,我想知道的是授权用户登录的最简单方法,因此[Authorize]数据批注将允许他们通过。

最佳答案

跟着这些步骤:

安装以下NuGet软件包


微软
Microsoft.Owin.Host.SystemWeb
微软安全
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);
        }
    }

}


要验证用户身份(通常在“登录操作”中):

//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来授权特定角色。

关于c# - MVC身份验证-最简单的方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32095889/

10-11 02:02