WebApi使用OAuth2认证

时间:2022-12-19 21:10:11

本篇文章实现了四种认证方式中的客户端模式和密码模式,未实现token持久化

未介绍OAuth2的相关概念,全部是干货,可自己在网上搜索OAuth2相关知识,在这不做过多阐述

  • 一、引用OAuth2所需的dll,使用nuget下载以下依赖项

       Microsoft.AspNet.WebApi.Owin
       Microsoft.Owin.Host.SystemWeb
       Microsoft.Owin.Security.OAuth
       Microsoft.AspNet.Identity.Owin

 

  • 二、重载OAuth2相应的验证方法
WebApi使用OAuth2认证WebApi使用OAuth2认证
 1 public class OAuthServerProvider : OAuthAuthorizationServerProvider
 2     {
 3         /// <summary>
 4         /// 验证OAuth请求
 5         /// </summary>
 6         /// <param name="context"></param>
 7         /// <returns></returns>
 8         public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
 9         {
10             string clientId;
11             string clientSecret;
12 
13             //获取客户端凭证
14             if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
15                 context.TryGetFormCredentials(out clientId, out clientSecret);
16 
17             //保存客户端凭证
18             context.OwinContext.Set<string>("clientId", clientId);
19             context.OwinContext.Set<string>("clientSecret", clientSecret);
20             //验证通过
21             context.Validated(clientId);
22 
23             return base.ValidateClientAuthentication(context);
24         }
25 
26         /// <summary>
27         /// 客户端模式 验证
28         /// </summary>
29         /// <param name="context"></param>
30         /// <returns></returns>
31         public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
32         {
33             var clientSecret = context.OwinContext.Get<string>("clientSecret");
34             if (context.ClientId == "admin" && clientSecret == "123")
35             {
36                 var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
37                 oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, "Clear App"));
38                 var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());
39                 context.Validated(ticket);
40             }
41             else
42             {
43                 context.SetError("invalid_grant", "The username or password is incorrect.");
44             }
45             return base.GrantClientCredentials(context);
46         }
47 
48         /// <summary>
49         /// 密码模式验证
50         /// </summary>
51         /// <param name="context"></param>
52         /// <returns></returns>
53         public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
54         {
55             if (context.UserName == "admin" && context.Password == "123456")
56             {
57                 var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
58                 oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
59                 var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());
60                 //替换上下文中票证信息,并将其标记为已验证
61                 context.Validated(ticket);
62             }
63             else
64             {
65                 context.SetError("invalid_grant", "The username or password is incorrect.");
66             }
67             return base.GrantResourceOwnerCredentials(context);
68         }
69 
70     }
重写OAuth验证方法

 

  • 三、添加Startup类
WebApi使用OAuth2认证WebApi使用OAuth2认证
 1  public class Startup
 2     {
 3         public void Configuration(IAppBuilder app)
 4         {
 5             var options = new OAuthAuthorizationServerOptions()
 6             {
 7                 TokenEndpointPath = new PathString("/oauth2/token"),//获取token访问路径
 8                 Provider = new OAuthServerProvider(),//oauth2服务配置
 9                 AccessTokenExpireTimeSpan = TimeSpan.FromDays(15),//token有效期
10                 AllowInsecureHttp = true
11             };
12             app.UseOAuthBearerTokens(options);
13         }
14     }
Startup配置OAuth2服务

 

  • 四、验证OAuth请求

 密码模式
WebApi使用OAuth2认证

客户端模式

WebApi使用OAuth2认证