Custom Claim with Boolean type

2020-07-27 04:48发布

问题:

I'm using Visual Studio 2015 to create an ASP.NET MVC 5 app. I'm using the Identity framework to add claims to a user after authentication. It's easy enough to add claims based on the built-in ClaimTypes, but I'm having challenges adding a custom claim that's a Boolean.

I've created this static class to hold my custom claim types:

public static class CustomClaimTypes
{
    public static readonly string IsEmployee = "http://example.com/claims/isemployee";
}

Then I try to add a custom claim to the ClaimsIdentity object:

userIdentity.AddClaim(new Claim(CustomClaimTypes.IsEmployee, isEmployee));

It gives this error on the line above:

cannot convert from 'bool?' to 'System.Security.Claims.ClaimsIdentity'

All the examples that I'm finding are adding strings. How do you add a bool, int, or other type? Thanks.

回答1:

The claims can only be represented as strings. Any numbers, booleans, guids, whatever all have to be strings when added to the claims collection. So ToString() it.

userIdentity.AddClaim(
    new Claim(CustomClaimTypes.IsEmployee, 
    isEmployee.GetValueOrDefault(false).ToString()));


标签: c# asp.net