public IActionResult ReceiveAuthorizationCodeFacebook( [FromQuery] RedirectionErrorModelFacebook error, [FromQuery] AuthorizationCodeModel authorizationCode) { if (authorizationCode?.SessionId == null) { _logger.LogError("Received redirect request from Facebook without session id (state)"); return(BadRequest(ErrorModel.AuthorizationError("Session Id is missing."))); } if (error.Error != null || error.ErrorDescription != null) { _logger.LogError(@$ "Received redirect request from Facebook with error query params: {error.Error} | {error.ErrorDescription}"); return(BadRequest(ErrorModel.AuthorizationError($"{error.Error} {error.ErrorDescription}"))); } string socialServiceName = "facebook"; _userProfileReceivingServiceContext.SetStrategies( _tokenReceivingServices.First(s => s.SocialServiceName == socialServiceName), _profileManagingServices.First(s => s.SocialServiceName == socialServiceName)); _memoryCache.TryGetValue(authorizationCode.SessionId, out CacheModel cache); string scope = _context.Settings.FirstOrDefault(x => x.AppId == cache.AppId && x.SocialId == cache.SocialId).Scope; authorizationCode.Scope = scope; return(ContinueFlow(authorizationCode)); }
public async Task <JsonResult> Post([FromBody] AuthorizationCodeModel data) { var parameters = $"grant_type=authorization_code&code={data.code}&state={data.state}&redirect_uri={data.redirect_uri}&client_id={AppSettings.ClientId}&client_secret={AppSettings.ClientSecret}"; var result = await Task.FromResult(WebUtils.DoPost(AppSettings.TokenEndpoint, parameters)); //得到令牌 var resdata = JsonConvert.DeserializeObject <dynamic>(result); if (resdata.access_token == null) { return(Json(ResponseResult.Execute("10027", "授权码已不存在或已过期"))); } string access_token = resdata.access_token; int expires_in = resdata.expires_in; string token_type = resdata.token_type; string refresh_token = resdata.refresh_token; if (string.IsNullOrEmpty(access_token)) { return(Json(ResponseResult.Execute("10009", "任务过多,系统繁忙"))); } _memoryCache.Set(access_token, DateTime.Now.AddSeconds(expires_in), TimeSpan.FromSeconds(expires_in)); //令牌写入缓存 return(Json(ResponseResult.Execute(new { access_token, token_type, expires_in, refresh_token }))); }
public ActionResult Authorize(AuthorizationCodeModel model) { if (!ModelState.IsValid) { return(StatusCode(StatusCodes.Status417ExpectationFailed)); } // TODO: do validation of the client id, scope, callback id, etc., and then let the user login return(RedirectToAction("Choose", "Home")); // ignore all this for now UriBuilder builder = new UriBuilder(model.redirect_uri); var qs = QueryString.FromUriComponent(builder.Query); //qs = qs.Add("code", Guid.NewGuid().ToString("N")); qs = qs.Add("code", "test123"); qs = qs.Add("state", DateTime.UtcNow.Ticks.ToString()); builder.Query = qs.ToUriComponent(); return(Redirect(builder.ToString())); }
// 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 override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var authCode = value as AuthorizationCode; var model = new AuthorizationCodeModel() { ClientId = authCode.ClientId, CodeChallenge = authCode.CodeChallenge, CodeChallengeMethod = authCode.CodeChallengeMethod, CreationTime = authCode.CreationTime, IsOpenId = authCode.IsOpenId, Nonce = authCode.Nonce, RedirectUri = authCode.RedirectUri, RequestedScopes = authCode.RequestedScopes, SessionId = authCode.SessionId, Subject = authCode.Subject, WasConsentShown = authCode.WasConsentShown }; serializer.Serialize(writer, model); }
public IActionResult ReceiveAuthorizationCodeGoogle( [FromQuery] RedirectionErrorModelGoogle error, [FromQuery] AuthorizationCodeModel authorizationCode) { if (authorizationCode?.SessionId == null) { _logger.LogError("Received redirect request from Google without session id (state)"); return(BadRequest(ErrorModel.AuthorizationError("Session Id is missing."))); } if (error.Error != null || error.ErrorDescription != null) { _logger.LogError(@$ "Received redirect request from Google with error query params: {error.Error} | {error.ErrorDescription}"); return(BadRequest(ErrorModel.AuthorizationError($"{error.Error} {error.ErrorDescription}"))); } string socialServiceName = "google"; _userProfileReceivingServiceContext.SetStrategies( _tokenReceivingServices.First(s => s.SocialServiceName == socialServiceName), _profileManagingServices.First(s => s.SocialServiceName == socialServiceName)); return(ContinueFlow(authorizationCode)); }
private IActionResult ContinueFlow(AuthorizationCodeModel authorizationCode) { CacheModel session = _memoryCache.Get <CacheModel>(authorizationCode.SessionId); if (session == null) { _logger.LogError("Authorization time has expired"); return(BadRequest(ErrorModel.AuthorizationError("Time for authorization has expired"))); } string device = session.Device.ToLower().Trim(); session.UserStartedAuthorization = true; try { _userProfileReceivingServiceContext.Execute(session.AppId, authorizationCode); } catch (AuthorizationCodeExchangeException exception) { _logger.LogError("Error occured during authorization code exchange or process of receiving user profile from social service\n " + $"Error: {exception.Description?.Error}\n ErrorDescription: {exception.Description?.ErrorDescription}"); } if (device.Equals("browser")) { return(new ContentResult { ContentType = "text/html", Content = "<script>window.close()</script>" }); } else { return(Redirect(device)); } }
public async Task Execute(int appId, AuthorizationCodeModel authorizationCodeModel) { TokenModel tokens = await _accessTokenReceivingStrategy.ExchangeAuthorizationCodeForTokens(appId, authorizationCodeModel); await _profileManagerStrategy.GetUserProfileAsync(tokens, authorizationCodeModel.SessionId); }
/// <summary> /// Method that exchange user authorization code for tokens /// </summary> /// <param name="appId">Application Id</param> /// <param name="authorizationCodeModel"> /// Authorization model that has code, scope and state /// </param> /// <returns>Tokens model</returns> public async Task <TokenModel> ExchangeAuthorizationCodeForTokens(int appId, AuthorizationCodeModel authorizationCodeModel) { bool isSuccess = _memoryCache.TryGetValue(authorizationCodeModel.SessionId, out CacheModel sessionInformation); if (isSuccess == false) { _logger.LogError("Unable to find session id in memory cache." + "Authorization timeout has expired"); var errorExplanation = new ErrorModel { Error = "Authorization timeout has expired.", ErrorDescription = "Try again later" }; throw new AuthorizationCodeExchangeException(errorExplanation); } string code = authorizationCodeModel.AuthorizationCode; string redirectUri = sessionInformation.RedirectUri; string clientId = _context.Settings.FirstOrDefault(s => s.AppId == appId && s.SocialId == sessionInformation.SocialId)?.ClientId; string clientSecret = _context.Settings.FirstOrDefault(s => s.AppId == appId && s.SocialId == sessionInformation.SocialId)?.SecretKey; if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(clientSecret)) { _logger.LogError("Client id or client secret is null or empty"); var errorExplanation = new ErrorModel { Error = "Trying to use unregistered social network", ErrorDescription = "There is no client id or client secret key registered in our widget." }; throw new AuthorizationCodeExchangeException(errorExplanation); } Dictionary <string, string> queryParams = new Dictionary <string, string> { { "code", code }, { "redirect_uri", redirectUri }, { "client_id", clientId }, { "client_secret", clientSecret }, { "scope", string.Empty } }; string tokenUri = _context.Socials.FirstOrDefault(s => s.Id == sessionInformation.SocialId)?.TokenUrl; string responseBody = await exchangeCodeForTokenService.ExchangeCodeForTokens(tokenUri, queryParams, SocialServiceName); if (string.IsNullOrWhiteSpace(responseBody)) { return(null); } try { FacebookTokensModel tokens = JsonSerializer.Deserialize <FacebookTokensModel>(responseBody); tokens.Scope = authorizationCodeModel.Scope; return(tokens); } catch (Exception exception) { if (exception is ArgumentNullException || exception is JsonException) { _logger.LogError($"Unable to deserialize response body. Received response body:\n{responseBody}"); return(null); } throw; } }
public async Task <IActionResult> Post([FromBody] AuthorizationCodeModel data) { var(error, result) = await _authorizeClient.GetToken(data.Code, data.State, data.RedirectUri); return(!string.IsNullOrEmpty(error) ? ObjectResponse.Ok(-1, error) : ObjectResponse.Ok(result)); }
public IActionResult Index([Bind("Response_Type,Client_Id,Redirect_Uri,State,Authen_To_System,username,password")] string username, string password, AuthorizationCodeModel authCodeObj) { try { IActionResult response = Unauthorized(); if (ModelState.IsValid) { if (username != string.Empty && username != "null" && username != null) { if (password != string.Empty && password != "null" && password != null) { var IsValidated = false; switch (authCodeObj.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 code = Guid.NewGuid(); var auth = new AuthorizationCodes(); auth.Id = code; auth.AuthenToSystem = authCodeObj.Authen_To_System; auth.ClientAppId = authCodeObj.Client_Id; auth.CreatedDateTime = DateTimes.GetCurrentUtcDateTimeInThaiTimeZone(DateTimes.DateTimeFormat.YearMonthDayByDashTHourMinuteSecondByColonZ, DateTimes.LanguageCultureName.ENGLISH_UNITED_STATES, DateTimes.DateTimeUtcOffset.HHMMByColon); var expdt = DateTime.UtcNow.AddSeconds(90); auth.ExpiryDateTime = DateTimes.ConvertToUtcDateTimeInThaiTimeZone(expdt, DateTimes.DateTimeFormat.YearMonthDayByDashTHourMinuteSecondByColonZ, DateTimes.LanguageCultureName.ENGLISH_UNITED_STATES, DateTimes.DateTimeUtcOffset.HHMMByColon); auth.RedirectUri = authCodeObj.Redirect_Uri; auth.State = authCodeObj.State; if (authCodeObj.State != string.Empty && authCodeObj.State != "null" && authCodeObj.State != null) { var resp = _authObj.PutAuthorizationCodes(auth); response = Redirect(authCodeObj.Redirect_Uri + "?code=" + code + "&state=" + authCodeObj.State); } else { response = Redirect(authCodeObj.Redirect_Uri + "?code=" + code); } return(response); } else { return(View()); } } else { return(View()); } } else { return(View()); } } else { return(View()); } } catch { return(View()); } }