public async Task <ActionResult> Index(UserProfileModel userProfile)
        {
            string id_token     = GenerateJWTClientToken(userProfile);
            string redirect_uri = this.Request.Query["redirect_uri"];
            string state        = this.Request.Query["state"];
            string rid          = this.Request.Query["rid"];

            IdentityEntity identityEntity = await GetIdentityEntity(rid);

            // Check the request
            if (!isValidRequest(identityEntity, redirect_uri))
            {
                return(View("Error"));
            }

            // Update the account
            AzureADGraphClient azureADGraphClient = new AzureADGraphClient(this.AppSettings.Tenant, this.AppSettings.ClientId, this.AppSettings.ClientSecret);

            // Create the user using Graph API
            await azureADGraphClient.UpdateAccount(identityEntity.userId, userProfile.City);

            // Wait until user is updated
            //await Task.Delay(2500);

            // Delete the entity
            await DeleteIdentityEntity(identityEntity);

            string redirectUri = $"{redirect_uri}?id_token={id_token}&state={state}";

            return(Redirect(redirectUri));
        }
Exemple #2
0
        /// <summary>
        /// 登入
        /// </summary>

        protected virtual void LoginUser()
        {
            if (GetMark() != Mark)
            {
                Response.Redirect("Default.aspx");
                return;
            }
            var login = new LoginEntity {
                Name = UserName, Type = "IgnorePassword"
            };
            var info     = Ioc.Resolve <ILoginApplicationService>().Login(login);
            var identity = new IdentityEntity {
                Name = login.Name
            };
            var error = info.Errors?.FirstOrDefault();

            if (info.Errors == null || info.Errors.Count == 0)
            {
                Ioc.Resolve <IIdentityApplicationService>().Set(info.Identity);
                identity = info.Identity;
                this.AddLoginLog(identity, error == null ? "" : error.Message);
                this.RedirectDefaultPage();
            }
            else
            {
                this.AddLoginLog(identity, error == null ? "" : error.Message);
                Response.Redirect("Default.aspx");
            }
        }
Exemple #3
0
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (IsShowCode && !CodeHelper.ValidateCode(txtCode.Value, "AdminCode"))
            {
                this.ExecuteScript("alert(\'验证码错误\');");
                return;
            }
            var login = new LoginEntity {
                Name = txtUserName.Value.Trim(), Password = txtPassword.Value.Trim()
            };
            var info     = Ioc.Resolve <ILoginApplicationService>().Login(login);
            var identity = new IdentityEntity {
                Name = login.Name
            };
            var error = info.Errors?.FirstOrDefault();

            if (info.Errors == null || info.Errors.Count == 0)
            {
                identity = info.Identity;
                Ioc.Resolve <IIdentityApplicationService>().Set(info.Identity);
                CodeHelper.RemoveCodeErrorCount(CodeName);
                this.AddLoginLog(identity, error == null ? "" : error.Message);
                this.RedirectDefaultPage();
            }
            else
            {
                CodeHelper.AddCodeErrorCount(CodeName);
                this.ExecuteScript(string.Format("alert('{0}')", info.Errors[0].Message), false);
                this.AddLoginLog(identity, error == null ? "" : error.Message);
            }
        }
        private async Task DeleteIdentityEntity(IdentityEntity identityEntity)
        {
            CloudTable table = await GetSignUpTable();

            // Delete the entity
            TableOperation deleteOperation = TableOperation.Delete(identityEntity);
            await table.ExecuteAsync(deleteOperation);
        }
 /// <summary>
 /// Validates the request
 /// </summary>
 private bool isValidRequest(IdentityEntity identityEntity, string redirect_uri)
 {
     // Check:
     //    1) request is existed in Azure Blob storage
     //    2) IP source
     //    3) redirect URL is the one registered in the app settings
     return(identityEntity != null &&
            (this.Request.HttpContext.Connection.RemoteIpAddress.ToString() != identityEntity.ipAddress) &&
            (redirect_uri.ToLower().StartsWith(AppSettings.AuthorizedRedirectUri.ToLower())));
 }
Exemple #6
0
        public void should_insert_entity_with_null_value()
        {
            var entity = new IdentityEntity();

            _identityTable1.Insert(entity);
            entity.Id.ShouldNotEqual(0);
            var newEntity = _identityTable1.First(x => x.Id == entity.Id);

            newEntity.Name.ShouldBeNull();
        }
Exemple #7
0
 public void Insert_Identity_Entity_Test()
 {
     var entity = new IdentityEntity();
     entity.Name = "oh hai";
     entity.Values.Add("timestamp", DateTime.Now);
     entity.Values.Add("hide", true);
     _identityTable1.Insert(entity);
     entity.Id.ShouldBeGreaterThan(0);
     var newEntity = _identityTable1.First(x => x.Id == entity.Id);
     newEntity.Name.ShouldEqual("oh hai");
     newEntity.Values["timestamp"].ToString().ShouldEqual(entity.Values["timestamp"].ToString());
     newEntity.Values["hide"].ShouldEqual(entity.Values["hide"]);
 }
Exemple #8
0
        /// <summary>
        /// 保存用户名
        /// </summary>
        public virtual void SaveUserName(Controller controller, TokenEntity token, IdentityEntity identity)
        {
            if (token == null || identity == null)
            {
                return;
            }
            var cookie = new HttpCookie("username")
            {
                Expires = DateTime.Now.AddMinutes(token.TimeOut),
                Value   = controller.Server.UrlEncode(identity.Name)
            };

            controller.Response.AppendCookie(cookie);
        }
Exemple #9
0
        /// <summary>
        /// 设置登录信息
        /// </summary>
        /// <param name="model"></param>
        /// <param name="token"></param>
        /// <param name="identity"></param>
        protected virtual void SetLoginCookie(LoginModel model, TokenEntity token, IdentityEntity identity)
        {
            if (identity == null || !model.IsSaveCookie)
            {
                return;
            }
            var usernamecookie = new HttpCookie("username")
            {
                Expires = DateTime.Now.AddDays(7),
                Value   = Server.UrlEncode(identity.Name)
            };

            Response.AppendCookie(usernamecookie);
        }
Exemple #10
0
        public void Insert_Identity_Entity_Test()
        {
            var entity = new IdentityEntity();

            entity.Name = "oh hai";
            entity.Values.Add("timestamp", DateTime.Now);
            entity.Values.Add("hide", true);
            _identityTable1.Insert(entity);
            entity.Id.ShouldBeGreaterThan(0);
            var newEntity = _identityTable1.First(x => x.Id == entity.Id);

            newEntity.Name.ShouldEqual("oh hai");
            newEntity.Values["timestamp"].ToString().ShouldEqual(entity.Values["timestamp"].ToString());
            newEntity.Values["hide"].ShouldEqual(entity.Values["hide"]);
        }
        public async Task <ActionResult> Index()
        {
            ViewData["rid"]          = this.Request.Query["rid"].ToString();
            ViewData["redirect_uri"] = this.Request.Query["redirect_uri"];
            ViewData["state"]        = this.Request.Query["state"];

            IdentityEntity identityEntity = await GetIdentityEntity(Request.Query["rid"]);

            // Check the request id
            if (!isValidRequest(identityEntity, this.Request.Query["redirect_uri"]))
            {
                return(View("Error"));
            }

            return(View());
        }
Exemple #12
0
        /// <summary>
        /// 添加登入日志
        /// </summary>
        /// <param name="page"></param>
        /// <param name="identity"></param>
        /// <param name="message"></param>
        public static void AddLoginLog(this Page page, IdentityEntity identity, string message)
        {
            var info = new LoginEntity
            {
                Type    = "User",
                Ip      = GetClientIp(),
                Address = page.Request.Url.ToString(),
                Device  = page.Request.UserAgent,
                Account = new AccountEntity {
                    Id = identity.Id
                },
                Message  = message,
                SaveType = SaveType.Add
            };

            Ioc.Resolve <IApplicationService, LoginEntity>().Save(info);
        }
Exemple #13
0
        /// <summary>
        /// 异步
        /// </summary>
        /// <param name="page"></param>
        /// <param name="identity"></param>
        /// <param name="name"></param>
        /// <param name="control"></param>
        /// <param name="detail"></param>
        private static void BeginAddOperationLog(Page page, IdentityEntity identity, string name, string control, string detail)
        {
            var info = new OperationEntity
            {
                Type    = "WebForm",
                Name    = name,
                Ip      = GetClientIp(),
                Address = page.Request.Url.ToString(),
                Device  = page.Request.UserAgent,
                Account = new AccountEntity {
                    Id = identity.Id
                },
                Detail   = detail,
                Control  = control,
                SaveType = SaveType.Add
            };

            Ioc.Resolve <IApplicationService, OperationEntity>().Save(info);
        }
        /// <summary>
        /// 添加错误信息
        /// </summary>
        public static void AddExceptionLog(this Controller handle, Exception ex, IdentityEntity identity = null)
        {
            var info = new ErrorEntity
            {
                Address  = HttpContext.Current.Request.Url.ToString(),
                Ip       = HttpContextHelper.GetClientIp(),
                Device   = HttpContext.Current.Request.UserAgent,
                SaveType = SaveType.Add
            };

            if (identity != null)
            {
                info.Account = new AccountEntity {
                    Id = identity.Id
                };
            }
            info.SetEntity(ex);
            Ioc.Resolve <IApplicationService, ErrorEntity>().Save(info);
        }
        /// <summary>
        /// 添加登入日志
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="identity"></param>
        /// <param name="type"></param>
        /// <param name="message"></param>
        public static void AddLoginLog(this Controller controller, IdentityEntity identity, string type, string message)
        {
            if (identity == null)
            {
                return;
            }
            var info = new LoginEntity
            {
                Type    = string.IsNullOrEmpty(type) ? "Account" : type,
                Ip      = HttpContextHelper.GetClientIp(),
                Address = controller.Request.Url.ToString(),
                Device  = controller.Request.UserAgent,
                Account = new AccountEntity {
                    Id = identity.Id
                },
                Message  = message,
                SaveType = SaveType.Add
            };

            Ioc.Resolve <IApplicationService, LoginEntity>().Save(info);
        }
        /// <summary>
        /// 添加登入日志
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="identity"></param>
        /// <param name="type"></param>
        /// <param name="ip"></param>
        /// <param name="city"></param>
        /// <param name="address"></param>
        /// <param name="device"></param>
        /// <param name="message"></param>
        public static void AddLoginLog(this Controller controller, IdentityEntity identity, string type, string ip, string city, string address, string device, string message)
        {
            if (identity == null)
            {
                return;
            }
            var info = new LoginEntity
            {
                Type    = string.IsNullOrEmpty(type)?"Account":type,
                Ip      = ip,
                Address = address,
                City    = city,
                Device  = device,
                Account = new AccountEntity {
                    Id = identity.Id
                },
                Message  = message,
                SaveType = SaveType.Add
            };

            Ioc.Resolve <IApplicationService, LoginEntity>().Save(info);
        }
Exemple #17
0
        public async Task <long> GenerateIdAsync(string entityType)
        {
            long id     = 0;
            var  result =
                await
                _tableStorage.InsertOrModifyAsync(IdentityEntity.GeneratePartitionKey(entityType),
                                                  IdentityEntity.GenerateRowKey,
                                                  () => IdentityEntity.Create(entityType),
                                                  itm =>
            {
                itm.Value++;
                id = itm.Value;
                return(true);
            }
                                                  );


            if (!result)
            {
                throw new InvalidOperationException("Error generating ID");
            }

            return(id);
        }
Exemple #18
0
        Task WriteIdentityEntityAsync(string identityUid, IdentityEntity identityConfiguration)
        {
            if (identityUid == null)
            {
                throw new ArgumentNullException(nameof(identityUid));
            }
            if (identityConfiguration == null)
            {
                throw new ArgumentNullException(nameof(identityConfiguration));
            }

            var filename = Path.Combine(_rootPath, identityUid);

            if (!Directory.Exists(filename))
            {
                Directory.CreateDirectory(filename);
            }

            filename = Path.Combine(filename, DefaultFileNames.Configuration);

            var json = JsonConvert.SerializeObject(identityConfiguration);

            return(File.WriteAllTextAsync(filename, json, Encoding.UTF8));
        }
Exemple #19
0
        public async Task <ActionResult> PostAsync()
        {
            string input = null;

            // If not data came in, then return
            if (this.Request.Body == null)
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("Request content is null", HttpStatusCode.Conflict)));
            }

            // Read the input claims from the request body
            using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
            {
                input = await reader.ReadToEndAsync();
            }

            // Check input content value
            if (string.IsNullOrEmpty(input))
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("Request content is empty", HttpStatusCode.Conflict)));
            }

            // Convert the input string into IdentityClaims object
            IdentityClaims inputClaims = IdentityClaims.Parse(input);

            if (inputClaims == null)
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("Can not deserialize input claims", HttpStatusCode.Conflict)));
            }

            if (string.IsNullOrEmpty(inputClaims.signInName))
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("User 'signInName' is null or empty", HttpStatusCode.Conflict)));
            }

            if (string.IsNullOrEmpty(inputClaims.password))
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("User 'password' is null or empty", HttpStatusCode.Conflict)));
            }

            // Create or reference an existing table
            CloudTable table = await Common.CreateTableAsync("identities");

            try
            {
                TableOperation retrieveOperation = TableOperation.Retrieve <IdentityEntity>("Account", inputClaims.signInName);
                TableResult    result            = await table.ExecuteAsync(retrieveOperation);

                IdentityEntity identityEntity = result.Result as IdentityEntity;
                if (identityEntity == null)
                {
                    return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("Account not found", HttpStatusCode.Conflict)));
                }

                if (inputClaims.password != identityEntity.password)
                {
                    return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("Bad username or password", HttpStatusCode.Conflict)));
                }

                IdentityClaims outputClaims = new IdentityClaims();
                outputClaims.signInName  = inputClaims.signInName;
                outputClaims.displayName = identityEntity.displayName;
                outputClaims.givenName   = identityEntity.givenName;
                outputClaims.surName     = identityEntity.surName;

                return(Ok(outputClaims));
            }
            catch (StorageException e)
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel(e.Message, HttpStatusCode.Conflict)));
            }
        }
Exemple #20
0
 public void should_insert_entity_with_null_value()
 {
     var entity = new IdentityEntity();
     _identityTable1.Insert(entity);
     entity.Id.ShouldNotEqual(0);
     var newEntity = _identityTable1.First(x => x.Id == entity.Id);
     newEntity.Name.ShouldBeNull();
 }
Exemple #21
0
        /// <summary>
        /// 添加登入日志
        /// </summary>
        /// <param name="page"></param>
        /// <param name="identity"></param>
        /// <param name="name"></param>
        /// <param name="control"></param>
        /// <param name="detail"></param>
        /// >
        public static void AddOperationLog(this Page page, IdentityEntity identity, string name, string control, string detail)
        {
            Action <Page, IdentityEntity, string, string, string> action = BeginAddOperationLog;

            action.BeginInvoke(page, identity, name, control, detail, null, null);
        }
        public async Task <ActionResult> CheckAppAttributes()
        {
            string input = null;

            // If not data came in, then return
            if (this.Request.Body == null)
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("Request content is null", HttpStatusCode.Conflict)));
            }

            // Read the input claims from the request body
            using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
            {
                input = await reader.ReadToEndAsync();
            }

            // Check input content value
            if (string.IsNullOrEmpty(input))
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("Request content is empty", HttpStatusCode.Conflict)));
            }

            // Convert the input string into InputClaimsModel object
            InputClaimsModel inputClaims = InputClaimsModel.Parse(input);

            if (inputClaims == null)
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("Can not deserialize input claims", HttpStatusCode.Conflict)));
            }

            if (string.IsNullOrEmpty(inputClaims.correlationId))
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("User 'requestId' is null or empty", HttpStatusCode.Conflict)));
            }

            if (string.IsNullOrEmpty(inputClaims.userId))
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("User 'userId' is null or empty", HttpStatusCode.Conflict)));
            }

            if (string.IsNullOrEmpty(inputClaims.ipAddress))
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("User 'ipAddress' is null or empty", HttpStatusCode.Conflict)));
            }

            if (string.IsNullOrEmpty(inputClaims.appId))
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("User 'appId' is null or empty", HttpStatusCode.Conflict)));
            }

            string requestId = Guid.NewGuid().ToString();

            try
            {
                if (inputClaims.appId == "0239a9cc-309c-4d41-87f1-31288feb2e82" && string.IsNullOrEmpty(inputClaims.city))
                {
                    CloudTable table = await GetSignUpTable();

                    IdentityEntity identityEntity = new IdentityEntity("SignInRequest", requestId);
                    identityEntity.ipAddress     = this.Request.HttpContext.Connection.RemoteIpAddress.ToString();
                    identityEntity.userId        = inputClaims.userId;
                    identityEntity.appId         = inputClaims.appId;
                    identityEntity.correlationId = inputClaims.correlationId.ToString();

                    TableOperation insertOperation = TableOperation.InsertOrReplace(identityEntity);
                    await table.ExecuteAsync(insertOperation);

                    //Output claims
                    B2CResponseModel b2CResponseModel = new B2CResponseModel("Ok", HttpStatusCode.OK);
                    b2CResponseModel.collectData = true;
                    b2CResponseModel.requestId   = EncryptAndBase64(requestId);

                    return(Ok(b2CResponseModel));
                }
                else
                {
                    //Output claims
                    B2CResponseModel b2CResponseModel = new B2CResponseModel("Ok", HttpStatusCode.OK);
                    b2CResponseModel.collectData = false;

                    return(Ok(b2CResponseModel));
                }
            }
            catch (Exception ex)
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel(ex.Message, HttpStatusCode.Conflict)));
            }
        }
 /// <summary>
 /// 得到票据
 /// </summary>
 /// <param name="info"></param>
 /// <returns></returns>
 public virtual string GetTicket(IdentityEntity info)
 {
     return(Guid.NewGuid().ToString().Replace("-", ""));
 }
Exemple #24
0
        public async Task <ActionResult> PostAsync()
        {
            string input = null;

            // If not data came in, then return
            if (this.Request.Body == null)
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("Request content is null", HttpStatusCode.Conflict)));
            }

            // Read the input claims from the request body
            using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
            {
                input = await reader.ReadToEndAsync();
            }

            // Check input content value
            if (string.IsNullOrEmpty(input))
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("Request content is empty", HttpStatusCode.Conflict)));
            }

            // Convert the input string into IdentityClaims object
            IdentityClaims inputClaims = IdentityClaims.Parse(input);

            if (inputClaims == null)
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("Can not deserialize input claims", HttpStatusCode.Conflict)));
            }

            if (string.IsNullOrEmpty(inputClaims.signInName))
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("User 'signInName' is null or empty", HttpStatusCode.Conflict)));
            }

            if (string.IsNullOrEmpty(inputClaims.password))
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel("User 'password' is null or empty", HttpStatusCode.Conflict)));
            }

            // Create or reference an existing table
            CloudTable table = await Common.CreateTableAsync("identities");

            var identityEntity = new IdentityEntity(inputClaims.signInName);

            identityEntity.displayName = inputClaims.displayName;
            identityEntity.password    = inputClaims.password;
            identityEntity.givenName   = inputClaims.givenName;
            identityEntity.surName     = inputClaims.surName;

            try
            {
                // Create the InsertOrReplace table operation
                TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(identityEntity);

                // Execute the operation.
                TableResult result = await table.ExecuteAsync(insertOrMergeOperation);
            }
            catch (StorageException e)
            {
                return(StatusCode((int)HttpStatusCode.Conflict, new B2CResponseModel(e.Message, HttpStatusCode.Conflict)));
            }
            return(Ok());
        }