1,在Webapi项目下添加如下引用:
Microsoft.AspNet.WebApi.Owin
Owin
Microsoft.Owin.Host.SystemWeb
Microsoft.Owin.Security.OAuth
Microsoft.Owin.Security.Cookies
Microsoft.AspNet.Identity.Owin
Microsoft.Owin.Cors
2, 在项目下新建Startup类,这个类将作为owin的启动入口,添加下面的代码
3,修改 Startup类中方法
1234567891011121314151617181920212223242526public class Startup{ public void
Configuration(IAppBuilder app) { // 有关如何配置应用程序的详细信息,请访问
http://go.microsoft.com/fwlink/?LinkID=316888 ConfigAuth(app);
HttpConfiguration config =new HttpConfiguration();
WebApiConfig.Register(config); app.UseCors(CorsOptions.AllowAll);
app.UseWebApi(config); } public void ConfigAuth(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()); }}
4, OAuth身份认证,新建SimpleAuthorizationServerProvider类
123456789101112131415161718192021222324public 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[] { "*" }); AccountService accService
=new AccountService(); string md5Pwd =
LogHelper.MD5CryptoPasswd(context.Password); IList<object[]> ul =
accService.Login(context.UserName, md5Pwd); if (ul.Count() == 0) {
context.SetError("invalid_grant", "The username 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); }}
5, 新建SimpleRefreshTokenProvider类
12345678910111213141516171819202122232425262728public 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); } }}
6, 在要加验证的接口上加上[Authorize]标记
12345678910[Authorize]public class EmployeeController : ApiController{
//查询所有员工 [HttpGet] public IList<UC_Employee> GetAllEmps() { return
new List<UC_Employee>(); }}
7,调用api程序
8,传入参数,获取token
9,传入access_token
本文版权归作者和博客园共有,欢迎转载,但未经作者同意需保留此段声明,且在文章页面明显位置给出原文连接。
作者:Lnice <http://www.cnblogs.com/lnice>
出处:https://www.cnblogs.com/lnice/p/6857203.html
<https://www.cnblogs.com/lnice/p/6857203.html>
热门工具 换一换