1
  • I can log in and get the token key from http://localhost:58507/token by Postman
  • I can call an api with just [Authorize] Attribute
  • But when I set the roles [Authorize(Roles= "Admin")] I get this server internal Error:

"Message": "An error has occurred.",

"ExceptionMessage": "Value cannot be null. Parameter name: username",

"ExceptionType": "System.ArgumentNullException",

"StackTrace": "at System.Web.Util.SecUtility.CheckParameter(String& param, Boolean checkForNull, Boolean checkIfEmpty, Boolean checkForCommas, Int32 maxSize, String paramName)

this is my Codes:

  • the AuthorizeAttribute Class:

public class AuthorizeAttribute : System.Web.Http.AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
                base.HandleUnauthorizedRequest(actionContext);
            else
                actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);
        }
    }
  • the OAuthAuthorizationServerProvider Class :

public class MyOAuthProvider : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials(
        OAuthGrantResourceOwnerCredentialsContext context)
    {
        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        string username = context.UserName;
        string password = context.Password;
        if (Membership.ValidateUser(username, password))
        {
            using (var ee = new DBEntities())
            {
                MembershipUser mu = Membership.GetUser(username);
                Guid guid = (Guid)mu.ProviderUserKey;
                string roles = string.Join(",", Roles.GetRolesForUser(username));
                identity.AddClaim(new Claim(ClaimTypes.Role, roles));
                identity.AddClaim(new Claim("username", username));
                context.Validated(identity);
            }
        }
        else
        {
            context.SetError("Login Field", "Error username or password");
        }
    }
}
alessandrio
  • 4,282
  • 2
  • 29
  • 40
Abdu Imam
  • 393
  • 3
  • 16

1 Answers1

2

I found the solution on: this post
the problem was in this line

identity.AddClaim(new Claim("username", username));

I change "username" to ClaimTypes.Name

identity.AddClaim(new Claim(ClaimTypes.Name, username));
Abdu Imam
  • 393
  • 3
  • 16