首先是Startup.cs
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseCors(CorsOptions.AllowAll);
ConfigureAuth(app);
app.UseWebApi(config);
}
然后把ConfigureAuth方法里面代码屏蔽,改成如下
OAuthAuthorizationServerOptions OAuthOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,//允许客户端一http协议请求
TokenEndpointPath = new PathString("/token"), //token请求的地址,即http://localhost:端口号/token;
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(600),
Provider = new ApplicationOAuthProvider("PublicClientId") //提供具体的认证策略;
};
app.UseOAuthAuthorizationServer(OAuthOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
最后是GrantResourceOwnerCredentials方法(这里面生成Token)
//API里面可以通过RequestContext.Principal.Identity.Name获取这里设置的用户标识
ClaimsIdentity oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, user.ID.ToString()));
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);