我不明白这一点,为什么您使用不记名身份验证但不想使用它(我想我不太了解您的帖子)
如果你想使用声明,这很简单。
如果您提供由您的应用程序创建的令牌,您必须提供您自己的 ServerOptions
OAuthAuthorizationServerOptions authServerOptions = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(30),
Provider = new AuthorizationServerProvider(),
};
AuthorizationServerProvider 是您自己的实现:
public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
你覆盖的地方
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
await Task.Run(() => Login(context));
}
private void Login(OAuthGrantResourceOwnerCredentialsContext ctx)
{
Guid? userid = userservice.GetId(ctx.UserName, ctx.Password);
if (userid != null)
{
////here you can start with your claim stuff
ClaimsIdentity identity = new ClaimsIdentity(new List<Claim> { new Claim("userId", userid.ToString()) }, OAuthDefaults.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, ctx.UserName));
ctx.Validated(identity);
return;
}
}
那么就可以使用授权属性了
public class UserAuthorizationAttribute : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext ctx)
{
return base.IsAuthorized(ctx) && CheckUserAuthorization(ctx.Request.GetOwinContext().Authentication);
}
private bool CheckUserAuthorization(IAuthenticationManager manager)
{
var claim = manager.User.Claims.FirstOrDefault(x => x.Type == "user_identifier");
if (claim != null)
{
Guid identifier = new Guid(claim.Value);
//// evaluate the claim, etc...
return true;
}
return false;
}
}