2017-03-23 124 views
1

我已經創建了一個允許進行外部身份驗證/註冊的MVC應用程序。它創建了所有必要的組件(Owin,EF,Regiter,Login,Logout),並且我能夠執行應用程序中的所有基本活動。WEB API - 使用不記名令牌進行身份驗證

現在,我想要將Web應用程序與將由我的移動應用程序使用的WEB API集成。我卡在web api調用中的身份驗證(使用從Web應用程序收到的不記名令牌)。

我看到了一些示例,可以在啓用OWIN中間件的情況下創建WEB API項目。但我不知道如何集中外部身份驗證過程,並使用令牌爲我的Web應用程序和移動應用程序 和我不想去角度或單頁應用程序。 任何人都可以建議我正確的技術路徑來解決這個問題。 謝謝。

第1步:

我創建在Visual Studio 2015年個人登錄一個MVC項目啓用。並配置了我在Google開發人員控制檯中配置所有內容的按鍵。我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帳戶和用戶詳細信息添加到ASPUSerTables在DB成功

第3步:

現在我想創建一個WEB API項目,該項目將連接到數據庫並將一些數據返回到MVC Web應用程序和移動應用程序(我在此處停留在身份驗證部分)。我需要使用第三方認證來我的移動應用程序太(Xamarin),並使用共同的API從我的移動應用程序和MVC網站

步驟4 所以我想取而代之的Web應用程序(步驟1),我應創建瞭如下所示的WEB API項目,以返回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 
     }; 

我不想去與棱角分明,我需要我的WebApplication(MVC)和Web API項目的正常進行身份驗證的所有請求。請告訴我 正確的道路。 感謝

+0

你在哪裏卡住與不記名令牌認證?什麼是你得到的錯誤將有助於回答你的問題。我已經完成了移動和Web使用相同的API沒有任何問題的項目。 –

+0

嗨Jawand。感謝您的即時回覆。在我的MVC項目中,我可以從我的AccountController中獲取谷歌的用戶聲明,並能夠在ASPUsers表中註冊詳細信息。我創建了獨立的web api項目,沒有owin組件(是否正確),需要從web應用程序授權。我不知道如何獲取Web應用程序Cookie中的訪問令牌並授權REST調用。請指導我創建簡單的MVC客戶端應用程序(而非angular)和web api項目的步驟,以支持Web和移動應用程序中的外部身份驗證。 – DevExpress

+0

@DevOne你可以在問題中添加一些代碼嗎? –

回答

2

你需要做的是請按照下列步驟

  • 創建個人用戶在Web API項目的賬目認證。
  • 現在,您將可以使用API​​的Register for Register,更改密碼以及API端點爲用戶生成令牌。
  • 創建另一個項目,但這次是MVC沒有驗證在相同的解決方案。

嗯,這將是我們的架構

enter image description here

這是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", "[email protected]"), 
             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"); 
    } 
} 
+0

嗨Jawand。感謝您的回答。我也想過這個解決方案,但我想要使用OWIN的所有默認功能,例如註冊,忘記密碼,重置密碼,外部認證重定向等。我是否仍然可以使用MVC應用程序中的所有API功能 - 無需身份驗證應用程序沒有任何麻煩? 。 – DevExpress

+1

是的,你將可以使用它沒有任何問題。我會添加更多的代碼來回答。 –

+0

@DevOne看看我已經使用了一個名爲'Register'的web api的方法,並用它來註冊一個新用戶。讓我知道如果你需要更多的幫助 –

相關問題