/// <summary>
 /// Initialises a new instance of the <see cref="OAuthAuthoriseAttribute"/> class.
 /// </summary>
 public OAuthAuthoriseAttribute()
 {
     var consumers = DependencyResolver.Current.GetService<Database.IConsumers>();
     var issuedTokens = DependencyResolver.Current.GetService<Database.IIssuedTokens>();
     var nonces = DependencyResolver.Current.GetService<Database.INonces>();
     this.serviceProvider = new OAuthServiceProvider(consumers, issuedTokens, nonces);
 }
Example #2
0
        protected void yesButton_Click(object sender, EventArgs e)
        {
            this.outerMultiView.SetActiveView(this.authorizationGrantedView);

            var consumer       = OAuthServiceProvider.PendingAuthorizationConsumer;
            var tokenManager   = OAuthServiceProvider.ServiceProvider.TokenManager;
            var pendingRequest = OAuthServiceProvider.PendingAuthorizationRequest;
            ITokenContainingMessage requestTokenMessage = pendingRequest;
            var requestToken = tokenManager.GetRequestToken(requestTokenMessage.Token);

            OAuthServiceProvider.AuthorizePendingRequestToken();

            // The rest of this method only executes if we couldn't automatically
            // redirect to the consumer.
            if (pendingRequest.IsUnsafeRequest)
            {
                this.verifierMultiView.SetActiveView(this.noCallbackView);
            }
            else
            {
                this.verifierMultiView.SetActiveView(this.verificationCodeView);
                string verifier = ServiceProvider.CreateVerificationCode(consumer.VerificationCodeFormat, consumer.VerificationCodeLength);
                this.verificationCodeLabel.Text = HttpUtility.HtmlEncode(verifier);
                requestToken.VerificationCode   = verifier;
                tokenManager.UpdateToken(requestToken);
            }
        }
        private static bool hasValidSignature(OAuthMessage message, String appUrl, String appId)
        {
            String sharedSecret = sampleContainerSharedSecrets[appId];

            if (sharedSecret == null)
            {
                return(false);
            }

            OAuthServiceProvider provider = new OAuthServiceProvider(null, null, null);
            OAuthConsumer        consumer = new OAuthConsumer(null, appUrl, sharedSecret, provider);
            OAuthAccessor        accessor = new OAuthAccessor(consumer);

            SimpleOAuthValidator validator = new SimpleOAuthValidator();

            try
            {
                validator.validateMessage(message, accessor);
            }
            catch (OAuthException)
            {
                return(false);
            }
            catch (IOException)
            {
                return(false);
            }
            catch (UriFormatException)
            {
                return(false);
            }

            return(true);
        }
        /**
         * Lookup information contained in the gadget spec.
         */
        private OAuthServiceProvider lookupSpecInfo(ISecurityToken securityToken, OAuthArguments arguments,
                                                    AccessorInfoBuilder accessorBuilder, OAuthResponseParams responseParams)
        {
            GadgetSpec spec      = findSpec(securityToken, arguments, responseParams);
            OAuthSpec  oauthSpec = spec.getModulePrefs().getOAuthSpec();

            if (oauthSpec == null)
            {
                throw responseParams.oauthRequestException(OAuthError.BAD_OAUTH_CONFIGURATION,
                                                           "Failed to retrieve OAuth URLs, spec for gadget " +
                                                           securityToken.getAppUrl() + " does not contain OAuth element.");
            }
            OAuthService service = oauthSpec.getServices()[arguments.getServiceName()];

            if (service == null)
            {
                throw responseParams.oauthRequestException(OAuthError.BAD_OAUTH_CONFIGURATION,
                                                           "Failed to retrieve OAuth URLs, spec for gadget does not contain OAuth service " +
                                                           arguments.getServiceName() + ".  Known services: " +
                                                           String.Join(",", oauthSpec.getServices().Keys.AsEnumerable().ToArray()) + '.');
            }
            // In theory some one could specify different parameter locations for request token and
            // access token requests, but that's probably not useful.  We just use the request token
            // rules for everything.
            accessorBuilder.setParameterLocation(getStoreLocation(service.getRequestUrl().location, responseParams));
            accessorBuilder.setMethod(getStoreMethod(service.getRequestUrl().method, responseParams));
            OAuthServiceProvider provider = new OAuthServiceProvider(
                service.getRequestUrl().url.ToString(),
                service.getAuthorizationUrl().ToString(),
                service.getAccessUrl().url.ToString());

            return(provider);
        }
 /// <summary>
 /// Initialises a new instance of the <see cref="AuthenticationHttpModule"/> class.
 /// </summary>
 public AuthenticationHttpModule()
 {
     var consumers = DependencyResolver.Current.GetService<Database.IConsumers>();
     var issuedTokens = DependencyResolver.Current.GetService<Database.IIssuedTokens>();
     var nonces = DependencyResolver.Current.GetService<Database.INonces>();
     this.serviceProviderConfiguration = Configuration.OAuthSectionGroup.ServiceProvider;
     this.serviceProvider = new OAuthServiceProvider(consumers, issuedTokens, nonces);
 }
        public void AccessToken()
        {
            var oauthServiceProvider = new OAuthServiceProvider(consumers, issuedTokens, nonces);
            var serviceProvider = oauthServiceProvider.ServiceProvider;
            var requestMessage = serviceProvider.ReadAccessTokenRequest(this.Request);

            if (requestMessage != null)
            {
                var response = serviceProvider.PrepareAccessTokenMessage(requestMessage);
                serviceProvider.Channel.Send(response);
            }
            else
            {
                throw new InvalidOperationException();
            }
        }
        public ActionResult Authorise(LoginModel model, string returnUrl)
        {
            var users = new Code.Users();
            if (users.Exists(model.UserName))
            {
                // Authorise the request
                var oauthServiceProvider = new OAuthServiceProvider(consumers, issuedTokens, nonces);
                oauthServiceProvider.AuthorizePendingRequestToken(model.UserName.ToLower().Trim());
                this.HttpContext.Response.End();
                return new EmptyResult();
            }

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError(string.Empty, "The user name does not exist.");
            return View(model);
        }
        /**
         * Retrieve an AccessorInfo and OAuthAccessor that are ready for signing OAuthMessages.  To do
         * this, we need to figure out:
         *
         * - what consumer key/secret to use for signing.
         * - if an access token should be used for the request, and if so what it is.   *
         * - the OAuth request/authorization/access URLs.
         * - what HTTP method to use for request token and access token requests
         * - where the OAuth parameters are located.
         *
         * Note that most of that work gets skipped for signed fetch, we just look up the consumer key
         * and secret for that.  Signed fetch always sticks the parameters in the query string.
         */
        public AccessorInfo getOAuthAccessor(ISecurityToken securityToken,
                                             OAuthArguments arguments, OAuthClientState clientState, OAuthResponseParams responseParams)
        {
            AccessorInfoBuilder accessorBuilder = new AccessorInfoBuilder();

            // Does the gadget spec tell us any details about the service provider, like where to put the
            // OAuth parameters and what methods to use for their URLs?
            OAuthServiceProvider provider = null;

            if (arguments.mayUseToken())
            {
                provider = lookupSpecInfo(securityToken, arguments, accessorBuilder, responseParams);
            }
            else
            {
                // This is plain old signed fetch.
                accessorBuilder.setParameterLocation(AccessorInfo.OAuthParamLocation.URI_QUERY);
            }

            // What consumer key/secret should we use?
            OAuthStore.ConsumerInfo consumer;
            try
            {
                consumer = store.getConsumerKeyAndSecret(
                    securityToken, arguments.getServiceName(), provider);
                accessorBuilder.setConsumer(consumer);
            }
            catch (GadgetException e)
            {
                throw responseParams.oauthRequestException(OAuthError.UNKNOWN_PROBLEM,
                                                           "Unable to retrieve consumer key", e);
            }


            // Should we use the OAuth access token?  We never do this unless the client allows it, and
            // if owner == viewer.
            if (arguments.mayUseToken() &&
                securityToken.getOwnerId() != null &&
                securityToken.getViewerId().Equals(securityToken.getOwnerId()))
            {
                lookupToken(securityToken, consumer, arguments, clientState, accessorBuilder, responseParams);
            }

            return(accessorBuilder.create(responseParams));
        }
        public void Authorise()
        {
            var oauthServiceProvider = new OAuthServiceProvider(consumers, issuedTokens, nonces);
            var serviceProvider = oauthServiceProvider.ServiceProvider;
            var requestMessage = serviceProvider.ReadAuthorizationRequest(this.Request);

            if (requestMessage != null)
            {
                // This is a browser opening to allow the user to authorize a request token,
                // so redirect to the authorization page, which will automatically redirect
                // to have the user log in if necessary.
                oauthServiceProvider.PendingAuthorisationRequest = requestMessage;
                this.Response.Redirect("~/Account/Authorise");
            }
            else
            {
                throw new InvalidOperationException();
            }
        }
Example #10
0
        public ActionResult Authorize(bool isApproved)
        {
            if (isApproved)
            {
                var consumer       = OAuthServiceProvider.PendingAuthorizationConsumer;
                var tokenManager   = OAuthServiceProvider.ServiceProvider.TokenManager;
                var pendingRequest = OAuthServiceProvider.PendingAuthorizationRequest;
                ITokenContainingMessage requestTokenMessage = pendingRequest;
                var requestToken = tokenManager.GetRequestToken(requestTokenMessage.Token);

                var response = OAuthServiceProvider.AuthorizePendingRequestTokenAsWebResponse();
                if (response != null)
                {
                    // The consumer provided a callback URL that can take care of everything else.
                    return(response.AsActionResult());
                }

                var model = new AccountAuthorizeModel {
                    ConsumerApp = consumer.Name,
                };

                if (!pendingRequest.IsUnsafeRequest)
                {
                    model.VerificationCode        = ServiceProvider.CreateVerificationCode(consumer.VerificationCodeFormat, consumer.VerificationCodeLength);
                    requestToken.VerificationCode = model.VerificationCode;
                    tokenManager.UpdateToken(requestToken);
                }

                return(View("AuthorizeApproved", model));
            }
            else
            {
                OAuthServiceProvider.PendingAuthorizationRequest = null;
                return(View("AuthorizeDenied"));
            }
        }
 partial void OnStateChanging(OAuthServiceProvider.Code.TokenAuthorizationState value);
Example #12
0
 /**
  * Retrieve OAuth consumer to use for requests.  The returned consumer is ready to use for signed
  * fetch requests.
  *
  * @param securityToken token for user/gadget making request.
  * @param serviceName gadget's nickname for the service being accessed.
  * @param provider OAuth service provider info to be inserted into the returned consumer.
  *
  * @throws GadgetException if no OAuth consumer can be found (e.g. no consumer key can be used.)
  */
 public abstract ConsumerInfo getConsumerKeyAndSecret(ISecurityToken securityToken, String serviceName,
                                                      OAuthServiceProvider provider);
Example #13
0
        public override ConsumerInfo getConsumerKeyAndSecret(ISecurityToken securityToken, String serviceName, OAuthServiceProvider provider)
        {
            ++consumerKeyLookupCount;
            BasicOAuthStoreConsumerIndex pk = new BasicOAuthStoreConsumerIndex();

            pk.setGadgetUri(securityToken.getAppUrl());
            pk.setServiceName(serviceName);
            BasicOAuthStoreConsumerKeyAndSecret cks = consumerInfos.ContainsKey(pk) ? consumerInfos[pk] : defaultKey;

            if (cks == null)
            {
                throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR,
                                          "No key for gadget " + securityToken.getAppUrl() + " and service " + serviceName);
            }
            OAuthConsumer consumer;

            if (cks.keyType == BasicOAuthStoreConsumerKeyAndSecret.KeyType.RSA_PRIVATE)
            {
                consumer = new OAuthConsumer(null, cks.ConsumerKey, null, provider);
                consumer.setProperty(OAuth.OAUTH_SIGNATURE_METHOD, OAuth.RSA_SHA1);
                consumer.setProperty(RSA_SHA1.X509_CERTIFICATE, cks.CertName);
                consumer.setProperty(RSA_SHA1.X509_CERTIFICATE_PASS, cks.CertPass);
            }
            else
            {
                consumer = new OAuthConsumer(null, cks.ConsumerKey, cks.ConsumerSecret, provider);
                consumer.setProperty(OAuth.OAUTH_SIGNATURE_METHOD, OAuth.HMAC_SHA1);
            }
            return(new ConsumerInfo(consumer, cks.ConsumerKey));
        }