ClaimType type execution on ClaimsIdentity

I am working on a new application and using the ASP.NET identifier and wondered if there is a way to enforce a certain type of ClaimsIdentity claim. Here is what I still .. It works, but it seems that this is what would / should be built in, and maybe I just can not find it.

 public void SignIn(IUserIdentity user, string authenticationType, bool isPersistent)
    {
        if (user == null)
        {
            string msg = "UserIdentity or UserIdentity is null";
            _logger.Error(msg);
            throw new NullReferenceException(msg);
        }
        List<Claim> claims = _claimService.GetClaims(user.UserId);

        var identity = new ClaimsIdentity(claims, authenticationType, ClaimTypes.Name, ClaimTypes.Role);
        if (claims.Any() && claims.Single(c => c.Type == ClaimTypes.Name).Value != null)
        {
            _owinContext.Authentication.SignIn(new AuthenticationProperties
            {
                IsPersistent = isPersistent
            }, identity);
        }
        else
        {
            throw new SecurityException("Invalid or null Name Claim");    
        }

    }
+3
source share
1 answer

I do not know of any built-in way of claiming that a claim exists.

Edit

You're right. My original solution has been redesigned. I think your decision is the only way to go.

The check is incorrect, but for two reasons:

  • the exception is throw, if the request is not found, because it is used .Single
  • Claim ,

:

List<Claim> claims = _claimService.GetClaims(user.UserId);
if (claims.Any(i => i.Type == ClaimTypes.Name)
{
    var identity = new ClaimsIdentity(claims, authenticationType, ClaimTypes.Name, ClaimTypes.Role);

var claims = _claimService.GetClaims(user.UserId);
var identity = new ClaimsIdentity(claims, authenticationType, ClaimTypes.Name, ClaimTypes.Role);
if (identity.Name != null)
{

, .

-

- , .

public class ClaimsAuthorizeAttribute : AuthorizeAttribute
{
    public string[] ClaimTypes { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null) { throw new ArgumentNullException("httpContext"); }

        var principal = httpContext.User as ClaimsPrincipal;
        return principal != null && HasAllClaimTypes(principal) && base.AuthorizeCore(httpContext);
    }

    private bool HasAllClaimTypes(ClaimsPrincipal principal)
    {
        return ClaimTypes == null || ClaimTypes.All(claimType => principal.HasClaim(claim => claim.Type == claimType));
    }
}

, , :

filters.Add(new ClaimsAuthorizeAttribute { ClaimTypes = new[]{ ClaimTypes.Name } });

, . ( , )

. http://leastprivilege.com/2012/10/26/using-claims-based-authorization-in-mvc-and-web-api/

+3

All Articles