- 我可以从http://localhost:58507/token登录并获取令牌键
- 我可以用[授权]属性调用API
- 但是,当我设置角色[授权(roles =" admin"(时,我会得到此服务器内部错误:
"消息":"发生了错误。",
" exceptionMessage":"值不能为null。参数名称:用户名",
" exceptiontype":" system.argumentNullexception",
" stacktrace":"在system.web.util.secutility.checkparameter(string& param,boolean checkfornull,boolean checkifement,boolean checkifempty,boolean checkforean checkforcommas,int32 maxsize,cartssize,maxsize,string string paramname(
p>这是我的代码:
- 授权奖学类:
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); } }
- oauthauthorizationserververprovider类:
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"); } } }
我在以下方面找到了解决方案
问题是在这条线
identity.AddClaim(new Claim("username", username));
我将"用户名"更改为sipertypes.name
identity.AddClaim(new Claim(ClaimTypes.Name, username));