WEB API - 使用承载令牌进行身份验证

时间:2017-03-23 18:50:25

标签: asp.net-mvc authentication oauth-2.0 asp.net-web-api2 owin

我创建了一个允许外部认证/注册的MVC应用程序。它创建了所有必要的组件(Owin,EF,Regiter,Login,Logout),我能够在应用程序中执行所有基本活动。

现在,我想将Web应用程序与我的移动应用程序将使用的WEB API集成。我坚持使用web api调用中的身份验证(使用从Web应用程序收到的持有者令牌)。

我看到了创建启用了OWIN中间件的WEB API项目的示例。但我不知道如何集中外部身份验证过程并将令牌用于我的Web应用程序和移动应用程序 并且我不想参加ANGULAR 或单页应用。 任何人都可以建议我正确的技术路径来解决这个问题。 谢谢。

第1步:

我在visual studio 2015中创建了一个MVC项目,启用了Individual Login。并配置了我在谷歌开发者控制台中配置所有内容的密钥。我的 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

第3步:

现在我想创建一个WEB API项目,它将连接到数据库,并将一些数据转发到MVC Web应用程序和移动应用程序(我在这里停留在身份验证部分)。我也需要对我的移动应用程序使用第三方身份验证(Xamarin)并使用我的移动应用程序和MVC网站上的通用API

第4步 所以我想,我应该创建WEB API项目,如下所示,在 Startup.cs 中返回auth令牌,并将该cookie存储在网站中以通过,而不是WEB应用程序(步骤1)。在随后的请求中。

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项目对所有请求进行正确的身份验证。请告诉我 正确的道路。 感谢

2 个答案:

答案 0 :(得分:3)

您需要执行的操作是按照以下步骤操作

  • 使用个人用户帐户身份验证创建Web API项目。
  • 现在,您已准备好使用API​​ 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", "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");
     }
}

答案 1 :(得分:0)

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