bearer token不能与我的Authorize Attribute Roles一起使用WebAPI,Username为null

时间:2017-06-03 15:29:17

标签: c# asp.net-web-api token roles authorize

  • 我可以登录并通过Postman
  • http://localhost:58507/token获取令牌密钥
  • 我可以用[授权]属性
  • 调用api
  • 但是当我设置角色[授权(角色="管理员")]时,我得到此服务器内部错误:
  

"消息":"发生了错误。",

     

" ExceptionMessage":"值不能为空。参数名称:username",

     

" ExceptionType":" System.ArgumentNullException",

     

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

这是我的代码:

  • AuthorizeAttribute类:
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);
        }
    }
  • OAuthAuthorizationServerProvider类:
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");
        }
    }
}

1 个答案:

答案 0 :(得分:2)

我找到了解决方案:post 问题出在这一行

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

我改变了#34;用户名"到ClaimTypes.Name

identity.AddClaim(new Claim(ClaimTypes.Name, username));