2017-06-03 97 views
2
  • 我可以登录并通过邮差得到http://localhost:58507/token令牌密钥
  • 我可以调用的API只用[授权]属性
  • 但是,当我设置的角色[授权(角色=“管理员”)我得到这个服务器内部错误:

"Message": "An error has occurred.",承载令牌是不是与我的授权工作属性角色用的WebAPI,用户名是空

"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)

这是我的代码:

  • 的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

我发现了解决方案:本post
的问题是在这条线

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

我改变 “用户名”,以ClaimTypes.Name

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