Example #1
0
        public static async Task <string> GetAccessToken(string sessionId, string localId)
        {
            var filterBuilder = Builders <BsonDocument> .Filter;
            var filter        = filterBuilder.Eq("_id", new ObjectId(sessionId)) & filterBuilder.Eq("local_id", localId);
            var users         = Database.GetCollection <BsonDocument>("users");
            var docs          = await users.Find(filter).ToListAsync();

            var doc         = docs.First();
            var accessToken = (string)doc["access_token"];

            DateTime expiresAt = (DateTime)doc["expires_at"];

            if (expiresAt < DateTime.UtcNow)
            {
                // refresh the access_token maintaining the session id (document ID on the database)
                ThreeLeggedApi    oauth  = new ThreeLeggedApi();
                DynamicDictionary bearer = await oauth.RefreshtokenAsync(ConfigVariables.FORGE_CLIENT_ID, ConfigVariables.FORGE_CLIENT_SECRET, "refresh_token", (string)doc["refresh_token"]);

                var update = Builders <BsonDocument> .Update
                             .Set("access_token", (string)bearer.Dictionary["access_token"])
                             .Set("refresh_token", (string)bearer.Dictionary["refresh_token"])
                             .Set("expires_at", DateTime.UtcNow.AddSeconds((long)bearer.Dictionary["expires_in"]));

                var result = await users.UpdateOneAsync(filter, update);

                accessToken = (string)bearer.Dictionary["access_token"];
            }

            return(accessToken);
        }
        [Route("api/forge/callback/oauth")] // see Web.Config FORGE_CALLBACK_URL variable
        public async Task <HttpResponseMessage> OAuthCallback(string code, string state)
        {
            ThreeLeggedApi    oauth  = new ThreeLeggedApi();
            DynamicDictionary bearer = await oauth.GettokenAsync(ConfigVariables.FORGE_CLIENT_ID, ConfigVariables.FORGE_CLIENT_SECRET, oAuthConstants.AUTHORIZATION_CODE, code, ConfigVariables.FORGE_CALLBACK_URL);

            // the local_id of the requester machine should be provised on the original
            // login call as passed as state
            if (!string.IsNullOrWhiteSpace(state))
            {
                bearer.Dictionary.Add("local_id", state);
            }

            // the respose come with expires_in in minutes, so let's also store the absolute time
            bearer.Dictionary.Add("expires_at", DateTime.UtcNow.AddSeconds((long)bearer.Dictionary["expires_in"]));

            // at this point we can store the access & refresh token on a database and return
            // the respective DB unique ID, that way the application can refresh the token in
            // and the client will not see it.
            string sessionIdUnprotected = await OAuthDB.RegisterUser(bearer);

            // and encrypt the database ID to send to the user
            string sessionIdProtected = Convert.ToBase64String(System.Web.Security.MachineKey.Protect(Encoding.UTF8.GetBytes(sessionIdUnprotected)));

            // return to user
            HttpResponseMessage res = Request.CreateResponse(System.Net.HttpStatusCode.OK);

            res.Content = new StringContent(sessionIdProtected, Encoding.UTF8, "text/plain");

            return(res);
        }
Example #3
0
        /// <summary>
        /// Refresh the credentials (internal & external)
        /// </summary>
        /// <returns></returns>
        public async Task RefreshAsync()
        {
            if (ExpiresAt > DateTime.Now)
            {
                return;
            }

            ThreeLeggedApi oauth = new ThreeLeggedApi();

            dynamic credentialInternal = await oauth.RefreshtokenAsync(
                Config.GetAppSetting("FORGE_CLIENT_ID"), Config.GetAppSetting("FORGE_CLIENT_SECRET"),
                "refresh_token", RefreshToken, new Scope[] { Scope.DataRead, Scope.DataCreate, Scope.DataWrite, Scope.ViewablesRead });

            dynamic credentialPublic = await oauth.RefreshtokenAsync(
                Config.GetAppSetting("FORGE_CLIENT_ID"), Config.GetAppSetting("FORGE_CLIENT_SECRET"),
                "refresh_token", credentialInternal.refresh_token, new Scope[] { Scope.ViewablesRead });

            TokenInternal = credentialInternal.access_token;
            TokenPublic   = credentialPublic.access_token;
            RefreshToken  = credentialPublic.refresh_token;
            ExpiresAt     = DateTime.Now.AddSeconds(credentialInternal.expires_in);

            // update the record on our database for the tokens and refresh token
            await OAuthDB.Register(await GetUserId(this), JsonConvert.SerializeObject(this));
        }
Example #4
0
        private void WebBrowser_LoadError(object sender, CefSharp.LoadErrorEventArgs e)
        {
            Uri uri = new Uri(e.FailedUrl);

            Debug.Print("WebBrowser_LoadError >> e.FailedUrl : " + e.FailedUrl);

            // get th host name from the full URL, e.g.:
            // https://myhost.com >> myhost.com
            string host = tbxCallbackUrl.Text.Split(new string[] { "//" }, StringSplitOptions.RemoveEmptyEntries)[1].ToLower();

            if (uri.Host.ToLower() == host)
            {
                // Get the code
                string code = HttpUtility.ParseQueryString(uri.Query).Get("code");

                // Navigate to something else to remove the
                // bad page
                webBrowser.Load(null);

                // Turn the code into access token
                var authApi  = new ThreeLeggedApi();
                var response = authApi.Gettoken(tbxClientId.Text, tbxClientSecret.Text, "authorization_code", code, tbxCallbackUrl.Text);
                logInInfo.accessToken  = response["access_token"];
                logInInfo.refreshToken = response["refresh_token"];
                logInInfo.expiresIn    = response["expires_in"];
                logInInfo.clientId     = tbxClientId.Text;
                logInInfo.clientSecret = tbxClientSecret.Text;

                //this.DialogResult = DialogResult.OK;
                //this.Close();
                closeDialog();
            }
        }
        /// <summary>
        /// Perform the OAuth authorization via code
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static async Task <Credentials> CreateFromCodeAsync(string code, IResponseCookies cookies)
        {
            ThreeLeggedApi oauth = new ThreeLeggedApi();

            dynamic credentialInternal = await oauth.GettokenAsync(
                GetAppSetting("FORGE_CLIENT_ID"), GetAppSetting("FORGE_CLIENT_SECRET"),
                oAuthConstants.AUTHORIZATION_CODE, code, GetAppSetting("FORGE_CALLBACK_URL")
                );

            dynamic credentialPublic = await oauth.RefreshtokenAsync(
                GetAppSetting("FORGE_CLIENT_ID"), GetAppSetting("FORGE_CLIENT_SECRET"),
                "refresh_token", credentialInternal.refresh_token, new Scope[] { Scope.ViewablesRead }
                );

            Credentials credentials = new Credentials();

            credentials.TokenInternal = credentialInternal.access_token;
            credentials.TokenPublic   = credentialPublic.access_token;
            credentials.RefreshToken  = credentialPublic.refresh_token;
            credentials.ExpiresAt     = DateTime.Now.AddSeconds(credentialInternal.expires_in);

            cookies.Append(FORGE_COOKIE, JsonConvert.SerializeObject(credentials));

            return(credentials);
        }
Example #6
0
        private void btnLogIn_Click(object sender, EventArgs e)
        {
            var authApi = new ThreeLeggedApi();
            var urlPath = authApi.Authorize(tbxClientId.Text, "code", tbxCallbackUrl.Text, logInInfo.scopes);

            //webBrowser.Url = new Uri(urlPath);
            webBrowser.Load(urlPath);
        }
Example #7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            ThreeLeggedApi oAuth3legged = new ThreeLeggedApi();
            string         oauthUrl     = oAuth3legged.Authorize(
                ConfigVariables.FORGE_CLIENT_ID,
                oAuthConstants.CODE,
                ConfigVariables.FORGE_CALLBACK_URL,
                new Scope[] { Scope.DataRead },
                Page.Request.QueryString["localId"]);

            Response.Redirect(oauthUrl);
        }
Example #8
0
        public string GetOAuthURL()
        {
            // prepare the sign in URL
            Scope[]        scopes          = { Scope.DataRead };
            ThreeLeggedApi _threeLeggedApi = new ThreeLeggedApi();
            string         oauthUrl        = _threeLeggedApi.Authorize(
                Credentials.GetAppSetting("FORGE_CLIENT_ID"),
                oAuthConstants.CODE,
                Credentials.GetAppSetting("FORGE_CALLBACK_URL"),
                new Scope[] { Scope.DataRead, Scope.DataCreate, Scope.DataWrite, Scope.ViewablesRead });

            return(oauthUrl);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsForgeAuthorized)
            {
                // redirect to Autodesk Accounts Sign-in page
                ThreeLeggedApi _threeLeggedApi = new ThreeLeggedApi();
                string         oauthUrl        = _threeLeggedApi.Authorize(
                    ConfigVariables.FORGE_CLIENT_ID,
                    oAuthConstants.CODE,
                    ConfigVariables.FORGE_CALLBACK_URL,
                    new Scope[] { Scope.DataRead, Scope.DataCreate, Scope.AccountWrite, Scope.BucketDelete });
                Response.Redirect(oauthUrl);
            }

            return;
        }
        public string GetOAuthURL()
        {
            Scope[]        scopes          = { Scope.DataRead };
            ThreeLeggedApi _threeLeggedApi = new ThreeLeggedApi();
            string         oauthUrl        = _threeLeggedApi.Authorize(
                Startup.Configuration["ForgeAPIID:FORGE_CLIENT_ID"],
                oAuthConstants.CODE,
                Startup.Configuration["ForgeAPIID:FORGE_CALLBACK_URL"],
                new Scope[] { Scope.DataRead, Scope.ViewablesRead }
                );

            // string url=Uri.EscapeDataString(oauthUrl);
            string url = Uri.UnescapeDataString(oauthUrl);

            return(oauthUrl);
        }
Example #11
0
        /// <summary>
        /// Refresh the credentials (internal & external)
        /// </summary>
        /// <returns></returns>
        private async Task RefreshAsync()
        {
            ThreeLeggedApi oauth = new ThreeLeggedApi();

            dynamic credentialInternal = await oauth.RefreshtokenAsync(
                GetAppSetting("FORGE_CLIENT_ID"), GetAppSetting("FORGE_CLIENT_SECRET"),
                "refresh_token", RefreshToken, new Scope[] { Scope.DataRead, Scope.DataCreate, Scope.DataWrite, Scope.ViewablesRead });

            dynamic credentialPublic = await oauth.RefreshtokenAsync(
                GetAppSetting("FORGE_CLIENT_ID"), GetAppSetting("FORGE_CLIENT_SECRET"),
                "refresh_token", credentialInternal.refresh_token, new Scope[] { Scope.ViewablesRead });

            TokenInternal = credentialInternal.access_token;
            TokenPublic   = credentialPublic.access_token;
            RefreshToken  = credentialPublic.refresh_token;
            ExpiresAt     = DateTime.Now.AddSeconds(credentialInternal.expires_in);
        }
Example #12
0
        public static async Task <Credencial> CreateFromCodeAsync(string code, IResponseCookies cookies)
        {
            ThreeLeggedApi oauth = new ThreeLeggedApi();

            dynamic credentialInternal = await oauth.GettokenAsync(
                GetAppSetting("FORGE_CLIENT_ID"), GetAppSetting("FORGE_CLIENT_SECRET"),
                oAuthConstants.AUTHORIZATION_CODE, code, GetAppSetting("FORGE_CALLBACK_URL"));

            dynamic credentialPublic = await oauth.RefreshtokenAsync(
                GetAppSetting("FORGE_CLIENT_ID"), GetAppSetting("FORGE_CLIENT_SECRET"),
                "refresh_token", credentialInternal.refresh_token, new Scope[] { Scope.ViewablesRead });

            Credencial credencial = new Credencial();

            credencial.FORGE_CLIENT_ID = GetAppSetting("FORGE_CLIENT_ID");
            credencial.TokenInternal   = credentialInternal.access_token;
            credencial.TokenPublic     = credentialPublic.access_token;
            credencial.RefreshToken    = credentialPublic.refresh_token;
            credencial.ExpiresAt       = DateTime.Now.AddSeconds(credentialInternal.expires_in);

            //cookies.Append(FORGE_COOKIE, JsonConvert.SerializeObject(credentials));

            var client   = new MongoClient("mongodb://localhost:27017/auth_brass");
            var database = client.GetDatabase("auth_brass");

            var collection = database.GetCollection <BsonDocument>("credenciais");

            var list = await collection.Find(new BsonDocument("FORGE_CLIENT_ID", GetAppSetting("FORGE_CLIENT_ID"))).ToListAsync();

            if (list.Count > 0)
            {
                collection.DeleteOne(list[0]);
            }

            var ver = GetAppSetting("FORGE_CLIENT_ID");

            var bsonDocument = credencial.ToBsonDocument();
            await collection.InsertOneAsync(bsonDocument);

            return(credencial);
        }
        public static async Task <Credentials> CreateFromCodeAsync(string code)
        {
            ThreeLeggedApi oauth             = new ThreeLeggedApi();
            dynamic        credentialInteral = await oauth.GettokenAsync(
                Startup.Configuration["ForgeAPIID:FORGE_CLIENT_ID"], Startup.Configuration["ForgeAPIID:FORGE_CLIENT_SECRET"],
                oAuthConstants.AUTHORIZATION_CODE, code, Startup.Configuration["ForgeAPIID:FORGE_CALLBACK_URL"]);

            dynamic credentialPublic = await oauth.RefreshtokenAsync(
                Startup.Configuration["ForgeAPIID:FORGE_CLIENT_ID"], Startup.Configuration["ForgeAPIID:FORGE_CLIENT_SECRET"],
                "refresh_token", credentialInteral.refresh_token, new Scope[] { Scope.ViewablesRead });

            Credentials credentials = new Credentials
            {
                TokenInternal = credentialInteral.access_token,
                TokenPublic   = credentialPublic.access_token,
                RefreshToken  = credentialPublic.refresh_token,
                ExpiresAt     = DateTime.Now.AddSeconds(credentialInteral.expires_in)
            };

            _session.SetString("ForgeCredentials", JsonConvert.SerializeObject(credentials));
            return(credentials);
        }
        public async Task <bool> refreshToken()
        {
            Debug.Print("refreshToken : Refreshing token...");

            try
            {
                var authApi  = new ThreeLeggedApi();
                var response = await authApi.RefreshtokenAsync(
                    logInInfo.clientId, logInInfo.clientSecret, "refresh_token", logInInfo.refreshToken);

                logInInfo.accessToken  = response["access_token"];
                logInInfo.refreshToken = response["refresh_token"];
                logInInfo.expiresIn    = response["expires_in"];
            }
            catch (Exception ex)
            {
                Debug.Print("refreshToken >> catch : " + ex.Message);
                return(false);
            }

            return(true);
        }
        private async Task <Credentials> RefreshAsync()
        {
            ThreeLeggedApi oauth = new ThreeLeggedApi();

            dynamic credentialInteral = await oauth.RefreshtokenAsync(
                Startup.Configuration["ForgeAPIID:FORGE_CLIENT_ID"], Startup.Configuration["ForgeAPIID:FORGE_CLIENT_SECRET"],
                "refresh_token", RefreshToken, new Scope[] { Scope.ViewablesRead });

            dynamic credentialPublic = await oauth.RefreshtokenAsync(
                Startup.Configuration["ForgeAPIID:FORGE_CLIENT_ID"], Startup.Configuration["ForgeAPIID:FORGE_CLIENT_SECRET"],
                "refresh_token", credentialInteral.refresh_token, new Scope[] { Scope.ViewablesRead });

            Credentials credentials = new Credentials
            {
                TokenInternal = credentialInteral.access_token,
                TokenPublic   = credentialPublic.access_token,
                RefreshToken  = credentialPublic.refresh_token,
                ExpiresAt     = DateTime.Now.AddSeconds(credentialInteral.expires_in)
            };

            return(credentials);
        }
        /// <summary>
        /// Refresh the credentials (internal & external)
        /// </summary>
        /// <returns></returns>
        private async Task RefreshAsync()
        {
            ThreeLeggedApi oauth     = new ThreeLeggedApi();
            TwoLeggedApi   da4rOauth = new TwoLeggedApi(); // added for DA4R

            dynamic credentialInternal = await oauth.RefreshtokenAsync(
                GetAppSetting("FORGE_CLIENT_ID"), GetAppSetting("FORGE_CLIENT_SECRET"),
                "refresh_token", RefreshToken, new Scope[] { Scope.DataRead, Scope.DataCreate, Scope.DataWrite, Scope.ViewablesRead });

            dynamic credentialPublic = await oauth.RefreshtokenAsync(
                GetAppSetting("FORGE_CLIENT_ID"), GetAppSetting("FORGE_CLIENT_SECRET"),
                "refresh_token", credentialInternal.refresh_token, new Scope[] { Scope.ViewablesRead });

            dynamic credentialDa4rInternal = await da4rOauth.AuthenticateAsync(
                GetAppSetting("FORGE_CLIENT_ID"), GetAppSetting("FORGE_CLIENT_SECRET"),
                "client_credentials", new Scope[] { Scope.BucketCreate, Scope.BucketRead, Scope.BucketUpdate, Scope.DataRead, Scope.DataWrite, Scope.DataCreate, Scope.CodeAll });

            TokenInternal     = credentialInternal.access_token;
            TokenPublic       = credentialPublic.access_token;
            DA4RTokenInternal = credentialDa4rInternal.access_token; //added for DA4R
            RefreshToken      = credentialPublic.refresh_token;
            ExpiresAt         = DateTime.Now.AddSeconds(credentialInternal.expires_in);
        }
        [Route("api/forge/callback/oauth")] // see Web.Config FORGE_CALLBACK_URL variable
        public async Task <HttpResponseMessage> OAuthCallback(string code)
        {
            ThreeLeggedApi oauth  = new ThreeLeggedApi();
            dynamic        bearer = await oauth.GettokenAsync(ConfigVariables.FORGE_CLIENT_ID, ConfigVariables.FORGE_CLIENT_SECRET, oAuthConstants.AUTHORIZATION_CODE, code, ConfigVariables.FORGE_CALLBACK_URL);

            OAuth auth = JsonConvert.DeserializeObject <OAuth>(bearer.ToString());

            // You can store the oauth Access Token and Refresh Token on your own authentication approach
            // The Refresh Token can be used later to get a new Access Token


            // For this basic sample, let's sent a Cooke to the end-user with the Access Token that only give
            // access to his/her own data, so no security breach (assuming a HTTPS connection), but there is a
            // accountability concern here (as the end-user will use this token to perform operation on the app behalf)
            HttpResponseMessage res    = Request.CreateResponse(System.Net.HttpStatusCode.Moved /* rorce redirect */);
            CookieHeaderValue   cookie = new CookieHeaderValue(ConfigVariables.FORGE_OAUTH, auth.AccessToken);

            cookie.Expires = auth.ExpiresAt;
            cookie.Path    = "/";
            res.Headers.AddCookies(new CookieHeaderValue[] { cookie });
            res.Headers.Location = new Uri("/", UriKind.Relative); // back to / (root, default)

            return(res);
        }