Exemple #1
0
        public void ValidateWithTrailingAmpersand_ForUrl()
        {
            string url =
                "http://demo.devdefined.com/OpenSocial/HelloWorld.aspx?oauth_nonce=c39f4e3e6c309988763eb8af85fcb74b&oauth_timestamp=1221992254&oauth_consumer_key=friendster.com&synd=friendster&container=default&opensocial_owner_id=82474146&opensocial_viewer_id=82474146&opensocial_app_id=52ae97f7aa8a7e7565dd40a4e00eb0f5&oauth_token=&xoauth_signature_publickey=http%3A%2F%2Fwww.fmodules.com%2Fpublic080813.crt&oauth_signature_method=RSA-SHA1&oauth_signature=PLOkRKwLLeJRZz18PsAVQgL5y9Rdf0AW5eicdT0xwauRe3bE2NTDFHoMsUtO6UMHEY0v9GRcKbvkgEWEGGtiGA%3D%3D&";

            IOAuthContext context        = new OAuthContextBuilder().FromUrl("GET", url);
            var           signer         = new OAuthContextSigner();
            var           signingContext = new SigningContext {
                Algorithm = FriendsterCertificate.PublicKey.Key
            };

            Assert.True(signer.ValidateSignature(context, signingContext));
        }
Exemple #2
0
        public void RequestFilter(IHttpRequest request, IHttpResponse response, object requestDto)
        {
            string Username = "";

            if (requestDto is UserRequest)
            {
                Username = ((UserRequest)requestDto).Username;
            }
            else if (requestDto is GetNotesRequest)
            {
                Username = ((GetNotesRequest)requestDto).Username;
            }
            else if (requestDto is PutNotesRequest)
            {
                Username = ((PutNotesRequest)requestDto).Username;
            }
            else
            {
                response.ReturnAuthRequired();
                return;
            }

            var           web_request = ((HttpListenerRequest)request.OriginalRequest).ToWebRequest();
            IOAuthContext context     = new OAuthContextBuilder().FromWebRequest(web_request, new MemoryStream());

            try {
                Logger.Debug("trying to acquire authorization");
                RainyStandaloneServer.OAuth.Provider.AccessProtectedResourceRequest(context);
            } catch {
                Logger.DebugFormat("failed to obtain authorization, oauth context is: {0}", context.Dump());
                response.ReturnAuthRequired();
            }

            // check if the access token matches the username
            var access_token = Rainy.RainyStandaloneServer.OAuth.AccessTokens.GetToken(context.Token);

            if (access_token.UserName != Username)
            {
                // forbidden
                Logger.Debug("username does not match the one in the access token, denying");
                response.ReturnAuthRequired();
                return;
            }
            Logger.DebugFormat("authorization granted for user {0}", Username);

            // possible race condition but locking is to expensive
            // at this point, rather accept non-precise values
            MainClass.ServedRequests++;
        }
Exemple #3
0
        private bool IsOAuthValid(string secret)
        {
            try {
                var context = new OAuthContextBuilder().FromHttpRequest(Request);

                IOAuthContextSigner signer = new OAuthContextSigner();

                SigningContext signingContext = new SigningContext {
                    ConsumerSecret = secret
                };

                return(signer.ValidateSignature(context, signingContext));
            } catch (OAuthException) {
                return(false);
            }
        }
        private void ValidateSignature()
        {
            if (!signedFetch)
            {
                return;
            }

            IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;

            IOAuthContext context = new OAuthContextBuilder().FromUri(request.Method, request.UriTemplateMatch.RequestUri);

            // use context.ConsumerKey to fetch information required for signature validation for this consumer.
            if (!signer.ValidateSignature(context, signingContext))
            {
                throw new Exception("Invalid signature : " + request.UriTemplateMatch.RequestUri);
            }
        }
        private bool IsOAuthSignatureValid()
        {
            string oauthKey = System.Configuration.ConfigurationManager.AppSettings["OauthKey"];
            // Normally would use key to lookup appropriate secret for the specifc LMS

            string oauthSecret = System.Configuration.ConfigurationManager.AppSettings["OauthSecret"];

            var context = new OAuthContextBuilder().FromHttpRequest(Request);

            IOAuthContextSigner signer = new OAuthContextSigner();

            SigningContext signingContext = new SigningContext {
                ConsumerSecret = oauthSecret
            };

            return(signer.ValidateSignature(context, signingContext));
        }
Exemple #6
0
        public object Get(OAuthRequestTokenRequest request)
        {
            // keep this line to inspect the Request in monodevelop's debugger
            // really helps debugging API calls
            var servicestack_http_request = Request;

            HttpWebRequest original_request = ((HttpListenerRequest)Request.OriginalRequest).ToWebRequest();

            IOAuthContext context = new OAuthContextBuilder().FromWebRequest(original_request, request.RequestStream);
            IToken        token   = RainyStandaloneServer.OAuth.Provider.GrantRequestToken(context);

            Logger.DebugFormat("granting request token {0} to consumer", token);
            Response.StatusCode = 200;
            Response.Write(token.ToString());
            Response.End();

            return(null);
        }
Exemple #7
0
        public object Get(OAuthRequestTokenRequest request)
        {
            HttpWebRequest original_request = ((HttpListenerRequest)Request.OriginalRequest).ToWebRequest();

            // it is not fatal that we do not really check the oauth signature for the request token request
            // all it takes to sign such a request is the consumer secret, which is "anyone" and hard-coded
            // into the tomboy and rainy source code - and we are open source so everybody knows it anyways
            IOAuthContext context;

            context = new OAuthContextBuilder().FromWebRequest(original_request, request.RequestStream);

            IToken token = oauthHandler.Provider.GrantRequestToken(context);

            Logger.DebugFormat("granting request token {0} to consumer", token);
            Response.StatusCode = 200;
            Response.Write(token.ToString());
            Response.End();

            return(null);
        }
Exemple #8
0
 public virtual void OnAuthorization(AuthorizationContext filterContext)
 {
     if (OAuthContextBuilder == null)
     {
         throw new NullReferenceException("OAuthContextBuilder wasn't set in the Authorisation filter, please use an IOC container to do this");
     }
     if (OAuthProvider == null)
     {
         throw new NullReferenceException("OAuthProvider wasn't set in the Authorisation filter, please use an IOC container to do this");
     }
     try
     {
         var context = OAuthContextBuilder.FromHttpRequest(filterContext.HttpContext.Request);
         OAuthProvider.AccessProtectedResourceRequest(context);
     }
     catch (OAuthException ex)
     {
         filterContext.Result = new OAuthExceptionResult(ex);
     }
 }
    protected void Page_Load(object sender, EventArgs e)
    {
      try
      {
        IOAuthContext context = new OAuthContextBuilder().FromHttpRequest(Request);

        IOAuthProvider provider = OAuthServicesLocator.Services.Provider;

        IToken token = provider.GrantRequestToken(context);

        Response.Write(token);        
      }
      catch (OAuthException ex)
      {
        Response.StatusCode = 400;
        Response.Write(ex.Report.ToString());        
      }

      Response.End();
    }
Exemple #10
0
        public void ValidateWithTrailingAmpersand()
        {
            // As reported in issue here:  http://code.google.com/p/devdefined-tools/issues/detail?id=1
            // validating OAuth requests from Friendster was failing - turns out to be OpenSocial platforms
            // incorrectly placing a "&" on the end of their query parameters, which was tripping up
            // query parameters collection - there is now a fix in the context builder to remove the problematic
            // character when parsing requests/Uri's.

            var uri =
                new Uri(
                    "http://demo.devdefined.com/OpenSocial/HelloWorld.aspx?oauth_nonce=c39f4e3e6c309988763eb8af85fcb74b&oauth_timestamp=1221992254&oauth_consumer_key=friendster.com&synd=friendster&container=default&opensocial_owner_id=82474146&opensocial_viewer_id=82474146&opensocial_app_id=52ae97f7aa8a7e7565dd40a4e00eb0f5&oauth_token=&xoauth_signature_publickey=http%3A%2F%2Fwww.fmodules.com%2Fpublic080813.crt&oauth_signature_method=RSA-SHA1&oauth_signature=PLOkRKwLLeJRZz18PsAVQgL5y9Rdf0AW5eicdT0xwauRe3bE2NTDFHoMsUtO6UMHEY0v9GRcKbvkgEWEGGtiGA%3D%3D&");

            IOAuthContext context        = new OAuthContextBuilder().FromUri("GET", uri);
            var           signer         = new OAuthContextSigner();
            var           signingContext = new SigningContext {
                Algorithm = FriendsterCertificate.PublicKey.Key
            };

            Assert.IsTrue(signer.ValidateSignature(context, signingContext));
        }
        void ValidateWithDevDefinedOAuth()
        {
            try
            {
                var context        = new OAuthContextBuilder().FromHttpRequest(Request);
                var signer         = new OAuthContextSigner();
                var signingContext = new SigningContext {
                    Algorithm = OpenSocialCertificates.FriendsterCertificate.PublicKey.Key
                };

                if (!signer.ValidateSignature(context, signingContext))
                {
                    throw new OAuthException(context, OAuthProblems.SignatureInvalid, "check certificate is still valid");
                }
            }
            catch (OAuthException authEx)
            {
                Response.Clear();
                Response.Write(authEx.Report.ToString());
                Response.End();
            }
        }
Exemple #12
0
        public void TestOAuth()
        {
            X509Certificate2    cert           = new X509Certificate2(ConfigurationSettings.AppSettings["OAuthCert"]);
            AsymmetricAlgorithm provider       = cert.PublicKey.Key;
            OAuthContextSigner  signer         = new OAuthContextSigner();
            SigningContext      signingContext = new SigningContext();

            //signingContext.ConsumerSecret = ...; // if there is a consumer secret
            signingContext.Algorithm = provider;

            Uri uri = new Uri(
                "http://dev-profiles.campus.net.ucsf.edu/chatter/ChatterProxyService.svc/user/5138614/unfollow/4621800?accessToken=00DZ0000000jhLQ!ARIAQAlqX_qtYj95uzEftkMIKQggfo.RoJ3KnvvakO97Xrjptfq89vTtwGFgR1jnyeNSm1CwnLSSz0N3g8.bQrX.jCpJ6Np3&oauth_body_hash=2jmj7l5rSw0yVb/vlWAYkK/YBwk=&opensocial_owner_id=4621800&opensocial_viewer_id=5138614&opensocial_app_id=http://dev-profiles.ucsf.edu/ORNG/ChatterFollow.xml&opensocial_app_url=http://dev-profiles.ucsf.edu/ORNG/ChatterFollow.xml&oauth_consumer_key=&xoauth_signature_publickey=mytestkey&xoauth_public_key=mytestkey&oauth_version=1.0&oauth_timestamp=1349466703&oauth_nonce=7533897618501371565&oauth_consumer_key=&oauth_signature_method=RSA-SHA1&oauth_signature=d0UIIXK+HwbkLD4VE59ylZ9XoBreMBqc0Kcf4v2DjzWT0AE1JtCUhDmS1Uy1P9K54tpeoQwjcu8mnWsA7PQpTRTYyU1k+ueT4M2ihoaB+CunpZz6Q3KE8MUZn4Sy0D7iNuje6WdgHZ80f9Ln8OwRPzrfHA5v0KowATRv7T2h+x0="
                );

            IOAuthContext context = new OAuthContextBuilder().FromUri("GET", uri);

            // use context.ConsumerKey to fetch information required for signature validation for this consumer.
            if (!signer.ValidateSignature(context, signingContext))
            {
                throw new Exception("Invalid signature : " + uri);
            }
        }
Exemple #13
0
    protected void Page_Load(object sender, EventArgs e)
    {
      try
      {
        IOAuthContext context = new OAuthContextBuilder().FromHttpRequest(Request);

        IOAuthProvider provider = OAuthServicesLocator.Services.Provider;

        IToken accessToken = provider.ExchangeRequestTokenForAccessToken(context);

        Response.Write(accessToken);
      }
      catch (OAuthException ex)
      {
        // fairly naieve approach to status codes, generally you would want to examine either the inner exception or the 
        // problem report to determine an appropriate status code for your technology / architecture.

        Response.StatusCode = 400;
        Response.Write(ex.Report.ToString());
      }

      Response.End();
    }
        public override void ProcessRequest(ref RequestContext requestContext)
        {
            if (requestContext == null || requestContext.RequestMessage == null)
            {
                return;
            }

            Message request = requestContext.RequestMessage;

            var requestProperty = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];

            IOAuthContext context = new OAuthContextBuilder().FromUri(requestProperty.Method, request.Headers.To);

            try
            {
                _provider.AccessProtectedResourceRequest(context);

                AccessToken accessToken = _repository.GetToken(context.Token);

                TokenPrincipal principal = CreatePrincipalFromToken(accessToken);

                InitializeSecurityContext(request, principal);
            }
            catch (OAuthException authEx)
            {
                XElement response         = GetHtmlFormattedErrorReport(authEx);
                Message  reply            = Message.CreateMessage(MessageVersion.None, null, response);
                var      responseProperty = new HttpResponseMessageProperty {
                    StatusCode = HttpStatusCode.Forbidden, StatusDescription = authEx.Report.ToString()
                };
                responseProperty.Headers[HttpResponseHeader.ContentType] = "text/html";
                reply.Properties[HttpResponseMessageProperty.Name]       = responseProperty;
                requestContext.Reply(reply);

                requestContext = null;
            }
        }
Exemple #15
0
        public void RequestFilter(IHttpRequest request, IHttpResponse response, object requestDto)
        {
            bool use_temp_access_token = request.Headers.AllKeys.Contains("AccessToken");
            bool check_oauth_signature = request.Headers.AllKeys.Contains("Authorization");

            string username = "";

            if (requestDto is UserRequest)
            {
                username = ((UserRequest)requestDto).Username;
            }
            else if (requestDto is GetNotesRequest)
            {
                username = ((GetNotesRequest)requestDto).Username;
            }
            else if (requestDto is GetSingleNoteRequest)
            {
                username = ((GetSingleNoteRequest)requestDto).Username;
            }
            else if (requestDto is PutNotesRequest)
            {
                username = ((PutNotesRequest)requestDto).Username;
            }
            else if (!check_oauth_signature && !use_temp_access_token)
            {
                throw new UnauthorizedException();
            }
            Logger.Debug("trying to acquire authorization");

            IOAuthContext context = null;
            AccessToken   access_token;

            try {
                var oauthHandler = EndpointHost.Container.Resolve <OAuthHandler> ();
                if (check_oauth_signature)
                {
                    var web_request = ((HttpListenerRequest)request.OriginalRequest).ToWebRequest();
                    context = new OAuthContextBuilder().FromWebRequest(web_request, new MemoryStream());
                    // HACK ServiceStack does not inject into custom attributes
                    oauthHandler.Provider.AccessProtectedResourceRequest(context);
                    // check if the access token matches the username given in an url
                    access_token = oauthHandler.AccessTokens.GetToken(context.Token);
                }
                else
                {
                    access_token = oauthHandler.AccessTokens.GetToken(request.Headers["AccessToken"]);
                }

                if (!string.IsNullOrEmpty(username) && access_token.UserName != username)
                {
                    // forbidden
                    Logger.Debug("username does not match the one in the access token, denying");
                    throw new UnauthorizedException();
                }
                else
                {
                    // TODO remove checks - why is it run twice?
                    if (!request.Items.Keys.Contains("AccessToken"))
                    {
                        if (use_temp_access_token)
                        {
                            request.Items.Add("AccessToken", request.Headers["AccessToken"]);
                        }
                        else
                        {
                            request.Items.Add("AccessToken", context.Token);
                        }
                    }
                    if (!request.Items.Keys.Contains("Username"))
                    {
                        request.Items.Add("Username", access_token.UserName);
                    }
                }
            } catch (Exception e) {
                if (context != null)
                {
                    Logger.DebugFormat("failed to obtain authorization, oauth context is: {0}", context.Dump());
                }
                throw new UnauthorizedException();
            }

            Logger.DebugFormat("authorization granted for user {0}", username);

            // possible race condition but locking is to expensive
            // at this point, rather accept non-precise values
            MainClass.ServedRequests++;
        }