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