简体   繁体   English

如何基于OAuth保护WCF Rest服务

[英]How to secure wcf rest services based on OAuth

I need to secure wcf services based on OAuth. 我需要保护基于OAuth的WCF服务。 In this case Java application is passing me a token which i need to validate based on Oauth in .Net layer and if token is passed then need to call wcf services. 在这种情况下,Java应用程序向我传递了一个令牌,我需要基于.Net层中的Oauth进行验证,如果传递了令牌,则需要调用wcf服务。

I have checked several examples based on OAuth but not got any idea to achieve this . 我已经检查了几个基于OAuth的示例,但不知道要实现这一目标。 Please help me how to achieve this based on OAuth in .net. 请帮助我如何基于.net中的OAuth实现此目标。

Finally i solved this by below implementation 最后我通过以下实现解决了这个问题

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM