Exemplo n.º 1
0
        public UserProfile GetUserInfo(TokenResult tokenResult)
        {
            if (tokenResult == null)
            {
                throw new ArgumentNullException("tokenResult");
            }
            bool        isIdTokenNull       = string.IsNullOrEmpty(tokenResult.IdToken);
            UserProfile userProfileFromJson = null;

            if (isIdTokenNull)
            {
                userProfileFromJson = this.GetUserProfileFromJson(this.GetJsonProfileFromAccessToken(tokenResult.AccessToken));
            }
            else
            {
                userProfileFromJson = this.GetUserProfileFromJson(this.GetJsonProfileFromIdToken(tokenResult.IdToken));
            }
            if (!string.IsNullOrEmpty(userProfileFromJson.UserId))
            {
                return(userProfileFromJson);
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 2
0
        public TokenResult Tokenize(TextReader reader)
        {
            var valueRead = reader.Read();

            if (valueRead < 0)
            {
                return(TokenResult.Fail(0));
            }

            var chr        = (char)valueRead;
            var identifier = string.Empty;

            if (!this.IsIdentifierBeginning(chr))
            {
                return(TokenResult.Fail(-1));
            }

            identifier += chr;

            while ((valueRead = reader.Read()) > 0)
            {
                chr = (char)valueRead;

                if (char.IsLetterOrDigit(chr) || chr == '_')
                {
                    identifier += chr;
                }
                else
                {
                    return(new TokenResult(-1, new Token(TokenType.Identifier, identifier)));
                }
            }

            return(new TokenResult(0, new Token(TokenType.Identifier, identifier)));
        }
Exemplo n.º 3
0
        public async Task GetAsync_PostReturnsOK_ReturnsToken()
        {
            var tokenResult = new TokenResult
            {
                Token = "super-token"
            };
            HttpRequestMessage request = null;

            _httpHandlerMock.Protected()
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>())
            .ReturnsAsync(
                new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(
                    "[{ \"name\": \"N1\", \"distance\": 333 }, { \"name\": \"N2\", \"distance\": 446 }]")
            })
            .Callback((HttpRequestMessage r, CancellationToken ct) => request = r);

            var result = await _sut.GetAsync(tokenResult);

            result.Should().HaveCount(2);
            result.Should().Contain(s => (s.Name == "N1") && (s.Distance == 333));
            result.Should().Contain(s => (s.Name == "N2") && (s.Distance == 446));
            AssertRequest(request, tokenResult);
        }
Exemplo n.º 4
0
        public void PopulateProviderCredentials_MicrosoftAccount_CreatesExpectedCredentials()
        {
            const string UserIdClaimValue = "MicrosoftId";

            MicrosoftAccountCredentials credentials = new MicrosoftAccountCredentials();

            TokenResult tokenResult = new TokenResult();

            tokenResult.Properties.Add(TokenResult.Authentication.AccessTokenName, "TestAccessToken");
            tokenResult.Properties.Add(TokenResult.Authentication.RefreshTokenName, "TestRefreshToken");
            tokenResult.Properties.Add("AccessTokenExpiration", "2015-03-12T16:49:28.504Z");
            Dictionary <string, string> claims = new Dictionary <string, string>
            {
                { "Claim1", "Value1" },
                { "Claim2", "Value1" },
                { "Claim3", "Value1" },
                { ClaimTypes.NameIdentifier, UserIdClaimValue }
            };

            tokenResult.Claims = claims;

            MobileAppUser.PopulateProviderCredentials(tokenResult, credentials);

            Assert.Equal("TestAccessToken", credentials.AccessToken);
            Assert.Equal("TestRefreshToken", credentials.RefreshToken);
            Assert.Equal(DateTimeOffset.Parse("2015-03-12T16:49:28.504Z"), credentials.AccessTokenExpiration);
            Assert.Equal(UserIdClaimValue, credentials.UserId);
            Assert.Equal(claims.Count, credentials.Claims.Count);
        }
Exemplo n.º 5
0
        public override IEnumerable<TokenResult> Parse(string input, string UserId)
        {
            var results = new List<TokenResult>();
            results.AddRange(base.Parse(input, UserId));

            if (results.Count > 0)
            {
                var searchTermResult = new TokenResult
                {
                    Length = input.Length - results[0].Length - 1,
                    Start = results[0].Start + results[0].Length + 1,
                    Token =
                        new TokenQuotedPhrase
                        {
                            Value =
                                input.Substring(results[0].Start + results[0].Length + 1)
                        },
                    TokenType = typeof(TokenQuotedPhrase).ToString(),
                    Value = input.Substring(results[0].Start + results[0].Length + 1)
                };
                results.Add(searchTermResult);
            }

            return results;
        }
Exemplo n.º 6
0
        public async Task <IList <Server> > GetAsync(TokenResult token)
        {
            try
            {
                if (TokenShouldBeProvided(token))
                {
                    return(new List <Server>());
                }

                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Token);
                var response = await _httpClient.GetAsync(_endpoint);

                var responseString = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                {
                    _logger.Log(LogLevel.Information, $"Get servers failed: {responseString}.");
                    return(new List <Server>());
                }

                return(JsonConvert.DeserializeObject <IList <Server> >(responseString, _jsonConverterSettings));
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Error, ex, "Unexpected error occured.");

                return(new List <Server>());
            }
        }
Exemplo n.º 7
0
        public async Task <ActionResult <TokenResult> > Login([FromBody] LoginFormModel model)
        {
            var person = PersonService.GetByEmail(model.Email);

            if (person == null)
            {
                return(BadRequest("Email lub hasło jest nieprawidłowe"));
            }

            if (!person.EmailConfirmed)
            {
                return(BadRequest("Konto nie zostało potwierdzone"));
            }

            var result = await _signInManager.CheckPasswordSignInAsync(person, model.Password, true);

            if (result.Succeeded)
            {
                var loggedInUser = new TokenResult()
                {
                    UserName = person.UserName,
                    Token    = AuthService.GenerateToken(person, tokenExpires),
                    Expires  = tokenExpires
                };

                return(Ok(loggedInUser));
            }

            return(BadRequest("Email lub hasło jest nieprawidłowe"));
        }
        public async Task <IActionResult> Create([FromBody] CreateSTokenModel model, [FromServices] IGenerateShortTokenCommand generateShortTokenCommand)
        {
            try
            {
                if (model == null || model.RToken == null)
                {
                    return(BadRequest(new Message("Invalid refresh token provided.")));
                }

                TokenResult sTokenRes = await generateShortTokenCommand.Execute(model.RToken);

                return(Created("", sTokenRes));
            }
            catch (Exception ex)
            {
                //Log error
                await _logger.LogErrorAsync("ShortTokenController.Create", "Exception was thrown", new
                {
                    CreateSTokenModel = model,
                    Exception         = ex
                });

                return(BadRequest(new Message("Something went wrong.")));
            }
        }
Exemplo n.º 9
0
        private async Task Authenticate()
        {
            var client = new RestClient
            {
                BaseUrl = "https://datamarket.accesscontrol.windows.net",
                UserAgent = UserAgent,
            };
            var request = new RestRequest("v2/OAuth2-13", HttpMethod.Post)
            {
                ContentType = ContentTypes.FormUrlEncoded,
                ReturnRawString = true,
            };
            request.AddParameter("client_id", ClientId);
            request.AddParameter("client_secret", ClientSecret);
            request.AddParameter("scope", "http://music.xboxlive.com");
            request.AddParameter("grant_type", "client_credentials");

            var result = await client.ExecuteAsync<string>(request);

            TokenResponse = JsonConvert.DeserializeObject<TokenResult>(result);
            if (TokenResponse != null)
            {
                TokenResponse.TimeStamp = DateTime.Now;
            }
        }
Exemplo n.º 10
0
        public static async Task <TokenResult> GetAccessTokenByRefreshToken(string authority, string clientId, string clientSecret, string refreshToken, string scope)
        {
            TokenResult tokenResult = null;

            scope = "offline_access " + scope; // Add the offline_access scope so we get a refresh token
            HttpRequestMessage httpRequestMessage           = new HttpRequestMessage(HttpMethod.Post, $"{authority}/oauth2/v2.0/token");
            List <KeyValuePair <string, string> > keyValues = new List <KeyValuePair <string, string> >();

            keyValues = new List <KeyValuePair <string, string> >();
            keyValues.Add(new KeyValuePair <string, string>("grant_type", "refresh_token"));
            keyValues.Add(new KeyValuePair <string, string>("client_id", clientId));
            keyValues.Add(new KeyValuePair <string, string>("refresh_token", refreshToken));
            keyValues.Add(new KeyValuePair <string, string>("scope", scope));
            keyValues.Add(new KeyValuePair <string, string>("client_secret", clientSecret));
            httpRequestMessage.Content = new FormUrlEncodedContent(keyValues);
            HttpResponseMessage response = await _httpClient.SendAsync(httpRequestMessage);

            string responseContent = await response.Content.ReadAsStringAsync();

            if (response.IsSuccessStatusCode)
            {
                tokenResult = JsonConvert.DeserializeObject <TokenResult>(responseContent);
            }

            return(tokenResult);
        }
Exemplo n.º 11
0
        static void Main(String[] args)
        {
            RongCloud rongCloud = RongCloud.GetInstance(appKey, appSecret);
            //自定义 api 地址方式
            // RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret,api);
            User User = rongCloud.user;

            /**
             * API 文档: http://www.rongcloud.cn/docs/server_sdk_api/user/user.html#register
             *
             * 注册用户,生成用户在融云的唯一身份标识 Token
             */
            UserModel user = new UserModel
            {
                Id       = "注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token注册用户,生成用户在融云的唯一身份标识 Token",
                Name     = "username",
                Portrait = "http://www.rongcloud.cn/images/logo.png"
            };

            TokenResult result = User.Register(user);

            Console.WriteLine("getToken:  " + result.ToString());

            /**
             *
             * API 文档: http://www.rongcloud.cn/docs/server_sdk_api/user/user.html#refresh
             *
             * 刷新用户信息方法
             */
            Result refreshResult = User.Update(user);

            Console.WriteLine("refresh:  " + refreshResult.ToString());

            Console.ReadLine();
        }
Exemplo n.º 12
0
        public async Task <IActionResult> Post([FromBody] TokenInput model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await _userManager.FindByNameAsync(model.Email).ConfigureAwait(false);

            if (user == null)
            {
                return(NotFound());
            }

            if (!await _userManager.CheckPasswordAsync(user, model.Password).ConfigureAwait(false))
            {
                return(Unauthorized());
            }

            var token = await GetJwtSecurityToken(user).ConfigureAwait(false);

            var response = new TokenResult
            {
                AccessToken = _tokenHandler.WriteToken(token),
                TokenType   = JwtBearerDefaults.AuthenticationScheme,
                ExpiresAt   = token.Payload.ValidTo
            };

            return(new OkObjectResult(response));
        }
Exemplo n.º 13
0
 private void AssertRequest(HttpRequestMessage request, TokenResult token)
 {
     request.Should().NotBeNull();
     request.Method.Should().Be(HttpMethod.Get);
     request.RequestUri.OriginalString.Should().Be("http://localhost/servers");
     request.Headers.Authorization.Should().BeEquivalentTo(new AuthenticationHeaderValue("Bearer", token.Token));
 }
Exemplo n.º 14
0
        public void ShouldReadValidDecimal(string text, string expected)
        {
            var result = new TokenResult();

            Assert.True(new Scanner(text).ReadDecimal(result));
            Assert.Equal(expected, result.Text);
        }
Exemplo n.º 15
0
        public override async Task <ProfileResult> ProfileAsync(TokenResult token, CancellationToken cancellationToken)
        {
            var query = HttpUtility.ParseQueryString(string.Empty);

            query.Add("fields", "email,first_name,last_name,verified");
            query.Add("access_token", token.AccessToken);

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://graph.facebook.com");

                var response = await client.GetAsync("me/?" + query.ToString(), cancellationToken);

                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync();

                    var profile = JsonConvert.DeserializeObject <FacebookProfileResult>(json);

                    return(new ProfileResult(profile));
                }
            }

            return(null);
        }
Exemplo n.º 16
0
        public IHttpActionResult Login([FromBody] RequestLogin request)
        {
            var userBll     = new UserManage();
            var tokenResult = new TokenResult();
            var isSuccess   = IdentityValid.ValidateSignature(request.Signature, request.TimeStamp, request.Nonce, request.Appid);

            if (isSuccess)
            {
                if (userBll.Login(request.UserName, request.Pwd))
                {
                    tokenResult.token     = IdentityValid.CreateToken(request.UserName, request.Appid);
                    tokenResult.IsSuccess = true;
                }
                else
                {
                    tokenResult.IsSuccess = false;
                    tokenResult.Msg       = "用户密码错误!";
                }
            }
            else
            {
                tokenResult.IsSuccess = false;
                tokenResult.Msg       = "签名验证失败!";
            }
            return(Json(tokenResult));
        }
Exemplo n.º 17
0
        private TokenResult GetUnitedToken(string teamName)
        {
            var inTheMid = " Юнайтед ";
            var inTheEnd = " Юнайтед";

            if (!(teamName.Contains(inTheMid) || teamName.EndsWith(inTheEnd)))
            {
                return new TokenResult
                       {
                           Token          = null,
                           RemainingTitle = teamName
                       }
            }
            ;

            var result = new TokenResult();

            result.Token          = TokenizerHelper.GetUnitedToken();
            result.RemainingTitle = teamName.Replace(inTheMid, string.Empty)
                                    .Replace(inTheEnd, string.Empty)
                                    .Trim();

            return(result);
        }
    }
        public async Task GetRawTokenAsync_SendsCorrectRequest()
        {
            HttpConfiguration config = new HttpConfiguration();

            config.SetMobileAppSettingsProvider(new MobileAppSettingsProvider());

            string      accessToken = "11111";
            string      facebookId  = "22222";
            TokenResult tokenResult = CreateTokenResult(facebookId, accessToken);

            MockHttpMessageHandler handlerMock = new MockHttpMessageHandler(CreateResponse(tokenResult));

            var gatewayUri = "http://test";
            Mock <AppServiceHttpClient> appServiceClientMock = new Mock <AppServiceHttpClient>(new Uri(gatewayUri));

            appServiceClientMock.CallBase = true;
            appServiceClientMock.Setup(c => c.CreateHttpClient())
            .Returns(new HttpClient(handlerMock));

            // Act
            TokenResult result = await appServiceClientMock.Object.GetRawTokenAsync(accessToken, "Facebook");

            // Assert
            Assert.Equal(accessToken, result.Properties[TokenResult.Authentication.AccessTokenName]);
            Assert.Equal(gatewayUri + "/api/tokens?tokenName=Facebook&api-version=2015-01-14", handlerMock.ActualRequest.RequestUri.ToString());
            Assert.Equal(accessToken, handlerMock.ActualRequest.Headers.GetValues("X-ZUMO-AUTH").Single());
            Assert.Equal("MobileAppNetServerSdk", handlerMock.ActualRequest.Headers.GetValues("User-Agent").Single());
        }
Exemplo n.º 19
0
        public static async Task <TokenResult> CheckIfTokenIsValidAsync()
        {
            TokenResult tokenResult = TokenResult.Empty;

            try
            {
                string accessToken = await BlobCache.UserAccount.GetObject <string>("Access Token");

                string refreshToken = await BlobCache.UserAccount.GetObject <string>("Refresh Token");

                DateTime expiration = await BlobCache.UserAccount.GetObject <DateTime>("Expiration");

                ParticleCloud.AccessToken = new ParticleAccessToken(accessToken, refreshToken, expiration);

                if (expiration > DateTime.Now || accessToken == null || accessToken == "")
                {
                    HasValidToken = false;
                    tokenResult   = TokenResult.Invalid;
                }
                else
                {
                    HasValidToken = true;
                }
            }
            catch (KeyNotFoundException e)
            {
                return(TokenResult.Error);
            }

            tokenResult = await CheckIfRefreshIsNeededAsync(tokenResult);

            return(tokenResult);
        }
Exemplo n.º 20
0
        public TokenResult ValidToken(String token)
        {
            TokenResult tokenResult = new TokenResult();

            Byte[]   ba    = StringToByteArray(token);
            String[] dados = Encoding.ASCII.GetString(ba).Split('|');
            DateTime dt    = DateTime.Parse(dados[2]);

            if (this.dalUsuario.Login(dados[0], dados[1]) && dt >= DateTime.Now)
            {
                tokenResult.MessageType   = MessageType.Ok;
                tokenResult.MessageString = Utils.Utils.GetDescriptionEnum(MessageType.Ok);
            }
            else if (this.dalUsuario.Login(dados[0], dados[1]) && dt < DateTime.Now)
            {
                tokenResult.MessageType   = MessageType.TimeExpired;
                tokenResult.MessageString = Utils.Utils.GetDescriptionEnum(MessageType.TimeExpired);
            }
            if (!this.dalUsuario.Login(dados[0], dados[1]))
            {
                tokenResult.MessageType   = MessageType.NotPermition;
                tokenResult.MessageString = Utils.Utils.GetDescriptionEnum(MessageType.NotPermition);
            }
            return(tokenResult);
        }
Exemplo n.º 21
0
        /// <summary>
        /// 获取令牌
        /// </summary>
        public void tk()
        {
            UploadToken uploadToken = new UploadToken();

            string name  = _request.QueryString["name"];
            string size  = _request.QueryString["size"];
            string ext   = name.Substring(name.LastIndexOf('.'));
            string token = SimpleEncryptor.MD5(name + size);

            uploadToken.name  = name;
            uploadToken.size  = string.IsNullOrEmpty(size) ? 0 : int.Parse(size);
            uploadToken.token = token;

            if (!File.Exists(_server.MapPath(_tokenPath + token + ".token")))
            {
                string modified = _request.QueryString["modified"];

                uploadToken.filePath = "";
                uploadToken.modified = modified;

                SetTokenInfo(token, uploadToken);
            }

            TokenResult tokenResult = new TokenResult();

            tokenResult.message = "";
            tokenResult.token   = token;
            tokenResult.success = true;

            string result = JSONHelper.SerializeObject(tokenResult);;

            _response.Write(result);
        }
Exemplo n.º 22
0
        internal SPOnlineConnection(ClientContext context, TokenResult tokenResult, ConnectionType connectionType, int minimalHealthScore, int retryCount, int retryWait, PSCredential credential, string url, string tenantAdminUrl, string pnpVersionTag, PSHost host, bool disableTelemetry, InitializationType initializationType)
        {
            if (!disableTelemetry)
            {
                InitializeTelemetry(context, host, initializationType);
            }

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            TokenResult = tokenResult;
            var coreAssembly = Assembly.GetExecutingAssembly();

            userAgent          = $"NONISV|SharePointPnP|PnPPS/{((AssemblyFileVersionAttribute)coreAssembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version}";
            Context            = context;
            ConnectionType     = connectionType;
            MinimalHealthScore = minimalHealthScore;
            RetryCount         = retryCount;
            RetryWait          = retryWait;
            PSCredential       = credential;
            TenantAdminUrl     = tenantAdminUrl;
            ContextCache       = new List <ClientContext> {
                context
            };
            PnPVersionTag                = pnpVersionTag;
            Url                          = (new Uri(url)).AbsoluteUri;
            ConnectionMethod             = ConnectionMethod.AccessToken;
            context.ExecutingWebRequest += (sender, args) =>
            {
                args.WebRequestExecutor.WebRequest.UserAgent            = userAgent;
                args.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + CurrentConnection.AccessToken;
            };
        }
Exemplo n.º 23
0
            private static TokenResult GetAccessToken(string AuthorizationCode)
            {
                var parameters = new NameValueCollection
                {
                    { "client_id", msa_client_id },
                    { "client_secret", msa_client_secret },
                    { "grant_type", "authorization_code" },
                    { "code", AuthorizationCode }
                };
                var result = OAuthUtility.ExecuteRequest
                             (
                    "POST",
                    "https://api.dropbox.com/1/oauth2/token",
                    parameters,
                    null
                             );

                if (result.ContainsKey("error"))
                {
                    return(null);
                }
                else
                {
                    TokenResult token = OAuth2AccessTokenToTokenResult(new OAuth2AccessToken(result));
                    return(token);
                }
            }
Exemplo n.º 24
0
        public void getSinaClient()
        {
            string code = "";

            if (string.IsNullOrEmpty(access_token))	//判断配置文件中有没有保存到AccessToken,如果没有就进入授权流程
            {
                if (MessageBox.Show("新浪微博未授权或授权已过期,请重新授权!", "注意", MessageBoxButtons.OKCancel, MessageBoxIcon.Error) == DialogResult.OK)
                {
                    Forms.SinaWBOauth sinaWbForm = new Forms.SinaWBOauth();
                    sinaWbForm.thread_in = "1";
                    if (sinaWbForm.ShowDialog() == DialogResult.OK)
                    {
                        if (sinaWbForm.retrun_url.Contains("code="))
                        {
                            string[] url = sinaWbForm.retrun_url.Split('=');
                            if (url.Length > 0) { code = url[1]; }
                            oauth = new NetDimension.Weibo.OAuth(app_key, app_secret, callback_url);
                            at = oauth.GetAccessTokenByAuthorizationCode(code);
                            xmlutil.SetValue("AccessToken", at.Token);
                            sina = new Client(new OAuth(app_key, app_secret, at.Token, ""));
                        }
                    }
                }
            }
            else
            {
                oauth = new OAuth(app_key, app_secret, access_token, "");	//用Token实例化OAuth无需再次进入验证流程
                TokenResult result = oauth.VerifierAccessToken();
                if (result == TokenResult.Success)
                {
                    sina = new Client(oauth);
                }
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Returns the claims associated with the Microsoft Account token,
        /// or reports errors if any occur.
        /// </summary>
        /// <returns></returns>
        public async Task <IList <string> > Get()
        {
            try
            {
                var runtime = Runtime.FromAppSettings(Request);
                if (runtime == null)
                {
                    return(new[] { "No runtime" });
                }
                var user = runtime.CurrentUser;
                if (user == null)
                {
                    return(new[] { "No user" });
                }
                TokenResult token = await user.GetRawTokenAsync("microsoftaccount");

                if (token == null)
                {
                    return(new[] { "No token" });
                }
                return(token.Claims.Select(c => $"{c.Key}: {c.Value}").ToList());
            }
            catch (Exception x)
            {
                return(new[] { "Exception: " + x });
            }
        }
Exemplo n.º 26
0
        public void PopulateProviderCredentials_Facebook_CreatesExpectedCredentials()
        {
            const string UserIdClaimValue = "FacebookId";

            FacebookCredentials credentials = new FacebookCredentials();

            TokenResult tokenResult = new TokenResult();

            tokenResult.Properties.Add(TokenResult.Authentication.AccessTokenName, "TestAccessToken");
            Dictionary <string, string> claims = new Dictionary <string, string>
            {
                { "Claim1", "Value1" },
                { "Claim2", "Value1" },
                { "Claim3", "Value1" },
                { ClaimTypes.NameIdentifier, UserIdClaimValue }
            };

            tokenResult.Claims = claims;

            MobileAppUser.PopulateProviderCredentials(tokenResult, credentials);

            Assert.Equal("TestAccessToken", credentials.AccessToken);
            Assert.Equal(UserIdClaimValue, credentials.UserId);
            Assert.Equal(claims.Count, credentials.Claims.Count);
        }
Exemplo n.º 27
0
        public IActionResult Login([FromBody] Users user)
        {
            var userData = _userService.Login(user);

            if (userData.Success)
            {
                TokenResult r               = new TokenResult();
                var         tokenHandler    = new JwtSecurityTokenHandler();
                DateTime    expaireDate     = DateTime.Now.AddDays(1);
                var         key             = Encoding.ASCII.GetBytes(_configuration.GetSection("AppSettings:TokenKey").Value);
                var         tokenDescrepter = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[] {
                        new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                        new Claim(ClaimTypes.Name, user.Email)
                    }),
                    Expires            = expaireDate,
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
                };
                var token = tokenHandler.CreateToken(tokenDescrepter);


                r.Token      = tokenHandler.WriteToken(token);
                r.ExpireDate = expaireDate;
                return(Ok(r));
            }
            return(Unauthorized());
        }
Exemplo n.º 28
0
 public TokenResult Login(String Email, String Senha)
 {
     try
     {
         TokenResult loginResult = new TokenResult();
         if (!this.dalUsuario.Login(Email, Senha))
         {
             loginResult.MessageType   = MessageType.NotPermition;
             loginResult.MessageString = Utils.Utils.GetDescriptionEnum(MessageType.NotPermition);
         }
         else
         {
             loginResult.MessageType   = MessageType.Ok;
             loginResult.MessageString = Utils.Utils.GetDescriptionEnum(MessageType.Ok);
             Int32  tempoValidadeToken = Int32.Parse(ConfigurationSettings.AppSettings["TempoValidadeTokenMinutos"]);
             String token = Email + "|" + Senha + "|" + DateTime.Now.AddMinutes(tempoValidadeToken).ToString("yyyy-MM-dd HH:mm:ss");
             Byte[] ba    = Encoding.ASCII.GetBytes(token);
             loginResult.Token = BitConverter.ToString(ba).Replace("-", "");
         }
         return(loginResult);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Exemplo n.º 29
0
        /// <summary>
        /// 直接通过appid和加密字符串获取访问令牌接口
        /// </summary>
        /// <param name="granttype">获取access_token填写client_credential</param>
        /// <param name="appid">用户唯一凭证AppId</param>
        /// <param name="secret">用户唯一凭证密钥,即appsecret</param>
        /// <returns></returns>
        public TokenResult GenerateToken(string granttype, string appid, string secret)
        {
            var keyByteArray       = Encoding.UTF8.GetBytes(secret);
            var signingKey         = new SymmetricSecurityKey(keyByteArray);
            var expires            = DateTime.UtcNow.Add(TimeSpan.FromMinutes(_jwtModel.Expiration));
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            var tokenDescripor     = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[] {
                    new Claim(JwtClaimTypes.Audience, appid),
                    new Claim(JwtClaimTypes.Issuer, _jwtModel.Issuer),
                    new Claim(JwtClaimTypes.Subject, GrantType.ClientCredentials)
                }, granttype),
                Expires = expires,
                //对称秘钥SymmetricSecurityKey
                //签名证书(秘钥,加密算法)SecurityAlgorithms
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(keyByteArray), SecurityAlgorithms.HmacSha256Signature)
            };
            var         tokenHandler = new JwtSecurityTokenHandler();
            var         token        = tokenHandler.CreateToken(tokenDescripor);
            var         tokenString  = tokenHandler.WriteToken(token);
            TokenResult result       = new TokenResult();

            result.AccessToken = tokenString;
            result.ExpiresIn   = (int)TimeSpan.FromMinutes(_jwtModel.Expiration).TotalMinutes;
            return(result);
        }
Exemplo n.º 30
0
        ////move to base method
        private TokenResult GetUnderToken(string teamName)
        {
            var result = new TokenResult();

            var regex   = new Regex(@" до (\d{1,2})");
            var matches = regex.Matches(teamName);

            if (matches.Count > 1)
            {
                throw new ArgumentException("matches.Count = " + matches.Count + "; teamName = " + teamName);
            }
            if (matches.Count == 1)
            {
                var match = matches[0];
                //there other index
                var underMatchYears = match.Value.Substring(4);
                result.Token          = TokenizerHelper.GetUnderToken(underMatchYears);
                result.RemainingTitle = regex.Replace(teamName, string.Empty).Trim();
            }
            else
            {
                result.RemainingTitle = teamName;
            }

            return(result);
        }
Exemplo n.º 31
0
        /// <summary>
        /// 根据登录用户获取token
        /// </summary>
        /// <param name="userInfo">用户信息</param>
        /// <param name="appid">应用Id</param>
        /// <returns></returns>
        public TokenResult GetUserToken(User userInfo, string appid)
        {
            var tokenHandler   = new JwtSecurityTokenHandler();
            var key            = Encoding.UTF8.GetBytes(_jwtModel.Secret);
            var authTime       = DateTime.UtcNow;                                          //授权时间
            var expires        = authTime.Add(TimeSpan.FromMinutes(_jwtModel.Expiration)); //过期时间
            var tokenDescripor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[] {
                    new Claim(JwtClaimTypes.Audience, appid),
                    new Claim(JwtClaimTypes.Issuer, _jwtModel.Issuer),
                    new Claim(JwtClaimTypes.Name, userInfo.Account),
                    new Claim(JwtClaimTypes.Id, userInfo.Id),
                    new Claim(JwtClaimTypes.Role, userInfo.RoleId),
                    new Claim(JwtClaimTypes.Subject, GrantType.Password)
                }),
                Expires = expires,
                //对称秘钥SymmetricSecurityKey
                //签名证书(秘钥,加密算法)SecurityAlgorithms
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var         token       = tokenHandler.CreateToken(tokenDescripor);
            var         tokenString = tokenHandler.WriteToken(token);
            TokenResult result      = new TokenResult();

            result.AccessToken = tokenString;
            result.ExpiresIn   = (int)TimeSpan.FromMinutes(_jwtModel.Expiration).TotalMinutes;
            return(result);
        }
Exemplo n.º 32
0
 private static void Main(string[] args)
 {
     try
     {
         string      url          = @"http://localhost:53879/";
         string      timestamp    = UnixEpochHelper.GetCurrentUnixTimestamp().TotalMilliseconds.ToString();
         string      nonce        = new Random().NextDouble().ToString();
         string      signature    = SignatureString("XXHHAREJDDF", timestamp, nonce);
         string      appended     = string.Format("&signature={0}&timestamp={1}&nonce={2}&appid={3}", signature, timestamp, nonce, "aabbcc");
         string      queryUrl     = url + "api/Auth?userId=test" + appended;
         TokenResult _tokenResult = WebRequest.HttpGet <TokenResult>(queryUrl, SerializationType.Json);
         Console.WriteLine(_tokenResult.Access_token);
         queryUrl = url + "api/Product/1?token=" + _tokenResult.Access_token;
         string  jsonText = WebRequest.HttpGet(queryUrl);
         JObject jsonObj  = JObject.Parse(jsonText);
         string  aa       = jsonObj["Data"].ToString();
         Console.WriteLine(jsonText);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
     finally
     {
         Console.ReadLine();
     }
 }
        /// <summary>
        /// Add OAuth 1.0 Authorization Header to the request 
        /// </summary>
        public override async Task AddOAuthHeader(HttpRequestMessage request)
        {
            // Try to get token result from request. If not found make call to Gateway to get the token.
            if (!this.TryGetTokenResultFromHeader(out tokenResult))
            {
                this.tokenResult = await this.GetTokenResultAsync();
            }

            if(this.tokenResult == null || this.tokenResult.Properties == null)
            {
                Logger.LogError(request, false, "Token result or properties returned are null");
                throw new UnauthorizedAccessException(CommonResource.AccessTokenNotFound);
            }

            if (!this.tokenResult.Properties.ContainsKey("AccessToken"))
            {
                Logger.LogError(request, false, "Couldn't find AccessToken in OAuth TokenResult.");
                throw new UnauthorizedAccessException(CommonResource.AccessTokenNotFound);
            }

            if (!this.tokenResult.Properties.ContainsKey("ConsumerKey"))
            {
                Logger.LogError(request, false, "Couldn't find ConsumerKey in OAuth TokenResult.");
                throw new UnauthorizedAccessException(CommonResource.AccessTokenInvalid);
            }

            if (!this.tokenResult.Properties.ContainsKey("AccessTokenSecret"))
            {
                Logger.LogError(request, false, "Couldn't find AccessTokenSecret in OAuth TokenResult.");
                throw new UnauthorizedAccessException(CommonResource.AccessTokenInvalid);
            }

            Dictionary<string, string> arguments = new Dictionary<string, string>();
            foreach (KeyValuePair<string, string> pair in request.GetQueryNameValuePairs())
            {
                if (!string.IsNullOrEmpty(pair.Value))
                {
                    arguments.Add(pair.Key, pair.Value);
                }
            }

            Uri baseUrl = new Uri(request.RequestUri.GetLeftPart(UriPartial.Path));

            string nonce = GenerateNonce();
            string timestamp = GenerateTimestamp();
            string signature = await this.GenerateSignature(request.Method, baseUrl, nonce, timestamp, arguments);

            string authHeader = string.Format(CultureInfo.InvariantCulture,
                                            AuthHeaderFormatOAuth1,
                                            Uri.EscapeDataString(this.tokenResult.Properties["AccessToken"]),
                                            Uri.EscapeDataString(nonce),
                                            Uri.EscapeDataString(this.tokenResult.Properties["ConsumerKey"]),
                                            Uri.EscapeDataString(HashAlgorithm),
                                            Uri.EscapeDataString(timestamp),
                                            Uri.EscapeDataString(Version),
                                            Uri.EscapeDataString(signature));

            request.Headers.Add(AuthorizationHeader, authHeader);
        }
Exemplo n.º 34
0
 public void Do(TokenResult action, IList<IGameObject> objects)
 {
     foreach(var item in objects)
     {
         if (item.Is(action.Words))
         {
             item.Look();
         }
     }
 }
Exemplo n.º 35
0
        public override IEnumerable<TokenResult> Parse(string input, string UserId)
        {
            var tokenResults = new List<TokenResult>();

            //if "in" is included, we'll defer this to TokenWhoWasIn
            if (input.IndexOf("who is in") > -1 || input.IndexOf("who was in") > -1)
            {
                return tokenResults;
            }

            var results = base.Parse(input, UserId);

            if (results.Any())
            {
                var tokenRequest = results.OrderByDescending(qty => qty.Length).First();

                if (tokenRequest.Start == 0)
                {
                    tokenResults.Add(tokenRequest);

                    var remainder = input.Substring(tokenRequest.Start + tokenRequest.Length + 1).Trim();

                    var topResults = new TokenQueryTop().Parse(remainder, UserId);

                    if (topResults.Any())
                    {
                        //tokenResults.AddRange(topResults);
                        return tokenResults;
                    }

                    var searchTermResult = new TokenResult
                    {
                        Length = input.Length - tokenRequest.Length - 1,
                        Start = tokenRequest.Start + tokenRequest.Length + 1,
                        Token = new TokenQuotedPhrase
                        {
                            Value = input.Substring(tokenRequest.Start + tokenRequest.Length + 1)
                        },
                        TokenType = typeof(TokenQuotedPhrase).ToString(),
                        Value = input.Substring(tokenRequest.Start + tokenRequest.Length + 1)
                    };

                    tokenResults.Add(searchTermResult);
                }
            }

            return tokenResults;
        }
Exemplo n.º 36
0
        // Temporary: Trying out retrieval of Facebook info of logged in user
        private async Task<User> GetFacebookWhoAmIAsync(TokenResult token)
        {
            string id, name;

            // Facebook Claim Type URIs: https://msdn.microsoft.com/en-us/library/azure/gg185967.aspx
            token.Claims.TryGetValue("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", out id);
            token.Claims.TryGetValue("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", out name);

            var profilePictureUrl = await this.GetFacebookProfilePictureUrlAsync(id);

            var user = new User
            {
                //Id = id,
                Name = name,
                PhotoUrl = profilePictureUrl
            };

            return user;
        }
Exemplo n.º 37
0
        public override IEnumerable<TokenResult> Parse(string input, string UserId)
        {
            var results = new List<TokenResult>();
            string testString = input;
            bool isInQuote = false;

            string[] words = input.Split(' ');

            foreach (var word in words)
            {
                if (word.IndexOf("\"") > -1)
                {
                    isInQuote = !isInQuote;
                }

                if (isInQuote)
                {
                    continue;
                }

                double dblTest;

                if (double.TryParse(word.Replace(",", "").Replace("%", ""), out dblTest))
                {
                    int intTest;
                    if (int.TryParse(word.Replace(",", "").Replace("%", ""), out intTest))
                    {
                        var result = new TokenResult
                        {
                            Length = word.Length,
                            Start = testString.IndexOf(word),
                            TokenType = typeof (TokenInt).ToString(),
                            Value = intTest,
                            Token = new TokenInt { Value = intTest }
                        };
                        results.Add(result);
                    }
                }
            }

            return results;
        }
Exemplo n.º 38
0
        public TokenResult Parse(string text)
        {
            TokenResult result = new TokenResult();

            string[] tokens = text.Trim().Split(' ');

            if (tokens.Length >= 1)
            {
                result.Verb = tokens[0];
            }

            if (tokens.Length > 1)
            {
                for (int x = 1; x < tokens.Length; x++)
                {
                    result.Words.Add(tokens[x]);
                }
            }

            return result;
        }
Exemplo n.º 39
0
        public override IEnumerable<TokenResult> Parse(string input, string UserId)
        {
            var results = new List<TokenResult>();
            results.AddRange(base.Parse(input, UserId));
            TokenResult foo = null;
            foreach (var result in results)
            {
                if (result.TokenType.ToLower().IndexOf("preposition") > -1)
                {
                    foo = result;
                }
            }

            if (foo != null)
            {
                results.Remove(foo);
            }

            if (results.Count > 0 && input.Length > results[0].Length)
            {
                var searchTermResult = new TokenResult
                {
                    Length = input.Length - results[0].Length - 1,
                    Start = results[0].Start + results[0].Length + 1,
                    Token =
                        new TokenQuotedPhrase
                        {
                            Value =
                                input.Substring(results[0].Start + results[0].Length + 1)
                        },
                    TokenType = typeof(TokenQuotedPhrase).ToString(),
                    Value = input.Substring(results[0].Start + results[0].Length + 1)
                };
                results.Add(searchTermResult);
            }

            return results;
        }
Exemplo n.º 40
0
        public override IEnumerable<TokenResult> Parse(string input, string UserId)
        {
            var results = new List<TokenResult>();
            string testString = input;

            string[] words = input.Split(' ');

            foreach (var word in words)
            {
                double dblTest;

                if (double.TryParse(word.Replace(",", "").Replace("%", ""), out dblTest))
                {
                    long longTest;
                    if (long.TryParse(word.Replace(",", "").Replace("%", ""), out longTest))
                    {
                        var result = new TokenResult
                        {
                            Length = word.Length,
                            Start = testString.IndexOf(word),
                            TokenType = typeof(TokenLong).ToString(),
                            Value = longTest,
                            Token = new TokenLong { Value = longTest }
                        };

                        results.Add(result);
                    }
                }
            }

            return results;
        }
        private bool TryGetTokenResultFromHeader(out TokenResult result)
        {
            IEnumerable<string> values;
            if (this.Request.Headers.TryGetValues(CommonConstants.tokenResultHeaderName, out values))
            {
                try
                {
                    result = JsonConvert.DeserializeObject<TokenResult>(values.First());
                    return true;
                }
                catch (JsonException)
                {
                    // Igonre the serialization exception. Caller will try to get the token by making a call to gateway directly 
                }
            }

            result = null;
            return false;
        }
Exemplo n.º 42
0
                public string Evaluate(SDFState state, ArrayList arguments)
                {
                    TokenResult result = new TokenResult();

                    state += result;
                    try
                    {
                        parent.EvaluateChildExpressions(state);
                    }
                    finally
                    {
                        state -= result;
                    }
                    return result.Result;
                }
Exemplo n.º 43
0
 public static async Task SaveToken(FileDataStore datastore, string userid, TokenResult token, CancellationToken cancellation)
 {
     cancellation.ThrowIfCancellationRequested();
     if (datastore != null)
     {
         await datastore.StoreAsync<TokenResult>(userid, token);
     }
 }
Exemplo n.º 44
0
 static TokenResult OAuth2AccessTokenToTokenResult(OAuth2AccessToken oauth2)
 {
     TokenResult token = new TokenResult();
     token.AccessToken = oauth2.Value;
     token.Uid = oauth2.CollectionItems["uid"].ToString();
     token.TokenType = oauth2.TokenType;
     return token;
 }
        public static TokenResult GetTestToken(IAsset MyAsset, CloudMediaContext _context, ContentKeyType? keytype = null, SigningCredentials signingcredentials = null, string optionid = null, bool displayUI = false)
        {

            TokenResult MyResult = new TokenResult();

            /// WITH UI
            if (displayUI)
            {
                CreateTestToken form = new CreateTestToken(MyAsset, _context, keytype, optionid) { StartDate = DateTime.Now.AddMinutes(-5), EndDate = DateTime.Now.AddMinutes(Properties.Settings.Default.DefaultTokenDuration) };
                if (form.ShowDialog() == DialogResult.OK)
                {

                    if (form.GetOption != null)
                    {
                        string tokenTemplateString = form.GetOption.Restrictions.FirstOrDefault().Requirements;
                        if (!string.IsNullOrEmpty(tokenTemplateString))
                        {
                            Guid rawkey = EncryptionUtils.GetKeyIdAsGuid(form.GetContentKeyFromSelectedOption.Id);
                            TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString);

                            if (tokenTemplate.OpenIdConnectDiscoveryDocument == null)
                            {
                                MyResult.TokenType = tokenTemplate.TokenType;
                                MyResult.IsTokenKeySymmetric = (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey));
                                MyResult.ContentKeyType = form.GetContentKeyFromSelectedOption.ContentKeyType;

                                if (tokenTemplate.TokenType == TokenType.SWT) //SWT
                                {
                                    MyResult.TokenString = TokenRestrictionTemplateSerializer.GenerateTestToken(tokenTemplate, null, rawkey, form.EndDate);

                                }
                                else // JWT
                                {
                                    IList<Claim> myclaims = null;
                                    myclaims = form.GetTokenRequiredClaims;
                                    if (form.PutContentKeyIdentifier)
                                        myclaims.Add(new Claim(TokenClaim.ContentKeyIdentifierClaimType, rawkey.ToString()));

                                    if (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey))
                                    {
                                        InMemorySymmetricSecurityKey tokenSigningKey = new InMemorySymmetricSecurityKey((tokenTemplate.PrimaryVerificationKey as SymmetricVerificationKey).KeyValue);
                                        signingcredentials = new SigningCredentials(tokenSigningKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);
                                    }
                                    else if (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(X509CertTokenVerificationKey))
                                    {
                                        X509Certificate2 cert = form.GetX509Certificate;
                                        if (cert != null) signingcredentials = new X509SigningCredentials(cert);
                                    }
                                    JwtSecurityToken token = new JwtSecurityToken(issuer: form.GetIssuerUri, audience: form.GetAudienceUri, notBefore: form.StartDate, expires: form.EndDate, signingCredentials: signingcredentials, claims: myclaims);
                                    JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
                                    MyResult.TokenString = handler.WriteToken(token);
                                }
                            }
                        }
                    }
                }
            }
            /////////////////////////////// NO UI
            else if (keytype != null)
            {

                IContentKey key = MyAsset.ContentKeys.Where(k => k.ContentKeyType == keytype).FirstOrDefault();
                if (key != null && key.AuthorizationPolicyId != null)
                {
                    IContentKeyAuthorizationPolicy policy = _context.ContentKeyAuthorizationPolicies.Where(p => p.Id == key.AuthorizationPolicyId).FirstOrDefault();
                    if (policy != null)
                    {
                        IContentKeyAuthorizationPolicyOption option = null;
                        if (optionid == null) // user does not want a specific option
                        {
                            option = policy.Options.Where(o => (ContentKeyRestrictionType)o.Restrictions.FirstOrDefault().KeyRestrictionType == ContentKeyRestrictionType.TokenRestricted).FirstOrDefault();
                        }
                        else
                        {
                            option = policy.Options.Where(o => o.Id == optionid).FirstOrDefault(); // user wants a token for a specific option
                        }

                        if (option != null) // && option.Restrictions.FirstOrDefault() != null && option.Restrictions.FirstOrDefault().KeyRestrictionType == (int)ContentKeyRestrictionType.TokenRestricted)
                        {
                            string tokenTemplateString = option.Restrictions.FirstOrDefault().Requirements;
                            if (!string.IsNullOrEmpty(tokenTemplateString))
                            {
                                Guid rawkey = EncryptionUtils.GetKeyIdAsGuid(key.Id);
                                TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString);

                                if (tokenTemplate.OpenIdConnectDiscoveryDocument == null)
                                {
                                    MyResult.TokenType = tokenTemplate.TokenType;
                                    MyResult.IsTokenKeySymmetric = (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey));
                                    MyResult.ContentKeyType = (ContentKeyType)keytype;

                                    if (tokenTemplate.TokenType == TokenType.SWT) //SWT
                                    {
                                        MyResult.TokenString = TokenRestrictionTemplateSerializer.GenerateTestToken(tokenTemplate, null, rawkey, DateTime.Now.AddMinutes(Properties.Settings.Default.DefaultTokenDuration));
                                    }
                                    else // JWT
                                    {
                                        List<Claim> myclaims = null;
                                        myclaims = new List<Claim>();
                                        myclaims.Add(new Claim(TokenClaim.ContentKeyIdentifierClaimType, rawkey.ToString()));

                                        if (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey))
                                        {
                                            InMemorySymmetricSecurityKey tokenSigningKey = new InMemorySymmetricSecurityKey((tokenTemplate.PrimaryVerificationKey as SymmetricVerificationKey).KeyValue);
                                            signingcredentials = new SigningCredentials(tokenSigningKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);
                                        }
                                        else if (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(X509CertTokenVerificationKey))
                                        {
                                            if (signingcredentials == null)
                                            {
                                                X509Certificate2 cert = DynamicEncryption.GetCertificateFromFile(true);
                                                if (cert != null) signingcredentials = new X509SigningCredentials(cert);
                                            }
                                        }
                                        JwtSecurityToken token = new JwtSecurityToken(issuer: tokenTemplate.Issuer, audience: tokenTemplate.Audience, notBefore: DateTime.Now.AddMinutes(-5), expires: DateTime.Now.AddMinutes(Properties.Settings.Default.DefaultTokenDuration), signingCredentials: signingcredentials, claims: myclaims);
                                        JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
                                        MyResult.TokenString = handler.WriteToken(token);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return MyResult;
        }
        private static TokenResult GetTokenResult(IEnumerable<KeyValuePair<string, IEnumerable<string>>> headers)
        {
            foreach (var header in headers)
            {
                if (header.Key == Runtime.XZumoAuthHeader
                    && header.Value != null
                    && !string.IsNullOrWhiteSpace(header.Value.FirstOrDefault()))
                {
                    string[] splitArray = header.Value.FirstOrDefault().Split(',');
                    TokenResult tokenResult = new TokenResult();

                    for (int i = 0; i < splitArray.Length; i++)
                    {
                        string[] keyValuePairSegments = splitArray[i].Trim().Split('=');
                        if (keyValuePairSegments.Count() == 2 && !string.IsNullOrWhiteSpace(keyValuePairSegments[0]) && !string.IsNullOrWhiteSpace(keyValuePairSegments[1]))
                        {
                            tokenResult.Properties[keyValuePairSegments[0]] = keyValuePairSegments[1];
                        }
                    }

                    return tokenResult;
                }
            }

            return null;
        }
        /// <summary>
        /// Sets given TokenResult into TokenStore
        /// </summary>
        /// <param name="request"></param>
        /// <param name="tokenResult"></param>
        /// <returns></returns>
        public async Task SetTokenAsync(HttpRequestMessage request, TokenResult tokenResult)
        {
            if (this.isSelfHosted)
            {
                return;
            }

            var runtime = Runtime.FromAppSettings(request);
            var emaUser = runtime.CurrentUser;
            await emaUser.SetTokenAsync(this.providerName, tokenResult);
        }
Exemplo n.º 48
0
		/// <summary>
		/// Takes a portion of the expression and determines if the
		/// expression begins with an operator. If so, return
		/// the operator code. The operator token is removed
		/// from the expression.
		/// </summary>
		/// <param name="exp">infix expression</param>
		/// <param name="operators">the set of operators to search for</param>
		/// <returns></returns>
		private TokenResult SeachOperators (ref string exp, ICollection operators)
		{
			TokenResult token = new TokenResult(false);
			foreach (string op in operators)
			{
				if (exp.StartsWith(op))
				{
					token = new TokenResult(op);
					exp = exp.Substring(op.Length);

					if (token.OpToken == OperatorTokens.Invalid)
					{
						throw new Exception("Bad code in GetToken()");
					}
					break;
				}
			}
		
			return token;
		}
Exemplo n.º 49
0
		/// <summary>
		/// Obtains the next token, given the current state and the expression.
		/// </summary>
		/// <param name="exp">the remaining portion of the infix expression to translate into a postfix expression</param>
		/// <param name="state">the state determines what types of tokens can be accepted.</param>
		/// <returns></returns>
		private TokenResult GetToken(ref string exp, RelExpStates state)
		{
			TokenResult token = new TokenResult(false);

			bool searchOps1 = false;
			bool searchOps2 = false;
			bool searchOps3 = false;
			bool parsePropName = false;
			bool parsePropValue = false;

			switch (state)
			{
				case RelExpStates.unknown:
					//look for everything
					searchOps1 = true;
					searchOps3 = true;
					parsePropName = true;
					break;

				case RelExpStates.expectOp:
					//look for relop, stringop, derived-op 
					searchOps2 = true;
					break;

				case RelExpStates.expectValue:
					parsePropValue = true;
					break;
			}

			//remove any preceding whitespace chars
			exp = exp.Trim();

			if (exp != "")
			{
				if ((searchOps1) && (token.TokenType == Tokens.Invalid))
				{
					token = this.SeachOperators(ref exp, Operators1);
				}

				if ((searchOps2) && (token.TokenType == Tokens.Invalid))
				{
					token = this.SeachOperators(ref exp, Operators2);
				}

				if ((searchOps3) && (token.TokenType == Tokens.Invalid))
				{
					token = this.SeachOperators(ref exp, Operators3);
				}


				if (token.TokenType == Tokens.Invalid)
				{
					if (parsePropValue)
					{
						//it must be an operand... so parse the next whitespace delimited string or 
						//extract the next string enclosed by quotes

						if ((exp.StartsWith("true")) || (exp.StartsWith("false")))
						{
							// This is a value for an existence-op operation
							token = new TokenResult(exp, false);
							exp = exp.Substring(exp.Length);
						}
						else if (exp.StartsWith("\""))
						{
							// This is a value operand that is delimited
							// by another double-quote
							int endQuote = 1;
							int escape = 0;
							bool endQuoteFound = false;

							// find the next end-quote that is not
							// an escaped end-quote.

							while (!endQuoteFound)
							{
								endQuote = exp.IndexOf("\"", endQuote);
								escape = exp.IndexOf("\\\"", escape);

								if (
									(escape < 0) ||
									(escape == endQuote - 1) ||
									(escape > endQuote)
									)
								{
									endQuoteFound = true;
								}
							}

							if (endQuote <= 0)
							{
								StringBuilder msg = new StringBuilder(exp.Length);
								msg.AppendFormat("Invalid Args: Unterminated end-quote in SearchCriteria, near \"{0}\"", exp);
								throw new UPnPCustomException(402, msg.ToString());
							}

							string unescaped = exp.Substring(1, endQuote-1);
							string escaped = unescaped.Replace("\\\\", "\\").Replace("\\\"", "\"");
							token = new TokenResult(escaped, false);
					
							exp = exp.Substring(endQuote+1);
						}
						else
						{
							// Assume the CP provided a white-space delimited value without quotes
						
							//int endPos = exp.IndexOf(" ");
							int endPos = this.FindNextIndexOf(exp, WHITESPACESANDENDPAREN);
							string str = exp;
							if (endPos > 0)
							{
								str = exp.Substring(0, endPos);
							}
							token = new TokenResult(str, false);

							exp = exp.Substring(str.Length);
						}
					}
					else
					{
						// This is a property name, that is delimited by 
						// a whitespace.

						//int endPos = exp.IndexOf(" ");
						int endPos = this.FindNextIndexOf(exp, WHITESPACES);
						if (endPos > 0)
						{
							string prop = exp.Substring(0, endPos);

							token = new TokenResult(prop, true);
							exp = exp.Substring(prop.Length);
						}
						else
						{
							throw new Error_MalformedSearchCriteria("Property name has not been properly delimited.");
						}
					}
				}
			}

			if (
				(token.TokenType == Tokens.Invalid) 
				)
			{
				throw new UPnPCustomException(402, "Invalid Args: Invalid SearchCriteria string.");
			}

			return token;
		}
Exemplo n.º 50
0
        public override IEnumerable<TokenResult> Parse(string input, string UserId)
        {
            ////chunk up the input sentence
            var words = SplitToWords(input);
            var results = new List<TokenResult>();
            bool inQuote = false;

            for (int i = 0; i < words.Count; i++)
            {
                Word word = words[i];

                //if we find a quote in the word or the word is a quote, ignore
                if (word.WordValue.IndexOf("\"") > -1)
                {
                    inQuote = !inQuote;
                }

                if (inQuote)
                {
                    continue;
                }

                bool isPm = false;
                int length = word.EndIndex - word.StartIndex;

                if (word.WordValue.IndexOf("pm") > -1)
                {
                    isPm = true;
                }

                word.WordValue = word.WordValue.Replace("am", "").Replace("pm", "");

                if (i < (words.Count - 1))
                {
                    Word nextWord = words[i + 1];

                    if (nextWord.WordValue.IndexOf("pm") > -1 && nextWord.WordValue.Length == 2)
                    {
                        isPm = true;
                        i = nextWord.EndIndex;
                        length = nextWord.EndIndex - word.StartIndex;
                    }
                }

                //number hunting
                if (word.WordValue.IndexOf(":") > -1)
                {
                    string[] parts = word.WordValue.Split(':');

                    int hours;
                    int minutes;
                    int seconds = 0;

                    if (!int.TryParse(parts[0], out hours))
                    {
                        continue;
                    }

                    if (!int.TryParse(parts[1], out minutes))
                    {
                        continue;
                    }

                    if (parts.Count() > 2)
                    {
                        if (int.TryParse(parts[2], out seconds))
                        {
                            continue;
                        }
                    }

                    if (isPm && hours < 12)
                    {
                        hours += 12;
                    }

                    var ts = new TimeSpan(hours, minutes, seconds);

                    var tr = new TokenResult
                    {
                        Length = length,
                        Start = word.StartIndex,
                        TokenType = this.GetType().ToString(),
                        Value = ts,
                        Token = new TokenTime { Value = ts }
                    };
                    results.Add(tr);
                }
                else
                {
                    int hours;

                    if (int.TryParse(word.WordValue, out hours))
                    {
                        if (isPm && hours < 12)
                        {
                            hours += 12;
                        }

                        var ts = new TimeSpan(hours, 0, 0);

                        var tr = new TokenResult
                        {
                            Length = length,
                            Start = word.StartIndex,
                            TokenType = this.GetType().ToString(),
                            Value = ts,
                            Token = new TokenTime { Value = ts }
                        };
                        results.Add(tr);
                    }
                }
            }

            return results;
        }
Exemplo n.º 51
0
		/// <summary>
		/// This constructor takes a Boolean expression in infix format.
		/// Some examples
		/// are shown below. Assume <b>T</b> is an instance of the 
		/// <see cref="Tags"/>
		/// class.
		/// <list type="table">
		/// <item>
		/// T[CommonPropertyNames.title] contains "foo"
		/// <term>
		/// </term>
		/// <description>
		/// <see cref="MediaComparer.IsMatch"/> will return
		/// true on media objects that have <i>foo</i> in the title.
		/// </description>
		/// </item>
		/// 
		/// <item>
		/// T[CommonPropertyNames.creator] doesNotContain "\"HappyBand\""
		/// <term>
		/// </term>
		/// <description>
		/// <see cref="MediaComparer.IsMatch"/> will return
		/// true on media objects that do not have <i>"HappyBand"</i> in the title.
		/// </description>
		/// </item>
		/// 
		/// <item>
		/// (T[CommonPropertyNames.Class] = "object.item.audioItem.musicTrack" and Tags.PropertyAttributes.res_size > "40") or (T[CommonPropertyNames.author] exists true)
		/// <term>
		/// </term>
		/// <description>
		/// <see cref="MediaComparer.IsMatch"/> will return
		/// true on media objects that are music tracks with at least one resource greater than 40 bytes
		/// OR on media objects that have a value set for the author metadata.
		/// </description>
		/// </item>
		/// </list>
		/// </summary>
		/// <param name="infix">The boolean infix expression conforming to the syntax and semantics of ContentDirectory's boolean query language.</param>
		/// <exception cref="OpenSource.UPnP.AV.CdsMetadata.Error_MalformedSearchCriteria">
		/// Thrown if the infix expression has a syntax error.
		/// </exception>
		public MediaComparer (string infix)
		{

			string allstring = infix.Trim();
			if ((allstring == "") || (allstring == "*"))
			{
				this.m_AlwaysMatch = true;
				return;
			}

			//Initialize an empty stack and empty result string variable.
			//
			Stack stack = new Stack();
			m_Postfix = new Queue();

			RelExpStates state = RelExpStates.unknown;
			TokenResult token;
			while (infix.Length > 0)
			{
				infix = infix.Trim();
				token = GetToken(ref infix, state);

				switch (state)
				{
					case RelExpStates.unknown:
						if (token.TokenType == Tokens.PropertyName)
						{
							state = RelExpStates.expectOp;
						} 
						break;
					case RelExpStates.expectOp:
						if (token.TokenType != Tokens.Operator)
						{
							throw new UPnPCustomException(402, "Invalid Args: Invalid operator " + token.Data);
						}
						state = RelExpStates.expectValue;
						break;
					case RelExpStates.expectValue:
						if (token.TokenType != Tokens.PropertyValue)
						{
							throw new UPnPCustomException(402, "Invalid Args: Unexpected value " + token.Data);
						}
						state = RelExpStates.unknown;
						break;
				}

				switch (token.TokenType)
				{
					case Tokens.Operator:
						if (token.OpToken == OperatorTokens.LParen)
						{
							//left paren
							//
							stack.Push(token);
						}
						else if (token.OpToken == OperatorTokens.RParen)
						{
							//right paren
							//
							TokenResult tr = new TokenResult(false);
							do
							{
								if (stack.Count > 0)
								{
									tr = (TokenResult) stack.Pop();
									if (tr.OpToken != OperatorTokens.LParen)
									{
										m_Postfix.Enqueue(tr);
									}
								}
								else
								{
									throw new UPnPCustomException(402, "Invalid Args: Missing Left Parenthesis.");
								}
							}
							while (tr.OpToken != OperatorTokens.LParen);
						}
						else
						{
							//standard operator
							//
							if (token.OpToken == OperatorTokens.Invalid)
							{
								throw new Exception("bad code");
							}

							while
								(
								(stack.Count > 0) && 
								( ((TokenResult) stack.Peek()).Precedence >= token.Precedence) && 
								( ((TokenResult) stack.Peek()).OpToken != OperatorTokens.LParen) 
								)
							{
								// While stack is not empty &&
								// top operator has higher or equal precedence...
								// pop operator and stuff into queue
								m_Postfix.Enqueue( stack.Pop() );
							}
							stack.Push(token);
						}
						break;

					case Tokens.PropertyName:
						m_Postfix.Enqueue(token);
						TagExtractor te = new TagExtractor(token.Data);
						this.m_PE[token.Data] = te;
						break;

					case Tokens.PropertyValue:
						m_Postfix.Enqueue(token);
						break;
				}
			}

			// pop remaining items in stack and stuff into queue
			// 

			while (stack.Count > 0)
			{
				TokenResult tr = (TokenResult) stack.Pop();
				if (tr.OpToken != OperatorTokens.LParen) 
				{
					m_Postfix.Enqueue( tr );
				}
			}
		}