public IActionResult ExchangeToken(AuthorizationCode exchangeCode) { if (string.IsNullOrEmpty(exchangeCode.Code)) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return(new JsonResult(HttpStatusCode.BadRequest.ToString())); } if (_cache.TryGetValue(exchangeCode, out AuthorizationCode authorizationCode)) { var credential = _context.Credential.SingleOrDefault(c => c.AccessToken == authorizationCode.Credential.AccessToken); if (credential == null) { credential.Status = CredentialStatus.Active; _context.Credential.Add(credential); _context.SaveChanges(); _cache.Remove(authorizationCode.Code); return(new JsonResult(credential)); } } Response.StatusCode = (int)HttpStatusCode.BadRequest; return(new JsonResult(HttpStatusCode.BadRequest.ToString())); }
public IActionResult PostConsent(int clientId, string scopes, string redirectUrl) { // Kiểm tra người dùng đăng nhập chưa var loggedEmail = HttpContext.Session.GetString("loggedUserEmail"); var loggedIdString = HttpContext.Session.GetString("loggedUserId"); long loggedId = 0; try { loggedId = Int64.Parse(loggedIdString); } catch (Exception e) { Console.WriteLine(e); } var currentAccount = _context.Account.SingleOrDefault(a => a.Id == loggedId); if (currentAccount == null) { // Đưa người dùng sang trang đăng nhập return(Redirect("/Accounts/Login?redirectUrl=" + WebUtility.UrlEncode(Request.GetDisplayUrl()))); } var currentApp = _context.RegisterApplication.SingleOrDefault(ra => ra.Id == clientId); if (currentApp == null) { Response.StatusCode = (int)(HttpStatusCode.Forbidden); return(new JsonResult(HttpStatusCode.Forbidden.ToString())); } var scopeIds = scopes.Split(","); List <CredentialScope> listRequestScopes = new List <CredentialScope>(); foreach (var strId in scopeIds) { var id = Int32.Parse(strId); if (!_credentialScopes.ContainsKey(id)) { Response.StatusCode = (int)(HttpStatusCode.NotFound); return(new JsonResult(HttpStatusCode.NotFound.ToString())); } } // Tạo credential lưu vào database với status deactive var credential = new Credential(currentAccount.Id, scopes); credential.Status = CredentialStatus.Deactive; _context.Credential.Add(credential); _context.SaveChanges(); var cacheEntryOptions = new MemoryCacheEntryOptions() // Keep in cache for this time, reset time if accessed. .SetSlidingExpiration(TimeSpan.FromSeconds(5)); AuthorizationCode authorizationCode = new AuthorizationCode(credential); // Tạo authorization code có liên kết với credential vừa tạo _cache.Set(authorizationCode.Code, authorizationCode, cacheEntryOptions); // Đưa người dùng về redirectUrl kèm theo return(Redirect(currentApp.RedirectUrl + "?exchange-code=" + authorizationCode.Code)); }