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.")); } }
// 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 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); }