如何将JWT身份验证与Web API集成
本文关键字:Web API 集成 身份验证 JWT | 更新日期: 2023-09-27 18:16:13
我在将JWT与我的Web API集成时遇到问题。我试着遵循这个教程和示例
看起来很简单,但是我很难把它和我的项目结合起来。你应该知道,我有一堆。aspx (Web Form)文件,使我的网站。这个网站正在使用javascript (Ajax)使用我的Web API。我已经安装了jose-jwt包,所以我可以在我的代码中使用它。
服务器端WebApiConfig.cs:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "defaultApiRoutes",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = @"'d+" } // Only matches if "id" is one or more digits.
);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
}
我的一个动作在'Request' Controller中的例子:
[HttpPost]
[ActionName("createRequest")]
public IHttpActionResult createRequest(Request request)
{
if (userIsAuthorized) // I am guessing that for each action there will be this kinda condition to check the token of the user
if (ModelState.IsValid) {
using (SqlConnection connection = WebApiApplication.reqeustConnection("ConStrMRR")) {
using (SqlCommand command = new SqlCommand("createRequest", connection)) {
try {
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("@status_id", request.StatusID));
command.Parameters.Add(new SqlParameter("@patient_firstname", request.PatientFirstName));
command.Parameters.Add(new SqlParameter("@patient_lastname", request.PatientLastName));
command.Parameters.Add(new SqlParameter("@patient_url", request.PatientURL));
command.Parameters.Add(new SqlParameter("@facility", request.Facility));
connection.Open();
int request_id = (int)command.ExecuteScalar();
return Ok(request_id);
} catch (Exception e) {
throw e;
} finally {
connection.Close();
}
}
}
}
return Content(HttpStatusCode.BadRequest, "Request has not been created.");
}
客户端Create-request.js
$.ajax({
url: "http://" + window.myLocalVar + "/api/requests/createRequest",
type: "POST",
dataType: 'json',
contentType: 'application/json',
data: request,
success: function (request_id, state) {
console.log(request_id);
},
error: function (err) {
if (err) {
notyMessage(err.responseJSON, 'error');
}
}
});
我猜之前的请求将被更新为在'success'函数之后具有以下内容:
beforeSend: function(xhr)
{
xhr.setRequestHeader("Authorization", "Bearer " + localStorage.getItem('token'));
},
我的登录页面如下:
<body id="cover">
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Please Sign In</h3>
</div>
<div class="panel-body">
<div align="center" style="margin-bottom: 50px;"><img class="img-responsive" src="../img/logo.jpg"/></div>
<form role="form" runat="server">
<fieldset>
<div class="form-group">
<asp:TextBox ID="usernameTextBox" CssClass="form-control" runat="server" placeholder="Username"></asp:TextBox>
</div>
<div class="form-group">
<asp:TextBox ID="passwordTextBox" CssClass="form-control" runat="server" placeholder="Password" TextMode="Password"></asp:TextBox>
</div>
<div class="checkbox">
<label>
<asp:CheckBox ID="rememberMeCheckBox" runat="server"/>Remember Me
</label>
</div>
<!-- Change this to a button or input when using this as a form -->
<asp:Button CssClass="btn btn-primary btn-block" Text="Login" ID="Login" runat="server"/>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
我有困难集成JWT身份验证与我的代码。你能帮我一下吗?
谢谢!
所以,你将有:
- 一个Web API服务器("API")
- 一个Web表单应用程序(客户端)
Web API Server
API将由JWT保护。API的每个客户端都应该在HTTP头中提供JWT(承载令牌)。这个JWT将在身份验证时由身份提供者给出。
Web API需要某种中间件从请求中获取JWT令牌,验证它(验证受众、发行者、过期和签名),并设置一个对请求有效的claimprincipal。这样就可以使用。net标准授权属性和过程,例如:
[Authorize] // requires the user to be authenticated
public IActionResult SomeProtectedAction()
{
}
如果你的Web API是针对ASP的。. NetCore,你可以使用Microsoft.AspNetCore.Authentication.JwtBearer来做到这一点,配置如下:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
var options = new JwtBearerOptions
{
Audience = "[Your API ID]",
Authority = $"[URL for your identity provider]/",
// certificate public keys will be read automatically from
// the identity provider if possible
// If using symmetric keys, you will have to provide them
};
app.UseJwtBearerAuthentication(options);
}
常规ASP。带有OWIN的。Net应用程序可以使用Microsoft.Owin.Security.ActiveDirectory包,配置代码如下:
public void Configuration(IAppBuilder app)
{
var issuer = $"[url to identity provider]/";
var audience = "[your API id];
app.UseActiveDirectoryFederationServicesBearerAuthentication(
new ActiveDirectoryFederationServicesBearerAuthenticationOptions
{
TokenValidationParameters = new TokenValidationParameters
{
ValidAudience = audience,
ValidIssuer = issuer
// you will also have to configure the keys/certificates
}
});
客户您的客户端应用程序将是一个webforms应用程序。在用户登录后(通常通过将用户重定向到身份提供者的登录页面),您将获得一个访问令牌。您可以将令牌存储在客户端(本地存储)中,并在调用API时使用它,如下所示:
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + localStorage.getItem('token'));
},