如何将JWT身份验证与Web API集成?

时间:2016-11-02 20:33:15

标签: javascript c# asp.net jwt

我在将JWT与我的Web API集成时出现问题。我尝试按照此tutorialexample

看起来非常简单,但我很难将它与我的项目集成。您应该知道我有一堆.aspx(Web窗体)文件,这些文件构成了我的网站。这个网站使用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"));

        }
    }

我在“请求”控制器中的一个操作示例:

[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.");
        }

客户端

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

我猜测之前的请求将在“成功”功能之后更新为具有以下内容:

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身份验证与我的代码集成。你能帮忙吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

所以,你将拥有:

  1. 一个Web API服务器(&#34; API&#34;)
  2. 一个Web表单应用程序(&#34;客户端&#34;)
  3. Web API服务器

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

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

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

    如果您的Web API适用于ASP.Net Core,您可以使用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);
    
    }
    

    使用OWIN的常规ASP.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'));
    },