public static void GetAuthorizationCodeAsync(string clientId, Action <AuthCodeResponse> callback) { if (string.IsNullOrEmpty(clientId)) { throw new ArgumentException("clientId is null or empty.", "clientId"); } if (callback == null) { throw new ArgumentNullException("callback"); } if (string.IsNullOrEmpty(UnityConnect.instance.GetAccessToken())) { throw new InvalidOperationException("User is not logged in or user status invalid."); } string url = string.Format("{0}/v1/oauth2/authorize", UnityConnect.instance.GetConfigurationURL(CloudConfigUrl.CloudIdentity)); AsyncHTTPClient client = new AsyncHTTPClient(url); client.postData = string.Format("client_id={0}&response_type=code&format=json&access_token={1}&prompt=none", clientId, UnityConnect.instance.GetAccessToken()); client.doneCallback = delegate(IAsyncHTTPClient c) { AuthCodeResponse response = new AuthCodeResponse(); if (!c.IsSuccess()) { response.Exception = new InvalidOperationException("Failed to call Unity ID to get auth code."); } else { try { var json = new JSONParser(c.text).Parse(); if (json.ContainsKey("code") && !json["code"].IsNull()) { response.AuthCode = json["code"].AsString(); } else if (json.ContainsKey("message")) { response.Exception = new InvalidOperationException(string.Format("Error from server: {0}", json["message"].AsString())); } else { response.Exception = new InvalidOperationException("Unexpected response from server."); } } catch (JSONParseException) { response.Exception = new InvalidOperationException("Unexpected response from server: Failed to parse JSON."); } } callback(response); }; client.Begin(); }
private TokenResponse GetAuthTokenResponse(OdsTokenSettings settings, AuthCodeResponse result) { var client = new RestClient(settings.TokenUrl); var request = new RestRequest(Method.POST); request.AddHeader("Accept", "application/json"); request.AddHeader("Content-Type", "application/x-www-form-urlencoded"); request.AddParameter("Client_id", settings.ClientId); request.AddParameter("Client_secret", settings.ClientSecret); request.AddParameter("Code", result.Code); request.AddParameter("Grant_type", "authorization_code"); var response = client.Execute(request); return(JsonConvert.DeserializeObject <TokenResponse>(response.Content)); }
public HttpResponseMessage StartAuthenicationSession(int siteId) { var response = new HttpResponseMessage(); var authCode = string.Empty; var deviceData = JsonConvert.DeserializeObject <DeviceData>(this.Request.GetHeader("X-Rock-DeviceData")); var site = SiteCache.Get(siteId); var authGenerationCount = 0; var maxAuthGenerationAttempts = 50; var rockContext = new RockContext(); var remoteAuthenticationSessionService = new RemoteAuthenticationSessionService(rockContext); // Get client IP var clientIp = GetClientIp(Request); var expireDateTime = RockDateTime.Now.AddMinutes(_codeReusePeriodInMinutes); // Get random code while (authCode == string.Empty && authGenerationCount < maxAuthGenerationAttempts) { authCode = RandomString(6); // Remove characters that could be confusing for clarity authCode.Replace('0', '2'); authCode.Replace('O', 'P'); // Check that the code is not already being used in the last 5 days var codeReuseWindow = RockDateTime.Now.AddDays(-5); var usedCodes = remoteAuthenticationSessionService.Queryable() .Where(s => s.Code == authCode && s.SessionStartDateTime > expireDateTime) .Any(); // If matching code was found try again if (usedCodes) { authCode = string.Empty; } // Remove bad sequences foreach (var badSequence in AttendanceCodeService.NoGood) { if (authCode.Contains(badSequence)) { authCode = string.Empty; } } authGenerationCount++; } // Check that we were able to generate an auth code if (authGenerationCount >= maxAuthGenerationAttempts) { response.StatusCode = HttpStatusCode.InternalServerError; return(response); } // Create authenication session var remoteSession = new RemoteAuthenticationSession(); remoteAuthenticationSessionService.Add(remoteSession); remoteSession.SiteId = siteId; remoteSession.ClientIpAddress = clientIp; remoteSession.Code = authCode; remoteSession.SessionStartDateTime = ( DateTime )RockDateTime.Now; remoteSession.DeviceUniqueIdentifier = deviceData.DeviceIdentifier; rockContext.SaveChanges(); var authReturn = new AuthCodeResponse(); authReturn.Code = authCode; authReturn.ExpireDateTime = expireDateTime; var loginPageReference = site.LoginPageReference; loginPageReference.Parameters.AddOrReplace("AuthCode", authCode); var qrData = HttpUtility.UrlEncode($"{GlobalAttributesCache.Value( "PublicApplicationRoot" ).TrimEnd( '/' )}{loginPageReference.BuildUrl()}"); authReturn.AuthenticationUrlQrCode = $"{GlobalAttributesCache.Value( "PublicApplicationRoot" )}GetQRCode.ashx?data={qrData}&outputType=png"; response.Content = new StringContent(authReturn.ToJson(), System.Text.Encoding.UTF8, "application/json"); response.StatusCode = HttpStatusCode.OK; return(response); }