예제 #1
0
        public OAuthValidateDto GetUserInfoByToken(string token)
        {
            AccessTokenDto accessTokenDto = new AccessTokenDto()
            {
                AccessToken = token
            };

            string accessToken = Serializer.ToJson(accessTokenDto);

            var entity = Repository.Queryable().FirstOrDefault(m => m.AccessToken == accessToken);

            if (entity != null)
            {
                if (!this.SessionManager.IsExist(new SessionModel()
                {
                    SessionID = entity.Code
                }))
                {
                    Repository.Delete(entity);
                    entity = null;
                }
            }

            return(entity != null?entity.ToDto() : new OAuthValidateDto());
        }
 public TokenResponseDto(AccessTokenDto accessToken, string refreshToken, bool success = false, string message = null)
     : base(success, new[] { message })
 {
     AccessToken  = accessToken;
     RefreshToken = refreshToken;
     Success      = success;
 }
        /// <summary>
        ///     Retrieve a single standing order associated to a specific account by its ID.
        /// </summary>
        /// <exception cref="ApiException">Thrown when fails to make API call</exception>
        /// <param name="accessToken"></param>
        /// <param name="accountId"></param>
        /// <param name="standingOrderId"></param>
        /// <returns>Task of StandingOrder</returns>
        public async Task <StandingOrder> GetAccountDetailAsync(AccessTokenDto accessToken, string accountId, string standingOrderId)
        {
            if (accessToken == null)
            {
                throw new ArgumentNullException(nameof(accessToken));
            }

            if (!accessToken.IsValid)
            {
                throw new ArgumentException($"{nameof(accessToken)} is expired.");
            }

            if (accountId == null)
            {
                throw new ArgumentNullException(nameof(accountId));
            }

            if (standingOrderId == null)
            {
                throw new ArgumentNullException(nameof(standingOrderId));
            }

            this.Configuration.AccessToken = accessToken.AccessToken;
            var standingOrdersApi = new StandingOrdersApi(this.Configuration, this.Logger);

            return(await standingOrdersApi
                   .GetStandingOrderOfAccountAsync(accountId, standingOrderId)
                   .ConfigureAwait(false));
        }
예제 #4
0
        public AuthTokenDto GenerateAuthToken(Credential credential, int userClientId, string refreshToken)
        {
            AccessTokenDto accessToken       = new AccessTokenDto(credential, userClientId);
            string         signedAccessToken = JWT.Encode(accessToken, secretKey, JwsAlgorithm.HS256);

            return(new AuthTokenDto(signedAccessToken, refreshToken, "bearer", credential));
        }
예제 #5
0
        /// <summary>
        ///     Get transaction of account Retrieve the details of a single transaction by its ID associated to a specific account.
        /// </summary>
        /// <exception cref="ApiException">Thrown when fails to make API call</exception>
        /// <param name="accessToken"></param>
        /// <param name="accountId"></param>
        /// <param name="transactionId"></param>
        /// <returns>Transaction</returns>
        public async Task <Transaction> GetDetailAsync(AccessTokenDto accessToken, string accountId, string transactionId)
        {
            if (accessToken == null)
            {
                throw new ArgumentNullException(nameof(accessToken));
            }

            if (!accessToken.IsValid)
            {
                throw new ArgumentException($"{nameof(accessToken)} is expired.");
            }

            if (accountId == null)
            {
                throw new ArgumentNullException(nameof(accountId));
            }

            if (transactionId == null)
            {
                throw new ArgumentNullException(nameof(transactionId));
            }

            this.Configuration.AccessToken = accessToken.AccessToken;
            var transactionsApi = new TransactionsApi(this.Configuration, this.Logger);

            return(await transactionsApi
                   .GetTransctionOfAccountAsync(accountId, transactionId)
                   .ConfigureAwait(false));
        }
예제 #6
0
        /// <summary>
        ///     List transactions Get a list of the transactions of all accounts. You can additionally constrain the amount of
        ///     transactions being returned by using the query parameters described below as filters.
        /// </summary>
        /// <exception cref="ApiException">Thrown when fails to make API call</exception>
        /// <param name="accessToken"></param>
        /// <param name="listFilter">
        ///     (optional)
        ///     count:
        ///     Limit the number of returned items. In combination with the offset parameter this can be used to
        ///     paginate the result list. (optional, default to 1000)
        ///     offset:
        ///     Skip this number of transactions in the response. In combination with the count parameter this can
        ///     be used to paginate the result list. (optional, default to 0)
        ///     since:
        ///     Return only transactions after this date based on since_type. This parameter can either
        ///     be a transaction ID or a date. Given at least one transaction matches the filter criterion, if provided as
        ///     transaction ID the result will *not* contain this ID. If provided as ISO date, the result *will* contain this date.
        ///     This behavior may change in the future. (optional)
        ///     sinceType:
        ///     This parameter defines how the parameter since will be interpreted. (optional,
        ///     default to created)
        ///     filter:
        ///     Filter transactions by given key:value combination. Possible keys:    - date (maps to
        ///     booked_at, please use ISO date here, not datetime)   - person (maps to payer/payee name)   - purpose
        ///     - amount  Values are interpreted using wildcards: person:John Doe will match %John Doe%.
        ///     (optional)
        ///     includePending:
        ///     This flag indicates whether pending transactions should be included in the response.
        ///     Pending transactions are always included as a complete set, regardless of the since parameter. (optional, default
        ///     to false)
        ///     sort
        ///     Determines whether results will be sorted in ascending or descending order. (optional)
        ///     until:
        ///     Return only transactions which were booked on or before this date. Please provide as ISO date. It
        ///     is not possible to use the since_type semantics with until. (optional)
        ///     includeStatistics:
        ///     If true includes statistics on the returned transactions: maximum deposit,
        ///     total deposits, maximum expense, total expenses.  (optional, default to false)
        ///     filter:
        ///     Filter transactions by given key:value combination. Possible keys:    - date (maps to
        ///     booked_at, please use ISO date here, not datetime)   - person (maps to payer/payee name)   - purpose
        ///     - amount  Values are interpreted using wildcards: person:John Doe will match %John Doe%.
        ///     (optional)
        /// </param>
        /// <returns>TransactionList</returns>
        public async Task <TransactionList> GetAllAsync(AccessTokenDto accessToken, AccountListFilter listFilter = default)
        {
            if (accessToken == null)
            {
                throw new ArgumentNullException(nameof(accessToken));
            }

            if (!accessToken.IsValid)
            {
                throw new ArgumentException($"{nameof(accessToken)} is expired.");
            }

            this.Configuration.AccessToken = accessToken.AccessToken;
            var transactionsApi = new TransactionsApi(this.Configuration, this.Logger);

            return(await transactionsApi.ListTransactionsAsync(
                       null,
                       listFilter?.Filter,
                       null,
                       listFilter?.Count,
                       listFilter?.Offset,
                       listFilter?.Sort,
                       listFilter?.Since?.ToString("O"),
                       listFilter?.Until?.ToString("O"),
                       listFilter?.SinceType,
                       listFilter?.Types,
                       listFilter?.Cents,
                       listFilter?.IncludePending,
                       listFilter?.IncludeStatistics).ConfigureAwait(false));
        }
예제 #7
0
        public void UpdateTokenDeviceName()
        {
            string new_device_name = "My home computer";

            var token  = testServer.GetAccessToken().Token.ToShortToken();
            var client = testServer.GetJsonClient();
            var url    = new UpdateTokenRequest().ToUrl("PUT");
            var req    = new AccessTokenDto {
                TokenPart  = token,
                DeviceName = new_device_name
            };
            var service_url = testServer.ListenUrl + url;

            client.Put <AccessTokenDto> (service_url, req);

            // check that the token has been updated
            var get_url = new GetTokenRequest()
            {
                Username = RainyTestServer.TEST_USER
            }.ToUrl("GET");
            var get_service_url          = testServer.ListenUrl + get_url;
            List <AccessTokenDto> tokens = client.Get <List <AccessTokenDto> > (get_service_url);
            var updated_token            = tokens.First(t => token == t.TokenPart);

            Assert.AreEqual(new_device_name, updated_token.DeviceName);
        }
        /// <summary>
        ///     Get a list of the securities of account per ID. You can additionally constrain the amount of
        ///     securities being returned by using the query parameters described below as filters.
        /// </summary>
        /// <exception cref="ApiException">Thrown when fails to make API call</exception>
        /// <param name="accessToken"></param>
        /// <param name="accountId"></param>
        /// <param name="listFilter">
        ///     (optional)
        ///     count:
        ///     Limit the number of returned items. In combination with the offset parameter this can be used to
        ///     paginate the result list. (optional, default to 1000)
        ///     offset:
        ///     Skip this number of transactions in the response. In combination with the count parameter this can
        ///     be used to paginate the result list. (optional, default to 0)
        ///     since:
        ///     Return only transactions after this date based on since_type. This parameter can either
        ///     be a transaction ID or a date. Given at least one transaction matches the filter criterion, if provided as
        ///     transaction ID the result will *not* contain this ID. If provided as ISO date, the result *will* contain this date.
        ///     This behavior may change in the future. (optional)
        ///     sinceType:
        ///     This parameter defines how the parameter since will be interpreted. (optional,
        ///     default to created)
        /// </param>
        /// <returns>SecuritiesApiResponse</returns>
        public async Task <SecuritiesApiResponse> GetAllAsync(AccessTokenDto accessToken, string accountId, SecurityListFilter listFilter = default)
        {
            if (accessToken == null)
            {
                throw new ArgumentNullException(nameof(accessToken));
            }

            if (accountId == null)
            {
                throw new ArgumentNullException(nameof(accountId));
            }

            if (!accessToken.IsValid)
            {
                throw new ArgumentException($"{nameof(accessToken)} is expired.");
            }

            this.Configuration.AccessToken = accessToken.AccessToken;
            var securitiesApi = new SecuritiesApi(this.Configuration, this.Logger);

            return(await securitiesApi
                   .ListSecuritiesOfAccountAsync(accountId,
                                                 listFilter?.Count,
                                                 listFilter?.Offset,
                                                 listFilter?.Since?.ToString("O"),
                                                 listFilter?.SinceType)
                   .ConfigureAwait(false));
        }
예제 #9
0
        public async Task <IHttpActionResult> Auth([FromBody] LoginDto login)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await _unitOfWork.Repository <User>().FindAsync(t => t.Email == login.Email && t.Password == login.Password);

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

            if (!user.IsActived)
            {
                return(StatusCode(System.Net.HttpStatusCode.Forbidden));
            }

            var accessToken = new AccessTokenDto()
            {
                AT_UserId = user.Id, AT_Time = DateTime.Now
            };
            var refreshToken = new RefreshTokenDto()
            {
                RT_UserId = user.Id, RT_Time = DateTime.Now, RT_AccessToken = accessToken
            };

            return(Ok(new { accessToken = Encrypt.EncryptAccessToken(accessToken), refreshToken = Encrypt.EncryptRefreshToken(refreshToken) }));
        }
예제 #10
0
        public HttpResponseMessage GetAuthorizationToken(GetTokenArgEntity arg)
        {
            BaseJsonResult <AccessTokenDto> resultMsg = null;

            Logger(this.GetType(), "获取授权Token-GetAuthorizationToken", () =>
            {
                if (this.CheckBaseArgument(arg, out resultMsg))
                {
                    if (arg.Account.Equals("guest") && arg.UserId.Equals("guest"))
                    {
                        JWTPlayloadInfo playload = new JWTPlayloadInfo
                        {
                            iss    = "S_COMMON_TOKTN",
                            sub    = arg.Account,
                            aud    = arg.UserId,
                            userid = CommonHelper.GetGuid(),
                            extend = "PUBLIC_TOKTN"
                        };
                        string token = JWTHelper.GetToken(playload);

                        AccessTokenDto access = new AccessTokenDto
                        {
                            AccessToken = token,
                            ExpiryTime  = playload.exp
                        };

                        resultMsg = this.GetBaseJsonResult <AccessTokenDto>(access, JsonObjectStatus.Success);
                    }
                    else
                    {
                        //TODO 根据UserID校验用户是否存在
                        //JWTPlayloadInfo playload = new JWTPlayloadInfo
                        //{
                        //    iss = "S_USER_TOKTN",
                        //    sub = arg.Account,
                        //    aud = arg.UserId,
                        //    userid = CommonHelper.GetGuid(),
                        //    extend = "USER_TOKTN"
                        //};
                        //string token = JWTHelper.GetToken(playload);

                        //AccessTokenDto access = new AccessTokenDto
                        //{
                        //    AccessToken = token,
                        //    ExpiryTime = playload.exp
                        //};
                        //resultMsg = this.GetBaseJsonResult<AccessTokenDto>(access, JsonObjectStatus.Success);

                        resultMsg = this.GetBaseJsonResult <AccessTokenDto>(JsonObjectStatus.UserNotExist);
                    }
                }
            }, e =>
            {
                resultMsg = this.GetBaseJsonResult <AccessTokenDto>(JsonObjectStatus.Exception, ",异常信息:" + e.Message);
            });

            return(resultMsg.TryToHttpResponseMessage());
        }
        public async Task <HttpResponseMessage> RefreshToken(string id, AccessTokenDto accessToken)
        {
            AssertIfServiceNotAlive();

            string resourceAddress = Path.Combine(_baseAddress, _resourceUri);
            var    baseClient      = new RestClient <AccessTokenDto>(_httpClient, resourceAddress, _customHeaders, "refreshToken");

            return(await baseClient.Put(id, accessToken));
        }
예제 #12
0
        public async Task <string> Login(AccessTokenDto accessToken)
        {
            var userInfo = await GetUserFromFacebook(accessToken);

            // ready to create the local user account (if necessary) and jwt

            var user = _userRepository.GetUserByEmail(EmailType.FACEBOOK, userInfo.Email);

            if (user != null)
            {
                if (!user.FacebookVerified)
                {
                    user.FacebookEmail = userInfo.Email;

                    if (user.GoogleVerified)
                    {
                        user.FacebookVerified = true;
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
            else
            {
                user = _userRepository.GetUserByEmail(EmailType.FACEBOOK, userInfo.Email);
                if (user == null)
                {
                    await _userRepository.CreateUser(new User
                    {
                        FirstName        = userInfo.FirstName,
                        LastName         = userInfo.LastName,
                        Email            = userInfo.Email,
                        PictureUrl       = userInfo.Picture.Data.Url,
                        FacebookVerified = false,
                        GoogleVerified   = false,
                        FacebookEmail    = userInfo.Email,
                        GoogleEmail      = null
                    });

                    _userRepository.CreateUnauthorizedUser(new UnauthorizedUser {
                        Email = userInfo.Email
                    });

                    return(null);
                }
                if (!user.FacebookVerified)
                {
                    return(null);
                }
            }


            return(await GenerateJwt(user));
        }
예제 #13
0
        public async Task ShouldNotMakeRepeatedCallsWithInvalidAccessTokenAsync()
        {
            // Arrange
            this.DateTimeOffsetProviderMock.Setup(x => x.GetUtcNow()).Returns(new DateTimeOffset(new DateTime(2005, 1, 1)));

            const string accessToken1    = "test access token 1";
            const string accessToken2    = "test access token 2";
            var          accessTokenDto1 = new AccessTokenDto {
                ExpiresIn = 3600, Token = accessToken1
            };
            var accessTokenDto2 = new AccessTokenDto {
                ExpiresIn = 3600, Token = accessToken2
            };

            const string userId        = "johnsmith";
            var          expectedUser1 = new PublicUser {
                Id = userId, DisplayName = "John Smith"
            };

            this.AuthorizationFlowsHttpClientMock
            .SetupSequence(x => x.SendAsync <AccessTokenDto>(
                               It.Is <UriParts>(item =>
                                                item.BaseUri == this.Options.TokenEndpoint &&
                                                item.QueryStringParameters == null &&
                                                item.RouteValues == null),
                               HttpMethod.Post,
                               It.Is <IEnumerable <KeyValuePair <string, string> > >((IEnumerable <KeyValuePair <string, string> > item) => item.Single().Equals(new KeyValuePair <string, string>("Authorization", $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{this.Options.ClientId}:{this.Options.ClientSecret}"))}"))),
                               It.Is <object>(item => SpotifyObjectHelpers.GetPropertyBag(item).Single().Equals(new KeyValuePair <string, object>("grant_type", "client_credentials"))),
                               It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(accessTokenDto1))
            .Throws(new SpotifyHttpResponseWithErrorCodeException(System.Net.HttpStatusCode.ServiceUnavailable, null, string.Empty))
            .Returns(Task.FromResult(accessTokenDto2));

            this.HttpClientWrapperMock
            .SetupSequence(x => x.SendAsync(
                               It.Is <HttpRequest <PublicUser> >(httpRequest => httpRequest.RequestHeaders.Contains(new KeyValuePair <string, string>("Authorization", $"Bearer {accessToken1}"))),
                               It.IsAny <CancellationToken>()))
            .Throws(new SpotifyHttpResponseWithErrorCodeException(System.Net.HttpStatusCode.Unauthorized, null, string.Empty));

            this.HttpClientWrapperMock
            .SetupSequence(x => x.SendAsync(
                               It.Is <HttpRequest <PublicUser> >(httpRequest => httpRequest.RequestHeaders.Contains(new KeyValuePair <string, string>("Authorization", $"Bearer {accessToken2}"))),
                               It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(expectedUser1));

            // Act + Assert
            ((Func <Task>)(() => this.Client.User(userId).GetAsync()))
            .ShouldThrow <SpotifyHttpResponseWithErrorCodeException>()
            .Which.ErrorCode.Should().Be(System.Net.HttpStatusCode.ServiceUnavailable);

            var user = await this.Client.User(userId).GetAsync();

            user.ShouldBeEquivalentTo(expectedUser1);
        }
예제 #14
0
        public async Task <bool> AddToken(AccessTokenDto accessTokenDto)
        {
            var token = new AccessToken {
                Level = accessTokenDto.Level, Token = accessTokenDto.Token
            };

            _context.AccessTokens.Add(token);
            var result = await _context.SaveChangesAsync();

            return(result > 0);
        }
예제 #15
0
        public static async Task <AccessTokenDto> AuthenticateUserAsync(this IClient client, string username, string password)
        {
            AccessTokenDto dto = null;

            Assert.Null(await Record.ExceptionAsync(async() =>
                                                    dto = await client.Authentication_AuthenticateAsync(new LoginUserDto {
                Username = username, Password = password
            })));

            return(dto);
        }
 public ExchangeRefreshTokenPresenter(ExchangeRefreshTokenResponse response) : base(response)
 {
     if (response.Succeeded)
     {
         Content = new AccessTokenDto
         {
             AccessToken  = response.AccessToken,
             ExpiresIn    = (int)response.ExpiresIn.TotalSeconds,
             RefreshToken = response.RefreshToken
         };
     }
 }
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (!actionContext.Request.Headers.Contains("Authorization"))
            {
                actionContext.Response = new HttpResponseMessage
                {
                    StatusCode = System.Net.HttpStatusCode.MethodNotAllowed,
                    Content    = new StringContent("I didn't see your access token in request")
                };
                return;
            }

            AccessTokenDto accessToken = null;

            try
            {
                accessToken = Encrypt.DecryptAccessToken(actionContext.Request.Headers.GetValues("Authorization").First());
            }
            catch
            {
                actionContext.Response = new HttpResponseMessage
                {
                    StatusCode = System.Net.HttpStatusCode.MethodNotAllowed,
                    Content    = new StringContent("Invalid access token")
                };
                return;
            }

            using (var unitOfWork = new UnitOfWork())
            {
                var user = unitOfWork.Repository <User>().Get(accessToken.AT_UserId);
                if (user == null)
                {
                    actionContext.Response = new HttpResponseMessage
                    {
                        StatusCode = System.Net.HttpStatusCode.MethodNotAllowed,
                        Content    = new StringContent("Invalid userID")
                    };
                    return;
                }
            }

            if (DateTime.Now - accessToken.AT_Time > accessTokenLifetime)
            {
                actionContext.Response = new HttpResponseMessage
                {
                    StatusCode = System.Net.HttpStatusCode.UpgradeRequired,
                    Content    = new StringContent("Access token life has expired")
                };
                return;
            }
        }
예제 #18
0
        public async Task AuthenticateUser_InvalidUsername_Fails()
        {
            AccessTokenDto dto       = null;
            var            exception = await Record.ExceptionAsync(async() =>
            {
                dto = await _client.Authentication_AuthenticateAsync(new LoginUserDto {
                    Username = "******", Password = "******"
                });
            });

            Assert.NotNull(exception);
            Assert.Null(dto);
        }
예제 #19
0
        public async Task <IActionResult> RefreshAccessToken(string id, [FromBody] AccessTokenDto accessToken)
        {
            var authorization = await _authorizationService.AuthorizeAsync(User, new UserDto { Id = id }, Operations.Update);

            if (!authorization.Succeeded)
            {
                return(Forbid());
            }

            await _userService.RefreshTokenAsync(id, accessToken);

            return(Ok());
        }
        public async Task RefreshTokenAsync(string id, AccessTokenDto accessToken)
        {
            var result = await _usersClient.RefreshToken(id, accessToken);

            if (!result.IsSuccessStatusCode)
            {
                var content = await result.Content.ReadAsStringAsync();

                throw new UpdateUserException("During refreshing user's access token error occurs: " + content);
            }

            _cacheService.ClearUsersCache();
        }
예제 #21
0
        public async Task LoggedInOrReverified()
        {
            var path = Path.Combine(TestContext.CurrentContext.TestDirectory, "accesstoken.json");

            this.AccessToken = JsonConvert.DeserializeObject <AccessTokenDto>(File.ReadAllText(path));

            if (!this.AccessToken.IsValid)
            {
                var authService = new AccessTokenService(this._configuration, this._logger);
                this.AccessToken = (await authService.CheckAndRevalidateIfNeededAsync(this.AccessToken).ConfigureAwait(false)).token;
                File.WriteAllText(path, JsonConvert.SerializeObject(this.AccessToken));
            }
        }
        public async Task <IActionResult> FacebookLogin([FromBody] AccessTokenDto accessToken)
        {
            var jwt = await _facebookIdentity.Login(accessToken);

            if (jwt != null)
            {
                AddJwtToCookie(jwt);
                return(Ok(jwt));
            }
            else
            {
                return(Unauthorized());
            }
        }
예제 #23
0
        public AccessTokenDto GetTokenByCode(FormDataCollection model)
        {
            if (model["grantType"] != "authorizationCode")
            {
                throw new System.Exception("grantType验证失败");
            }

            var            oAuthDto       = OAuthValidateService.GetOAuthTokenByCode(model["clientId"], model["clientSecret"], model["redirectUrl"], model["code"]);
            AccessTokenDto accessTokenDto = oAuthDto != null?
                                            Serializer.FromJson <AccessTokenDto>(oAuthDto.AccessToken) :
                                                throw new System.Exception("Token不存在");

            return(accessTokenDto);
        }
예제 #24
0
        private async Task <AccessTokenDto> PrepareGenerateTokenExternalLogin(string username)
        {
            AccessTokenDto Detail = new AccessTokenDto();

            //Detail.Secret = Guid.NewGuid().ToString();
            //Detail.hashSecret = await Startup.GetHashSecret(Detail.Secret);
            Detail.Sub = username;
            Detail.Jti = await Task.FromResult(Guid.NewGuid().ToString());

            Detail.Iat      = DateTimeUtils.ToUnixEpochDate(Detail.now).ToString();
            Detail.Issuer   = "ExampleIssuer";
            Detail.Audience = "ExampleAudience";
            return(Detail);
        }
예제 #25
0
 public static Zidium.Core.Api.AccessToken ConvertToCore(AccessTokenDto accessToken)
 {
     if (accessToken == null)
     {
         return(null);
     }
     return(new Zidium.Core.Api.AccessToken()
     {
         AccountId = accessToken.AccountId,
         SecretKey = accessToken.SecretKey,
         ProgramName = accessToken.Program,
         IsLocalRequest = false
     });
 }
예제 #26
0
        public static void AssertValidToken(this AccessTokenDto dto)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            Assert.True(tokenHandler.CanReadToken(dto.AccessToken));
            var token = tokenHandler.ReadJwtToken(dto.AccessToken);

            Assert.Contains(token.Claims, claim => claim.Type == "iss" && claim.Value == "KIOT");
            Assert.Contains(token.Claims, claim => claim.Type == "role" && claim.Value == "Customer");
            Assert.Contains(token.Claims, claim => claim.Type == "given_name" && claim.Value == "Matt");
            Assert.Contains(token.Claims, claim => claim.Type == "family_name" && claim.Value == "Wilson");
            Assert.Contains(token.Claims, claim => claim.Type == "guid" && claim.Value == "d53a5412-efdd-4905-9f5d-5c2a624726a2");
            Assert.Contains(token.Claims, claim => claim.Type == "identity_id" && claim.Value == "24cfabf2-30e5-4e59-9be1-88dd861dec3c");
        }
예제 #27
0
        public async Task <bool> LoginSession(string username, string password, string clientos)
        {
            var param    = new AccessTokenRM(username, password, clientos);
            var response = await _sgService
                           .LoginSession(Priority.UserInitiated, param)
                           .ConfigureAwait(false);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var responseDto = new AccessTokenDto();
                //responseDto = await response.Content.ReadAsAsync<AccessTokenDto>(new[] { new JsonMediaTypeFormatter() });
                var responseString = response.Content.ReadAsStringAsync().Result;
                responseDto = JsonConvert.DeserializeObject <AccessTokenDto>(responseString);
                var appinfoDto = JsonConvert.DeserializeObject <AppInfo>(responseDto.appinfo);

                Globals.LoginStatus    = LoginStatusType.Success;
                Globals.LoginUsername  = responseDto.username;
                Globals.AccessToken    = responseDto.access_token;
                Globals.RefreshToken   = responseDto.refresh_token;
                Globals.AppInformation = appinfoDto;
                this.accessToken       = responseDto.access_token;
                this.tokenType         = responseDto.token_type;
                this.authToken         = this.tokenType + " " + this.accessToken;

                return(true);
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
            {
                var responseErrorDto = new AccessTokenErrorDto();
                //responseErrorDto = await response.Content.ReadAsAsync<AccessTokenErrorDto>(new[] { new JsonMediaTypeFormatter() });
                //var responseString = response.Content.ReadAsStringAsync().Result;
                //responseErrorDto = JsonConvert.DeserializeObject<AccessTokenErrorDto>(responseString);

                var responseString = "";
                using (var responseStream = await response.Content.ReadAsStreamAsync())
                {
                    responseString = new StreamReader(responseStream).ReadToEnd();
                }
                responseErrorDto = JsonConvert.DeserializeObject <AccessTokenErrorDto>(responseString);

                Globals.LoginStatus      = LoginStatusType.LoginError;
                Globals.ErrorTitle       = responseErrorDto.error;
                Globals.ErrorDescription = responseErrorDto.error_description;

                return(true);
            }

            return(false);
        }
예제 #28
0
        public static async Task AssertRequiresValidAuthorization(this IClient client, HttpClient httpClient, string username, string password, Func <Task> action)
        {
            Assert.NotNull(await Record.ExceptionAsync(async() => await action()));

            AccessTokenDto dto = null;

            Assert.Null(await Record.ExceptionAsync(async() =>
                                                    dto = await client.Authentication_AuthenticateAsync(new LoginUserDto {
                Username = username, Password = password
            })));

            dto.AddAuthorization(httpClient);

            Assert.NotNull(await Record.ExceptionAsync(async() => await action()));
        }
예제 #29
0
        private async Task CheckIfAccessTokenIsValid(AccessTokenDto facebookAccessToken, FacebookAppAccessTokenDto appAccessToken)
        {
            var debugTokenUrl = _fbAuthSettings.DebugTokenUrl
                                .Replace("{FacebookAccessToken}", facebookAccessToken.AccessToken)
                                .Replace("{AccessToken}", appAccessToken.AccessToken);
            var userAccessTokenValidationResponse = await Client.GetStringAsync(debugTokenUrl);

            var userAccessTokenValidation =
                JsonConvert.DeserializeObject <FacebookUserAccessTokenValidation>(userAccessTokenValidationResponse);

            if (!userAccessTokenValidation.Data.IsValid)
            {
                throw new ArgumentException("Invalid facebook token.");
            }
        }
예제 #30
0
        public async Task <IActionResult> Facebook([FromBody] AccessTokenDto facebookAccessToken)
        {
            try
            {
                var jwt = await _facebookIdentity.Login(facebookAccessToken);

                AddJwtToCookie(jwt);
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }

            return(Ok());
        }
예제 #31
0
파일: OAuthTests.cs 프로젝트: Dynalon/Rainy
        public void UpdateTokenDeviceName()
        {
            string new_device_name = "My home computer";

            var token = testServer.GetAccessToken ().Token.ToShortToken ();
            var client = testServer.GetJsonClient ();
            var url = new UpdateTokenRequest ().ToUrl ("PUT");
            var req = new AccessTokenDto {
                TokenPart = token,
                DeviceName = new_device_name };
            var service_url = testServer.ListenUrl + url;
            client.Put<AccessTokenDto> (service_url, req);

            // check that the token has been updated
            var get_url = new GetTokenRequest () { Username = RainyTestServer.TEST_USER }.ToUrl ("GET");
            var get_service_url = testServer.ListenUrl + get_url;
            List<AccessTokenDto> tokens = client.Get<List<AccessTokenDto>> (get_service_url);
            var updated_token = tokens.First (t => token == t.TokenPart);

            Assert.AreEqual (new_device_name, updated_token.DeviceName);
        }