Пример #1
0
        public static void SignIdentityToken(IdentityToken token)
        {
            string text      = token.PayloadString();
            string signature = TokenSignFactory.SignToken(text);

            token.Signature = signature;
        }
Пример #2
0
        private async Task <LoginUserDto> GenerateLoginUserDto(ApplicationUser user)
        {
            // generate jwt token
            var userClaims = await _iUserRepository.GetClaimsByUserIdAsync(user.Id);

            var userRoles          = (await _userManager.GetRolesAsync(user)).Select(role => new Claim("roles", role));
            JwtSecurityToken token = TokenHelper.GenerateToken(
                user.UserName,
                _tokenConfig.Key,
                _tokenConfig.Issuer,
                _tokenConfig.Audience,
                _tokenConfig.Expires,
                userClaims.ToList(),
                userRoles.ToList()
                );
            // save the token info into database
            IdentityToken identityToken = new IdentityToken()
            {
                Id = Guid.Parse(token.Id),
                ApplicationUser = user,
                Issuer          = _tokenConfig.Issuer,
                Audience        = _tokenConfig.Audience,
                Expires         = token.ValidTo
            };
            await _identityTokenRepository.CreateAsync(identityToken);

            await _identityTokenRepository.SaveAsync();

            return(new LoginUserDto()
            {
                User = Mapper.Map <UserDto>(user),
                Token = new JwtSecurityTokenHandler().WriteToken(token),
                Expiration = token.ValidTo
            });;
        }
Пример #3
0
        public async Task <Guid> SendMessageAsync(string key, string ipAddress, string userAgent, CancellationToken ct)
        {
            var now           = DateTime.UtcNow;
            var code          = Generator.GenerateAlphaNumericString(256);
            var identityTypes = IdentityTypeExtensions.TypesWithPassword;
            var identity      = await _identitiesService.GetByKeyAndTypesAsync(key, identityTypes, ct);

            var emailIdentity = await _identitiesService.GetByProfileIdAndTypeAsync(identity.ProfileId,
                                                                                    IdentityType.EmailAndPassword, ct);

            var token = new IdentityToken
            {
                IdentityId         = emailIdentity.Id,
                Type               = IdentityTokenType.PasswordReset,
                Value              = code,
                CreateDateTime     = now,
                ExpirationDateTime = now.AddDays(1),
                IpAddress          = ipAddress,
                UserAgent          = userAgent
            };

            var id = await _identityTokensService.CreateAsync(token, ct);

            await SendCodeAsync(emailIdentity.Key, id, code);

            return(id);
        }
Пример #4
0
        public async Task <Guid> SendMessageAsync(
            string country,
            string phone,
            string ipAddress,
            string userAgent,
            CancellationToken ct)
        {
            var now           = DateTime.UtcNow;
            var code          = new Random().Next(0, 9999).ToString("0000");
            var identityTypes = new[] { IdentityType.PhoneAndPassword };
            var identity      = await _identitiesService.GetByKeyAndTypesAsync(phone, identityTypes, ct);

            var token = new IdentityToken
            {
                IdentityId         = identity.Id,
                Type               = IdentityTokenType.PhoneValidation,
                Value              = code,
                CreateDateTime     = now,
                ExpirationDateTime = now.AddMinutes(10),
                IpAddress          = ipAddress,
                UserAgent          = userAgent
            };

            var id = await _identityTokensService.CreateAsync(token, ct);

            var phoneWithPrefix = country.GetInternationalPhonePrefix() + phone;

            await SendCodeAsync(phoneWithPrefix, code);

            return(id);
        }
        public IdentityTokenResponse PostJSONToken(IdentityTokenRequest token)
        {
            IdentityTokenResponse response = new IdentityTokenResponse();

            try
            {
                IdentityToken identityToken = null;

                using (DecodedJsonToken decodedToken = JsonTokenDecoder.Decode(token))
                {
                    if (decodedToken.IsValid)
                    {
                        identityToken = new IdentityToken(token, decodedToken.Audience, decodedToken.AuthMetadataUri);
                    }
                }

                response.token = identityToken;
            }
            catch (Exception ex)
            {
                response.errorMessage = ex.Message;
            }

            return(response);
        }
Пример #6
0
        public void LoginTestMethod1()
        {
            Configuration.Configure();
            AccountBussiness accountBussines = new AccountBussiness();
            SignInMessage    msg             = new SignInMessage();

            msg.UserName = "******";
            RSAEncryptionCreator encryption = new RSAEncryptionCreator();

            msg.Password = encryption.PublicEncryption("123");
            msg.ClientId = "1";
            var result = accountBussines.Authenticate(msg);

            Assert.AreNotEqual(result.HasError, true);
            Assert.AreNotEqual(result.IdentityToken.Signature, string.Empty);

            TokenValidator validator       = new TokenValidator();
            var            tokenValidation = validator.ValiateIdentityToken(result.IdentityToken);
            var            strToken        = result.IdentityToken.ToString();
            IdentityToken  cToken          = new IdentityToken(strToken);
            var            strCtoken       = cToken.ToString();

            Assert.AreEqual(strToken, strCtoken);
            Assert.AreEqual(tokenValidation.IsError, true);
        }
Пример #7
0
        public async Task LoadNewToken(RefreshTokenResponse response)
        {
            IdentityToken = new IdentityToken(response.IdentityToken);
            await _tokenRepo.SaveIdentityToken(response.IdentityToken);

            await _tokenRepo.SaveRefreshToken(response.RefreshToken);
        }
Пример #8
0
        public static UserInformation GenerateUserInfo(AccessToken aToken, IdentityToken iToke)
        {
            int  userId   = 0;
            int  perId    = 0;
            int  actionId = -1;
            bool noUpdate = false;

            int.TryParse(iToke.ClaimValue(ClaimTypes.Subject), out userId);
            string fname    = iToke.ClaimValue(ClaimTypes.Name);
            string lname    = iToke.ClaimValue(ClaimTypes.FamilyName);
            string userName = iToke.ClaimValue(ClaimTypes.PreferredUserName);

            int.TryParse(iToke.ClaimValue(ClaimTypes.PersonId), out perId);
            var actionOperation = aToken.Operations.Where(it => it.IsActionId > 0).FirstOrDefault();
            var viewOperation   = aToken.Operations.Where(it => it.OperationName.ToLower() == "view").FirstOrDefault();

            if (actionOperation != null)
            {
                actionId = (int)actionOperation.OperationId;
            }
            if (viewOperation != null && aToken.Operations.Count == 1)
            {
                noUpdate = true;
            }
            UserInformation userInfo = new UserInformation(userId, userName, fname, lname, perId, actionId, noUpdate);

            return(userInfo);
        }
Пример #9
0
        public async Task LoadFromRepoAsync()
        {
            User = await GetUserObjectAsync();

            Permissions   = new PermissionsToken(await _tokenRepo.GetPermissionsTokenAsync());
            IdentityToken = new IdentityToken(await GetIdentityTokenAsync());
        }
        /// <inheritdoc/>
        /// <remarks>
        /// This method calls <see cref="ProviderBase{TProvider}.PrepareRequestImpl"/> to create the
        /// initial <see cref="HttpWebRequest"/>, and then sets the <c>Client-Id</c> header according
        /// to the Marconi (Cloud Queues) specification before returning.
        /// </remarks>
        protected override HttpWebRequest PrepareRequestImpl(HttpMethod method, IdentityToken identityToken, UriTemplate template, Uri baseUri, IDictionary <string, string> parameters, Func <Uri, Uri> uriTransform)
        {
            HttpWebRequest request = base.PrepareRequestImpl(method, identityToken, template, baseUri, parameters, uriTransform);

            request.Headers["Client-Id"] = _clientId.ToString("D");
            return(request);
        }
Пример #11
0
 private static bool IsValidToken(IdentityToken token, string code)
 {
     return(token != null &&
            !token.UseDateTime.HasValue &&
            token.ExpirationDateTime >= DateTime.UtcNow &&
            token.Type == IdentityTokenType.PasswordReset &&
            token.Value == code);
 }
Пример #12
0
        public static void SetToken(IdentityToken token)
        {
            // HttpContext.Current.Session["identityToken"] = token;
            var strToken = token.ToString();
            var encToken = ISE.Framework.Utility.Utils.Encryption.EncryptData(strToken);

            HttpContext.Current.Response.Cookies.Add(new HttpCookie("identityToken", encToken));
        }
Пример #13
0
        public ActionResult ExternalTokenLogin()
        {
            string                 encToken   = Request.Headers["Authorization"].ToString();
            var                    token      = ISE.Framework.Utility.Utils.Encryption.DecryptData(encToken);
            IdentityToken          itoken     = new IdentityToken(token);
            AuthorizationPresenter presenter  = new AuthorizationPresenter();
            var                    validateor = presenter.ValidateIdentityToken(itoken);

            return(RedirectToAction("About", "Home"));
        }
        public void Logout(IdentityToken token, string clientId)
        {
            SignOutMessage msg = new SignOutMessage()
            {
                ClientId      = clientId,
                IdentityToken = token
            };
            var result = AuthenticationServiceAdapter.Execute(it => it.Logout(msg));

            token = result.IdentityToken;
        }
        public AuthorizationResult CheckAccess(SecurityResourceDto resource, IdentityToken token)
        {
            AuthorizationRequest request = new AuthorizationRequest()
            {
                IdentityToken = token,
                Resource      = resource
            };
            var result = AuthorizationServiceAdapter.Execute(it => it.CheckAccess(request));

            //if (result.HasError)
            //    return null;
            return(result);
        }
Пример #16
0
        public async Task LoadLoginResponse(LoginResponse loginResponse)
        {
            IdentityToken = new IdentityToken(loginResponse.IdentityToken);
            Permissions   = new PermissionsToken(loginResponse.PermissionsToken);
            User          = loginResponse.MappedUser;

            await SaveUserObject(User);

            await _tokenRepo.SaveIdentityToken(loginResponse.IdentityToken);

            await _tokenRepo.SavePermissionsToken(loginResponse.PermissionsToken);

            await _tokenRepo.SaveRefreshToken(loginResponse.RefreshToken);
        }
Пример #17
0
        public void BuildAUser()
        {
            string        userId    = "TestUserId";
            string        firstName = "First";
            string        lastName  = "Last";
            IdentityToken token     = new IdentityToken(userId);
            var           roles     = GetUserRoles();

            var target = new User(1, userId, firstName, lastName, token, roles);

            Assert.Equal(userId, target.UserId);
            Assert.Equal(firstName, target.FirstName);
            Assert.Equal(lastName, target.LastName);
            Assert.NotEmpty(target.Token.Token);
        }
Пример #18
0
        /// <summary>
        /// Ensures the lifespan.
        /// </summary>
        /// <param name="token">The token.</param>
        /// <returns></returns>
        public IdentityResponse <IdentityToken> EnsureLifespan(IdentityToken token = null)
        {
            if (token?.HasExpired() == false)
            {
                return(new IdentityResponse <IdentityToken>
                {
                    StatusCode = HttpStatusCode.OK,
                    StatusMessage = HttpStatusCode.OK.ToString(),
                    Token = token,
                });
            }

            var response = RefreshToken(token);

            return(response);
        }
        public List <SecurityResourceDto> GetMenuList(IdentityToken token, int appDomainId)
        {
            AuthorizationRequest request = new AuthorizationRequest()
            {
                AppDomainId   = appDomainId,
                IdentityToken = token,
            };
            var result = AuthorizationServiceAdapter.Execute(it => it.MenuList(request));

            if (result.Response.HasException)
            {
                return(null);
            }

            return(result.SecurityResourceDtoList);
        }
        public async System.Threading.Tasks.Task <AppointmentProxyResponse> PostServiceRequest(AppointmentProxyRequest proxyRequest)
        {
            AppointmentProxyResponse proxyResponse = new AppointmentProxyResponse();

            try
            {
                IdentityToken identityToken       = null;
                var           organizerDomain     = string.Empty;
                var           thirdPartyEventId   = (string.IsNullOrEmpty(proxyRequest.thirdPartyEventId)) ? string.Empty : proxyRequest.thirdPartyEventId;
                var           thirdPartySecretKey = string.Empty;

                using (DecodedJsonToken decodedToken = JsonTokenDecoder.Decode(proxyRequest))
                {
                    if (decodedToken.IsValid)
                    {
                        identityToken = new IdentityToken(proxyRequest, decodedToken.Audience, decodedToken.AuthMetadataUri);

                        // todo - add whatever logic you need to do here
                        if (!string.IsNullOrEmpty(proxyRequest.organizerEmailAddress))
                        {
                            organizerDomain = proxyRequest.organizerEmailAddress.Split('@')[1];
                        }

                        if (string.IsNullOrEmpty(thirdPartyEventId))
                        {
                            thirdPartyEventId = $"KF{Guid.NewGuid().ToString()}";
                        }

                        var secretKey = organizerDomain.Replace('.', '-');

                        thirdPartySecretKey = await KeyVaultClientHelper.GetDomainSecret(secretKey);
                    }
                }

                proxyResponse.token               = identityToken;
                proxyResponse.organizerTenant     = organizerDomain;
                proxyResponse.thirdPartyEventId   = thirdPartyEventId;
                proxyResponse.thirdPartySecretKey = thirdPartySecretKey;
            }
            catch (Exception ex)
            {
                proxyResponse.errorMessage = ex.Message;
            }

            return(proxyResponse);
        }
Пример #21
0
        public Task <LoginCommandResponse> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            return(Task.Run(() =>
            {
                var userNames = GetUserNames(request.userId);
                var token = new IdentityToken(request.userId);
                User user = null;
                //new User(
                //    1, // TODO: hardcoded key
                //    request.userId,
                //    userNames.Item1,
                //    userNames.Item2,
                //    token,
                //    GetUserRoles(request.userId));

                return new LoginCommandResponse(user, (userNames.Item1 != "Guest"));
            }, cancellationToken));
        }
Пример #22
0
        /// <summary>
        ///     创建合法用户获取访问令牌接口数据
        /// </summary>
        /// <param name="identityUser">IdentityUser</param>
        /// <param name="appConfig">AppConfig</param>
        /// <returns>IdentityToken</returns>
        public OperatedResult <IdentityToken> CreateIdentityToken(IdentityUser identityUser, AppConfig appConfig)
        {
            ValidateOperator.Begin()
            .NotNull(identityUser, "IdentityUser")
            .NotNull(appConfig, "AppConfig");
            var payload = new Dictionary <string, object>
            {
                { "iss", identityUser.UserId },
                { "iat", UnixEpochHelper.GetCurrentUnixTimestamp().TotalSeconds }
            };
            var identityToken = new IdentityToken
            {
                AccessToken = CreateIdentityToken(appConfig.SharedKey, payload),
                ExpiresIn   = appConfig.TokenExpiredDay * 24 * 3600
            };

            return(OperatedResult <IdentityToken> .Success(identityToken));
        }
Пример #23
0
        /// <summary>
        /// Refreshes the token.
        /// </summary>
        /// <param name="token">The token.</param>
        /// <returns></returns>
        public IdentityResponse <IdentityToken> RefreshToken(IdentityToken token)
        {
            if (DateTimeOffset.UtcNow >= token?.ExpireTime ||
                string.IsNullOrWhiteSpace(token?.RefreshToken) == true)
            {
                var authResponse = _onAuthRequest?.Invoke(this);

                return(authResponse ?? new IdentityResponse <IdentityToken>
                {
                    StatusCode = HttpStatusCode.Unauthorized,
                    StatusMessage = HttpStatusCode.Unauthorized.ToString(),
                });
            }

            var response = _identityAccess.GetUserRefreshToken(token?.RefreshToken);

            return(response);
        }
Пример #24
0
        public TokenValidationResult ValiateIdentityToken(IdentityToken token)
        {
            if (token != null)
            {
                TokenValidationResult result = new TokenValidationResult();
                if (DateTime.Now > token.ExpirationTime)
                {
                    result.Error   = "Token Expired.";
                    result.IsValid = false;
                    return(result);
                }
                var hashData  = HashFactory.GetHash(token.PayloadString());
                var plainData = TokenSignFactory.GetHashData(token.Signature);
                if (!string.Equals(hashData, plainData))
                {
                    result.Error   = "Token Not Verified.";
                    result.IsValid = false;
                    return(result);
                }
                SessionBussiness sessionBs = new SessionBussiness();


                var session = sessionBs.GetSingle(it => it.SecuritySessionId == token.SessionId);
                if (session != null)
                {
                    if (session.ExpiredDate != null)
                    {
                        result.Error   = "Session Is Expired.";
                        result.IsValid = false;
                        return(result);
                    }
                }
                else
                {
                    result.Error   = "Session not exist.";
                    result.IsValid = false;
                    return(result);
                }
                result.IsValid = true;
                return(result);
            }
            return(null);
        }
Пример #25
0
        public IdentityToken ExpireToken(IdentityToken token)
        {
            SessionBussiness sessionBs = new SessionBussiness();

            TokenValidator tokenValidator   = new TokenValidator();
            var            validationResult = tokenValidator.ValiateIdentityToken(token);

            if (validationResult.IsError)
            {
                return(token);
            }
            if (token.HasLogin)
            {
                sessionBs.ExpireSession(token.SessionId);
                token.HasLogin = false;
                TokenSigner.SignIdentityToken(token);
            }
            return(token);
        }
Пример #26
0
        private async Task <string> GetTokenAsync()
        {
            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("grant_type", "password"),
                new KeyValuePair <string, string>("username", UserName),
                new KeyValuePair <string, string>("password", Password)
            });

            HttpResponseMessage response = await client.PostAsync("Token", content);

            if (response.IsSuccessStatusCode)
            {
                IdentityToken identityToken = await response.Content.ReadAsAsync <IdentityToken>();

                return(identityToken.AccessToken);
            }

            return(null);
        }
Пример #27
0
        public async Task <ActionResult> Create(CreateProduct request)
        {
            var authorizationHeader = HttpContext.Request.Headers["Authorization"];
            var idToken             = new IdentityToken(AuthenticationHeaderValue.Parse(authorizationHeader));

            try
            {
                _logger.LogInformation($"in create function...UserId-{idToken.UserId} and Role-{idToken.Role}");
                var result = await _mediator.Send(request);

                _logger.LogInformation("out from repo function...");

                throw new Exception("this is test exception");
                //return new OkObjectResult(result);
            }
            catch (Exception ex)
            {
                return(LogExceptionHelper.CreateApiError(ex, _logger));
            }
        }
Пример #28
0
        public async Task <Guid> CreateAsync(IdentityToken token, CancellationToken ct)
        {
            var newToken = new IdentityToken
            {
                Id                 = Guid.NewGuid(),
                IdentityId         = token.IdentityId,
                Type               = token.Type,
                Value              = token.Value,
                CreateDateTime     = DateTime.UtcNow,
                ExpirationDateTime = token.ExpirationDateTime,
                IpAddress          = token.IpAddress,
                UserAgent          = token.UserAgent
            };

            var entry = await _storage.AddAsync(newToken, ct);

            await _storage.SaveChangesAsync(ct);

            return(entry.Entity.Id);
        }
        /// <summary>
        /// Gets the authentication token for the specified impersonation identity. If necessary, the
        /// identity is authenticated on the server to obtain a token.
        /// </summary>
        /// <remarks>
        /// If <paramref name="forceCacheRefresh"/> is <see langword="false"/> and a cached <see cref="IdentityToken"/>
        /// is available for the specified <paramref name="identity"/>, this method may return the cached
        /// value without performing an authentication against the server. If <paramref name="forceCacheRefresh"/>
        /// is <see langword="true"/>, this method always authenticates the identity with the server.
        /// </remarks>
        /// <param name="identity">The identity of the user to authenticate. If this value is <see langword="null"/>, the authentication is performed with the <see cref="DefaultIdentity"/>.</param>
        /// <param name="forceCacheRefresh">If <see langword="true"/>, the user is always authenticated against the server; otherwise a cached <see cref="IdentityToken"/> may be returned.</param>
        /// <returns>The user's authentication token.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="identity"/> is <see langword="null"/>.</exception>
        /// <exception cref="NotSupportedException">If the provider does not support the given <paramref name="identity"/> type.</exception>
        /// <exception cref="InvalidOperationException">If <paramref name="identity"/> is <see langword="null"/> and no default identity is available for the provider.</exception>
        /// <exception cref="ResponseException">If the authentication request failed.</exception>
        protected virtual UserAccess Impersonate(RackspaceImpersonationIdentity identity, bool forceCacheRefresh)
        {
            if (identity == null)
            {
                throw new ArgumentNullException("identity");
            }

            var impToken = TokenCache.Get(string.Format("{0}:{1}/imp/{2}/{3}", UrlBase, identity.Username, identity.UserToImpersonate.Domain == null ? "none" : identity.UserToImpersonate.Domain.Name, identity.UserToImpersonate.Username), () =>
            {
                const string urlPath = "/v2.0/RAX-AUTH/impersonation-tokens";
                var request          = BuildImpersonationRequestJson(identity.UserToImpersonate.Username, 600);
                var parentIdentity   = new RackspaceCloudIdentity(identity);
                var response         = ExecuteRESTRequest <UserImpersonationResponse>(parentIdentity, new Uri(UrlBase, urlPath), HttpMethod.POST, request);
                if (response == null || response.Data == null || response.Data.UserAccess == null)
                {
                    return(null);
                }

                IdentityToken impersonationToken = response.Data.UserAccess.Token;
                if (impersonationToken == null)
                {
                    return(null);
                }

                var userAccess = ValidateToken(impersonationToken.Id, identity: parentIdentity);
                if (userAccess == null)
                {
                    return(null);
                }

                var endpoints = ListEndpoints(impersonationToken.Id, parentIdentity);

                var serviceCatalog = BuildServiceCatalog(endpoints);

                return(new UserAccess(userAccess.Token, userAccess.User, serviceCatalog));
            }, forceCacheRefresh);

            return(impToken);
        }
Пример #30
0
        public void TestGetToken()
        {
            IIdentityProvider provider = new CloudIdentityProvider(Bootstrapper.Settings.TestIdentity);

            IdentityToken token = provider.GetToken();

            Assert.IsNotNull(token);

            // ensure the provider is caching the access token
            IdentityToken cachedToken = provider.GetToken();

            Assert.AreSame(token, cachedToken);

            // ensure that the provider refreshes the token upon request
            IdentityToken newToken = provider.GetToken(forceCacheRefresh: true);

            Assert.AreNotSame(token, newToken);

            // ensure the the refresh was applied to the cache
            IdentityToken newCachedToken = provider.GetToken();

            Assert.AreSame(newToken, newCachedToken);
        }
Пример #31
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ClientHelper"/> class.
 /// </summary>
 public ClientHelper()
     : base()
 {
     m_authenticationMethod = DefaultAuthenticationMethod;
     m_authenticationInput = DefaultAuthenticationInput;
     m_persistSettings = DefaultPersistSettings;
     m_settingsCategory = DefaultSettingsCategory;
 }