async public Task<IHttpActionResult> CallbackSaveFiles([FromBody] CallBackParams2 param)
        {
            var boxClient = new BoxClient(new BoxConfig(ClientId, ClientSecret, new Uri("http://localhost:1176/Auth/Callback")));
            OAuthSession authSession = await boxClient.Auth.AuthenticateAsync(code);

            try
            {
                //foreach (var id in param.ids)
                {
                    var filestream = await boxClient.FilesManager.DownloadStreamAsync(param.ids);

                    var path = Path.GetTempFileName();
                    var bytes = new byte[param.length];
                    filestream.Read(bytes, 0, bytes.Length);

                    File.OpenWrite(path).Write(bytes, 0, bytes.Length);
                }
            }
            catch (Exception ex)
            {

                throw;
            }

            return Ok();
        }
        public async Task<bool> Claim(Uri uri, string documentTitle)
        {
            IDictionary<string, string> keyDictionary = new Dictionary<string, string>();
            var qSplit = uri.Query.Split('?');
            foreach (var kvp in qSplit[qSplit.Length - 1].Split('&'))
            {
                var kvpSplit = kvp.Split('=');
                if (kvpSplit.Length == 2)
                {
                    keyDictionary.Add(kvpSplit[0], kvpSplit[1]);
                }
            }

            if (!keyDictionary.ContainsKey("code"))
                return false;

            var authCode = keyDictionary["code"];
            if (string.IsNullOrEmpty(authCode))
                return false;

            _api = BoxHelper.GetClient();
            _token = await _api.Auth.AuthenticateAsync(authCode);

            return _token != null && _token.RefreshToken != null && _token.AccessToken != null;
        }
示例#3
0
文件: BoxAPI.cs 项目: rbhttchr/WebAPI
        // To generate authCode on a browser open,
        // https://account.box.com/api/oauth2/authorize?client_id=[CLIENT_ID]&response_type=code
        /// <summary>Updates Box accessToken and refreshToken values in the Dictionary table.
        /// Optionally creates these keys if they do not exist.
        /// </summary>
        public async Task CreateAccessTokenAsync(string authCode)
        {
            // This implementation is overly chatty with the database, but we rarely create access tokens so it is not a problem
            using (var _context = CTDbContext.CreateDbContext())
            {
                if (!await _context.Dictionaries.Where(d => d.Key == CommonUtils.BOX_ACCESS_TOKEN).AnyAsync())
                {
                    _context.Dictionaries.Add(new Dictionary
                    {
                        Key = CommonUtils.BOX_ACCESS_TOKEN
                    });
                    await _context.SaveChangesAsync();
                }
                if (!await _context.Dictionaries.Where(d => d.Key == CommonUtils.BOX_REFRESH_TOKEN).AnyAsync())
                {
                    _context.Dictionaries.Add(new Dictionary
                    {
                        Key = CommonUtils.BOX_REFRESH_TOKEN
                    });
                    await _context.SaveChangesAsync();
                }


                var accessToken  = _context.Dictionaries.Where(d => d.Key == CommonUtils.BOX_ACCESS_TOKEN).First();
                var refreshToken = _context.Dictionaries.Where(d => d.Key == CommonUtils.BOX_REFRESH_TOKEN).First();
                var config       = new BoxConfig(Globals.appSettings.BOX_CLIENT_ID, Globals.appSettings.BOX_CLIENT_SECRET, new Uri("http://locahost"));
                var client       = new Box.V2.BoxClient(config);
                var auth         = await client.Auth.AuthenticateAsync(authCode);

                _logger.LogInformation("Created Box Tokens");
                accessToken.Value  = auth.AccessToken;
                refreshToken.Value = auth.RefreshToken;
                await _context.SaveChangesAsync();
            }
        }
        /// <summary>
        /// Print inforamation about the currently authenticated Box user
        /// </summary>
        /// <param name="client">An authenticated Box client</param>
        private static void PrintServiceAccountInformation(Box.V2.BoxClient client)
        {
            var user = client.UsersManager.GetCurrentUserInformationAsync().Result;

            Console.Out.WriteLine("");
            Console.Out.WriteLine("Authenticated as");
            Console.Out.WriteLine($"  Name: {user.Name}");
            Console.Out.WriteLine($"  Login: {user.Login}");
        }
示例#5
0
        public static BoxClient GetClient(OAuthSession session)
        {
            var handler = new BoxHttpRequestHandler();
            var converter = new BoxJsonConverter();
            var service = new BoxService(handler);
            var authRepository = new AuthRepository(Config, service, converter, session);

            var client = new BoxClient(Config, converter, handler, service, authRepository);
            return client;
        }
示例#6
0
 public static Box.V2.BoxClient GetClient()
 {
     Box.V2.BoxClient client = null;
     try
     {
         var config  = new BoxConfig(ClientId, ClientSecret, redirectUri);
         var session = new OAuthSession(AccessToken, "REFRESH_TOKEN", 3600, "bearer");
         client = new Box.V2.BoxClient(config, session);
     }
     catch (BoxException e)
     {
         Console.WriteLine(e.Message);
     }
     return(client);
 }
示例#7
0
文件: BoxAPI.cs 项目: rbhttchr/WebAPI
        /// <summary>
        /// Creates a new box client, after first refreshing the access and refresh token.
        /// </summary>
        public async Task <BoxClient> GetBoxClientAsync()
        {
            // Todo RefreshAccessTokenAsync could return this information for us; and avoid another trip to the database
            await RefreshAccessTokenAsync();

            BoxClient boxClient;

            using (var _context = CTDbContext.CreateDbContext())
            {
                var accessToken = await _context.Dictionaries.Where(d => d.Key == CommonUtils.BOX_ACCESS_TOKEN).FirstAsync();

                var refreshToken = await _context.Dictionaries.Where(d => d.Key == CommonUtils.BOX_REFRESH_TOKEN).FirstAsync();

                var config = new BoxConfig(Globals.appSettings.BOX_CLIENT_ID, Globals.appSettings.BOX_CLIENT_SECRET, new Uri("http://locahost"));
                var auth   = new OAuthSession(accessToken.Value, refreshToken.Value, 3600, "bearer");
                boxClient = new Box.V2.BoxClient(config, auth);
            }
            return(boxClient);
        }
示例#8
0
        private async Task<BoxClient> GetApi()
        {
            if (_api == null)
                _api = await BoxHelper.GetClient(_account);

            return _api;
        }
示例#9
0
        /// <summary>
        /// The second and final step of the OAuth2 flow. The user has authorized this application at Box's site and redirected them back to this site. Validate the redirect and exchange the authorization code for a access/refresh token pair.
        /// </summary>
        private async Task<ActionResult> Token(string code, string state)
        {
            try
            {
                // Validate that the 'code' has not already been exchanged for an access token. This prevents replay attacks.
                if (!ValidateAntiforgeryToken(state))
                {
                    Response.StatusCode = 400;
                    return View("Error", new ErrorModel { Message = "forged_request", Description = "This code has already been used to fetch an authorization token." });
                }

                // Fetch the stashed Client ID/Secret from the Session
                var clientId = ClientId ;// Session[ClientId] as string;
                var clientSecret = ClientSecret;// Session[ClientSecret] as string;

                // Exchange the 'code' for an authorization/refresh token pair
                // var authSession = await ExchangeCodeForTokenPair(code, clientId, clientSecret);

                var boxClient = new BoxClient(new BoxConfig(clientId, clientSecret, new Uri("http://localhost:1176/Auth/Callback")));
                OAuthSession authSession = await boxClient.Auth.AuthenticateAsync(code);

                

                // TODO:


                // Clear out the session variables for security
                ClearSession();

                var authInfo = new AuthModel { ClientId = clientId, ClientSecret = clientSecret, AuthToken = authSession.AccessToken, RefreshToken = authSession.RefreshToken };
                return View("Index", authInfo);
            }
            catch (BoxException e)
            {
                // Response.StatusCode = (int)e.StatusCode;
                return Error(". . .", e.Message);
            }
            catch (Exception e)
            {
                Response.StatusCode = 500;
                return Error(e.Message, e.StackTrace);
            }
        }
示例#10
0
 /// <summary>
 /// Exchange the Box authorization code for an access/refresh token pair
 /// </summary>
 /// <param name="code">The Box authorization code provided when the user is redirected back to this site from Box</param>
 /// <param name="clientId">The Box application's client ID</param>
 /// <param name="clientSecret">The Box application's client secret</param>
 private static async Task<OAuthSession> ExchangeCodeForTokenPair(string code, string clientId, string clientSecret)
 {
     var boxClient = new BoxClient(new BoxConfig(clientId, clientSecret, new Uri("http://localhost:1176/Auth/Callback")));
     OAuthSession authSession = await boxClient.Auth.AuthenticateAsync(code);
     return authSession;
 }
        public static async Task<BoxClient> Login(string account, string code)
        {
            if (string.IsNullOrEmpty(account))
                throw new ArgumentNullException(nameof(account));

            string refreshToken = LoadRefreshToken(account);

            var client = default(BoxClient);
            var config = new BoxConfig(Secrets.CLIENT_ID, Secrets.CLIENT_SECRET, new Uri(BOX_LOGIN_DESKTOP_URI));

            var response = default(OAuthSession);
            if (!string.IsNullOrEmpty(refreshToken)) {
                client = new BoxClient(config, new OAuthSession(null, refreshToken, 0, "bearer"));
                response = await client.Auth.RefreshAccessTokenAsync(refreshToken);
            }

            if (response == null) {
                client = new BoxClient(config, null);
                if (string.IsNullOrEmpty(code)) {
                    Uri authenticationUri = client.Config.AuthCodeUri;
                    code = GetAuthCode(account, authenticationUri, new Uri(BOX_LOGIN_DESKTOP_URI));
                    if (string.IsNullOrEmpty(code))
                        throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.RetrieveAuthenticationCodeFromUri, authenticationUri.ToString()));
                }

                response = await client.Auth.AuthenticateAsync(code);
            }

            SaveRefreshToken(account, response != null ? response.RefreshToken : null);

            return client;
        }
 public BoxContext(BoxClient client)
 {
     Client = client;
 }