Web API – 使用不记名令牌进行身份验证

Web API – authenticate with bearer token

我创建了一个 MVC 应用程序以允许外部 authentication/registration。它是用所有必要的组件(Owin、EF、注册、登录、注销)创建的,我能够在应用程序中执行所有基本活动。

现在,我想将 Web 应用程序与我的移动应用程序也将使用的 Web API 集成。我卡在 Web API 调用中的身份验证(使用我从 Web 应用程序收到的不记名令牌)。

我看到了创建启用了 OWIN 中间件的 WEB API 项目的示例。但我不知道如何集中外部身份验证过程并将令牌用于我的网络应用程序和移动应用程序 我不想使用 ANGULAR 或单页应用程序。 谁能建议我解决此问题的正确技术途径。 谢谢。

第 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 帐户通过 google 成功登录,并且用户详细信息已成功添加到数据库中的 ASPUSerTables

第 3 步:

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

中的通用 API

步骤 4 所以我想,而不是 WEB 应用程序(第 1 步),我应该创建 WEB API 项目,它看起来像下面 return 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");
     }
}

我这里没有用async,不过你可以用。当你 运行 它时,你还需要启动你的两个项目。右键单击解决方案并单击 Set Start Up projects 然后您可以 select 多个项目并将操作设置为 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");
       }
 }