标签:
OAuth(Open Authorization)
为用户资源的授权提供了一个安全的、开放而又简易的标准。与以往的授权方式不同之处是OAuth的授权不会使第三方触及到用户的帐号信息(如用户名与密码),即第三方无需使用用户的用户名与密码就可以申请获得该用户资源的授权,因此OAuth是安全的。
本节目录:
1.创建一个控制台项目(其实类库都可以)ApiServer
Nuget引用:
Install-Package Microsoft.AspNet.WebApi.OwinSelfHost
或者引用以下三个
Install-Package Microsoft.AspNet.WebApi.Owin (让WebApi作为中间件)
Install-Package Microsoft.Owin.Hosting (Hosting接口默认使用HttpListener作为Server)
Install-Package Microsoft.Owin.Host.HttpListener (默认的Server实现)
2.添加Startup类
public void Configuration(IAppBuilder app)
{
// 有关如何配置应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=316888
ApiConfig(app);
}
private static void ApiConfig(IAppBuilder app)
{
var config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional , action = RouteParameter.Optional }
);
app.UseWebApi(config);
}
如何让Owin关联到Startup类的方法,可以看我的博客:
3.创建一个Api控制器
public class ValuesController : ApiController
{
public string Get()
{
return "Never、C";
}
}
4.Main方法启动
static void Main(string[] args)
{
const string url = "http://localhost:1234/";
using (WebApp.Start<Startup>(url))
{
Console.WriteLine("开启成功");
Console.ReadLine();
}
}
5.浏览器访问

在上面的Owin Web API的基础上,开始实现OAuth.
Nuget:
Install-Package Microsoft.Owin.Security.OAuth(owin的oauth的实现)
使用OAuth会要求Owin使用UseOAuthBearerTokens认证方式,所以引用
Install-Package Microsoft.AspNet.Identity.Owin
1.在Startup添加一个中间件配置
private static void OAuthConfig(IAppBuilder app)
{
var OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/token"),
Provider = new OTWAuthorizationServerProvider(),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true,
};
app.UseOAuthBearerTokens(OAuthOptions);
}
并且设置Web API使用OAuth
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); //添加的配置
app.UseWebApi(config);
2.自定义的provider
public class OTWAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
//1.验证客户
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
//此处可以判断client和user
//this.ClientId = clientId;
//this.IsValidated = true;
//this.HasError = false;
context.Validated("自定义的clientId");
return base.ValidateClientAuthentication(context);
}
//授权客户
public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
{
var ticket = new AuthenticationTicket(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "Never、C") }, context.Options.AuthenticationType), null);
//this.Ticket = ticket;
//this.IsValidated = true;
//this.HasError = false;
context.Validated(ticket);
return base.GrantClientCredentials(context);
}
}
3.用客户端来调用我们的(建议不要用单元测试,此处新建一个控制台项目)
static void Main(string[] args)
{
const string url = "http://localhost:1234/";
var client = new HttpClient();
var rst = client.PostAsync(url + "token", new StringContent("grant_type=client_credentials")).Result.Content.ReadAsStringAsync().Result;
Console.WriteLine(rst);
}
4.先启动服务端,再启动客户端

1.ValuesController添加特性Authorize
[Authorize]
public class ValuesController : ApiController
{
public string Get()
{
return User.Identity.Name;
}
}
访问会返回
{"Response status code does not indicate success: 401 (Unauthorized)."}
2.客户端引用
Install-Package Newtonsoft.Json -Version 7.0.1
3.修改Main方法,带上Token
class Program
{
static void Main(string[] args)
{
const string url = "http://localhost:1234/";
var client = new HttpClient();
var rst = client.PostAsync(url + "token", new StringContent("grant_type=client_credentials")).Result.Content.ReadAsStringAsync().Result;
var obj = JsonConvert.DeserializeObject<Token>(rst);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", obj.AccessToken);
rst = client.GetStringAsync(url + "api/values").Result;
Console.WriteLine(rst);
Console.ReadLine();
}
}
public class Token
{
[JsonProperty("Access_Token")]
public string AccessToken { get; set; }
}
4.先启动服务端,再启动客户端

扩展
其实OAuth自己也能实现,本质是生成一个加密的唯一的字符串
OAuth的实现方案还有DotNetOpenAuth、Thinktecture IdentityServer
参考:
http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/
http://www.cnblogs.com/dudu/p/4569857.html
[ASP.NET] 结合Web API在OWIN下实现OAuth
标签:
原文地址:http://www.cnblogs.com/neverc/p/4970996.html