【问题标题】:How to get data from Web.API to a Windows application when the desired Controller requires user authorization?当所需的控制器需要用户授权时,如何从 Web.API 获取数据到 Windows 应用程序?
【发布时间】:2015-02-03 20:25:13
【问题描述】:

有很多关于通过 Windows 应用程序从 Web.Api 获取数据的示例,但我所看到的都是使用不需要用户身份验证的控件。 在我的情况下,我需要从 Windows 应用程序获取数据,但我需要调用的 Web.Api 方法是需要用户认证的控制器方法(控制器由[Authorize] 属性修饰)。

我在这里找到了一个关于获取数据的简单示例:http://www.asp.net/web-api/overview/mobile-clients/calling-web-api-from-a-windows-phone-8-application

但那里没有关于用户的信息:

  public void LoadData()
        {
            if (this.IsDataLoaded == false)
            {
                this.Items.Clear();
                this.Items.Add(new ItemViewModel() { ID = "0", LineOne = "Please Wait...", LineTwo = "Please wait while the catalog is downloaded from the server.", LineThree = null });
                WebClient webClient = new WebClient();
                webClient.Headers["Accept"] = "application/json";
                webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadCatalogCompleted);
                webClient.DownloadStringAsync(new Uri(apiUrl));
            }
        }

        private void webClient_DownloadCatalogCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                this.Items.Clear();
                if (e.Result != null)
                {
                    var books = JsonConvert.DeserializeObject<BookDetails[]>(e.Result);
                    int id = 0;
                    foreach (BookDetails book in books)
                    {
                        this.Items.Add(new ItemViewModel()
                        {
                            ID = (id++).ToString(),
                            LineOne = book.Title,
                            LineTwo = book.Author,
                            LineThree = book.Description.Replace("\n", " ")
                        });
                    }
                    this.IsDataLoaded = true;
                }
            }
            catch (Exception ex)
            {
                this.Items.Add(new ItemViewModel()
                {
                    ID = "0",
                    LineOne = "An Error Occurred",
                    LineTwo = String.Format("The following exception occured: {0}", ex.Message),
                    LineThree = String.Format("Additional inner exception information: {0}", ex.InnerException.Message)
                });
            }
        }

如何完成LoadData方法,以便通过谷歌认证后得到结果? (微软?)

【问题讨论】:

    标签: c# oauth-2.0


    【解决方案1】:

    如果我理解正确:因为您需要授权您的请求。在您的应用程序(WebAPI)中创建一个名为“Attributes”的文件夹,添加一个函数来检查您的参数是否正确。例如:

    public class AuthWebsiteAttribute : System.Web.Http.AuthorizeAttribute
    {       
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            var auth = actionContext.Request.Headers.Authorization;
    
            if (auth == null)
                return false;
    
            var param = auth.Parameter;
    
            if (String.IsNullOrEmpty(param))
                return false;
    
            // now check if the parameter is correct, for example ask your database if the // user email exists or something
    
            return company != null;
        }
    }
    

    没有你的属性被命名为“AuthWebsite”并且你在你的控制器中使用它。例如:

      [AuthWebsite, RoutePrefix("api/basket")]
    public class SomeController : ApiController
    {
    /// if you are here then you are already authenticated
    }
    

    但是您如何进行身份验证?很简单,您需要在请求中添加一个参数:“授权:”。我正在使用 base64 编码,所以这就是它在提琴手中的样子:

     Authorization: Basic MOdzIEFyWm==
    

    这些字符是我的密码和我的用户名。

    【讨论】:

    • 如果我错了请纠正我,但您的授权规范是在 IIS 上提供给特定站点的基础授权策略。但我要求的是通过第三方身份验证提供的身份验证,如谷歌、微软、Facebook 等。
    猜你喜欢
    • 2020-10-25
    • 2019-09-09
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-09
    • 1970-01-01
    相关资源
    最近更新 更多