【问题标题】:How to secure wcf rest services based on OAuth如何基于 OAuth 保护 wcf REST 服务
【发布时间】:2016-07-04 14:34:18
【问题描述】:

我需要保护基于 OAuth 的 wcf 服务。在这种情况下,Java 应用程序向我传递了一个令牌,我需要基于 .Net 层中的 Oauth 进行验证,如果令牌通过,则需要调用 wcf 服务。

我已经检查了几个基于 OAuth 的示例,但没有任何想法来实现这一点。请帮助我如何基于 .net 中的 OAuth 实现这一目标。

【问题讨论】:

    标签: c# rest wcf oauth


    【解决方案1】:

    最后我通过下面的实现解决了这个问题

    var authHeader = WebOperationContext.Current.IncomingRequest.Headers.GetValues("Authorization");
                    if (authHeader == null || authHeader.Length == 0)
                    {
                        throw new WebFaultException(HttpStatusCode.Unauthorized);
                    }
                    NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty);
    
                    var parts = authHeader[0].Split(' ');
                    if (parts[0] == "Bearer")
                    {
                        string token = parts[1];
    
                        outgoingQueryString.Add("token", token);
                        byte[] postdata = Encoding.ASCII.GetBytes(outgoingQueryString.ToString());
    
                        var result = string.Empty;
                        var httpWebRequest = (HttpWebRequest)WebRequest.Create(oauthConfiguration.Setting.CheckUrl);
                        httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                        httpWebRequest.Method = "POST";
                        httpWebRequest.Headers.Add("Authorization", GetAuthorizationHeader(oauthConfiguration.Setting.ClientId, oauthConfiguration.Setting.ClientSecret));
                        httpWebRequest.ContentLength = postdata.Length;
                        using (Stream postStream = httpWebRequest.GetRequestStream())
                        {
                            postStream.Write(postdata, 0, postdata.Length);
                            postStream.Flush();
                            postStream.Close();
                        }
    
                        var response = (HttpWebResponse)httpWebRequest.GetResponse();
                        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-19
      • 2015-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      相关资源
      最近更新 更多