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;
      }
    }
Example #2
0
        public object Get(OAuthAccessTokenRequest request)
        {
            // keep this line to inspect the Request in monodevelop's debugger
            // really helps debugging API calls
            var servicestack_http_request = this.Request;

            // TODO the OAuth spec allows other ways of specifying the parameters besides the query string
            // (i.e. the authorization header, form-encoded POST values, etc. We have to handle those
            // in the future
            var original_request = ((HttpListenerRequest)Request.OriginalRequest).ToWebRequest ();

            try {
                var context = new OAuthContextBuilder ()
                    .FromWebRequest (original_request, new MemoryStream ());
                AccessToken access_token = (AccessToken) RainyStandaloneServer.OAuth.Provider.ExchangeRequestTokenForAccessToken (context);

                Logger.DebugFormat ("permanently authorizing access token: {0}", access_token);
                RainyStandaloneServer.OAuth.AccessTokens.SaveToken (access_token);
                Response.Write (access_token.ToString ());
                Response.End ();
            } catch (Exception e) {
                throw new UnauthorizedException (){ ErrorMessage = "failed to exchange request token for access token: {0}".Fmt(e.Message)};
            }
            return null;
        }
    protected void Page_Load(object sender, EventArgs e)
    {
      var context = new OAuthContextBuilder().FromHttpRequest(Request);

      IOAuthProvider provider = OAuthServicesLocator.Services.Provider;

      var tokenRepository = OAuthServicesLocator.Services.AccessTokenRepository;

      try
      {
        provider.AccessProtectedResourceRequest(context);

        var accessToken = tokenRepository.GetToken(context.Token);

        string userName = accessToken.UserName;

        XDocument contactsDocument = GetContactsForUser(userName);

        Response.ContentType = "text/xml";
        Response.Write(contactsDocument);
        Response.End();
      }
      catch (OAuthException authEx)
      {
        // fairly naieve approach to status codes, generally you would want to examine eiter the inner exception of the 
        // problem report to determine an appropriate status code for your technology / architecture.

        Response.StatusCode = 403;
        Response.Write(authEx.Report);
        Response.End();
      }
    }
		public void ValidateWithTrailingAmpersand_ForUri()
		{
			Uri 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.True(signer.ValidateSignature(context, signingContext));
		}
    protected void Page_Load(object sender, EventArgs e)
    {
      IOAuthContext context = new OAuthContextBuilder().FromHttpRequest(Request);

      IOAuthProvider provider = OAuthServicesLocator.Provider;

      IToken token = provider.GrantRequestToken(context);

      Response.Write(token);
      Response.End();
    }
    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));
    }
    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();
    }
        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);
            }
        }
Example #9
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++;
        }
    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();
    }
        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;
            }
        }
Example #12
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;
        }
Example #13
0
        public object Any(OAuthAuthorizeRequest request)
        {
            // keep this line to inspect the Request in monodevelop's debugger
            // really helps debugging API calls
            var servicestack_http_request = Request;

            // TODO the OAuth spec allows other ways of specifying the parameters besides the query string
            // (i.e. the authorization header, form-encoded POST values, etc. We have to handle those
            // in the future.
            var original_request = (HttpListenerRequest)Request.OriginalRequest;
            var context = new OAuthContextBuilder ().FromUri (Request.HttpMethod, original_request.Url);

            // check if the user is authorized
            // TODO this is just a basic hack to enable authorization
            if (!userIsAllowed (request.Username, request.Password)) {
                // unauthorized
                Logger.WarnFormat ("Failed to authorize user {0}", request.Username);
                Response.StatusCode = 403;
                Response.StatusDescription ="Authorization failed";
                Response.Write (
                    "<html><h1 style='margin-top: 1em'>Authorization failed for user "
                    + "<b>" + request.Username + "</b>"
                    + " (maybe wrong password?).</h1></html>"
                );
                Response.Close ();
                return null;
            }
            // authorization succeeded, continue
            Logger.InfoFormat ("Successfully authorized user: {0}", request.Username);

            var request_token = Rainy.RainyStandaloneServer.OAuth.RequestTokens.GetToken (context.Token);
            request_token.Verifier = Guid.NewGuid ().ToString ();
            request_token.AccessDenied = false;

            request_token.AccessToken = new AccessToken () {
                ConsumerKey = request_token.ConsumerKey,
                Realm = request_token.Realm,
                Token = Guid.NewGuid ().ToString (),
                TokenSecret = Guid.NewGuid ().ToString (),
                UserName = request.Username,
                ExpiryDate = DateTime.Now.AddYears (99)
            };

            RainyStandaloneServer.OAuth.RequestTokens.SaveToken (request_token);
            Logger.DebugFormat ("created an access token for user {0}: {1}", request.Username, request_token);

            // redirect to the provded callback
            var redirect_url = request_token.CallbackUrl + "?oauth_verifier=" + request_token.Verifier + "&oauth_token=" + request_token.Token;
            Logger.DebugFormat ("redirecting user to consumer at: {1}", request.Username, redirect_url);
            Response.Redirect (redirect_url);
            return null;
        }
Example #14
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;
        }
Example #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++;
        }
        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 );
        }
Example #17
0
        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);
            }
        }
Example #18
0
        public object Any(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 ();

            try {
                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 ());
            } catch (Exception e) {
                Logger.ErrorFormat ("Caught exception: {0}", e.Message);
                Response.StatusCode = 500;
                Response.StatusDescription = e.Message;
            } finally {
                Response.Close ();
            }
            return null;
        }