首页 文章

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

提问于
浏览
2

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

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

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

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

Step 2:

更改了webconfig文件以指向我的本地数据库并运行应用程序,我能够使用我的gmail帐户成功登录google并将用户详细信息成功添加到数据库中的ASPUSerTables

Step 3:

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

Step 4 所以我想,我应该创建WEB API项目,而不是WEB应用程序(步骤1),它将如下所示返回 Startup.cs 中的auth令牌并将该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项目正确地对所有请求进行身份验证 . 请告诉我正确的道路 . 谢谢

2 回答

  • 2

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

    • 使用 Individual User Accounts 身份验证创建Web API项目 .

    • 现在,您将准备好使用API for Register,更改密码以及API endpoints 为用户生成令牌 .

    • 创建另一个项目,但这次是 MVCNo Authentication 在同一解决方案中 .

    这将是我们的架构

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

    }`

相关问题