WebApi增加Oauth2认证

前期搭建可看这篇博文:https://www.cnblogs.com/lnice/p/6857203.html,此博文是在本篇博文实践才产生的,在实践中,也产生了几个问题,希望能够共同交流,一起进步。

在此次测试,我们分为前后端:后端 :WebAPI

 前段  Jquery 

主要是测试,对于前段框架,我也不怎么熟悉,比如VUE,这些类似风格的  ,我熟悉知识 Boostrap  这种简单样式框架,不得不说,这是我的悲哀

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 
 6 namespace WebAPI5.Models
 7 {
 8     /// <summary>
 9     /// 用户信息类
10     /// </summary>
11     public class UserInfo
12     {
13        /// <summary>
14        /// ID
15        /// </summary>
16         public int id { get; set; }
17         /// <summary>
18         /// 用户姓名
19         /// </summary>
20         public string UserName { get; set; }
21         /// <summary>
22         /// 用户密码
23         /// </summary>
24         public string UserPwd { get; set; }
25         /// <summary>
26         /// 性别   0 是女 1 是男
27         /// </summary>
28         public int UserSex { get; set; }
29 
30 
31     }
32 }
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Net;
 5 using System.Net.Http;
 6 using System.Web.Http;
 7 using WebAPI5.Models;
 8 
 9 namespace WebAPI5.Controllers
10 {
11     [Authorize]
12     public class BlogController : ApiController
13     {
14         //查询所有员工
15         [HttpGet]
16         public IHttpActionResult GetAll()
17         {
18             List<UserInfo> uf = new List<UserInfo>() {
19                  new UserInfo {  id=1, UserName="陈粒", UserPwd="weeweewwee", UserSex=0},
20                  new UserInfo {  id=1, UserName="小半", UserPwd="qdaqwdqqd", UserSex=1},
21                  new UserInfo {  id=1, UserName="Grain", UserPwd="dasad", UserSex=0},
22                  new UserInfo {  id=1, UserName="Cgrain", UserPwd="weeadadweewwee", UserSex=1}
23             };
24             return Json(uf);
25         }
26     }
27 }
Controllers
 1   public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
 2         {
 3 
 4             context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
 5 
 6             string usepwd = context.Password;
 7             string usename = context.UserName;
 8             ////判断是否有这个账号,有才能访问
 9             if (usename.Contains("C")&& usepwd.Contains("C"))
10             {  
11                 context.SetError("invalid_grant", "The username or password is incorrect");
12                 return;
13             }
14             var identity = new ClaimsIdentity(context.Options.AuthenticationType);
15             identity.AddClaim(new Claim("sub", context.UserName)); 
16             context.Validated(identity);
17          
18         }
SimpleAuthorizationServerProvider
  1 <!DOCTYPE html>
  2 <html lang="en">
  3 
  4 <head>
  5     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  6     <meta charset="utf-8" />
  7     <title>你的 ASP.NET 应用程序</title>
  8     <script src="jquery-1.10.2.min.js"></script>
  9 </head>
 10 
 11 <body>
 12     <input type="text" id="username" />
 13     <input type="text" id="pwd" />
 14     <input type="button" onclick="add()" value="Come On" />
 15     <input type="button" onclick="showdata()" value="显示data" />
 16     <input type="button" onclick="reftoken()" value="刷新token" />
 17 
 18     <div>
 19         <ul id="My_ul"></ul>
 20     </div>
 21     <script>
 22         var token;
 23         var refresh_token;
 24         function add() {
 25             $.ajax({
 26                 url: "http://localhost:1985/token",
 27                 dataType: "Json",
 28                 method: "POST",
 29                 data: {
 30                     "grant_type": "password",
 31                     "UserName": $("#username").val(),
 32                     "Password": $("#pwd").val()
 33 
 34                 },
 35                 success: function (data) {
 36                     console.log(data);
 37                     token = data["access_token"];
 38                     refresh_token = data["refresh_token"];
 39                     console.log(refresh_token);
 40                     $.ajax({
 41                         url: "http://localhost:1985/api/Blog/GetAll",
 42                         dataType: "Json",
 43                         method: "GET",
 44                         headers: {
 45                             "Authorization": "Bearer  " + token   //把登录获取的Token加入到http请求头中
 46                         },
 47                         success: function (data) {
 48 
 49                             console.log(data);
 50                         },
 51                         error: function (error) {
 52                             alert(error["message"]);
 53 
 54                         }
 55 
 56                     });
 57                 },
 58                 error: function (error) {
 59 
 60                     alert(error["responseJSON"]["error_description"]);
 61                     //console.log(error);
 62                     //                 alert(error["error_description"]);
 63                 }
 64 
 65             });
 66 
 67 
 68         };
 69         function showdata() {
 70             $.ajax({
 71                 url: "http://localhost:1985/api/Blog/GetAll",
 72                 dataType: "Json",
 73                 method: "GET",
 74                 headers: {
 75                     "Authorization": "Bearer  " + token   //把登录获取的Token加入到http请求头中
 76                 },
 77                 success: function (data) {
 78                     var html = "";
 79                     for (index = 0; index < data.length; index++) {
 80                         html += "<li> " + data[index]["UserName"] + "  </li>";
 81 
 82 
 83                     }
 84                     $("#My_ul").append(html)
 85                     console.log(data);
 86                 },
 87                 complete: function (xhr, ts) {
 88                    
 89                     // console.log(); 
 90                     // console.log
 91                     // (ts);
 92                     if (xhr.status== 401 ) {
 93                         reftoken();
 94                         showdata();
 95                     }
 96                 }
 97                 // },
 98                 // error: function (error) {
 99                 //     alert(error["responseJSON"]["message"]); 
100 
101                 // }
102 
103             });
104 
105 
106         }
107 
108         function reftoken() { 
109             $.ajax({
110                 url: "http://localhost:1985/token",
111                 dataType:"Json",
112                 type:"POST", 
113                 data: {
114                     "grant_type": "refresh_token",
115                     "refresh_token": refresh_token
116                 }, 
117                 success: function (data) { 
118                     console.log(data)
119                     token=data["access_token"];
120                     refresh_token=data["refresh_token"];
121                 
122                 },
123                 error: function (error) {
124                     console.log(error);  
125                 }
126 
127             });
128 
129 
130         }
131     </script> 
132 </body>
133 
134 </html>
Html

 为了便于观察 ,我expires_in 设置一分钟

 这里报错是因为我们的token 已经过期,为了不影响用户操作,我们刷新了token,在重新请求了数据

 随后我又点击了显示数据按钮

显示了两次:

 为了便于观察,我们修改已经ajax

showdata 方法,我们注释掉token过期重新获取的方法调用

 

 点击请求都没有了数据

 我们刷新token

 

 我们突然发现,刚刚获取的token过期(其实没过期的)

 ajax 请求,每次都会进入这个方法,所以才会有我们的  if 判断  ,只有当请求是401 的时候(这里可以再详细一点,指出错误请求的类型或者原因,更精确的判断)

好了,这里就是简单的介绍了,当时这样,我也发现了几个问题:

第一个问题: 尽管我们用到了api的授权,可是,如何防止他大规模的数据调用。

第二个问题:前后端分离的项目,或者说未分离的项目,肯定不是这样调用的,这样子,我总根据不安全(只能把一些技术在我之下的大佬给拦截,技术在我之上的大佬,估计看到这篇文件就在呵呵了,心想:要是每个api都这样,我就不难了 o(╥﹏╥)o),好了,这个问题就是:如何标准化?没用到vue  前段只是简单的使用 boostrap +ajax (自我感觉这个问题也问到了也许有部分人的心声,并不是每个人做的项目都比较超强,其实还有许多大佬们,许多普通人,做的项目都比较普通,还有很多人还在苦海中挣扎,比如我),如何更安全的使用标准化?

第三个问题:自定义修改他的返回:比如说:

 如何修改呀??

第四个问题:  我们返回给前段的token ,需要加密不?

觉得好就点个关注点个赞,留下你的思路或者说改进点哦  ☺ 还可以留下大佬有话的代码

猜你喜欢

转载自www.cnblogs.com/whatarey/p/11438243.html