asp.net-mvc-4 - 使用 ASP.NET MVC 进行基于声明的授权

标签 asp.net-mvc-4 authentication authorization claims-based-identity

我阅读了很多博客文章和 stackoverflow 答案,但仍然无法找到一个使用基于声明的身份验证和授权的现实世界开源项目,以便我可以了解如何实际实现这些项目。

到目前为止我能找到的是 Thinktecture.IdentityModelthis blog在示例网站上实现基于声明的授权。如果你们能给我指出一些使用声明的开源项目,那将非常有帮助。

我感兴趣的是如何使用数据库检索我的应用程序的声明。

到目前为止,我尝试的是使用内存中的声明存储来模拟数据库,我创建了一个 CustomClaimsTransformerCustomAuthorizationManager 像这样。

public class CustomClaimsTransformer : ClaimsAuthenticationManager
    {
        public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
        {
            //validate name claim
            string nameClaimValue = incomingPrincipal.Identity.Name;

            return CreatePrincipal(nameClaimValue);
        }

        private ClaimsPrincipal CreatePrincipal(string userName)
        {
            int userId = ClaimStore.Users.First(u => u.Value == userName).Key;
            var claims = ClaimStore.ClaimsSet.Where(c => c.Key == userId);

            var claimsCollection = claims.Select(kp => kp.Value).ToList();

            return new ClaimsPrincipal(new ClaimsIdentity(claimsCollection, "Custom"));
        }
    }

public class CustomAuthorisationManager : ClaimsAuthorizationManager
    { 
        public override bool CheckAccess(AuthorizationContext context)
        {
            string resource = context.Resource.First().Value;
            string action = context.Action.First().Value;

            if (action == "Show" && resource == "Code")
            {
                bool likesJava = context.Principal.HasClaim(ClaimStore._httpMyclaimsUsers, "True");
                return likesJava;
            }
            else if (action == "Read" && resource == "Departments")
            {
                bool readDeps = context.Principal.HasClaim(ClaimStore._httpMyclaimsDepartments, "Read");
                return readDeps;
            }
            return false;
        }
    }

如何在现实场景中实现这些而不需要太多 IF 条件?

最佳答案

关于asp.net-mvc-4 - 使用 ASP.NET MVC 进行基于声明的授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21807528/

相关文章:

asp.net-mvc - 默认页面重定向到登录 - MVC 4

asp.net-mvc - 使用声明和 AntiforgeryToken 的 MVC 5 OWIN 登录。我是否错过了 ClaimIdentity 提供商?

c# - 与存储库模式一起使用时,ServiceStack 操作未显示在元数据中

authentication - Google-Oauth 身份验证错误

c# - 没有指定 authenticationScheme,也没有找到基于自定义策略的授权的 DefaultForbidScheme

asp.net-mvc - 使用EF连接现有数据库

java - facebook 的 Facebook 身份验证问题(不是 facebook lite)

authentication - 在推送 GitHub 期间从命令行使用 SSH key ?

jsp - 如何根据用户角色有条件地显示 JSP 页面元素

http - Angular2 http 默认 header 通用授权 token