示例#1
0
        CharacterAuthInfo InstallAuthToken(Stream stream)
        {
            StreamReader sr   = new StreamReader(stream);
            string       json = sr.ReadToEnd();

            AuthToken token = JsonConvert.DeserializeObject <AuthToken>(json);

            CharacterAuthInfo authInfo = UnpackToken(token);

            List <CharacterAuthInfo> authInfos = ReadAuthTokens();

            for (int i = 0; i < authInfos.Count; i++)
            {
                if (authInfos[i].CharacterID == authInfo.CharacterID)
                {
                    authInfos.RemoveAt(i);
                    i--;
                }
            }

            authInfos.Add(authInfo);

            WriteAuthTokens(authInfos);

            return(authInfo);
        }
示例#2
0
        public CharacterAuthInfo RefreshToken(CharacterAuthInfo authInfo)
        {
            byte[] requestData;

            {
                StringBuilder tokenSB = new StringBuilder();
                tokenSB.Append("grant_type=refresh_token");
                tokenSB.Append("&refresh_token=");
                tokenSB.Append(WebUtility.UrlEncode(authInfo.RefreshToken));
                tokenSB.Append("&client_id=");
                tokenSB.Append(this.clientID);

                string tokenStr = tokenSB.ToString();

                requestData = Encoding.ASCII.GetBytes(tokenStr);
            }

            HttpWebRequest webRequest = WebRequest.CreateHttp("https://login.eveonline.com/v2/oauth/token");

            webRequest.Method        = "POST";
            webRequest.ContentType   = "application/x-www-form-urlencoded";
            webRequest.Host          = "login.eveonline.com";
            webRequest.ContentLength = requestData.Length;

            Stream rq = webRequest.GetRequestStream();

            rq.Write(requestData, 0, requestData.Length);
            rq.Close();

            WebResponse response       = webRequest.GetResponse();
            Stream      responseStream = response.GetResponseStream();

            return(InstallAuthToken(responseStream));
        }
示例#3
0
        static CharacterAuthInfo UnpackToken(AuthToken authToken)
        {
            string[] tokenParts = authToken.access_token.Split('.');

            byte[] payload = UrlSafeBase64Decode(tokenParts[1]);

            JsonTextReader reader     = new JsonTextReader(new StringReader(Encoding.ASCII.GetString(payload)));
            JObject        rootObject = (JObject)JToken.ReadFrom(reader);

            JToken subToken;

            if (!rootObject.TryGetValue("sub", out subToken))
            {
                throw new Exception("Missing 'sub' in JWT token");
            }

            JValue subValue    = (JValue)subToken;
            string packedSubID = (string)subValue.Value;

            string charPrefix = "CHARACTER:EVE:";

            if (!packedSubID.StartsWith(charPrefix))
            {
                throw new Exception("Malformed(?) character ID");
            }

            JToken nameToken;

            if (!rootObject.TryGetValue("name", out nameToken))
            {
                throw new Exception("Missing character name");
            }

            CharacterAuthInfo authInfo = new CharacterAuthInfo();

            authInfo.AccessToken       = authToken.access_token;
            authInfo.RefreshToken      = authToken.refresh_token;
            authInfo.ExpirationTimeUTC = DateTime.UtcNow.AddSeconds(authToken.expires_in);
            authInfo.CharacterID       = long.Parse(packedSubID.Substring(charPrefix.Length));
            authInfo.CharacterName     = (string)((JValue)nameToken).Value;

            return(authInfo);
        }
示例#4
0
        public string Authorize(long characterID)
        {
            int index = -1;

            for (int i = 0; i < authInfos.Count; i++)
            {
                if (authInfos[i].CharacterID == characterID)
                {
                    index = i;
                }
            }

            if (index == -1)
            {
                throw new Exception("Bad character ID");
            }

            CharacterAuthInfo authInfo = authInfos[index];

            double expiryTolerance = 60.0;

            double timeToExpiry = authInfo.ExpirationTimeUTC.Subtract(DateTime.UtcNow).TotalSeconds;

            if (timeToExpiry < expiryTolerance)
            {
                Console.WriteLine("Auth token expired for " + authInfo.CharacterName + ", getting a new one...");
                authInfo = RefreshToken(authInfo);
                if (authInfo == null)
                {
                    authInfos.RemoveAt(index);
                    return(null);
                }
                else
                {
                    authInfos[index] = authInfo;
                }
            }

            return(authInfo.AccessToken);
        }
示例#5
0
        List <CharacterAuthInfo> ReadAuthTokens()
        {
            string authTokensPath = GetRootDirectory() + "/" + tokenFilePath;

            try
            {
                using (StreamReader sr = new StreamReader(authTokensPath))
                {
                    List <CharacterAuthInfo> authInfos = new List <CharacterAuthInfo>();

                    int version = int.Parse(sr.ReadLine());
                    if (version != TokenFileVersion)
                    {
                        return(authInfos);
                    }

                    int numTokens = int.Parse(sr.ReadLine());

                    for (int i = 0; i < numTokens; i++)
                    {
                        CharacterAuthInfo authInfo = new CharacterAuthInfo();

                        authInfo.CharacterName     = sr.ReadLine();
                        authInfo.CharacterID       = long.Parse(sr.ReadLine());
                        authInfo.ExpirationTimeUTC = DateTime.FromBinary(long.Parse(sr.ReadLine()));
                        authInfo.AccessToken       = sr.ReadLine();
                        authInfo.RefreshToken      = sr.ReadLine();

                        authInfos.Add(authInfo);
                    }

                    return(authInfos);
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Auth tokens file was unreadable or doesn't exist, creating a new one.");
                return(new List <CharacterAuthInfo>());
            }
        }
示例#6
0
        public void InstallTokenFromUri(string uri)
        {
            if (!uri.StartsWith(callbackURI + "?"))
            {
                Console.WriteLine("Invalid callback URI");
                Environment.ExitCode = -1;
                return;
            }

            Dictionary <string, string> queryParams = new Dictionary <string, string>();

            foreach (string kvp in uri.Substring(callbackURI.Length + 1).Split('&'))
            {
                int    split = kvp.IndexOf('=');
                string key, value;
                if (split < 0)
                {
                    key   = kvp;
                    value = "";
                }
                else
                {
                    key   = kvp.Substring(0, split);
                    value = kvp.Substring(split + 1);
                }

                queryParams[WebUtility.UrlDecode(key)] = WebUtility.UrlDecode(value);
            }

            string pendingAuthPath = GetRootDirectory() + "/" + this.pendingAuthPath;

            if (!File.Exists(pendingAuthPath))
            {
                Console.WriteLine("No pending authorization was found");
                Environment.ExitCode = -1;
                CloseoutCountdown(10);
                return;
            }

            string keyBase64;
            string expectedState;

            using (StreamReader sr = new StreamReader(pendingAuthPath))
            {
                keyBase64     = sr.ReadLine();
                expectedState = sr.ReadLine();
            }

            if (expectedState != queryParams["state"])
            {
                Console.WriteLine("State from ESI didn't match pending auth, something's weird.");
                Environment.ExitCode = -1;
                CloseoutCountdown(10);
                return;
            }

            string code = queryParams["code"];

            byte[] requestData;

            {
                StringBuilder tokenSB = new StringBuilder();
                tokenSB.Append("grant_type=authorization_code");
                tokenSB.Append("&code=");
                tokenSB.Append(WebUtility.UrlEncode(code));
                tokenSB.Append("&client_id=");
                tokenSB.Append(clientID);
                tokenSB.Append("&code_verifier=");
                tokenSB.Append(keyBase64);

                string tokenStr = tokenSB.ToString();

                requestData = Encoding.ASCII.GetBytes(tokenStr);
            }

            HttpWebRequest webRequest = WebRequest.CreateHttp("https://login.eveonline.com/v2/oauth/token");

            webRequest.Method        = "POST";
            webRequest.ContentType   = "application/x-www-form-urlencoded";
            webRequest.Host          = "login.eveonline.com";
            webRequest.ContentLength = requestData.Length;

            Stream rq = webRequest.GetRequestStream();

            rq.Write(requestData, 0, requestData.Length);
            rq.Close();

            Console.WriteLine("Requesting authorization...");

            WebResponse response       = webRequest.GetResponse();
            Stream      responseStream = response.GetResponseStream();

            CharacterAuthInfo authInfo = InstallAuthToken(responseStream);

            Console.WriteLine("Authorization was successful!  Installed token for character " + authInfo.CharacterName);
            CloseoutCountdown(10);
        }