如何将JWT身份验证与Web API集成在一起? [英] How to integrate JWT authentication with Web API?

查看:78
本文介绍了如何将JWT身份验证与Web API集成在一起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将JWT与Web API集成时遇到问题.我尝试遵循此教程示例

I am having problem integrating JWT with my Web API.. I tried to follow this tutorial and example

这似乎很简单,但是我很难将其与我的项目集成.您应该知道,我有一堆.aspx(网络表单)文件构成了我的网站.这个网站正在使用javascript(Ajax)使用我的Web API.我已经安装了jose-jwt软件包,因此可以在我的代码中使用它.

It seems pretty straight forward, but I am having difficulties integrating it with my project. You should know that I have a bunch of .aspx (Web Form) files that makes my website. This website is consuming my Web API using javascript (Ajax). I have installed jose-jwt package so I can use it in my code.

WebApiConfig.cs:

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"));

        }
    }

我在请求"控制器中执行的操作之一的示例:

Example of one of my actions inside '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

Client Side

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');
                }
            }
        });      

我想在成功"功能之后,先前的请求将被更新为具有以下内容:

I am guessing that the previous request will be updated to have the following after the 'success' function:

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身份验证与我的代码集成在一起.您能帮上忙吗?

I am having difficulties to integrate JWT authentication with my code. Could you please help with that.

谢谢!

推荐答案

因此,您将拥有:

  1. 一个Web API服务器("API")
  2. 一个Web窗体应用程序(客户端")

Web API服务器

该API将受JWT保护. API的每个客户端都应在HTTP标头(承载令牌)中提供JWT.身份验证提供商将在身份验证时提供此JWT.

Web API Server

The API will be protected by JWT. Every client of the API should provide a JWT in the HTTP header (a Bearer token). This JWT will be given by the Identity Provider at the time of authentication.

Web API需要某种中间件来从请求中获取JWT令牌,对其进行验证(验证受众,发行者,到期和签名),并设置一个对请求有效的ClaimsPrincipal.这样,您可以使用.Net标准授权属性和过程,例如:

The Web API needs some kind of middleware to get the JWT token from the request, validate it (verify audience, issuer, expiration and signature) and set a ClaimsPrincipal that will be valid for the request. That way you can use .Net standard authorization attributes and procedures, such as:

[Authorize] // requires the user to be authenticated
public IActionResult SomeProtectedAction()
{
}

如果您的Web API用于ASP.Net Core,则可以使用 Microsoft.AspNetCore.Authentication.JwtBearer 进行配置,如下所示:

If your Web API is for ASP.Net Core, you can use the Microsoft.AspNetCore.Authentication.JwtBearer to do that, configured like this:

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);

}

带有OWIN的常规ASP.Net应用程序可以使用 Microsoft.Owin. Security.ActiveDirectory 软件包,其配置代码如下:

Regular ASP.Net applications with OWIN can use the Microsoft.Owin.Security.ActiveDirectory package, with configuration code like this:

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时使用它,如下所示:

Client

Your client application will be a webforms app. After the user signs in (usually by redirecting the user to the identity provider's login page), you will get an access token back. You can store the token in the client (local storage), and use it when making calls to the API as you showed:

beforeSend: function(xhr) {
    xhr.setRequestHeader("Authorization", "Bearer " + localStorage.getItem('token'));
},

这篇关于如何将JWT身份验证与Web API集成在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆