簡體   English   中英

Web API – 使用不記名令牌進行身份驗證

[英]Web API – authenticate with bearer token

我創建了一個 MVC 應用程序,用於允許外部身份驗證/注冊。 它已經創建了所有必要的組件(Owin、EF、注冊、登錄、注銷),我能夠在應用程序中執行所有基本活動。

現在,我想將 Web 應用程序與我的移動應用程序也將使用的 Web API 集成。 我堅持在 Web API 調用中進行身份驗證(使用我從 Web 應用程序收到的不記名令牌)。

我看到了在啟用 OWIN 中間件的情況下創建 WEB API 項目的示例。 但我不知道如何集中外部身份驗證過程並為我的 Web 應用程序和移動應用程序使用令牌而且我不想使用 ANGULAR或單頁應用程序。 任何人都可以建議我解決此問題的正確技術途徑。 謝謝你。

第1步:

我在 Visual Studio 2015 中創建了一個啟用個人登錄的 MVC 項目。 並配置了我在谷歌開發者控制台中配置所有內容的密鑰。 我的Startup.cs會有以下代碼

 public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });

第2步:

更改了 webconfig 文件以指向我的本地數據庫並運行該應用程序,我能夠使用我的 gmail 帳戶通過 google 成功登錄,並且用戶詳細信息已成功添加到數據庫中的 ASPUSerTables

第 3 步:

現在我想創建一個 WEB API 項目,它將連接到數據庫並將一些數據檢索到 MVC Web 應用程序和移動應用程序(我在這里卡在身份驗證部分)。 我也需要對我的移動應用程序使用第三方身份驗證 (Xamarin) 並使用我的移動應用程序和 MVC 網站中的通用 API

第 4 步所以我想,我應該創建 WEB API 項目,而不是 WEB 應用程序(第 1 步),它如下所示,在Startup.cs 中返回身份驗證令牌,並將該 cookie 存儲在網站中以傳遞后續請求。

app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Configure the application for OAuth based flow
        PublicClientId = "self";
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            // In production mode set AllowInsecureHttp = false
            AllowInsecureHttp = true
        };

我不想使用 ANGULAR,我需要我的 WebApplication(MVC) 和 WEB API 項目正確驗證所有請求。 請告訴我正確的道路。 謝謝

您需要做的是按照以下步驟操作

  • 創建具有個人用戶帳戶身份驗證的 Web API 項目。
  • 現在,您將准備好使用 API 進行注冊、更改密碼以及 API 端點來為用戶生成令牌。
  • 創建另一個項目,但這次是同一解決方案中沒有身份驗證的MVC

這將是我們的架構

在此處輸入圖片說明

這是 API 控制器

[Authorize]
public class ValuesController : ApiController
{
      [HttpGet]
      public IEnumerable<string> Get()
      {
         return new string[] { "values1", "values2" };
      }
}

這是你的 MVC 控制器

public class MVCValuesController : Controller
{
     HttpClient client;

     // web api Url
     string url = string.Format("http://localhost:60143/api/Values");
     string bearerToken = string.Format("bearer token from web api");
     public MVCValuesController()
     {
        client = new HttpClient(); 
        client.BaseAddress = new Uri(url);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Accept.Add("Authorization", "Bearer " + bearerToken);
     }

     public ActionResult GetValues()
     {
         HttpResponseMessage responseMessage = client.Get(url);
         if (responseMessage.IsSuccessStatusCode)
         {
             var responseData =   responseMessage.Content.ReadAsStringAsync().Result;
             var jsonResponse = JsonConvert.DeserializeObject<List<string>>(responseData);
             return View(jsonResponse);
         }
         return View("Error");
     }
}

我沒有在這里使用異步,但你可以做到。 並且您還需要在運行時啟動您的兩個項目。 右鍵單擊解決方案並單擊Set Start Up projects然后您可以選擇多個項目並將操作設置為Start

public class MVCAccountController : Controller
{
     HttpClient client;

     // web api Url
     string url = string.Format("http://localhost:60143/");
     //string bearerToken = string.Format("bearer token from web api");
     public MVCValuesController()
     {
        client = new HttpClient(); 
        client.BaseAddress = new Uri(url);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
         // just adding a JObject you can create a class 

         JObject tokenJobject = new JObject(
                                        new JProperty("Email", "someone@example.com"),
                                        new JProperty("Password", "Pass123"));
                                        new JProperty("ConfirmPassword", "Pass123"));
            HttpContent baseContent = new StringContent(tokenJobject.ToString(), Encoding.UTF8, "application/json");
        //client.DefaultRequestHeaders.Accept.Add("Authorization", "Bearer " + bearerToken);


     }

     public async Task<ActionResult> GetValues()
     {
         string requestUri = string.Format("api/Account/Register");
         HttpResponseMessage responseMessage = await client.PostAsync(requestUri, baseContent);
         if (responseMessage.IsSuccessStatusCode)
         {
             var responseData =   responseMessage.Content.ReadAsStringAsync();
             var jsonResponse = JsonConvert.DeserializeObject<string>(responseData);
             return View(jsonResponse);
         }
         return View("Error");
     }
}
 public class MVCValuesController : Controller 
 {
       HttpClient client;

       // web api Url
       string url = string.Format("http://localhost:60143/api/Values");
       string bearerToken = string.Format("bearer token from web api");

       public MVCValuesController()
       {
          client = new HttpClient(); 
          client.BaseAddress = new Uri(url);
          client.DefaultRequestHeaders.Accept.Clear();
          client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
          client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
       }

       public ActionResult GetValues()
       {
          HttpResponseMessage responseMessage = client.Get(url);
          if (responseMessage.IsSuccessStatusCode)
          {
              var responseData =   responseMessage.Content.ReadAsStringAsync().Result;
              var jsonResponse = JsonConvert.DeserializeObject<List<string>>(responseData);
              return View(jsonResponse);
          }
          return View("Error");
       }
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM