创建一个webapi项目,不进行身份认证
通过Nuget引入下面的组件
Microsoft.AspNet.WebApi.Owin
Microsoft.Owin.Host.SystemWeb
Microsoft.Owin.Security.OAuth
Microsoft.Owin.Security.Cookies
Microsoft.AspNet.Identity.Owin
Microsoft.Owin.Cors
在项目下新建Startup类,这个类将作为owin的启动入口
修改startup的内容
[assembly: OwinStartup(typeof(OAuth.Startup))]
namespace OAuth
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
//ConfigureAuth(app);
MyConfigAuth(app);
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseCors(CorsOptions.AllowAll);
app.UseWebApi(config);
}
public void MyConfigAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions option = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"), //获取 access_token 授权服务请求地址
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), //access_token 过期时间
Provider = new SimpleAuthorizationServerProvider(), //access_token 相关授权服务
RefreshTokenProvider = new SimpleRefreshTokenProvider() //refresh_token 授权服务
};
app.UseOAuthAuthorizationServer(option);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
}
OAuth身份认证,新建SimpleAuthorizationServerProvider类
namespace OAuth.OAuth
{
public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
return Task.FromResult<object>(null);
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
/*
* 对用户名、密码进行数据校验,这里我们省略
using (AuthRepository _repo = new AuthRepository())
{
IdentityUser user = await _repo.FindUser(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
}*/
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));
context.Validated(identity);
}
}
}
新建SimpleRefreshTokenProvider类
namespace OAuth.OAuth
{
public class SimpleRefreshTokenProvider : AuthenticationTokenProvider
{
private static ConcurrentDictionary<string, string> _refreshTokens = new ConcurrentDictionary<string, string>();
/// <summary>
/// 生成 refresh_token
/// </summary>
public override void Create(AuthenticationTokenCreateContext context)
{
context.Ticket.Properties.IssuedUtc = DateTime.UtcNow;
context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(60);
context.SetToken(Guid.NewGuid().ToString("n"));
_refreshTokens[context.Token] = context.SerializeTicket();
}
/// <summary>
/// 由 refresh_token 解析成 access_token
/// </summary>
public override void Receive(AuthenticationTokenReceiveContext context)
{
string value;
if (_refreshTokens.TryRemove(context.Token, out value))
{
context.DeserializeTicket(value);
}
}
}
}
js调用
<script>
function getToken() {
var data = {
'password': '1',
'username': '1',
'grant_type': 'password'
};
$.ajax({
url: "http://localhost:52386/token",
type: "post",
data: data,
async: false,
contentType: 'application/x-www-form-urlencoded',
success: function (sResponse) {
console.log('refresh_token ok: ' + sResponse.access_token + ' expires_in:' + sResponse.expires_in);
},
error: function (a, b, c) {
if (a.status == 400 && a.responseJSON.error == 'invalid_grant') {
console.log('refresh token invalid');
}
}
});
}
</script>