public ActionResult List([FromQuery(Name = "ids")] string Ids) { List <int> IdArray = new List <int>(); if (Ids != null && Ids != "") { Ids.Split(",").ToList().ForEach(Id => { IdArray.Add(int.Parse(Id)); }); } var ListResponse = CustomHttpResponse.List <Category>(); var ResultResponse = new JsonResult(ListResponse); ResultResponse.ContentType = "application/json"; ResultResponse.StatusCode = 200; ListResponse.IsEnd = true; ListResponse.Results = this.CategoryBusinessInstance.List(IdArray); ListResponse.Length = ListResponse.Results.Count; ListResponse.RecordPerPage = ListResponse.Results.Count; ListResponse.Page = 1; ListResponse.Total = ListResponse.Results.Count; return(ResultResponse); }
public async Task <ActionResult> GetUser() { try { var Token = HttpContext.Request.Headers["Token"]; var users = await this.AccountServiceInstance.GetUser(Token); var ListResponse = CustomHttpResponse.List <UserView>(); ListResponse.Length = users.Count; ListResponse.Page = 1; ListResponse.IsEnd = true; ListResponse.RecordPerPage = users.Count; ListResponse.Total = users.Count; ListResponse.Results = users; return(Json(ListResponse)); } catch (CustomHttpResponseException ex) { var StateResponse = CustomHttpResponse.State(); StateResponse.Status = ex.CustomData.Status; StateResponse.Message = ex.CustomData.Message; var Response = Json(StateResponse); Response.StatusCode = ex.CustomData.StatusCode; return(Response); } catch (Exception) { var StateResponse = CustomHttpResponse.State(); StateResponse.Status = "Internal Server Error"; StateResponse.Message = "There is something wrong. Come back later please."; var Response = Json(StateResponse); Response.StatusCode = 500; return(Response); } }
public async Task <IActionResult> Update([FromBody] StoryAggregate StoryInstance) { try { string Token = HttpContext.Request.Headers["Token"]; StoryAggregate StoryAggregate = this.StoryBusinessInstance.Update(Token, StoryInstance); var Response = CustomHttpResponse.Single <StoryAggregate>(); var ResultResponse = new JsonResult(Response); ResultResponse.StatusCode = 200; ResultResponse.ContentType = "application/json"; Response.Result = StoryAggregate; return(ResultResponse); } catch (Exception ex) { Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++"); Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++"); Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++"); Console.WriteLine(JsonConvert.SerializeObject(ex)); var Response = CustomHttpResponse.State(); var ResultResponse = new JsonResult(Response); ResultResponse.StatusCode = 400; ResultResponse.ContentType = "application/json"; Response.Status = "BadRequest"; Response.Message = "Missing token"; return(ResultResponse); } }
public async Task <IActionResult> Get(string id) { IActionResult response = Unauthorized(); if (id.Length == 6) { if (CheckIsValidJwt()) { var resp = await _fireObj.GetEmployeesById(id); var jsonString = resp.Content.ReadAsStringAsync().Result; if (resp.StatusCode == HttpStatusCode.OK && (jsonString != "null" && jsonString != null)) { var emp = JsonConvert.DeserializeObject <Employees>(jsonString); response = Ok(emp); } else { response = CustomHttpResponse.Error(HttpStatusCode.NotFound, "UND002", "No Data Found.", "ไม่พบข้อมูล", "No data found."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, "UND999", "Unauthorized, Invalid AccessToken.", "แอพฯ ของคุณไม่มีสิทธิ์ใช้งาน เนื่องจาก AccessToken ไม่ถูกต้อง หรือหมดอายุแล้ว, กรุณาติดต่อผู้ดูแลแอพฯ ของคุณ", "The AccessToken is invalid or expired, please contact your Application Administrator."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.BadRequest, "UND001", "Invalid Request (Id '" + id + "').", "คุณไม่มีสิทธิ์ใช้งาน เนื่องจากส่งคำร้องขอมาไม่ถูกต้อง", "The request is invalid."); } return(response); }
public async Task <ActionResult> Get(string id) { Guid guid; if (Guid.TryParse(id, out guid)) { if (CheckIsValidJwt()) { // Data Payload var resp = await _fireObj.GetUserProfilesById(guid); var content = resp.Content.ReadAsStringAsync().Result; if (resp.StatusCode == HttpStatusCode.OK && (content != "null" && content != null && content != "")) { var user = JsonConvert.DeserializeObject <UserProfiles>(content); return(Ok(user)); } else { return(CustomHttpResponse.Error(HttpStatusCode.NotFound, "UND002", "No Data Found.", "ไม่พบข้อมูล", "No data found.")); } } else { return(CustomHttpResponse.Error(HttpStatusCode.Unauthorized, "UND999", "Unauthorized, Invalid AccessToken.", "แอพฯ ของคุณไม่มีสิทธิ์ใช้งาน เนื่องจาก AccessToken ไม่ถูกต้อง หรือหมดอายุแล้ว, กรุณาติดต่อผู้ดูแลแอพฯ ของคุณ", "The AccessToken is invalid or expired, please contact your Application Administrator.")); } } else { return(CustomHttpResponse.Error(HttpStatusCode.Unauthorized, "UND001", "Invalid Request (Id '" + id + "').", "คุณไม่มีสิทธิ์ใช้งาน เนื่องจากส่งคำร้องขอมาไม่ถูกต้อง", "The request is invalid.")); } }
public async Task <IHttpActionResult> GetById(int?id) { UserEntity userEntity = await _userService.GetUsersById(id); if (userEntity == null) { HttpResponseMessage response = CustomHttpResponse.SetNotFoundMessage("User ID not found."); throw new HttpResponseException(response); } return(Ok(userEntity)); }
public ActionResult Detail(int Id) { var SingleResponse = CustomHttpResponse.Single <Category>(); JsonResult ResultResponse = new JsonResult(SingleResponse); ResultResponse.ContentType = "application/json"; ResultResponse.StatusCode = 200; SingleResponse.Result = this.CategoryBusinessInstance.Detail(Id); return(ResultResponse); }
public IActionResult PublicDetail(int Id) { StoryAggregate StoryAggregate = this.StoryBusinessInstance.PublicDetail(Id); var Response = CustomHttpResponse.Single <StoryAggregate>(); var ResultResponse = new JsonResult(Response); ResultResponse.StatusCode = 200; ResultResponse.ContentType = "application/json"; Response.Result = StoryAggregate; return(ResultResponse); }
private async Task <bool> GenerateErrorResponse(DownstreamContext Context, int StatusCode, string ContentType, string Status, string Message) { var StateResponse = CustomHttpResponse.State(); Context.HttpContext.Response.StatusCode = StatusCode; Context.HttpContext.Response.ContentType = ContentType; StateResponse.Status = Status; StateResponse.Message = Message; var Response = JsonConvert.SerializeObject(StateResponse); var ResponseBytes = Encoding.UTF8.GetBytes(Response); await Context.HttpContext.Response.Body.WriteAsync(ResponseBytes, 0, ResponseBytes.Length); return(true); }
// GET /Auth/ public IActionResult Index([FromQuery] string response_type, string client_id, string redirect_uri, string state, string authen_to_system) { if (response_type != string.Empty && response_type != "null" && response_type != null && response_type.ToLower() == "code") { if (client_id != string.Empty && client_id != "null" & client_id != null) { if (redirect_uri != string.Empty && redirect_uri != "null" && redirect_uri != null) { if (authen_to_system != string.Empty && authen_to_system != "null" && authen_to_system != null) { var appAudObj = GetAppAudiencesById(client_id).Result; if (appAudObj != null) { var authCodeObj = new AuthorizationCodeModel(); authCodeObj.Authen_To_System = authen_to_system; authCodeObj.Client_Id = client_id; authCodeObj.Redirect_Uri = redirect_uri; authCodeObj.Response_Type = response_type; authCodeObj.State = state; authCodeObj.System_Name = appAudObj.Name; return(View(authCodeObj)); } else { return(CustomHttpResponse.Error(HttpStatusCode.BadRequest, Errors.InvalidOrEmpty_ClientAppId, "Client_Id is invalid")); } } else { return(CustomHttpResponse.Error(HttpStatusCode.BadRequest, Errors.ExceptionalOccured, "Authen_To_System is empty")); } } else { return(CustomHttpResponse.Error(HttpStatusCode.BadRequest, Errors.ExceptionalOccured, "Redirect_Uri is empty")); } } else { return(CustomHttpResponse.Error(HttpStatusCode.BadRequest, Errors.ExceptionalOccured, "Client_Id is empty")); } } else { return(CustomHttpResponse.Error(HttpStatusCode.BadRequest, Errors.ExceptionalOccured, "Response_Type is invalid")); } }
public ActionResult Clear() { var Folder = ""; this.EnsureUploadFolder(out Folder); var stateResponse = CustomHttpResponse.State(); stateResponse.Message = "All files are clear"; stateResponse.Status = "Done"; foreach (var FilePath in Directory.EnumerateFiles(Folder, "*", SearchOption.AllDirectories)) { System.IO.File.Delete(FilePath); } return(Json(stateResponse)); }
public async Task Invoke(HttpContext Context) { var Token = Context.Request.Headers.FirstOrDefault(h => h.Key == "Token").Value.ToString(); string Path = Context.Request.Path.ToString(); if (!Utilities.CheckExceptPaths(ExceptPaths, Path)) { if (!string.IsNullOrEmpty(Token)) { try { if (!Token.Contains("Bearer") || ((Token.Contains("Bearer") && !Token.StartsWith("Bearer")))) { throw new Exception("Invalid Token"); } Token = Token.Replace("Bearer", "").Trim(); var Handler = new JwtSecurityTokenHandler(); var JsonToken = Handler.ReadJwtToken(Token); } catch (Exception) { Context.Response.StatusCode = 401; var StateResponse = CustomHttpResponse.State(); StateResponse.Status = "Unauthorized"; StateResponse.Message = "Token Invalid"; var ResponseBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(StateResponse)); await Context.Response.Body.WriteAsync(ResponseBytes, 0, ResponseBytes.Length); return; } await Next(Context); } else { Context.Response.StatusCode = 403; var StateResponse = CustomHttpResponse.State(); StateResponse.Status = "Forbidden"; StateResponse.Message = "Missing token"; var ResponseBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(StateResponse)); await Context.Response.Body.WriteAsync(ResponseBytes, 0, ResponseBytes.Length); } } else { await Next(Context); } }
public ActionResult Initiate() { var ListResponse = CustomHttpResponse.List <Category>(); var ResultResponse = new JsonResult(ListResponse); ResultResponse.ContentType = "application/json"; ResultResponse.StatusCode = 200; ListResponse.IsEnd = true; ListResponse.Results = this.CategoryBusinessInstance.Initiate(); ListResponse.Length = ListResponse.Results.Count; ListResponse.RecordPerPage = ListResponse.Results.Count; ListResponse.Page = 1; ListResponse.Total = ListResponse.Results.Count; return(ResultResponse); }
public IActionResult PublicList() { List <StoryAggregate> StoryAggregate = this.StoryBusinessInstance.PublicList(); var ListResponse = CustomHttpResponse.List <StoryAggregate>(); var ResultResponse = new JsonResult(ListResponse); ResultResponse.StatusCode = 200; ResultResponse.ContentType = "application/json"; ListResponse.IsEnd = true; ListResponse.Length = StoryAggregate.Count; ListResponse.Page = 1; ListResponse.Total = StoryAggregate.Count; ListResponse.RecordPerPage = StoryAggregate.Count; ListResponse.Results = StoryAggregate; return(ResultResponse); }
public async Task <IHttpActionResult> Delete(int?id) { UserEntity userEntity = await _userService.GetUsersById(id); if (userEntity == null) { HttpResponseMessage response = CustomHttpResponse.SetNotFoundMessage("User ID not found."); throw new HttpResponseException(response); } await _userService.RemoveUser(id); int totalEntriesAffected = await _userService.SaveUser(); if (totalEntriesAffected > 0) { return(Ok("User deleted successfully.")); } return(BadRequest("User delete has failed.")); }
public async Task <IHttpActionResult> Update([FromBody] List <UserEntity> usersEntity) { List <UserEntity> usersEntityFound = _userService.GetUsersListInclude(usersEntity).ToList(); if (usersEntityFound == null) { HttpResponseMessage response = CustomHttpResponse.SetNotFoundMessage("User ID not found."); throw new HttpResponseException(response); } await _userService.UpdateUser(usersEntity); int totalEntriesAffected = await _userService.SaveUser(); if (totalEntriesAffected > 0) { return(Ok("User(s) updated successfully.")); } return(BadRequest("User(s) update has failed.")); }
public IActionResult List() { try { string Token = HttpContext.Request.Headers["Token"]; List <StoryAggregate> StoryAggregate = this.StoryBusinessInstance.List(Token); var ListResponse = CustomHttpResponse.List <StoryAggregate>(); var ResultResponse = new JsonResult(ListResponse); ResultResponse.StatusCode = 200; ResultResponse.ContentType = "application/json"; ListResponse.IsEnd = true; ListResponse.Length = StoryAggregate.Count; ListResponse.Page = 1; ListResponse.Total = StoryAggregate.Count; ListResponse.RecordPerPage = StoryAggregate.Count; ListResponse.Results = StoryAggregate; return(ResultResponse); } catch (Exception ex) { Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++"); Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++"); Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++"); Console.WriteLine(ex.Message); var Response = CustomHttpResponse.State(); var ResultResponse = new JsonResult(Response); ResultResponse.StatusCode = 400; ResultResponse.ContentType = "application/json"; Response.Status = "BadRequest"; Response.Message = "Missing token"; return(ResultResponse); } }
public async Task <ActionResult> Upload() { try { string Token = HttpContext.Request.Headers["Token"]; var Folder = ""; this.EnsureUploadFolder(out Folder); var FilePath = Path.Combine(Folder, DateTime.Now.Ticks.ToString()); Model.File FileInstance = await this.FileBusinessInstance.UploadFile(Request, Token, FilePath); var Response = CustomHttpResponse.Single <Model.File>(); var ResultResponse = new JsonResult(Response); ResultResponse.StatusCode = 200; ResultResponse.ContentType = "application/json"; Response.Result = FileInstance; return(ResultResponse); } catch (Exception ex) { Console.WriteLine("============================================="); Console.WriteLine("============================================="); Console.WriteLine("============================================="); Console.WriteLine(JsonConvert.SerializeObject(ex)); var Response = CustomHttpResponse.State(); var ResultResponse = new JsonResult(Response); ResultResponse.StatusCode = 400; ResultResponse.ContentType = "application/json"; Response.Status = "BadRequest"; Response.Message = "Missing token"; return(ResultResponse); } }
public async Task <IActionResult> Get([FromQuery] int?offset, int?limit) { IActionResult response = Unauthorized(); if (CheckIsValidJwt()) { // Data Payload var employees = new List <EmployeesPayload>(); var resp = await _fireObj.GetEmployees(); var jsonString = resp.Content.ReadAsStringAsync().Result; if (resp.StatusCode == HttpStatusCode.OK && (jsonString != "null" && jsonString != null)) { var jObj = JObject.Parse(jsonString); foreach (var item in jObj) { var emp = item.Value.ToObject <EmployeesPayload>(); var listTypes = new List <string>(); listTypes.Add("application/json"); emp.links = new EmployeesPayloadLinksDetail { rel = "Employee information of " + emp.Name + " " + emp.Surname, href = Request.Scheme + "://" + Request.Host + Request.Path.Value + "/" + emp.Id, action = "GET", types = listTypes }; if (emp.Status == true) { employees.Add(emp); } } // Pagination Payload var pTotal = employees.Count; var pOffset = 0; var pLimit = 0; var pNext = 0; var pPrev = 0; var pFirst = 0; var pLast = 0; if ((offset != null && limit != null)) // With Pagination QueryString { pOffset = offset.Value; if (offset >= 0 && limit >= 1) { employees = employees.OrderBy(u => u.Id).Skip(offset.Value).Take(limit.Value).ToList(); pLimit = limit.Value; pNext = pOffset + pLimit >= pTotal ? pOffset : pOffset + pLimit; pPrev = pOffset - pLimit < 0 ? 0 : pOffset - pLimit; pLast = (((pTotal - 1) - pOffset) % pLimit) == 0 ? pTotal - 1 : (pTotal - 1) - (((pTotal - 1) - pOffset) % pLimit); } } else // Without Pagination QueryString { pOffset = 0; if (pTotal < DEFAULT_LIMIT) { employees = employees.OrderBy(u => u.Id).Skip(0).Take(pTotal).ToList(); pLimit = pTotal; pNext = 0; pPrev = 0; pLast = 0; } else { employees = employees.OrderBy(u => u.Id).Skip(0).Take(DEFAULT_LIMIT).ToList(); pLimit = DEFAULT_LIMIT; pNext = pOffset + pLimit >= pTotal ? pOffset : pOffset + pLimit; pPrev = 0; pLast = (((pTotal - 1) - pOffset) % pLimit) == 0 ? pTotal - 1 : (pTotal - 1) - (((pTotal - 1) - pOffset) % pLimit); } } var pagination = new PaginationPayload { offset = pOffset, limit = pLimit, total = pTotal, links = new PaginationPayloadLinksDetail { next = Request.Scheme + "://" + Request.Host + Request.Path.Value + "?offset=" + pNext + "&limit=" + pLimit, prev = Request.Scheme + "://" + Request.Host + Request.Path.Value + "?offset=" + pPrev + "&limit=" + pLimit, first = Request.Scheme + "://" + Request.Host + Request.Path.Value + "?offset=" + pFirst + "&limit=" + pLimit, last = Request.Scheme + "://" + Request.Host + Request.Path.Value + "?offset=" + pLast + "&limit=" + pLimit } }; response = Ok(new { employees, pagination }); } else { response = CustomHttpResponse.Error(HttpStatusCode.NotFound, "UND002", "No Data Found.", "ไม่พบข้อมูล", "No data found."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, "UND999", "Unauthorized, Invalid AccessToken.", "แอพฯ ของคุณไม่มีสิทธิ์ใช้งาน เนื่องจาก AccessToken ไม่ถูกต้อง หรือหมดอายุแล้ว, กรุณาติดต่อผู้ดูแลแอพฯ ของคุณ", "The AccessToken is invalid or expired, please contact your Application Administrator."); } return(response); }
public IActionResult CreateToken([FromForm] AuthenticationModel authen) { IActionResult response = Unauthorized(); var objResult = new ObjectResult(String.Empty); try { if (ModelState.IsValid) // ModelState อาจจะไม่จำเป็นต้องใช้ หรือใช้ไม่ได้กับ API { if (authen.grant_type.ToLower() == GRANT_TYPE_CLIENT_CREDENTIALS) { if (authen.client_id != string.Empty && authen.client_id != "null" && authen.client_id != null) { if (authen.client_secret != string.Empty && authen.client_secret != "null" && authen.client_secret != null) { var appAudObj = GetAppAudiencesById(authen.client_id).Result; if (appAudObj != null) { if (appAudObj.ExpiryDate > DateTime.UtcNow) { if (appAudObj.AppSecretKey == authen.client_secret) { var refreshTokenObj = BuildRefreshToken(authen.username, authen.client_id, GRANT_TYPE_CLIENT_CREDENTIALS, authen.authen_to_system, authen.code); var accessTokenObj = BuildAccessToken(authen.username, authen.client_id, refreshTokenObj.RefreshToken, Jwt.Algorithm.ES256, GRANT_TYPE_CLIENT_CREDENTIALS); var tokenResp = new TokenResponse(); tokenResp.token_type = "Bearer"; tokenResp.access_token = accessTokenObj.AccessToken; tokenResp.expires_in = _config["Jwt:Expires"]; tokenResp.refresh_token = refreshTokenObj.RefreshToken; tokenResp.refresh_token_expires_in = _config["Jwt:RefreshTokenExpires"]; response = Ok(tokenResp); } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientSecretKey, "Unauthorized, Client App Secret Key (" + authen.client_secret + ") is invalid."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientAppId, "Unauthorized, Client App Id (" + authen.client_id + ") is expired (" + appAudObj.ExpiryDate + ")."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientAppId, "Unauthorized, Client App Id (" + authen.client_id + ") is invalid."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientSecretKey, "Unauthorized, Client App Secret Key is empty."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientAppId, "Unauthorized, Client App Id is empty."); } } else if (authen.grant_type.ToLower() == GRANT_TYPE_PASSWORD) { if (authen.client_id != string.Empty && authen.client_id != "null" && authen.client_id != null) { if (authen.client_secret != string.Empty && authen.client_secret != "null" && authen.client_secret != null) { if (authen.username != string.Empty && authen.username != "null" && authen.username != null) { if (authen.password != string.Empty && authen.password != "null" && authen.password != null) { if (authen.authen_to_system != string.Empty && authen.authen_to_system != "null" && authen.authen_to_system != null) { var appAudObj = GetAppAudiencesById(authen.client_id).Result; if (appAudObj != null) { if (appAudObj.ExpiryDate > DateTime.UtcNow) { if (appAudObj.AppSecretKey == authen.client_secret) { var IsValidated = false; switch (authen.authen_to_system.ToLower()) { case "mtl-agent": // TODO: TO VALIDATE USERNAME AND PASSWORD AGAINST MTL AGENT SYSTEM break; case "mtl-smileclub": // TODO: TO VALIDATE USERNAME AND PASSWORD AGAINST MTL SMILE CLUB SYSTEM break; case "mtl-employee": // TODO: TO VALIDATE USERNAME AND PASSWORD AGAINST MTL EMPLOYEE SYSTEM IsValidated = true; break; } if (IsValidated) { var refreshTokenObj = BuildRefreshToken(authen.username, authen.client_id, GRANT_TYPE_PASSWORD, authen.authen_to_system, authen.code); var accessTokenObj = BuildAccessToken(authen.username, authen.client_id, refreshTokenObj.RefreshToken, Jwt.Algorithm.ES256, GRANT_TYPE_PASSWORD); var tokenResp = new TokenResponse(); tokenResp.token_type = "Bearer"; tokenResp.access_token = accessTokenObj.AccessToken; tokenResp.expires_in = _config["Jwt:Expires"]; tokenResp.refresh_token = refreshTokenObj.RefreshToken; tokenResp.refresh_token_expires_in = _config["Jwt:RefreshTokenExpires"]; response = Ok(tokenResp); } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.ExceptionalOccured, "Unauthorized, Username and Password is not valid for the system (" + authen.authen_to_system + ")."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientSecretKey, "Unauthorized, Client App Secret Key (" + authen.client_secret + ") is invalid."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientAppId, "Unauthorized, Client App Id (" + authen.client_id + ") is expired (" + appAudObj.ExpiryDate + ")."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientAppId, "Unauthorized, Client App Id (" + authen.client_id + ") is invalid."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.ExceptionalOccured, "Unauthorized, Authentication System is empty."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_Password, "Unauthorized, Password is empty."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_Username, "Unauthorized, Username is empty."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientSecretKey, "Unauthorized, Client App Secret Key is empty."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientAppId, "Unauthorized, Client App Id is empty."); } } else if (authen.grant_type.ToLower() == GRANT_TYPE_AUTHORIZATION_CODE) { if (authen.client_id != string.Empty && authen.client_id != "null" && authen.client_id != null) { if (authen.client_secret != string.Empty && authen.client_secret != "null" && authen.client_secret != null) { if (authen.code != string.Empty && authen.code != "null" && authen.code != null) { if (authen.redirect_uri != string.Empty && authen.redirect_uri != "null" && authen.redirect_uri != null) { var appAudObj = GetAppAudiencesById(authen.client_id).Result; if (appAudObj != null) { if (appAudObj.ExpiryDate > DateTime.UtcNow) { if (appAudObj.AppSecretKey == authen.client_secret) { var authCode = GetAuthorizationCodesById(authen.code).Result; if (authCode != null) { if (authCode.ClientAppId == authen.client_id) { if (DateTime.Parse(authCode.ExpiryDateTime.Replace("Z", ".0000000")) > DateTime.Parse(DateTimes.ConvertToUtcDateTimeInThaiTimeZone(DateTime.UtcNow, DateTimes.DateTimeFormat.YearMonthDayByDashTHourMinuteSecondByColonZ, DateTimes.LanguageCultureName.ENGLISH_UNITED_STATES, DateTimes.DateTimeUtcOffset.HHMMByColon).Replace("Z", ".0000000"))) { var refreshTokenObj = BuildRefreshToken(authen.username, authen.client_id, GRANT_TYPE_AUTHORIZATION_CODE, authen.authen_to_system, authen.code); var accessTokenObj = BuildAccessToken(authen.username, authen.client_id, refreshTokenObj.RefreshToken, Jwt.Algorithm.ES256, GRANT_TYPE_AUTHORIZATION_CODE); var tokenResp = new TokenResponse(); tokenResp.token_type = "Bearer"; tokenResp.access_token = accessTokenObj.AccessToken; tokenResp.expires_in = _config["Jwt:Expires"]; tokenResp.refresh_token = refreshTokenObj.RefreshToken; tokenResp.refresh_token_expires_in = _config["Jwt:RefreshTokenExpires"]; response = Ok(tokenResp); } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_AuthorizationCode, "Unauthorized, Authorization Code (" + authen.code + ") is expired (" + authCode.ExpiryDateTime + ")."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_AuthorizationCode, "Unauthorized, Authorization Code (" + authen.code + ") is invalid (AuthorizationCode is not belong to Client App Id)."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_AuthorizationCode, "Unauthorized, Authorization Code (" + authen.code + ") is invalid."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientSecretKey, "Unauthorized, Client App Secret Key (" + authen.client_secret + ") is invalid."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientAppId, "Unauthorized, Client App Id (" + authen.client_id + ") is expired (" + appAudObj.ExpiryDate + ")."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientAppId, "Unauthorized, Client App Id (" + authen.client_id + ") is invalid."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_RedirectUri, "Unauthorized, Client App Redirect Uri is empty."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_AuthorizationCode, "Unauthorized, Authorization Code is empty."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientSecretKey, "Unauthorized, Client App Secret Key is empty."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientAppId, "Unauthorized, Client App Id is empty."); } } else if (authen.grant_type.ToLower() == GRANT_TYPE_REFRESH_TOKEN) { if (authen.client_id != string.Empty && authen.client_id != "null" && authen.client_id != null) { if (authen.client_secret != string.Empty && authen.client_secret != "null" && authen.client_secret != null) { if (authen.refresh_token != string.Empty && authen.refresh_token != "null" && authen.refresh_token != null) { var appAudObj = GetAppAudiencesById(authen.client_id).Result; if (appAudObj != null) { if (appAudObj.ExpiryDate > DateTime.UtcNow) { if (appAudObj.AppSecretKey == authen.client_secret) { var rftkObj = GetRefreshTokenByToken(authen.refresh_token).Result; if (rftkObj != null) { if (rftkObj.AppAudienceId == authen.client_id) { if (DateTime.Parse(rftkObj.ExpiryDateTime.Replace("Z", ".0000000")) > DateTime.Parse(DateTimes.ConvertToUtcDateTimeInThaiTimeZone(DateTime.UtcNow, DateTimes.DateTimeFormat.YearMonthDayByDashTHourMinuteSecondByColonZ, DateTimes.LanguageCultureName.ENGLISH_UNITED_STATES, DateTimes.DateTimeUtcOffset.HHMMByColon).Replace("Z", ".0000000")) && rftkObj.Status == true) { var alg = GetLastestAccessTokenAlgorithmByRefreshToken(authen.refresh_token).Result; if (rftkObj.GrantType == GRANT_TYPE_PASSWORD) { var userId = GetUserIdByRefreshToken(authen.refresh_token).Result; if (userId != null) { var accessTokenObj = BuildAccessToken(userId, authen.client_id, authen.refresh_token, alg, GRANT_TYPE_REFRESH_TOKEN); var tokenResp = new TokenResponse(); tokenResp.token_type = "Bearer"; tokenResp.access_token = accessTokenObj.AccessToken; tokenResp.expires_in = _config["Jwt:Expires"]; tokenResp.refresh_token = authen.refresh_token; tokenResp.refresh_token_expires_in = _config["Jwt:RefreshTokenExpires"]; response = Ok(tokenResp); } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.Invalid_RefreshToken, "Unauthorized, RefreshToken (" + authen.refresh_token + ") is invalid (UserId is not found)."); } } else { var accessTokenObj = BuildAccessToken(authen.username, authen.client_id, authen.refresh_token, alg, GRANT_TYPE_REFRESH_TOKEN); var tokenResp = new TokenResponse(); tokenResp.token_type = "Bearer"; tokenResp.access_token = accessTokenObj.AccessToken; tokenResp.expires_in = _config["Jwt:Expires"]; tokenResp.refresh_token = authen.refresh_token; tokenResp.refresh_token_expires_in = _config["Jwt:RefreshTokenExpires"]; response = Ok(tokenResp); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.Invalid_RefreshToken, "Unauthorized, RefreshToken (" + authen.refresh_token + ") is expired (" + rftkObj.ExpiryDateTime + ")."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.Invalid_RefreshToken, "Unauthorized, RefreshToken (" + authen.refresh_token + ") is invalid (RefreshToken is not belong to Client App Id)."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.Invalid_RefreshToken, "Unauthorized, RefreshToken (" + authen.refresh_token + ") is not found."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientSecretKey, "Unauthorized, Client App Secret Key (" + authen.client_secret + ") is invalid."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientAppId, "Unauthorized, Client App Id (" + authen.client_id + ") is expired (" + appAudObj.ExpiryDate + ")."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientAppId, "Unauthorized, Client App Id (" + authen.client_id + ") is invalid."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.Invalid_RefreshToken, "Unauthorized, RefreshToken is empty."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientSecretKey, "Unauthorized, Client App Secret Key is empty."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.InvalidOrEmpty_ClientAppId, "Unauthorized, Client App Id is empty."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.ExceptionalOccured, "Unauthorized, Grant Type (" + authen.grant_type.ToLower() + ") is invalid."); } } else // ModelState อาจจะไม่จำเป็นต้องใช้ หรือใช้ไม่ได้กับ API { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.ExceptionalOccured, "Unauthorized, Input Model (grant_type: '" + authen.grant_type.ToLower() + "', client_id: '" + authen.client_id + "', user_id: '" + authen.username + "', refresh_token: '" + authen.refresh_token + "') is invalid."); } } catch (Exception ex) { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.ExceptionalOccured, "Unauthorized, Exception occurred (" + ex.Message + " - " + ex.Source + " - " + ex.StackTrace + " - " + ex.InnerException + " - " + ex.HelpLink + ")."); } return(response); }
public IActionResult VerifyToken([FromHeader(Name = HEADER_AUTH)] string token) { IActionResult response = Unauthorized(); var headerKeys = string.Empty; foreach (var key in Request.Headers.Keys) { headerKeys += key.ToString() + ", "; } headerKeys = headerKeys.Substring(0, headerKeys.Length - 2); if (Request.Headers.Keys.Contains(HEADER_AUTH)) { var reqHeader = Request.Headers.FirstOrDefault(h => h.Key == HEADER_AUTH); if (reqHeader.Value != string.Empty && reqHeader.Value != "null") { try { if (ModelState.IsValid) // ModelState อาจจะไม่จำเป็นต้องใช้ หรือใช้ไม่ได้กับ API { try { var handler = new JwtSecurityTokenHandler(); var jwtSecToken = handler.ReadToken(token) as JwtSecurityToken; string[] jwtArray = token.Split('.'); var jwtHeader = JwtHeader.Base64UrlDeserialize(jwtArray[0]); var jwtPayload = JwtPayload.Base64UrlDeserialize(jwtArray[1]); Jwt.Algorithm jwtAlg; if (jwtHeader.Alg == "HS256") { jwtAlg = Jwt.Algorithm.HS256; } else if (jwtHeader.Alg == "RS256") { jwtAlg = Jwt.Algorithm.RS256; } else if (jwtHeader.Alg == "ES256") { jwtAlg = Jwt.Algorithm.ES256; } else { jwtAlg = Jwt.Algorithm.HS256; } var tokenHandler = new JwtSecurityTokenHandler(); try { var claimPrincipal = tokenHandler.ValidateToken(token, new TokenValidationParameters { ValidIssuer = _config["Jwt:Issuer"], ValidAudience = _config["Jwt:Audience"], ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ClockSkew = TimeSpan.Zero, IssuerSigningKey = Jwt.GetSecurityKey(jwtAlg, _config, _azObj) }, out var parsedToken); var isAuthen = claimPrincipal.Identity.IsAuthenticated; if (isAuthen) { var result = "valid"; return(Ok(new { result, token })); } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.Invalid_AccessToken, "Unauthorized, AccessToken (" + token + ") is invalid (Can Not Authenticated)."); } } catch (Exception ex) { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.Invalid_AccessToken, "Unauthorized, AccessToken (" + token + ") is invalid (>> " + ex.Message + ")."); } } catch (Exception ex) { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.Invalid_AccessToken, "Unauthorized, AccessToken (" + token + ") is invalid (> " + ex.Message + ")."); } } else // ModelState อาจจะไม่จำเป็นต้องใช้ หรือใช้ไม่ได้กับ API { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.ExceptionalOccured, "Unauthorized, Input Model ('" + headerKeys + "') is invalid."); } } catch (Exception ex) { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.ExceptionalOccured, "Unauthorized, Exception occurred (" + ex.Message + " - " + ex.Source + " - " + ex.StackTrace + " - " + ex.InnerException + " - " + ex.HelpLink + ")."); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.Invalid_AccessToken, "Unauthorized, AccessToken is empty"); } } else { response = CustomHttpResponse.Error(HttpStatusCode.Unauthorized, Errors.ExceptionalOccured, "Unauthorized, Input Model is invalid (There is no Auth-Jwt)."); } return(response); }