前期搭建可看這篇博文: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 }

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 }

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>
為了便於觀察 ,我expires_in 設置一分鍾
這里報錯是因為我們的token 已經過期,為了不影響用戶操作,我們刷新了token,在重新請求了數據
隨后我又點擊了顯示數據按鈕
顯示了兩次:
為了便於觀察,我們修改已經ajax
showdata 方法,我們注釋掉token過期重新獲取的方法調用
點擊請求都沒有了數據
我們刷新token
我們突然發現,剛剛獲取的token過期(其實沒過期的)
ajax 請求,每次都會進入這個方法,所以才會有我們的 if 判斷 ,只有當請求是401 的時候(這里可以再詳細一點,指出錯誤請求的類型或者原因,更精確的判斷)
好了,這里就是簡單的介紹了,當時這樣,我也發現了幾個問題:
第一個問題: 盡管我們用到了api的授權,可是,如何防止他大規模的數據調用。
第二個問題:前后端分離的項目,或者說未分離的項目,肯定不是這樣調用的,這樣子,我總根據不安全(只能把一些技術在我之下的大佬給攔截,技術在我之上的大佬,估計看到這篇文件就在呵呵了,心想:要是每個api都這樣,我就不難了 o(╥﹏╥)o),好了,這個問題就是:如何標准化?沒用到vue 前段只是簡單的使用 boostrap +ajax (自我感覺這個問題也問到了也許有部分人的心聲,並不是每個人做的項目都比較超強,其實還有許多大佬們,許多普通人,做的項目都比較普通,還有很多人還在苦海中掙扎,比如我),如何更安全的使用標准化?
第三個問題:自定義修改他的返回:比如說:
如何修改呀??
第四個問題: 我們返回給前段的token ,需要加密不?
覺得好就點個關注點個贊,留下你的思路或者說改進點哦 ☺ 還可以留下大佬有話的代碼