Exemple #1
0
        private static void DoConsumerRequest(Uri protectedResource, string consumerKey, string consumerSecret)
        {
            var request = OAuthConsumerRequest.Create(
                new EndPoint(protectedResource),
                OAuthService.Create(
                    new EndPoint(),
                    NullUri,
                    new EndPoint(),
                    new OAuth.Net.Components.OAuthConsumer(consumerKey, consumerSecret)));


            OAuthResponse response = request.GetResource();

            if (!response.HasProtectedResource)
            {
                Console.Write("OAuth request did not respond with a resource");
            }
            else
            {
                using (System.IO.StreamReader reader = new System.IO.StreamReader(response.ProtectedResource.GetResponseStream()))
                {
                    Console.Write(reader.ReadToEnd());
                }
            }
        }
Exemple #2
0
        /// <summary>
        /// 添加绑定账号
        /// </summary>
        /// <param name="bindAccount"></param>
        /// <returns></returns>
        public bool SetBindAccount(string bindAccount)
        {
            if (!string.IsNullOrEmpty(openID) && !string.IsNullOrEmpty(token) && !string.IsNullOrEmpty(bindAccount))
            {
                var oa = OAuthService.GetOAuth2(openID, server.ToString());

                var username = string.Format("{0}#{1}", bindAccount, server.ToString());

                if (oa == null)
                {
                    OAuthService.CreateNew(server.ToString(), token, openID, expiresTime, nickName, username, headUrl);
                }

                var user = UserService.GetUserByUserNameNoCache(bindAccount);
                if (!user.IsNull())
                {
                    return(true);
                }

                //add a record to user table:
                user = new User
                {
                    BindAccount  = username,
                    UserName     = bindAccount,
                    Password     = string.Empty,
                    Email        = "请在此处输入您的邮件地址",
                    LastActiveIP = Tool.GetIP()
                };
                UserService.RegisterUser(user);
                return(true);
            }
            return(false);
        }
 public void GetToken(Credentials inCredentials, string inFilename)
 {
     try
     {
         _configurationCloud = new ApiConfiguration(inCredentials.ConsumerKey, inCredentials.ConsumerSecret, "http://desktop");
         _oAuthKeyService    = new MYOBOAuthKeyService();
         var    dateTimeNow   = DateTime.UtcNow;
         var    lastTokenTime = _oAuthKeyService.OAuthResponse.ReceivedTime;
         double days          = (dateTimeNow - lastTokenTime).TotalDays;
         string days1         = days.ToString();
         ServiceLogger.Log(string.Format(@"days: {0}", days1));
         if (days < 365)
         {
             if (_oAuthKeyService.OAuthResponse.HasExpired)
             {
                 var oauthService = new OAuthService(_configurationCloud);
                 _oAuthKeyService.OAuthResponse = oauthService.RenewTokens(_oAuthKeyService.OAuthResponse);
                 ServiceLogger.Log("Token Renewed");
             }
             else
             {
                 ServiceLogger.Log("Token not Expired");
             }
             MYOBCompanyFiles companyFiles = new MYOBCompanyFiles(inCredentials);
             companyFiles.FetchFile(_configurationCloud, null, _oAuthKeyService, inFilename);
         }
     }
     catch (Exception exception)
     {
         ServiceLogger.LogException("Exception in GetTokens", exception);
     }
 }
        public async Task <T> AuthApp(AuthResultAddressModel model, bool isPersistent = false)
        {
            var openId = await OAuthService.CodeToOpenIdAsync(model.code, await AppsContainer.AccessToken()());

            var userinfo = await OAuthService.OpenIdToUserInfo(AccessToken : await AppsContainer.AccessToken()(), openid : openId.openid);

            var current = await _userManager.FindByIdAsync(userinfo.User.Id);

            if (current == null)
            {
                current = new T();
                current.Update(userinfo);
                var result = await _userManager.CreateAsync(current);

                if (!result.Succeeded)
                {
                    var message = new StringBuilder();
                    foreach (var error in result.Errors)
                    {
                        message.AppendLine(error.Description);
                    }
                    throw new InvalidOperationException($"The user info ({userinfo.User.Id}) we get could not register to our database because {message}.");
                }
            }
            else
            {
                current.Update(userinfo);
                await _userManager.UpdateAsync(current);
            }
            await _signInManager.SignInAsync(current, isPersistent);

            return(current);
        }
Exemple #5
0
        public void CommitUploadStream(params object[] arg)
        {
            // convert the args
            OAuthService   svc             = arg[0] as OAuthService;
            HttpWebRequest uploadRequest   = arg[1] as HttpWebRequest;
            long           uploadSize      = (long)arg[2];
            BaseFileEntry  fileSystemEntry = arg[3] as BaseFileEntry;

#if !WINDOWS_PHONE && !MONODROID
            WebRequestStream requestStream = arg[4] as WebRequestStream;

            // check if all data was written into stream
            if (requestStream.WrittenBytes != uploadRequest.ContentLength)
            {
                // nothing todo request was aborted
                return;
            }
#endif

            // perform the request
            int          code;
            WebException e;
            svc.PerformWebRequest(uploadRequest, null, out code, out e);

            // check the ret value
            if (code != (int)HttpStatusCode.OK)
            {
                SharpBoxException.ThrowSharpBoxExceptionBasedOnHttpErrorCode(uploadRequest, (HttpStatusCode)code, e);
            }

            // set the length
            fileSystemEntry.Length = uploadSize;
        }
Exemple #6
0
 /// <summary>
 /// Sequence:
 /// -->Retrieve the Request token
 /// -->Retrieve the value from query string
 /// -->Retrieve acces token
 /// -->Retrieve acces secret
 /// -->Redirect to close
 /// </summary>
 /// <returns></returns>
 public ActionResult Response()
 {
     oAuthorizationDB  = new OAuthTokens();
     oAuthService      = new OAuthService(oAuthorizationdto);
     oAuthorizationdto = oAuthService.GetRequestToken(this);
     if (Request.QueryString.HasKeys())
     {
         oAuthorizationdto.OauthVerifyer = Request.QueryString["oauth_verifier"].ToString();
         oAuthorizationDB.realmid        = Request.QueryString["realmId"].ToString();
         oAuthorizationdto.Realmid       = oAuthorizationDB.realmid;
         oAuthorizationDB.datasource     = Request.QueryString["dataSource"].ToString();
         oAuthorizationdto.DataSource    = oAuthorizationDB.datasource;
         oAuthorizationdto = oAuthService.GetAccessTokenFromServer(this, oAuthorizationdto);
         //encrypt the tokens
         oAuthorizationDB.access_secret = Utility.Encrypt(oAuthorizationdto.AccessTokenSecret, oAuthorizationdto.SecurityKey);
         oAuthorizationDB.access_token  = Utility.Encrypt(oAuthorizationdto.AccessToken, oAuthorizationdto.SecurityKey);
         using (var oAuthorizationDBContext = new OAuthdataContext("DBContext"))
         {
             //store the encrypted tokens to DB.
             oAuthorizationDBContext.Tokens.Add(oAuthorizationDB);
             oAuthorizationDBContext.SaveChanges();
         }
     }
     return(RedirectToAction("Close", "Home"));
 }
        public override Stream CreateDownloadStream(IStorageProviderSession session, ICloudFileSystemEntry fileSystemEntry)
        {
            // build the url
            var url = GetDownloadFileUrlInternal(session, fileSystemEntry);

            // build the service
            var svc = new OAuthService();

            // get the dropbox session
            var dropBoxSession = session as DropBoxStorageProviderSession;

            // create webrequst
            var requestProtected = svc.CreateWebRequest(url, WebRequestMethodsEx.Http.Get, null, null, dropBoxSession.Context, (DropBoxToken)dropBoxSession.SessionToken, null);

            // get the response
            var response = svc.GetWebResponse(requestProtected);

            // get the data stream
            var orgStream = svc.GetResponseStream(response);

            // build the download stream
            var dStream = new BaseFileEntryDownloadStream(orgStream, fileSystemEntry);

            // put the disposable on the stack
            dStream._DisposableObjects.Push(response);

            // go ahead
            return(dStream);
        }
Exemple #8
0
 public OAuthController(OAuthService authService, IConfiguration configuration, ICookieManager cookieManager, IWarcraftClient warcraftClient)
 {
     _authService    = authService;
     _configuration  = configuration;
     _cookieManager  = cookieManager;
     _warcraftClient = warcraftClient;
 }
        /// <summary>
        /// This method is able to exchange the request token into an access token which can be used in
        /// sharpbox. It is necessary that the user validated the request via authorization url otherwise
        /// this call wil results in an unauthorized exception!
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="ConsumerKey"></param>
        /// <param name="ConsumerSecret"></param>
        /// <param name="DropBoxRequestToken"></param>
        /// <returns></returns>
        static public ICloudStorageAccessToken ExchangeDropBoxRequestTokenIntoAccessToken(DropBoxConfiguration configuration, String ConsumerKey, String ConsumerSecret, DropBoxRequestToken DropBoxRequestToken)
        {
            // build the consumer context
            var consumerContext = new OAuthConsumerContext(ConsumerKey, ConsumerSecret);

            // build up the oauth session
            var serviceContext = new OAuthServiceContext(configuration.RequestTokenUrl.ToString(),
                                                         configuration.AuthorizationTokenUrl.ToString(), configuration.AuthorizationCallBack.ToString(),
                                                         configuration.AccessTokenUrl.ToString());

            // build the access token
            OAuthService svc         = new OAuthService();
            OAuthToken   accessToken = svc.GetAccessToken(serviceContext, consumerContext, DropBoxRequestToken.RealToken);

            if (accessToken == null)
            {
                throw new UnauthorizedAccessException();
            }

            // create the access token
            return(new DropBoxToken(accessToken,
                                    new DropBoxBaseTokenInformation()
            {
                ConsumerKey = ConsumerKey,
                ConsumerSecret = ConsumerSecret
            }));
        }
        /// <summary>
        /// Intitalise multiple models and kick start oauth/sync
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            multiplemodels = new Multiplemodels();
            multiplemodels.SyncObjectsModel    = new Syncdto();
            multiplemodels.OAuthorizationModel = new OAuthorizationdto();
            multiplemodels.TimeActivityModel   = new TimeActivitydto();
            multiplemodels.IsReadySync         = false;
            var oAuthModel = new OAuthService(multiplemodels.OAuthorizationModel).IsTokenAvailable(this);

            if (oAuthModel.IsConnected)
            {
                multiplemodels.IsReadySync         = true;
                multiplemodels.OAuthorizationModel = oAuthModel;
                multiplemodels.IsConnected         = oAuthModel.IsConnected;
                var syncService = new SyncService(oAuthModel);
                multiplemodels.SyncObjectsModel.OauthToken = oAuthModel;
                multiplemodels.SyncObjectsModel            = syncService.IsEmpSync(multiplemodels.SyncObjectsModel, syncService);
                multiplemodels.SyncObjectsModel            = syncService.IsCustSync(multiplemodels.SyncObjectsModel, syncService);
                multiplemodels.SyncObjectsModel            = syncService.IsServiceItemSync(multiplemodels.SyncObjectsModel, syncService);
                multiplemodels.SyncObjectsModel.CompanyId  = oAuthModel.Realmid;
                multiplemodels.SyncObjectsModel            = syncRepo.Save(this, multiplemodels.SyncObjectsModel);
                multiplemodels.IsReadyTimeentry            = multiplemodels.SyncObjectsModel.IsEmployeeSync || multiplemodels.SyncObjectsModel.IsCustomerSync || multiplemodels.SyncObjectsModel.IsServiceItemSync;
                multiplemodels.IsReadytoInvoice            = false;
                return(View(multiplemodels));
            }
            else
            {
                return(View(multiplemodels));
            }
        }
Exemple #11
0
 public ApiController(
     UserManager <KahlaUser> userManager,
     SignInManager <KahlaUser> signInManager,
     KahlaDbContext dbContext,
     PushKahlaMessageService pushService,
     IConfiguration configuration,
     AuthService <KahlaUser> authService,
     ServiceLocation serviceLocation,
     OAuthService oauthService,
     ChannelService channelService,
     StorageService storageService,
     AppsContainer appsContainer,
     UserService userService)
 {
     _userManager     = userManager;
     _signInManager   = signInManager;
     _dbContext       = dbContext;
     _pusher          = pushService;
     _configuration   = configuration;
     _authService     = authService;
     _serviceLocation = serviceLocation;
     _oauthService    = oauthService;
     _channelService  = channelService;
     _storageService  = storageService;
     _appsContainer   = appsContainer;
     _userService     = userService;
 }
Exemple #12
0
        // GET: Sales
        public ActionResult SalesRecord()
        {
            // SalesRequest sales = new SalesRequest();


            multiplemodels = new Multiplemodels
            {
                taxtoobj            = new List <TaxCode>(),
                CustomersObj        = new Tuple <IEnumerable <CustomerTo>, IEnumerable <Record> >(null, null),
                OAuthorizationModel = new OAuthorizationdto()
            };

            var oAuthModel = new OAuthService(multiplemodels.OAuthorizationModel).IsTokenAvailable(this);

            var taxObj = new TaxService(oAuthModel);

            if (oAuthModel.IsConnected)
            {
                multiplemodels.OAuthorizationModel = oAuthModel;

                multiplemodels.IsConnected = oAuthModel.IsConnected;
                var customerobj = new CustomerService(oAuthModel);
                multiplemodels.taxtoobj     = taxObj.GeTaxCodes();
                multiplemodels.CustomersObj = customerobj.MatchCustomerWithApi();

                //  multiplemodels.SalesItems = sales.GetCall();


                return(View(multiplemodels));
            }
            else
            {
                return(View(multiplemodels));
            }
        }
Exemple #13
0
        public void ShouldGenerateSignatureForFlickr()
        {
            //given
            OAuth.Net.Common.ISigningProvider provider      = new OAuth.Net.Components.HmacSha1SigningProvider();
            OAuth.Net.Common.INonceProvider   nonceProvider = new OAuth.Net.Components.GuidNonceProvider();
            DateTime        time       = DateTime.Now;
            OAuthParameters parameters = new OAuthParameters()
            {
                Nonce           = nonceProvider.GenerateNonce(),
                SignatureMethod = "HMAC-SHA1",
                Timestamp       = "1316657628",
                Version         = "1.0",
                Callback        = "http://www.wackylabs.net/oauth/test",
                ConsumerKey     = "768fe946d252b119746fda82e1599980"
            };
            string       baseString     = SignatureBase.Create("GET", new Uri("http://www.flickr.com/services/oauth/request_token"), parameters);
            string       consumerSecret = "1a3c208e172d3edc";
            string       tokenSecret    = string.Empty;
            OAuthService testee         = new OAuthService();
            //when
            string result = provider.ComputeSignature(baseString, consumerSecret, tokenSecret);

            //then
            Assert.AreEqual(expected, result);
        }
Exemple #14
0
        public static OAuthService ToEntity(this OAuthServiceDto dto)
        {
            OAuthService entity = null;

            if (dto != null)
            {
                entity = new OAuthService()
                {
                    ID            = dto.Id,
                    ClientSecret  = dto.ClientSecret,
                    AccessToken   = dto.AccessToken,
                    CreatedBy     = dto.CreatedBy,
                    CreatedTime   = dto.CreatedTime,
                    DomainName    = dto.DomainName,
                    ModifiedBy    = dto.ModifiedBy,
                    ModifiedTime  = dto.ModifiedTime,
                    RedirectUri   = dto.RedirectUri,
                    ServiceNumber = dto.ServiceNumber,
                    ServiceName   = dto.ServiceSign,
                    TeamLeader    = dto.TeamLeader,
                    Scope         = dto.Scope
                };
            }
            return(entity);
        }
Exemple #15
0
 private void GetTokenForMYOB(Credentials crendetials)
 {
     try
     {
         _configurationCloud            = new ApiConfiguration(crendetials.ConsumerKey, crendetials.ConsumerSecret, "http://desktop");
         _oAuthKeyService               = new MYOBOAuthKeyService();
         _oAuthKeyService.OAuthResponse = null;
         if (_oAuthKeyService.OAuthResponse == null)
         {
             var    oauthService = new OAuthService(_configurationCloud);
             string _accessCode  = OAuthLogin.GetAuthorizationCode(_configurationCloud);
             _oAuthKeyService.OAuthResponse =
                 oauthService.GetTokens(_accessCode);
             var frmLogin = new CompanyFileLogin();
             frmLogin.ShowDialog(this);
             if (frmLogin.Username.Length > 0)
             {
                 AccountingIntegrationConfigManager.Instance.SaveCompanyFileCredentials(frmLogin.Username, frmLogin.Password);
             }
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Exemple #16
0
        private void loginToolStripMenuItemLogin_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;

            OAuthService oauthSvc = new OAuthService(m_ConsumerKey, m_ConsumerSecret, m_baseURL);

            authenticated = oauthSvc.StartOAuth();
            if (!authenticated)
            {
                MessageBox.Show("authentication failed.");
                return;
            }

            plmSvc = new PLM360RestService(tanentName, oauthSvc);

            Session session = plmSvc.Login();

            if (session == null)
            {
                MessageBox.Show("Login to PLM360 failed.");
                return;
            }

            refreshWorkspacesToolStripMenuItemRefreshWorkspaces.Enabled = true;
            BindWorkspaces();

            Cursor.Current = Cursors.Default;
        }
Exemple #17
0
        /// <summary>
        /// Creates an <see cref="OAuthRequest"/> for the specified resource
        /// </summary>
        /// <param name="service">OAuth service</param>
        /// <param name="uriFormat">Resource URI (optionally with format
        /// placeholders)</param>
        /// <param name="args">Arguments to format with</param>
        /// <returns>
        /// <see cref="OAuthRequest"/> for the specified resource
        /// </returns>
        private OAuthRequest CreateRequest(
            OAuthService service,
            string uriFormat,
            string httpMethod,
            params string[] args)
        {
            if (service == null)
            {
                throw new ArgumentNullException("service");
            }

            if (uriFormat == null)
            {
                throw new ArgumentNullException("uriFormat");
            }

            if (string.IsNullOrEmpty(uriFormat))
            {
                throw new ArgumentException("uriFormat must not be empty", "uriFormat");
            }

            return(AspNetOAuthRequest.Create(
                       new OAuth.Net.Consumer.EndPoint(
                           string.Format(
                               CultureInfo.InvariantCulture,
                               uriFormat,
                               args), httpMethod),
                       service,
                       this.options.AuthorizationCallbackUri,
                       HttpContext.Current.Session.SessionID));
        }
Exemple #18
0
 private void LoadTokens()
 {
     if (Customer != null)
     {
         OAuthService.BeginGetTokensForCustomer(Customer.Id, EndGetTokens, null);
     }
 }
Exemple #19
0
        protected void ValidateOAuth3rdLoginRequest(OAuthService provider, IOAuthTokenPost dataPost)
        {
            if (!OAuth.IsRequestToken)
            {
                throw new HttpBadRequestException(
                          "106 " + ControllerStrings.Warning106_RequestTokenRequired
                          );
            }

            this.OAuth3rdCredential =
                Database.OAuthCredentialStore.GetFirst(
                    filter: f =>
                    f.OAuthProvider == provider &&
                    f.Uid == dataPost.ID,
                    include:
                    new string[] { "User" }
                    );

            if (this.OAuth3rdCredential == null)
            {
                OAuth.Token.LoginAttempts++;
                Database.TokenStore.Update(OAuth.Token);
                Database.SaveChanges();

                throw new HttpNotFoundException(
                          "105 " + ControllerStrings.Warning105_SocialTokenNotFound
                          );
            }
        }
Exemple #20
0
        public static String RequestResourceByUrl(String url, Dictionary <String, String> parameters, IStorageProviderService service, IStorageProviderSession session, out int netErrorCode)
        {
            // cast the dropbox session
            DropBoxStorageProviderSession dropBoxSession = session as DropBoxStorageProviderSession;

            // instance the oAuthServer
            OAuthService svc = new OAuthService();

            // build the webrequest to protected resource
            WebRequest request = svc.CreateWebRequest(url, WebRequestMethodsEx.Http.Get, null, null, dropBoxSession.Context, (DropBoxToken)dropBoxSession.SessionToken, parameters);

            // get the error code
            WebException ex;

            // perform a simple webrequest
            Stream s = svc.PerformWebRequest(request, null, out netErrorCode, out ex);

            if (s == null)
            {
                return("");
            }

            // read the memory stream and convert to string
            return(new StreamReader(s).ReadToEnd());
        }
        public OAuthServiceTest()
        {
            _token = new Token();

            _credentialsMock = new Mock <ICredentials>();
            _credentialsMock
            .SetupGet(credentials => credentials.RefreshToken)
            .Returns(_refreshToken);

            _apiRequestSenderMock = new Mock <IApiRequestSender>();
            _apiRequestSenderMock
            .Setup(sender => sender.SendRequestAsync(It.IsAny <OAuthRequest <Token> >()))
            .Returns(Task.FromResult(_token));

            _oauthService = new OAuthService(
                new Configuration
            {
                BaseUrl      = new Uri(_baseUrl),
                ClientId     = _clientId,
                ClientSecret = _clientSecret,
                RedirectUri  = _redirectUrl,
            },
                _credentialsMock.Object,
                _apiRequestSenderMock.Object
                );
        }
Exemple #22
0
        public static async Task AuthApp <T>(Controller _controller, AuthResultAddressModel model, UserManager <T> _userManager, SignInManager <T> _signInManager) where T : AiurUserBase, new()
        {
            var openId = await OAuthService.CodeToOpenIdAsync(model.code, await Values.AccessToken());

            var userinfo = await OAuthService.OpenIdToUserInfo(AccessToken : await Values.AccessToken(), openid : openId.openid);

            var current = await _userManager.FindByIdAsync(userinfo.User.OpenId);

            if (current == null)
            {
                current = new T()
                {
                    Id                = userinfo.User.OpenId,
                    NickName          = userinfo.User.NickName,
                    Sex               = userinfo.User.Sex,
                    HeadImgUrl        = userinfo.User.HeadImgUrl,
                    UserName          = userinfo.User.OpenId,
                    PreferedLanguage  = userinfo.User.PreferedLanguage,
                    AccountCreateTime = userinfo.User.AccountCreateTime
                };
                var result = await _userManager.CreateAsync(current);
            }
            else
            {
                current.Update(userinfo);
                await _userManager.UpdateAsync(current);
            }
            await _signInManager.SignInAsync(current, false);
        }
Exemple #23
0
        public override void UploadChunk(IStorageProviderSession session, IResumableUploadSession uploadSession, Stream stream, long chunkLength)
        {
            if (uploadSession.Status == ResumableUploadSessionStatus.Completed || uploadSession.Status == ResumableUploadSessionStatus.Aborted)
            {
                throw new InvalidOperationException("Upload session was either completed or aborted.");
            }

            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            var requestParams = new Dictionary <string, string>();

            if (uploadSession.Status == ResumableUploadSessionStatus.Started)
            {
                requestParams.Add("upload_id", uploadSession.GetItem <string>("UploadId"));
                requestParams.Add("offset", uploadSession.BytesTransfered.ToString());
            }

            var request = new OAuthService().CreateWebRequest(GetUrlString(DropBoxChunkedUpload, session.ServiceConfiguration),
                                                              "PUT",
                                                              null,
                                                              null,
                                                              ((DropBoxStorageProviderSession)session).Context,
                                                              (DropBoxToken)session.SessionToken,
                                                              requestParams);

            request.ContentLength = chunkLength;
            using (var requestStream = request.GetRequestStream())
            {
                stream.CopyTo(requestStream);
            }

            using (var response = request.GetResponse())
                using (var responseStream = response.GetResponseStream())
                {
                    if (responseStream == null)
                    {
                        return;
                    }

                    var json = new JsonHelper();
                    using (var streamReader = new StreamReader(responseStream))
                    {
                        json.ParseJsonMessage(streamReader.ReadToEnd());
                    }

                    var uplSession = (ResumableUploadSession)uploadSession;
                    uplSession["UploadId"]      = json.GetProperty("upload_id");
                    uplSession["Expired"]       = json.GetDateTimeProperty("expired");
                    uplSession.BytesTransfered += chunkLength;
                    uplSession.Status           = ResumableUploadSessionStatus.Started;

                    if (uplSession.BytesToTransfer == uploadSession.BytesTransfered)
                    {
                        CommitUploadSession(session, uploadSession);
                    }
                }
        }
Exemple #24
0
 public AuthController(
     ServiceLocation serviceLocation,
     IConfiguration configuration,
     IHostingEnvironment env,
     AuthService <ApplicationUser> authService,
     OAuthService oauthService,
     UserManager <ApplicationUser> userManager,
     SignInManager <ApplicationUser> signInManager,
     UserService userService,
     AppsContainer appsContainer,
     ChatPushService pusher,
     ChannelService channelService,
     VersionChecker version,
     ApplicationDbContext dbContext,
     ThirdPartyPushService thirdPartyPushService)
 {
     _serviceLocation       = serviceLocation;
     _configuration         = configuration;
     _env                   = env;
     _authService           = authService;
     _oauthService          = oauthService;
     _userManager           = userManager;
     _signInManager         = signInManager;
     _userService           = userService;
     _appsContainer         = appsContainer;
     _pusher                = pusher;
     _channelService        = channelService;
     _version               = version;
     _dbContext             = dbContext;
     _thirdPartyPushService = thirdPartyPushService;
 }
Exemple #25
0
 /// <summary>
 /// Action Result for Index, This flow will create OAuthConsumer Context using Consumer key and Consuler Secret key
 /// obtained when Application is added at intuit workspace. It creates OAuth Session out of OAuthConsumer and Calls
 /// Intuit Workpsace endpoint for OAuth.
 /// </summary>
 /// <returns>Redirect Result.</returns>
 public RedirectResult Index()
 {
     oAuthorizationdto             = new OAuthorizationdto();
     oAuthService                  = new OAuthService(oAuthorizationdto);
     oAuthorizationdto.CallBackUrl = Request.Url.GetLeftPart(UriPartial.Authority) + "/Oauth/Response";
     return(Redirect(oAuthService.GrantUrl(this)));
 }
Exemple #26
0
 public AuthController(
     ServiceLocation serviceLocation,
     IConfiguration configuration,
     IHostingEnvironment env,
     AuthService <KahlaUser> authService,
     OAuthService oauthService,
     UserManager <KahlaUser> userManager,
     SignInManager <KahlaUser> signInManager,
     UserService userService,
     AppsContainer appsContainer,
     KahlaPushService pusher,
     ChannelService channelService,
     VersionChecker version,
     KahlaDbContext dbContext,
     IMemoryCache cache)
 {
     _serviceLocation = serviceLocation;
     _configuration   = configuration;
     _env             = env;
     _authService     = authService;
     _oauthService    = oauthService;
     _userManager     = userManager;
     _signInManager   = signInManager;
     _userService     = userService;
     _appsContainer   = appsContainer;
     _pusher          = pusher;
     _channelService  = channelService;
     _version         = version;
     _dbContext       = dbContext;
     _cache           = cache;
 }
        /// <summary>
        /// NOTE: There is a known issue with the Mixer APIs where authenticating with a short code as opposed to the regular OAuth process, where certain
        /// Chat Client commands will not work (EX: Timeout, Clear Messages, Delete Message, etc). The current work around to this is to use the traditional
        /// OAuth authentication methods.
        /// </summary>
        /// <param name="clientID"></param>
        /// <param name="clientSecret"></param>
        /// <param name="scopes"></param>
        /// <param name="codeCallback"></param>
        /// <returns></returns>
        public static async Task <MixerConnection> ConnectViaShortCode(string clientID, string clientSecret, IEnumerable <OAuthClientScopeEnum> scopes, Action <OAuthShortCodeModel> codeCallback)
        {
            Validator.ValidateString(clientID, "clientID");
            Validator.ValidateList(scopes, "scopes");
            Validator.ValidateVariable(codeCallback, "codeCallback");

            OAuthService        oauthService = new OAuthService();
            OAuthShortCodeModel shortCode    = await oauthService.GetShortCode(clientID, clientSecret, scopes);

            codeCallback(shortCode);

            string authorizationCode = null;

            for (int i = 0; i < shortCode.expires_in && string.IsNullOrEmpty(authorizationCode); i++)
            {
                await Task.Delay(500);

                authorizationCode = await oauthService.ValidateShortCode(shortCode);
            }

            if (!string.IsNullOrEmpty(authorizationCode))
            {
                return(await MixerConnection.ConnectViaAuthorizationCode(clientID, clientSecret, authorizationCode, authorizationCode));
            }
            return(null);
        }
 public DebugApiController(
     UserManager <KahlaUser> userManager,
     SignInManager <KahlaUser> signInManager,
     KahlaDbContext dbContext,
     PushKahlaMessageService pushService,
     IConfiguration configuration,
     AuthService <KahlaUser> authService,
     ServiceLocation serviceLocation,
     OAuthService oauthService,
     ChannelService channelService,
     StorageService storageService,
     AppsContainer appsContainer,
     UserService userService) : base(
         userManager,
         signInManager,
         dbContext,
         pushService,
         configuration,
         authService,
         serviceLocation,
         oauthService,
         channelService,
         storageService,
         appsContainer,
         userService)
 {
 }
        public override Stream CreateUploadStream(IStorageProviderSession session, ICloudFileSystemEntry fileSystemEntry, long uploadSize)
        {
            // build the url
            var url = GetDownloadFileUrlInternal(session, fileSystemEntry.Parent);

            // get the session
            var dbSession = session as DropBoxStorageProviderSession;

            // build service
            var svc = new OAuthService();

            // encode the filename
            var fileName = fileSystemEntry.Name;

            // build oAuth parameter
            var param = new Dictionary <string, string>();

            param.Add("file", fileName);

            // sign the url
            var signedUrl = svc.GetSignedUrl(url, dbSession.Context, dbSession.SessionToken as DropBoxToken, param);

            // build upload web request
            var uploadRequest = svc.CreateWebRequestMultiPartUpload(signedUrl, null);

            // get the network stream
            var ws = svc.GetRequestStreamMultiPartUpload(uploadRequest, fileName, uploadSize);

            // register the post dispose opp
            ws.PushPostDisposeOperation(CommitUploadStream, svc, uploadRequest, uploadSize, fileSystemEntry, ws);

            // go ahead
            return(ws);
        }
Exemple #30
0
        private OAuthResource ExecuteRequest(
            OAuthService service,
            NameValueCollection parameters,
            string uriFormat,
            string httpMethod,
            params string[] args)
        {
            if (service == null)
            {
                throw new ArgumentNullException("service");
            }

            if (options.AuthorizationCallbackUri == null)
            {
                throw new ArgumentException("AuthorizationCallbackUri option must not be null", "options");
            }

            if (uriFormat == null)
            {
                throw new ArgumentNullException("uriFormat");
            }

            if (string.IsNullOrEmpty(uriFormat))
            {
                throw new ArgumentException("uriFormat must not be empty", "uriFormat");
            }

            var request = this.CreateRequest(service, uriFormat, httpMethod, args);

            var response = request.GetResource(parameters);

            return(response.ProtectedResource);
        }
Exemple #31
0
        // This method gets called by the runtime. Use this method to add services to the container
        public void ConfigureServices(IServiceCollection services)
        {
            var authService = new OAuthService(new OAuthServiceOptions());

            this.AddFacebookOAuthStrategy(authService);
            this.AddGoogleOAuthStrategy(authService);

            services.AddSingleton(authService);
        }
Exemple #32
0
        private void AddFacebookOAuthStrategy(OAuthService authService)
        {
            var fbOptions = FacebookStrategyOptions.CreateDefault();
            fbOptions.ClientId = Configuration["facebook:appid"];
            fbOptions.ClientSecret = Configuration["facebook:appsecret"];
            fbOptions.CallbackPath = "auth/facebook/callback";

            var fbStrategy = new FacebookOAuthStrategy(fbOptions);

            authService.AddStrategy(fbStrategy);
        }
Exemple #33
0
        private void AddGoogleOAuthStrategy(OAuthService authService)
        {
            var gOptions = GoogleStrategyOptions.CreateDefault();
            gOptions.ClientId = Configuration["google:clientid"];
            gOptions.ClientSecret = Configuration["google:clientsecret"];
            gOptions.CallbackPath = "auth/google/callback";

            var gStrategy = new GoogleOAuthStrategy(gOptions);

            authService.AddStrategy(gStrategy);

        }
        private static AccessorInfo.HttpMethod getStoreMethod(OAuthService.Method method, OAuthResponseParams responseParams)
        {
            if (method == OAuthService.Method.GET)
            {
                return AccessorInfo.HttpMethod.GET;
            }
            if (method == OAuthService.Method.POST)
            {
                return AccessorInfo.HttpMethod.POST;
            }
            throw responseParams.oauthRequestException(OAuthError.INVALID_REQUEST, "Unknown method " + method);

        }
 private static AccessorInfo.OAuthParamLocation getStoreLocation(OAuthService.Location location, OAuthResponseParams responseParams)
 {
     if (location == OAuthService.Location.HEADER)
     {
         return AccessorInfo.OAuthParamLocation.AUTH_HEADER;
     }
     if (location == OAuthService.Location.URL)
     {
         return AccessorInfo.OAuthParamLocation.URI_QUERY;
     }
     if (location == OAuthService.Location.BODY)
     {
         return AccessorInfo.OAuthParamLocation.POST_BODY;
     }
     throw responseParams.oauthRequestException(OAuthError.INVALID_REQUEST,
                                                "Unknown parameter location " + location);
 }
Exemple #36
0
 private void parseService(XmlElement serviceElement, Uri _base)
 {
     OAuthService service = new OAuthService(serviceElement, _base);
     serviceMap.Add(service.getName(), service);
 }