首页 文章

如何登录并将令牌传递给WebAPI2

提问于
浏览
1

我将WebApi2添加到我的MVC应用程序中,我可以通过浏览器成功调用我的API . 如果用户未经过身份验证,则会显示我的标准登录屏幕然后运行 .

但我真的想把api称为来自移动应用程序的REST api . 我将以下代码添加到搜索时找到的启动中 . 但我不知道如何通过网址实际登录,或者在我的通话中传递和使用令牌 .

我试过例如myurl / api / Account / ExternalLogin,但是我得到了无效的请求 .

PublicClientId = "self";
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            // Note: Remove the following line before you deploy to production:
            AllowInsecureHttp = true
        };

所以问题是,如何实际使用REST api调用,或者我是否需要在控制器中添加其他代码 .

1 回答

  • 1

    将API配置为使用OAuth后,您可以使用以下代码获取访问令牌

    /// <summary>
            /// This method uses the OAuth Client Credentials Flow to get an Access Token to provide
            /// Authorization to the APIs.
            /// </summary>
            /// <returns></returns>
            private static async Task<string> GetAccessToken()
            {
                if (accessToken == null)
                using (var client = new HttpClient())
                {
                    var email = "xyz"
                    var password = "abc";
                    var clientId = "123"
                    var clientSecret = "456";
    
                    client.BaseAddress = new Uri(baseUrl);
    
                    // We want the response to be JSON.
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                    // Build up the data to POST.
                    List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>();
    
                    postData.Add(new KeyValuePair<string, string>("grant_type",    "password"));
                    postData.Add(new KeyValuePair<string, string>("client_id",     clientId));
                    postData.Add(new KeyValuePair<string, string>("client_secret", clientSecret));
                    postData.Add(new KeyValuePair<string, string>("username",      email));
                    postData.Add(new KeyValuePair<string, string>("password",      password));
    
                    FormUrlEncodedContent content = new FormUrlEncodedContent(postData);
    
                    // Post to the Server and parse the response.
                    HttpResponseMessage response = await client.PostAsync("Token", content);
                    string jsonString            = await response.Content.ReadAsStringAsync();
                    object responseData          = JsonConvert.DeserializeObject(jsonString);
    
                    // return the Access Token.
                    accessToken = ((dynamic)responseData).access_token;
                }
    
                return accessToken;
            }
    

    一旦有了访问令牌,就可以使用类似下面的内容将访问令牌传递给API调用

    using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri(baseUrl);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                    // Add the Authorization header with the AccessToken.
                    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken); // accessToken is returned from GetAccessToken function
    
                    // create the URL string.
                    string url = string.Format("API url goes here");
    
                    // make the request
                    HttpResponseMessage response = await client.GetAsync(url);
    
                    // parse the response and return the data.
                    string jsonString = await response.Content.ReadAsStringAsync();
                    object responseData = JsonConvert.DeserializeObject(jsonString);
                    return (dynamic)responseData;
                }
    

相关问题