.Net Framework WebApi使用OAuth2.0
2018-02-09 14:15
465 查看
参考资料:https://olepetterdahlmann.com/2016/08/08/implement-an-oauth-2-0-authorization-server-using-owin-oauth-middleware-on-asp-net-web-api/
1.新建webapi项目,并添加以下三个库引用:
Microsoft.AspNet.WebApi.Owin
Microsoft.Owin.Host.SystemWeb
Microsoft ASP.NET Identity Owin
2.App_Start目录下新建类:Startup.Auth.csusing Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace YFAPICommon
{
//Startup.Auth.cs
public partial class Startup
{
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
static Startup()
{
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/token"),
//Provider = new OAuthAppProvider(),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(2),
AllowInsecureHttp = true
};
}
public void ConfigureAuth(IAppBuilder app)
{
app.UseOAuthBearerTokens(OAuthOptions);
}
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
3.新建用来创建Token的控制器:AuthenticateController.csusing Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Web.Http;
namespace YFAPICommon.Controllers
{
public class LoginInput
{
public string account { set; get; }
public string pass { set; get; }
}
public class AuthenticateController : ApiController
{
[HttpPost]
public JObject GetAccessTokenByPass(LoginInput input)
{
var tokenExpiration = TimeSpan.FromDays(14);
ClaimsIdentity identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, "zzzili"));
identity.AddClaim(new Claim(ClaimTypes.Sid, "1"));
var props = new AuthenticationProperties()
{
IssuedUtc = DateTime.UtcNow,
ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration),
};
var ticket = new AuthenticationTicket(identity, props);
var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
JObject tokenResponse = new JObject(
new JProperty("userName", "zzzili"),
new JProperty("access_token", accessToken),
new JProperty("token_type", "bearer"),
new JProperty("expires_in", tokenExpiration.TotalSeconds.ToString()),
new JProperty(".issued", ticket.Properties.IssuedUtc.ToString()),
new JProperty(".expires", ticket.Properties.ExpiresUtc.ToString()));
return tokenResponse;
}
}
}4.添加Swagger支持:
参看:https://www.cnblogs.com/daxnet/p/6181366.html
5.添加swagger对OAuth的支持,可以在swagger页面上输入token:
在SwaggerConfig.cs文件中修改如下代码:
c.EnableApiKeySupport("Authorization", "header");
6.项目启动后可以在Swagger页面的右上角api_key处输入access_Token,例如:
Bearer NfHlhFRSf78Ig9cIQ7H2l0P9nxMpaU4H53j_h2PFf2PlqPnIJ**************
7.添加完成后,即可在控制器内对方法添加Auth身份认证: [Authorize]
[HttpPost]
public string Test1()
{
var ident = this.User.Identity;
return "test";
}
工程git地址:https://github.com/zzzili/YFAPICommon
1.新建webapi项目,并添加以下三个库引用:
Microsoft.AspNet.WebApi.Owin
Microsoft.Owin.Host.SystemWeb
Microsoft ASP.NET Identity Owin
2.App_Start目录下新建类:Startup.Auth.csusing Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace YFAPICommon
{
//Startup.Auth.cs
public partial class Startup
{
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
static Startup()
{
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/token"),
//Provider = new OAuthAppProvider(),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(2),
AllowInsecureHttp = true
};
}
public void ConfigureAuth(IAppBuilder app)
{
app.UseOAuthBearerTokens(OAuthOptions);
}
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
3.新建用来创建Token的控制器:AuthenticateController.csusing Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Web.Http;
namespace YFAPICommon.Controllers
{
public class LoginInput
{
public string account { set; get; }
public string pass { set; get; }
}
public class AuthenticateController : ApiController
{
[HttpPost]
public JObject GetAccessTokenByPass(LoginInput input)
{
var tokenExpiration = TimeSpan.FromDays(14);
ClaimsIdentity identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, "zzzili"));
identity.AddClaim(new Claim(ClaimTypes.Sid, "1"));
var props = new AuthenticationProperties()
{
IssuedUtc = DateTime.UtcNow,
ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration),
};
var ticket = new AuthenticationTicket(identity, props);
var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
JObject tokenResponse = new JObject(
new JProperty("userName", "zzzili"),
new JProperty("access_token", accessToken),
new JProperty("token_type", "bearer"),
new JProperty("expires_in", tokenExpiration.TotalSeconds.ToString()),
new JProperty(".issued", ticket.Properties.IssuedUtc.ToString()),
new JProperty(".expires", ticket.Properties.ExpiresUtc.ToString()));
return tokenResponse;
}
}
}4.添加Swagger支持:
参看:https://www.cnblogs.com/daxnet/p/6181366.html
5.添加swagger对OAuth的支持,可以在swagger页面上输入token:
在SwaggerConfig.cs文件中修改如下代码:
c.EnableApiKeySupport("Authorization", "header");
6.项目启动后可以在Swagger页面的右上角api_key处输入access_Token,例如:
Bearer NfHlhFRSf78Ig9cIQ7H2l0P9nxMpaU4H53j_h2PFf2PlqPnIJ**************
7.添加完成后,即可在控制器内对方法添加Auth身份认证: [Authorize]
[HttpPost]
public string Test1()
{
var ident = this.User.Identity;
return "test";
}
工程git地址:https://github.com/zzzili/YFAPICommon
相关文章推荐
- RDIFramework.NET开发实例━表约束条件权限的使用-Web
- .NET Compact Framework 下Win32 API P/Invoke 的使用
- net WebApi中使用swagger
- .net web api 中调用post方法和调用自定义方法名session使用
- 《Asp.Net Web API》-----webApi的简单使用
- 实例演示使用RDIFramework.NET 框架的工作流组件进行业务流程的定义—请假申请流程-Web
- C#与.NET Framework, ASP.NET Web API RC版本新特性:Web API的帮助文档制作
- Asp.net Core WebApi 使用Swagger做帮助文档,并且自定义Swagger的UI
- 在ASP.NET Core Web API上使用Swagger提供API文档
- 使用Visual Studio Code开发Asp.Net Core WebApi学习笔记(二)-- Web Api Demo
- .NET Core WebAPI Swagger使用
- 通过Reflector和.net的反射机制来探索和使用.net framework未文档化的API
- 在ASP.NET Core Web API上使用Swagger提供API文档
- 使用 asp.net Web API 2的坑
- 【原创】.NET Web API之filter ActionFilterAttribute 过滤器使用
- 在ASP.NET Core Web API上使用Swagger提供API文档
- RDIFramework.NET开发实例━表约束条件权限的使用-Web
- 使用 Swagger 自动生成 ASP.NET Core Web API 的文档、在线帮助测试文档(ASP.NET Core Web API 自动生成文档)
- RDIFramework.NET开发实例━表约束条件权限的使用-Web
- .net WebApi中使用swagger