/// <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);
        }
        [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
        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);
        }
        [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);
        }