Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Asp.NET核心MVC基于角色的授权_C#_Asp.net Core_.net Core_Asp.net Core Mvc_Asp.net Core 2.1 - Fatal编程技术网

C# Asp.NET核心MVC基于角色的授权

C# Asp.NET核心MVC基于角色的授权,c#,asp.net-core,.net-core,asp.net-core-mvc,asp.net-core-2.1,C#,Asp.net Core,.net Core,Asp.net Core Mvc,Asp.net Core 2.1,我正在开发基于角色的授权。使用User.AddIdentity成功定义角色后,当我退出页面时,该角色将消失 [AllowAnonymous] [HttpPost] public IActionResult Index(User user) { try { var currentUser = _UserService.login(user, _context); if (currentUser.userID != 0) {

我正在开发基于角色的授权。使用
User.AddIdentity
成功定义角色后,当我退出页面时,该角色将消失

[AllowAnonymous]
[HttpPost]
public IActionResult Index(User user)
{
    try
    {
    var currentUser = _UserService.login(user, _context);                

    if (currentUser.userID != 0)
    {                                        
        CookieOptions options = new CookieOptions();
        options.Expires = DateTime.Now.AddDays(1);

        var identity = new ClaimsIdentity(new[] {
            new Claim(ClaimTypes.Name, currentUser.NAME_SURNAME),                                                
            new Claim(ClaimTypes.Role, "Admin")                        
        },
        "ApplicationCookie");    

        User.AddIdentity(new ClaimsIdentity(identity));

        var isin = User.IsInRole("Admin");

        var cacheValue = _UserService.stringToMd5(currentUser.NAME_SURNAME);
        Response.Cookies.Append("login_cache", cacheValue, options);                                    

        TempData["error"] = null;
        return RedirectToAction("index", "home");
    }
    else
    {
        TempData["error"] = "Kullanıcı adı yada şifre yanlıştır.";
        return RedirectToAction("index", "home");
    }                    
    }
    catch(Exception ex){
        TempData["error"] = ex.Message;
        //TempData["error"] = "User not found.";
        return RedirectToAction("index", "home");
    }
} 


[Area("Admin")]
[Authorize(Roles = "Admin")]
public class FaqController : Controller
{
    ....
}
Startup.cs

public void ConfigureServices(IServiceCollection services) 
{
    services.AddDistributedMemoryCache();
    services.AddSession();
    services.AddSession(options => {
    options.IdleTimeout = TimeSpan.FromMinutes(60);
});

    services.AddMvc();           

    services.AddDbContext<ModelContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
    if (env.IsDevelopment())
    {
        app.UseBrowserLink();
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();

    app.UseAuthentication();

    app.UseMvc(routes =>
{
    routes.MapRoute(
       name: "admin",
       template: "{area}/{controller=Home}/{action=Index}/{id?}");
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");               
});
}   
public void ConfigureServices(IServiceCollection services)
{
   services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
   services.AddTransient<IClaimsTransformation, ClaimsTransformer>();
   ...

   services.AddAuthorization(options =>
        {
            options.AddPolicy("MasterAdminsOnly", policy => policy.RequireClaim(ClaimTypes.Role, "MasterAdmin"));
            options.AddPolicy("AdminsOnly", policy => policy.RequireClaim(ClaimTypes.Role, "MasterAdmin", "DeptAdmin"));
        });
}
public void配置服务(IServiceCollection服务)
{
AddDistributedMemoryCache();
services.AddSession();
services.AddSession(选项=>{
options.IdleTimeout=TimeSpan.frommins(60);
});
services.AddMvc();
services.AddDbContext(选项=>
options.UseSqlServer(Configuration.GetConnectionString(“DefaultConnection”));
}
public void配置(IApplicationBuilder应用程序、IHostingEnvironment环境、IServiceProvider服务提供商)
{
if(env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(路由=>
{
routes.MapRoute(
名称:“管理员”,
模板:“{area}/{controller=Home}/{action=Index}/{id?}”);
routes.MapRoute(
名称:“默认”,
模板:“{controller=Home}/{action=Index}/{id?}”);
});
}   

您尚未定义应用程序的身份验证工作方式。 这应该在Startup类中的ConfigureServices方法中完成。 在这里,您需要告诉框架查找cookie,并从中验证用户

我已经修改了cookie创建,并添加了默认的asp.net核心方式。 然后,我通过在ConfigureServices方法中添加AddAuthentication()来启用cookie身份验证

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie();
这里有一个完整的例子

[AllowAnonymous]
[HttpPost]
public IActionResult Index(User user)
{
    try
    {
        var currentUser = _UserService.login(user, _context);                
        if (currentUser.userID != 0)
        {                                        
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, currentUser.NAME_SURNAME),                                                
                new Claim(ClaimTypes.Role, "Admin")      
            };

            var claimsIdentity = new ClaimsIdentity(
                claims, CookieAuthenticationDefaults.AuthenticationScheme);

            var authProperties = new AuthenticationProperties
            {
                ExpiresUtc = DateTimeOffset.UtcNow.AddDays(1)
            };

            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme, 
                new ClaimsPrincipal(claimsIdentity), 
                authProperties);

            return RedirectToAction("index", "home");
        }
        else
        {
            TempData["error"] = "Kullanıcı adı yada şifre yanlıştır.";
            return RedirectToAction("index", "home");
        }                    
    }
    catch(Exception ex){
        TempData["error"] = ex.Message;
        //TempData["error"] = "User not found.";
        return RedirectToAction("index", "home");
    }

} 
[AllowAnonymous]
[HttpPost]
公共IActionResult索引(用户)
{
尝试
{
var currentUser=_UserService.login(用户,_上下文);
如果(currentUser.userID!=0)
{                                        
var索赔=新列表
{
新索赔(ClaimTypes.Name、currentUser.Name\u姓氏),
新索赔(ClaimTypes.Role,“Admin”)
};
var claimsIdentity=新的claimsIdentity(
声明,CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties=新的AuthenticationProperties
{
ExpiresUtc=DateTimeOffset.UtcNow.AddDays(1)
};
等待HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
新的索赔(索赔实体),
版权所有),;
返回重定向到操作(“索引”、“主页”);
}
其他的
{
TempData[“error”]=“Kullanıcıadıyadaşifre yanlıtır.”;
返回重定向到操作(“索引”、“主页”);
}                    
}
捕获(例外情况除外){
TempData[“error”]=例如消息;
//TempData[“错误”]=“未找到用户。”;
返回重定向到操作(“索引”、“主页”);
}
} 
然后是创业

public void ConfigureServices(IServiceCollection services) 
{
    services.AddDistributedMemoryCache();
    services.AddSession();
    services.AddSession(options => {
        options.IdleTimeout = TimeSpan.FromMinutes(60);
    });

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie();

    services.AddMvc();           

    services.AddDbContext<ModelContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
    if (env.IsDevelopment())
    {
        app.UseBrowserLink();
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();

    app.UseAuthentication();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
           name: "admin",
           template: "{area}/{controller=Home}/{action=Index}/{id?}");
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");               
    });
}   
public void配置服务(IServiceCollection服务)
{
AddDistributedMemoryCache();
services.AddSession();
services.AddSession(选项=>{
options.IdleTimeout=TimeSpan.frommins(60);
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
services.AddMvc();
services.AddDbContext(选项=>
options.UseSqlServer(Configuration.GetConnectionString(“DefaultConnection”));
}
public void配置(IApplicationBuilder应用程序、IHostingEnvironment环境、IServiceProvider服务提供商)
{
if(env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(路由=>
{
routes.MapRoute(
名称:“管理员”,
模板:“{area}/{controller=Home}/{action=Index}/{id?}”);
routes.MapRoute(
名称:“默认”,
模板:“{controller=Home}/{action=Index}/{id?}”);
});
}   

您需要一个索赔转换器,并根据角色创建策略

//ClaimsTransformer.cs

public class ClaimsTransformer : IClaimsTransformation
{
    private IRepository _repository;
    private IHttpContextAccessor _httpContextAccessor;        
    private IMemoryCache _cache;

    public ClaimsTransformer(IRepository repository, IHttpContextAccessor httpContextAccessor, IMemoryCache cache)
    {
        _repository = repository;
        _httpContextAccessor = httpContextAccessor;           
        _cache = cache;
    }
    public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
   {
        if (principal.Identity.IsAuthenticated)
        {
            var currentPrincipal = (ClaimsIdentity)principal.Identity;

            var ci = (ClaimsIdentity)principal.Identity;
            var cacheKey = ci.Name;

            if (_cache.TryGetValue(cacheKey, out List<Claim> claims))
            {
                currentPrincipal.AddClaims(claims);
            }
            else
            {
                claims = new List<Claim>();
                var isUserMasterAdmin = await _repository.IsUserMasterAdmin(ci.Name);
                if (isUserMasterAdmin)
                {
                    var c = new Claim(ClaimTypes.Role, "MasterAdmin");
                    claims.Add(c);
                }

                var isUserDeptAdmin = await _repository.IsUserDeptAdmin(ci.Name);
                if (isUserDeptAdmin)
                {
                    var c = new Claim(ClaimTypes.Role, "DeptAdmin");
                    claims.Add(c);
                }

                _cache.Set(cacheKey, claims);
                currentPrincipal.AddClaims(claims);
            }                
        }

        return await Task.FromResult(principal);
    }
}

如何对用户进行身份验证?请分享你的startup classI added startup.cst非常感谢。你能告诉我怎么注销吗?
[Authorize(Policy = "MasterAdminsOnly")]
public class UsersController : Controller
{
  ....
}