.Net Framework WebApi使用OAuth2.0

举报
清雨小竹 发表于 2022/09/25 02:38:31 2022/09/25
【摘要】 参考资料:https://olepetterdahlmann.com/2016/08/08/implement-an-oauth-2-0-authorization-server-using-owin-oauth-middleware-on-asp-net-web-api/   1.新建webapi项目,并添加以下三个库引用...

参考资料: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.cs


  
  1. using Microsoft.Owin;
  2. using Microsoft.Owin.Security.OAuth;
  3. using Owin;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Web;
  8. namespace YFAPICommon
  9. {
  10. //Startup.Auth.cs
  11. public partial class Startup
  12. {
  13. public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
  14. static Startup()
  15. {
  16. OAuthOptions = new OAuthAuthorizationServerOptions
  17. {
  18. TokenEndpointPath = new PathString("/token"),
  19. //Provider = new OAuthAppProvider(),
  20. AccessTokenExpireTimeSpan = TimeSpan.FromDays(2),
  21. AllowInsecureHttp = true
  22. };
  23. }
  24. public void ConfigureAuth(IAppBuilder app)
  25. {
  26. app.UseOAuthBearerTokens(OAuthOptions);
  27. }
  28. public void Configuration(IAppBuilder app)
  29. {
  30. ConfigureAuth(app);
  31. }
  32. }
  33. }

 

3.新建用来创建Token的控制器:AuthenticateController.cs


  
  1. using Microsoft.Owin.Security;
  2. using Microsoft.Owin.Security.OAuth;
  3. using Newtonsoft.Json.Linq;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Http;
  9. using System.Security.Claims;
  10. using System.Web.Http;
  11. namespace YFAPICommon.Controllers
  12. {
  13. public class LoginInput
  14. {
  15. public string account { set; get; }
  16. public string pass { set; get; }
  17. }
  18. public class AuthenticateController : ApiController
  19. {
  20. [HttpPost]
  21. public JObject GetAccessTokenByPass(LoginInput input)
  22. {
  23. var tokenExpiration = TimeSpan.FromDays(14);
  24. ClaimsIdentity identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
  25. identity.AddClaim(new Claim(ClaimTypes.Name, "zzzili"));
  26. identity.AddClaim(new Claim(ClaimTypes.Sid, "1"));
  27. var props = new AuthenticationProperties()
  28. {
  29. IssuedUtc = DateTime.UtcNow,
  30. ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration),
  31. };
  32. var ticket = new AuthenticationTicket(identity, props);
  33. var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
  34. JObject tokenResponse = new JObject(
  35. new JProperty("userName", "zzzili"),
  36. new JProperty("access_token", accessToken),
  37. new JProperty("token_type", "bearer"),
  38. new JProperty("expires_in", tokenExpiration.TotalSeconds.ToString()),
  39. new JProperty(".issued", ticket.Properties.IssuedUtc.ToString()),
  40. new JProperty(".expires", ticket.Properties.ExpiresUtc.ToString()));
  41. return tokenResponse;
  42. }
  43. }
  44. }

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身份认证:


  
  1. [Authorize]
  2. [HttpPost]
  3. public string Test1()
  4. {
  5. var ident = this.User.Identity;
  6. return "test";
  7. }

 


  
  1. protected int GetAuthUserId()
  2. {
  3. var ident = (ClaimsIdentity)User.Identity;
  4. return int.Parse(ident.FindFirst(ClaimTypes.Sid).Value);
  5. }

工程git地址:https://github.com/zzzili/YFAPICommon

文章来源: zzzili.blog.csdn.net,作者:清雨小竹,版权归原作者所有,如需转载,请联系作者。

原文链接:zzzili.blog.csdn.net/article/details/79297800

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。