Exemplo n.º 1
0
        /// <summary>
        /// This helper initialize a test user and return a valid Beared token
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        public async Task <string> GetValidBearerToken(HttpClient client)
        {
            var registerDto = new RegisterDto()
            {
                Username        = "******",
                Password        = "******",
                ConfirmPassword = "******"
            };

            var basicLoginDto = new BasicLoginDto()
            {
                Username = registerDto.Username,
                Password = registerDto.Password
            };

            await client.PostAsJsonAsync($"http://testserver/{BaseController.Version}/account/register", registerDto);

            var response2 = await client.PostAsJsonAsync($"http://testserver/{BaseController.Version}/account/login", basicLoginDto);

            var authToken = await response2.Content.ReadAsAsync <AuthTokenDto>();

            Assert.AreEqual(HttpStatusCode.OK, response2.StatusCode);
            Assert.IsNotNull(authToken);
            Assert.IsNotNull(authToken.AccessToken);

            return(authToken.AccessToken);
        }
        public async Task <AuthTokenDto> GetBearerToken(BasicLoginDto loginDto)
        {
            var user = await UserManager.FindAsync(loginDto.Username, loginDto.Password);

            if (user == null)
            {
                throw new UnauthorizedAccessException();
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType);

            AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);

            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            var accessToken             = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);

            return(new AuthTokenDto
            {
                AccessToken = accessToken,
                UserName = user.UserName
            });
        }