如何使用 GET/POST 和令牌密钥基于 Ajax 调用 ASP.NET Web API
How to Call ASP.NET Web API base on Ajax with GET/POST and Token key
我知道如何将 Ajax 与 GET/POST 数据一起使用,如下面的代码,但我不知道如何将其与令牌密钥一起使用(已获得令牌密钥)
$("#read1").click(function () {
$.support.cors = true;
$.ajax({
crossDomain: true,
url: 'http://localhost:65370/api/travels',
type: 'GET',
cache: false,
error: function (xhr, status, errorThrow) {
},
complete: function (xhr) {
},
success: function (data) {
}
});
});
$("#create1").click(function () {
var person = {
"travel_id": 4
};
$.ajax({
},
type: "post",
url: 'http://localhost:65370/api/travels',
datatype: "json",
contenttype: "application/json; charset=utf-8",
data: person,
success: function (data) {
},
error: function (xhr, status, errorThrow) {
}
});
});
我找到了如下代码的方法
//you just need to put it in Ajax content
headers:{
'Authorization': 'Bearer ' + token
}
当您获得令牌密钥后,您可以在“Headers”中添加代码。
带有令牌
的完整 JavaScript 代码
<script>
$(document).ready(function()
{
var bearer ="";
var user ={
grant_type:'password',
username:'a',
password:'a'
};
$.ajax({
type: "POST",
url: "http://localhost:50971/token",
data:user,
contentType: "application/x-www-form-urlencoded",
dataType: "json",
success: function (data) {
bearer = JSON.parse(JSON.stringify(data));
bearer = bearer.access_token;
Authorization();
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
function Authorization() {
$.ajax({
type: "GET",
url: "http://localhost:50971/api/employee/GetEmployees",
headers: {
'Authorization': 'Bearer ' + bearer
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (a) {
alert(JSON.stringify(a))
//$.each(a, function (x, y) {
// alert(x)
// alert(y)
// $.each(y, function (x, y) {
// alert(x)
// alert(y)
// });
//});
//alert("Hello: " + a.Name + ".\nCurrent Date and Time: " + a.address);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
}
})
</script>
标记如何使用带有基本令牌身份验证的网络 api [ref]
请按照以下步骤操作
步骤 1. 分别创建虚拟数据库“Test”和两个表“Users”和“Employee”
CREATE DATABASE TEST GO
USE TEST GO
CREATE TABLE Users(Id INT IDENTITY(1,1) PRIMARY KEY, Name varchar(255) NOT NULL, UserName varchar(50), Password varchar(50)) INSERT INTO [TEST].[dbo].[Users](Name, UserName, Password) VALUES('Mukesh Kumar', 'Mukesh', AAAAAA');
CREATE TABLE Employees(Id INT IDENTITY(1,1) PRIMARY KEY, Name varchar(255) NOT NULL, Address varchar(500))
INSERT INTO Employees (Name, Address) VALUES('Mukesh Kumar', 'New Delhi')
INSERT INTO Employees (Name, Address) VALUES('John Right', 'England')
INSERT INTO Employees (Name, Address) VALUES('Chris Roy', 'France')
INSERT INTO Employees (Name, Address) VALUES('Anand Mahajan', 'Canada')
INSERT INTO Employees (Name, Address) VALUES('Prince Singh', 'India')
步骤2.To新建ASP.NET带有WebAPI(无身份验证)的项目并在NuGet中找到点击安装;安装后,这些包将在参考中可用。
1.Microsoft.Owin
2.Microsoft.Owin.Host.SystemWeb
3.Microsoft.Owin.Security.OAuth
4.Microsoft.Owin.Security
5.Microsoft.AspNet.Identity.Owin
6.Microsoft.AspNet.WebApi.Cors
第 3 步。删除 Global.asax 并在 Global.asax 文件的相同位置添加新的 class “Startup.cs” 并添加以下代码。 (不用担心错误信息)
using EmployeeService.Provider;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
[assembly: OwinStartup(typeof(EmployeeService.Startup))]
namespace EmployeeService
{
public class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
var OAuthOptions = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(20),
Provider = new SimpleAuthorizationServerProvider()
};
app.UseOAuthBearerTokens(OAuthOptions);
app.UseOAuthAuthorizationServer(OAuthOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
}
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
}
第 4 步。添加新项目并选择 Ado.Net 实体模型(名称:EmployeeModel)
第 5 步。将新控制器添加为 EmployeeController 并添加以下代码。
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace EmployeeService.Controllers
{
public class EmployeeController : ApiController
{
[HttpGet]
[Authorize]
public List<Employee> GetEmployees()
{
using (var db = new TESTEntities())
{
var employees = db.Employees.ToList();
return employees;
}
}
}
}
第 6 步。在 Provider 文件夹中添加 class "SimpleAuthorizationServerProvider.cs" 的名称并添加以下代码
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web.Http.Cors;
namespace EmployeeService.Provider
{
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated(); //
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
using (var db = new TESTEntities())
{
if (db != null)
{
var empl = db.Employees.ToList();
var user = db.Users.ToList();
if (user != null)
{
if (!string.IsNullOrEmpty(user.Where(u => u.UserName == context.UserName && u.Password == context.Password).FirstOrDefault().Name))
{
identity.AddClaim(new Claim("Age", "16"));
var props = new AuthenticationProperties(new Dictionary<string, string>
{
{
"userdisplayname", context.UserName
},
{
"role", "admin"
}
});
var ticket = new AuthenticationTicket(identity, props);
context.Validated(ticket);
}
else
{
context.SetError("invalid_grant", "Provided username and password is incorrect");
context.Rejected();
}
}
}
else
{
context.SetError("invalid_grant", "Provided username and password is incorrect");
context.Rejected();
}
return;
}
}
}
}
第 7 步。您只需在 WebAPIConfig.cs 的 app_Start 文件夹中启用 CORS。
using Newtonsoft.Json.Serialization;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http;
using System.Web.Http.Cors;
namespace EmployeeService
{
public class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
}
}
Done with server side
客户端
你可以使用邮递员或提琴手来测试服务器代码是否可以
我知道如何将 Ajax 与 GET/POST 数据一起使用,如下面的代码,但我不知道如何将其与令牌密钥一起使用(已获得令牌密钥)
$("#read1").click(function () {
$.support.cors = true;
$.ajax({
crossDomain: true,
url: 'http://localhost:65370/api/travels',
type: 'GET',
cache: false,
error: function (xhr, status, errorThrow) {
},
complete: function (xhr) {
},
success: function (data) {
}
});
});
$("#create1").click(function () {
var person = {
"travel_id": 4
};
$.ajax({
},
type: "post",
url: 'http://localhost:65370/api/travels',
datatype: "json",
contenttype: "application/json; charset=utf-8",
data: person,
success: function (data) {
},
error: function (xhr, status, errorThrow) {
}
});
});
我找到了如下代码的方法
//you just need to put it in Ajax content
headers:{
'Authorization': 'Bearer ' + token
}
当您获得令牌密钥后,您可以在“Headers”中添加代码。
带有令牌
的完整 JavaScript 代码<script> $(document).ready(function() { var bearer =""; var user ={ grant_type:'password', username:'a', password:'a' }; $.ajax({ type: "POST", url: "http://localhost:50971/token", data:user, contentType: "application/x-www-form-urlencoded", dataType: "json", success: function (data) { bearer = JSON.parse(JSON.stringify(data)); bearer = bearer.access_token; Authorization(); }, failure: function (response) { alert(response.responseText); }, error: function (response) { alert(response.responseText); } }); function Authorization() { $.ajax({ type: "GET", url: "http://localhost:50971/api/employee/GetEmployees", headers: { 'Authorization': 'Bearer ' + bearer }, contentType: "application/json; charset=utf-8", dataType: "json", success: function (a) { alert(JSON.stringify(a)) //$.each(a, function (x, y) { // alert(x) // alert(y) // $.each(y, function (x, y) { // alert(x) // alert(y) // }); //}); //alert("Hello: " + a.Name + ".\nCurrent Date and Time: " + a.address); }, failure: function (response) { alert(response.responseText); }, error: function (response) { alert(response.responseText); } }); } }) </script>
标记如何使用带有基本令牌身份验证的网络 api [ref]
请按照以下步骤操作
步骤 1. 分别创建虚拟数据库“Test”和两个表“Users”和“Employee”
CREATE DATABASE TEST GO
USE TEST GO
CREATE TABLE Users(Id INT IDENTITY(1,1) PRIMARY KEY, Name varchar(255) NOT NULL, UserName varchar(50), Password varchar(50)) INSERT INTO [TEST].[dbo].[Users](Name, UserName, Password) VALUES('Mukesh Kumar', 'Mukesh', AAAAAA');
CREATE TABLE Employees(Id INT IDENTITY(1,1) PRIMARY KEY, Name varchar(255) NOT NULL, Address varchar(500))
INSERT INTO Employees (Name, Address) VALUES('Mukesh Kumar', 'New Delhi')
INSERT INTO Employees (Name, Address) VALUES('John Right', 'England')
INSERT INTO Employees (Name, Address) VALUES('Chris Roy', 'France')
INSERT INTO Employees (Name, Address) VALUES('Anand Mahajan', 'Canada')
INSERT INTO Employees (Name, Address) VALUES('Prince Singh', 'India')
步骤2.To新建ASP.NET带有WebAPI(无身份验证)的项目并在NuGet中找到点击安装;安装后,这些包将在参考中可用。
1.Microsoft.Owin
2.Microsoft.Owin.Host.SystemWeb
3.Microsoft.Owin.Security.OAuth
4.Microsoft.Owin.Security
5.Microsoft.AspNet.Identity.Owin
6.Microsoft.AspNet.WebApi.Cors
第 3 步。删除 Global.asax 并在 Global.asax 文件的相同位置添加新的 class “Startup.cs” 并添加以下代码。 (不用担心错误信息)
using EmployeeService.Provider; using Microsoft.Owin; using Microsoft.Owin.Security.OAuth; using Owin; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; [assembly: OwinStartup(typeof(EmployeeService.Startup))] namespace EmployeeService { public class Startup { public void ConfigureAuth(IAppBuilder app) { var OAuthOptions = new OAuthAuthorizationServerOptions { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(20), Provider = new SimpleAuthorizationServerProvider() }; app.UseOAuthBearerTokens(OAuthOptions); app.UseOAuthAuthorizationServer(OAuthOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); HttpConfiguration config = new HttpConfiguration(); WebApiConfig.Register(config); } public void Configuration(IAppBuilder app) { ConfigureAuth(app); GlobalConfiguration.Configure(WebApiConfig.Register); } } }
第 4 步。添加新项目并选择 Ado.Net 实体模型(名称:EmployeeModel)
第 5 步。将新控制器添加为 EmployeeController 并添加以下代码。
using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace EmployeeService.Controllers { public class EmployeeController : ApiController { [HttpGet] [Authorize] public List<Employee> GetEmployees() { using (var db = new TESTEntities()) { var employees = db.Employees.ToList(); return employees; } } } }
第 6 步。在 Provider 文件夹中添加 class "SimpleAuthorizationServerProvider.cs" 的名称并添加以下代码
using Microsoft.Owin.Security; using Microsoft.Owin.Security.OAuth; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using System.Web.Http.Cors; namespace EmployeeService.Provider { [EnableCors(origins: "*", headers: "*", methods: "*")] public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider { public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { context.Validated(); // } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var identity = new ClaimsIdentity(context.Options.AuthenticationType); context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); using (var db = new TESTEntities()) { if (db != null) { var empl = db.Employees.ToList(); var user = db.Users.ToList(); if (user != null) { if (!string.IsNullOrEmpty(user.Where(u => u.UserName == context.UserName && u.Password == context.Password).FirstOrDefault().Name)) { identity.AddClaim(new Claim("Age", "16")); var props = new AuthenticationProperties(new Dictionary<string, string> { { "userdisplayname", context.UserName }, { "role", "admin" } }); var ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); } else { context.SetError("invalid_grant", "Provided username and password is incorrect"); context.Rejected(); } } } else { context.SetError("invalid_grant", "Provided username and password is incorrect"); context.Rejected(); } return; } } } }
第 7 步。您只需在 WebAPIConfig.cs 的 app_Start 文件夹中启用 CORS。
using Newtonsoft.Json.Serialization; using System.Linq; using System.Net.Http.Formatting; using System.Web.Http; using System.Web.Http.Cors; namespace EmployeeService { public class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(cors); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First(); jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); } } }
Done with server side
客户端
你可以使用邮递员或提琴手来测试服务器代码是否可以