久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

    1. <legend id='oQZOY'><style id='oQZOY'><dir id='oQZOY'><q id='oQZOY'></q></dir></style></legend>
    2. <small id='oQZOY'></small><noframes id='oQZOY'>

    3. <tfoot id='oQZOY'></tfoot>
        <i id='oQZOY'><tr id='oQZOY'><dt id='oQZOY'><q id='oQZOY'><span id='oQZOY'><b id='oQZOY'><form id='oQZOY'><ins id='oQZOY'></ins><ul id='oQZOY'></ul><sub id='oQZOY'></sub></form><legend id='oQZOY'></legend><bdo id='oQZOY'><pre id='oQZOY'><center id='oQZOY'></center></pre></bdo></b><th id='oQZOY'></th></span></q></dt></tr></i><div class="qwawimqqmiuu" id='oQZOY'><tfoot id='oQZOY'></tfoot><dl id='oQZOY'><fieldset id='oQZOY'></fieldset></dl></div>
          <bdo id='oQZOY'></bdo><ul id='oQZOY'></ul>
      1. JWT 和 Web API (JwtAuthForWebAPI?) - 尋找示例

        JWT and Web API (JwtAuthForWebAPI?) - Looking For An Example(JWT 和 Web API (JwtAuthForWebAPI?) - 尋找示例)

        • <legend id='0mVfp'><style id='0mVfp'><dir id='0mVfp'><q id='0mVfp'></q></dir></style></legend>
            <tbody id='0mVfp'></tbody>

            <tfoot id='0mVfp'></tfoot>

          1. <small id='0mVfp'></small><noframes id='0mVfp'>

              <bdo id='0mVfp'></bdo><ul id='0mVfp'></ul>

              <i id='0mVfp'><tr id='0mVfp'><dt id='0mVfp'><q id='0mVfp'><span id='0mVfp'><b id='0mVfp'><form id='0mVfp'><ins id='0mVfp'></ins><ul id='0mVfp'></ul><sub id='0mVfp'></sub></form><legend id='0mVfp'></legend><bdo id='0mVfp'><pre id='0mVfp'><center id='0mVfp'></center></pre></bdo></b><th id='0mVfp'></th></span></q></dt></tr></i><div class="qwawimqqmiuu" id='0mVfp'><tfoot id='0mVfp'></tfoot><dl id='0mVfp'><fieldset id='0mVfp'></fieldset></dl></div>
                  本文介紹了JWT 和 Web API (JwtAuthForWebAPI?) - 尋找示例的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

                  問題描述

                  限時送ChatGPT賬號..

                  我有一個以 Angular 為前端的 Web API 項目,我想使用 JWT 令牌保護它.我已經進行了用戶/通行證驗證,所以我認為我只需要實現 JWT 部分.

                  I've got a Web API project fronted by Angular, and I want to secure it using a JWT token. I've already got user/pass validation happening, so I think i just need to implement the JWT part.

                  我相信我已經選擇了 JwtAuthForWebAPI,所以一個使用它的例子會很棒.

                  I believe I've settled on JwtAuthForWebAPI so an example using that would be great.

                  我假設任何沒有用 [Authorize] 修飾的方法都會像往常一樣運行,并且如果客戶端傳遞的令牌不匹配,任何用 [Authorize] 修飾的方法都會 401.

                  I assume any method not decorated with [Authorize] will behave as it always does, and that any method decorated with [Authorize] will 401 if the token passed by the client doesn't match.

                  我還不知道如何在初始身份驗證時將令牌發送回客戶端.

                  What I can't yet figure out it how to send the token back to the client upon initial authentication.

                  我試圖只使用一個魔術字符串開始,所以我有這個代碼:

                  I'm trying to just use a magic string to begin, so I have this code:

                  RegisterRoutes(GlobalConfiguration.Configuration.Routes);
                  var builder = new SecurityTokenBuilder();
                  var jwtHandler = new JwtAuthenticationMessageHandler
                  {
                      AllowedAudience = "http://xxxx.com",
                      Issuer = "corp",
                      SigningToken = builder.CreateFromKey(Convert.ToBase64String(new byte[]{4,2,2,6}))
                  };
                  
                  GlobalConfiguration.Configuration.MessageHandlers.Add(jwtHandler);
                  

                  但我不確定最初是如何返回給客戶的.我想我知道如何在客戶端處理這個問題,但是如果你也可以展示這種交互的 Angular 方面,那么我會加分.

                  But I'm not sure how that gets back to the client initially. I think I understand how to handle this on the client, but bonus points if you can also show the Angular side of this interaction.

                  推薦答案

                  我最終不得不從幾個不同的地方獲取信息來創建一個適合我的解決方案(實際上,生產可行解決方案的開始 -但它有效!)

                  I ended-up having to take a information from several different places to create a solution that works for me (in reality, the beginnings of a production viable solution - but it works!)

                  我擺脫了 JwtAuthForWebAPI (盡管我確實從中借了一件,以允許沒有授權標頭的請求流向不受 [Authorize] 保護的 WebAPI 控制器方法).

                  I got rid of JwtAuthForWebAPI (though I did borrow one piece from it to allow requests with no Authorization header to flow through to WebAPI Controller methods not guarded by [Authorize]).

                  相反,我使用的是 Microsoft 的 JWT 庫 (Microsoft 的 JSON Web 令牌處理程序.NET 框架 - 來自 NuGet).

                  Instead I'm using Microsoft's JWT Library (JSON Web Token Handler for the Microsoft .NET Framework - from NuGet).

                  在我的身份驗證方法中,在進行實際身份驗證后,我創建了令牌的字符串版本,并將其與經過身份驗證的名稱(在這種情況下傳遞給我的用戶名相同)和一個角色一起傳回,實際上, 可能是在身份驗證期間派生的.

                  In my authentication method, after doing the actual authentication, I create the string version of the token and pass it back along with the authenticated name (the same username passed into me, in this case) and a role which, in reality, would likely be derived during authentication.

                  方法如下:

                  [HttpPost]
                  public LoginResult PostSignIn([FromBody] Credentials credentials)
                  {
                      var auth = new LoginResult() { Authenticated = false };
                  
                      if (TryLogon(credentials.UserName, credentials.Password))
                      {
                          var tokenDescriptor = new SecurityTokenDescriptor
                          {
                              Subject = new ClaimsIdentity(new[]
                              {
                                  new Claim(ClaimTypes.Name, credentials.UserName), 
                                  new Claim(ClaimTypes.Role, "Admin")
                              }),
                  
                              AppliesToAddress = ConfigurationManager.AppSettings["JwtAllowedAudience"],
                              TokenIssuerName = ConfigurationManager.AppSettings["JwtValidIssuer"],
                              SigningCredentials = new SigningCredentials(new 
                                  InMemorySymmetricSecurityKey(JwtTokenValidationHandler.SymmetricKey),
                                  "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
                                  "http://www.w3.org/2001/04/xmlenc#sha256")
                              };
                  
                              var tokenHandler = new JwtSecurityTokenHandler();
                              var token = tokenHandler.CreateToken(tokenDescriptor);
                              var tokenString = tokenHandler.WriteToken(token);
                  
                              auth.Token = tokenString;
                              auth.Authenticated = true;
                          }
                  
                      return auth;
                  }
                  

                  更新

                  有一個關于在后續請求中處理令牌的問題.我所做的是創建一個 DelegatingHandler 來嘗試讀取/解碼令牌,然后創建一個 Principal 并將其設置為 Thread.CurrentPrincipal 和 HttpContext.Current.User (您需要將其設置為兩者).最后,我用適當的訪問限制來裝飾控制器方法.

                  There was a question about handling the token on subsequent requests. What I did was create a DelegatingHandler to try and read/decode the token, then create a Principal and set it into Thread.CurrentPrincipal and HttpContext.Current.User (you need to set it into both). Finally, I decorate the controller methods with the appropriate access restrictions.

                  這是 DelegatingHandler 的主要內容:

                  Here's the meat of the DelegatingHandler:

                  private static bool TryRetrieveToken(HttpRequestMessage request, out string token)
                  {
                      token = null;
                      IEnumerable<string> authzHeaders;
                      if (!request.Headers.TryGetValues("Authorization", out authzHeaders) || authzHeaders.Count() > 1)
                      {
                          return false;
                      }
                      var bearerToken = authzHeaders.ElementAt(0);
                      token = bearerToken.StartsWith("Bearer ") ? bearerToken.Substring(7) : bearerToken;
                      return true;
                  }
                  
                  
                  protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
                  {
                      HttpStatusCode statusCode;
                      string token;
                  
                      var authHeader = request.Headers.Authorization;
                      if (authHeader == null)
                      {
                          // missing authorization header
                          return base.SendAsync(request, cancellationToken);
                      }
                  
                      if (!TryRetrieveToken(request, out token))
                      {
                          statusCode = HttpStatusCode.Unauthorized;
                          return Task<HttpResponseMessage>.Factory.StartNew(() => new HttpResponseMessage(statusCode));
                      }
                  
                      try
                      {
                          JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
                          TokenValidationParameters validationParameters =
                              new TokenValidationParameters()
                              {
                                  AllowedAudience = ConfigurationManager.AppSettings["JwtAllowedAudience"],
                                  ValidIssuer = ConfigurationManager.AppSettings["JwtValidIssuer"],
                                  SigningToken = new BinarySecretSecurityToken(SymmetricKey)
                              };
                  
                          IPrincipal principal = tokenHandler.ValidateToken(token, validationParameters);
                          Thread.CurrentPrincipal = principal;
                          HttpContext.Current.User = principal;
                  
                          return base.SendAsync(request, cancellationToken);
                      }
                      catch (SecurityTokenValidationException e)
                      {
                          statusCode = HttpStatusCode.Unauthorized;
                      }
                      catch (Exception)
                      {
                          statusCode = HttpStatusCode.InternalServerError;
                      }
                  
                      return Task<HttpResponseMessage>.Factory.StartNew(() => new HttpResponseMessage(statusCode));
                  }
                  

                  不要忘記將其添加到 MessageHandlers 管道中:

                  Don't forget to add it into the MessageHandlers pipeline:

                  public static void Start()
                  {
                      GlobalConfiguration.Configuration.MessageHandlers.Add(new JwtTokenValidationHandler());
                  }
                  

                  最后,裝飾你的控制器方法:

                  Finally, decorate your controller methods:

                  [Authorize(Roles = "OneRoleHere")]
                  [GET("/api/admin/settings/product/allorgs")]
                  [HttpGet]
                  public List<Org> GetAllOrganizations()
                  {
                      return QueryableDependencies.GetMergedOrganizations().ToList();
                  }
                  
                  [Authorize(Roles = "ADifferentRoleHere")]
                  [GET("/api/admin/settings/product/allorgswithapproval")]
                  [HttpGet]
                  public List<ApprovableOrg> GetAllOrganizationsWithApproval()
                  {
                      return QueryableDependencies.GetMergedOrganizationsWithApproval().ToList();
                  }
                  

                  這篇關于JWT 和 Web API (JwtAuthForWebAPI?) - 尋找示例的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

                  【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

                  相關文檔推薦

                  What are good algorithms for vehicle license plate detection?(車牌檢測有哪些好的算法?)
                  onClick event for Image in Unity(Unity中圖像的onClick事件)
                  Running Total C#(運行總 C#)
                  Deleting a directory when clicked on a hyperlink with JAvascript.ASP.NET C#(單擊帶有 JAvascript.ASP.NET C# 的超鏈接時刪除目錄)
                  asp.net listview highlight row on click(asp.net listview 在單擊時突出顯示行)
                  Calling A Button OnClick from a function(從函數調用按鈕 OnClick)
                    <bdo id='yvhbc'></bdo><ul id='yvhbc'></ul>

                      <small id='yvhbc'></small><noframes id='yvhbc'>

                      <legend id='yvhbc'><style id='yvhbc'><dir id='yvhbc'><q id='yvhbc'></q></dir></style></legend>

                        1. <tfoot id='yvhbc'></tfoot>
                            <i id='yvhbc'><tr id='yvhbc'><dt id='yvhbc'><q id='yvhbc'><span id='yvhbc'><b id='yvhbc'><form id='yvhbc'><ins id='yvhbc'></ins><ul id='yvhbc'></ul><sub id='yvhbc'></sub></form><legend id='yvhbc'></legend><bdo id='yvhbc'><pre id='yvhbc'><center id='yvhbc'></center></pre></bdo></b><th id='yvhbc'></th></span></q></dt></tr></i><div class="qwawimqqmiuu" id='yvhbc'><tfoot id='yvhbc'></tfoot><dl id='yvhbc'><fieldset id='yvhbc'></fieldset></dl></div>

                              <tbody id='yvhbc'></tbody>
                            主站蜘蛛池模板: 国内自拍第一页 | 男人的天堂久久 | 国产午夜精品视频 | 久久国产免费 | www.久| 亚洲a一区 | av中文字幕在线播放 | 人人草天天草 | 日韩欧美在线视频 | 成人二区 | 国产一区中文字幕 | 在线观看亚洲 | 中文字幕丁香5月 | 欧美色综合一区二区三区 | 综合色久| 国产自产c区 | 久久精品国产亚洲一区二区 | 欧美在线一区二区三区 | 国产成都精品91一区二区三 | www久久国产 | 中文字幕在线精品 | 午夜免费视频 | 麻豆a级片 | 黄视频免费观看 | 日韩在线精品视频 | 亚洲国产高清在线 | 国产欧美日韩一区 | 妞干网av| 亚洲精品白浆高清久久久久久 | 日一区二区 | 国产精品亚洲片在线播放 | 亚洲国产成人精品女人久久久 | 欧美一区二区在线观看 | 中文字幕精品一区 | julia中文字幕久久一区二区 | 欧产日产国产精品v | 日韩精品一二三区 | 蜜臀网| 一区二区影院 | 欧美在线资源 | 99视频网站 |