示例#1
0
        public async Task <RedirectResult> AuthorizeCallback(string code, string state)
        {
            if (string.IsNullOrEmpty(state) || !Memory.TryGetValue(state, out _))
            {
                // Unrecognized Nonce, go back home
                return(BackToHome());
            }

            // Delete the nonce now, we are done with it
            Memory.Remove(state);

            // Check if we already recognize this code, if not, build it
            var codeEntity = await DBContext.OAuthCodes.FindAsync(code);

            if (codeEntity == null)
            {
                codeEntity = new OAuthCodeEntity
                {
                    Value = code
                };
                await DBContext.AddAsync(codeEntity);

                await DBContext.SaveChangesAsync();
            }

            var token = string.IsNullOrEmpty(codeEntity.UserId) ? null :
                        DBContext
                        .OAuthTokens
                        .FirstOrDefault(t =>
                                        t.UserId == codeEntity.UserId && (t.Expiry == null || t.Expiry.Value > DateTime.Now)
                                        );

            // This user already has a valid access token, lets just use that instead
            if (token != null)
            {
                return(BackToHome(token));
            }

            // This is a new, unrecognized user, try and fetch an access token

            var tokenUri = UriPath.Combine(Config.PathOfExileApi.Route, "/OAuth/Token");

            var redirectUri = Url.Action("TokenCallback", "OAuth", null, Request.Scheme);
            var queryParams = new Dictionary <string, string>
            {
                { "client_id", Config.PathOfExileApi.ClientId },
                { "client_secret", Config.PathOfExileApi.ClientSecret },
                { "code", code },
                { "grant_type", "authorization_code" },
                { "redirect_uri", redirectUri }
            };

            var tokenQuery = QueryHelpers.AddQueryString(tokenUri, queryParams);

            return(Redirect(tokenQuery));
        }
示例#2
0
        public Tuple <OAuthErrorType, string> GetCode(string clientID, ICollection <string> scopes)
        {
            if (VerifyScopes(scopes) == OAuthErrorType.InvalidScope)
            {
                return(Tuple.Create(OAuthErrorType.InvalidScope, String.Empty));
            }

            OAuthCodeEntity entity = new OAuthCodeEntity()
            {
                Code             = RandomGenerator.GeneratorRandomNQCode(32),
                ClientID         = clientID,
                TimeoutTimestamp = ConvertTimespan.Get(DateTime.Now.AddMinutes(10)),
                Scopes           = scopes
            };

            AccessCodeDataProvider.Instance.Insert(entity);
            return(Tuple.Create(OAuthErrorType.NoError, entity.Code));
        }
示例#3
0
        public Tuple <OAuthErrorType, OAuthTokenEntity> GetToken(string clientID, string code)
        {
            OAuthCodeEntity codeEntity = AccessCodeDataProvider.Instance.Get(code, clientID);

            if (codeEntity == null)
            {
                return(Tuple.Create(OAuthErrorType.UnAuthorizedClient, new OAuthTokenEntity()));
            }
            ClientEntity     clientEntity = ClientInformationDataProvider.Instance.GetClientMetadata(clientID);
            OAuthTokenEntity accessToken  = new OAuthTokenEntity()
            {
                AccessToken  = RandomGenerator.GeneratorRandomNQCode(32),
                TokenType    = "authorization_code",
                ExpiresIn    = clientEntity.ExpiresIn,
                RefreshToken = RandomGenerator.GeneratorRandomNQCode(32),
                Scopes       = codeEntity.Scopes,
                StartTime    = ConvertTimespan.Get(DateTime.Now)
            };

            TokenDataProvider.Instance.Insert(accessToken);

            return(Tuple.Create(OAuthErrorType.NoError, accessToken));
        }
 internal void Insert(OAuthCodeEntity entity)
 {
     this.GetCollection <OAuthCodeEntity>().InsertOne(entity);
 }
示例#5
0
        public static async Task Authenticate()
        {
            string redirect_URL              = ConfigurationManager.AppSettings.Get("OAUTH_REDIRECT");
            string gitkraken_authorize_URL   = ConfigurationManager.AppSettings.Get("GITKRAKEN_AUTHORIZE");
            string gitkraken_accessToken_URL = ConfigurationManager.AppSettings.Get("GITKRAKEN_ACCESSTOKEN");
            string clientID     = ConfigurationManager.AppSettings.Get("OAUTH_CLIENTID");
            string clientSecret = ConfigurationManager.AppSettings.Get("OAUTH_SECRET");
            int    loginTimeout = int.Parse(ConfigurationManager.AppSettings.Get("APP_LOGIN_TIMEOUT"));

            string state = randomB64(32);

            _listener = new HttpListener();
            _listener.Prefixes.Add(redirect_URL);
            _listener.Start();

            string request_URL = string.Format("{0}?response_type=code&scope=board:write user:read&state={1}&client_id={2}", new object[] {
                gitkraken_authorize_URL,
                state,
                clientID
            });

            System.Diagnostics.Process.Start(request_URL);

            Timer timeoutTimer = new Timer
            {
                Enabled   = true,
                AutoReset = false,
                Interval  = loginTimeout
            };

            timeoutTimer.Elapsed += new ElapsedEventHandler(StopListening);

            HttpListenerContext requestContext = null;

            try
            {
                requestContext = await _listener.GetContextAsync();
            }
            catch (HttpListenerException)
            {
                SendPage("UI\\HTML\\OAuthErrorPage.html", requestContext.Response);
                requestContext.Response.StatusCode = 500;;
                LastErrorMessage = "You took too long to login. Try again.";

                return;
            }

            OAuthCodeEntity oAuthResponse = OAuthCodeEntity.CreateEntity(requestContext.Request);

            if (!state.Equals(oAuthResponse.State))
            {
                SendPage("UI\\HTML\\OAuthErrorPage.html", requestContext.Response);
                requestContext.Response.StatusCode = 500;

                throw new OAuthException("Error Validation Token. Please Try Again.");
            }
            else
            {
                SendPage("UI\\HTML\\OAuthSuccessPage.html", requestContext.Response);
                requestContext.Response.StatusCode = 200;
            }

            requestContext.Response.Close();
            _listener.Stop();

            AccessTokenSegment tokenRequestBody = new AccessTokenSegment("authorization_code", clientID, clientSecret, oAuthResponse.Code);

            HttpRequest <AccessTokenSegment> tokenRequest = new HttpRequest <AccessTokenSegment>(gitkraken_accessToken_URL, HttpMethod.Post, tokenRequestBody, null, AccessToken);

            AccessToken = await Requesting.MakeRequest <OAuthTokenEntity>(tokenRequest);
        }