html代码我就不写了,直接上jquery怎么写的,先引用jquery类库
内部js写法,使用了sessionStorage存储token。
1 var TokenUrl = "http://localhost:5000/connect/token"; 2 var UserApiUrl = "http://localhost:5002"; 3 4 //获取token 5 function getToken(username, password) { 6 sessionStorage["token"] = ""; 7 $.ajax({ 8 url: TokenUrl, 9 dataType: "json", 10 type: ‘post‘, 11 async: false, 12 data: { "client_id": "webclient", "grant_type": "password", "username": username, "password": password }, 13 success: function (json) { 14 if (json.access_token) { 15 sessionStorage["token"] = json.access_token; 16 } 17 }, 18 error: function (json) { 19 $("token").html("错误"); 20 } 21 }); 22 } 23 24 //使用token获取资源内容 25 function getUserApi() { 26 var token = sessionStorage["token"]; 27 $.ajax({ 28 beforeSend: function(xhr) { 29 xhr.setRequestHeader("Authorization", "Bearer "+token); 30 }, 31 url: UserApiUrl + ‘/api/home/index‘, 32 dataType: "text", 33 type: ‘post‘, 34 async: false, 35 success: function (text) { 36 alert(text); 37 }, 38 error: function (text) { 39 } 40 }); 41 }