public AuthState(int opaque) { Opaque = opaque; Nonce = Nonce.Generate(Opaque); LastAccess = Environment.TickCount; NonceCount = int.MinValue; }
public NegotiationToken GetToken() { WebRequest request = WebRequest.Create(requestUri); request.Method = "POST"; Nonce nonce = Nonce.Generate(); TimeStamp timestamp = TimeStamp.Generate(); BaseString baseString = new BaseString(request.RequestUri, request.Method, nonce, timestamp, credentials, HmacSha1Signature.MethodName); Signature signature = new HmacSha1Signature(baseString.ToString(), credentials); AuthorizationHeader header = new AuthorizationHeader(credentials, nonce, timestamp, signature); request.Headers.Add(HttpRequestHeader.Authorization, header.ToString()); using (WebResponse res = request.GetResponse()) using (Stream s = res.GetResponseStream()) using (StreamReader sr = new StreamReader(s)) { NameValueCollection response = HttpUtility.ParseQueryString(sr.ReadToEnd()); return(new NegotiationToken(response["oauth_token"], response["oauth_token_secret"])); } }
public void SignRequest(WebRequest request) { Nonce nonce = Nonce.Generate(); TimeStamp timestamp = TimeStamp.Generate(); Signature signature = GenerateSignature(request, nonce, timestamp); AuthorizationHeader header = GenerateAuthorizationHeader(nonce, timestamp, signature); AddAuthorizationHeaderToRequest(request, header); }
public void NonceIsSufficientlyRandom() { var a = Nonce.Generate(8); // Not entirely scientific ;-) for (var i = 0; i < 100; ++i) { var b = Nonce.Generate(8); Assert.NotEqual(a, b); } }
async void SimulateStartup() { var googleApiClient = new GoogleApiClient.Builder(this) .EnableAutoManage(this, 1, result => { // Toast.MakeText(this, "Failed to connect to Google Play Services", ToastLength.Long).Show(); }) .AddApi(SafetyNetClass.API) .Build(); var nonce = Nonce.Generate(); // Should be at least 16 bytes in length. var r = await SafetyNetClass.SafetyNetApi.AttestAsync(googleApiClient, nonce); // Get the JSON from the JWS result by decoding var decodedResult = r.DecodeJwsResult(nonce); await Task.Delay(1000); StartActivity(new Intent(Application.Context, typeof(MainActivity))); }
public async Task <Response> ExecuteAsync(NancyContext context, IResponseFormatter response) { if (ConfigurationStore.GetIsEnabled() == false) { log.Warn($"{ConfigurationStore.ConfigurationSettingsName} user authentication API was called while the provider was disabled."); return(ResponseCreator.BadRequest(new string[] { "This authentication provider is disabled." })); } if (context.Request.Url.SiteBase.StartsWith("https://", StringComparison.OrdinalIgnoreCase) == false) { log.Warn($"{ConfigurationStore.ConfigurationSettingsName} user authentication API was called without using https."); } var postLoginRedirectTo = context.Request.Query["redirectTo"]; var state = "~/app"; if (string.IsNullOrWhiteSpace(postLoginRedirectTo) == false) { state = postLoginRedirectTo; } var nonce = Nonce.Generate(); try { var issuer = ConfigurationStore.GetIssuer(); var issuerConfig = await identityProviderConfigDiscoverer.GetConfigurationAsync(issuer); var url = urlBuilder.Build(context.Request.Url.SiteBase, issuerConfig, nonce, state); return(response.AsRedirect(url) .WithCookie(new NancyCookie("s", State.Protect(state), true, false, DateTime.UtcNow.AddMinutes(20))) .WithCookie(new NancyCookie("n", Nonce.Protect(nonce), true, false, DateTime.UtcNow.AddMinutes(20)))); } catch (Exception ex) { log.Error(ex); return(response.AsRedirect($"{state}?error=Login failed. Please see the Octopus Server logs for more details.")); } }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); buttonCheck = FindViewById <Button> (Resource.Id.buttonCheck); buttonVerify = FindViewById <Button> (Resource.Id.buttonVerify); buttonVerify.Enabled = false; googleApiClient = new GoogleApiClient.Builder(this) .EnableAutoManage(this, 1, result => { Toast.MakeText(this, "Failed to connect to Google Play Services", ToastLength.Long).Show(); }) .AddApi(SafetyNetClass.API) .Build(); buttonCheck.Click += async delegate { var nonce = Nonce.Generate(); // Should be at least 16 bytes in length. var r = await SafetyNetClass.SafetyNetApi.AttestAsync(googleApiClient, nonce); if (r.Status.IsSuccess) { // Store for future verification with google servers attestationResult = r; // Get the JSON from the JWS result by decoding var decodedResult = r.DecodeJwsResult(nonce); string error = null; // Try and verify the body of the response if (VerifyAttestResponse(decodedResult, nonce, out error)) { Toast.MakeText(this, "Compatibility Passed!", ToastLength.Long).Show(); buttonVerify.Enabled = true; } else { Toast.MakeText(this, "Compatibility Failed: " + error, ToastLength.Long).Show(); } } else { // Error Toast.MakeText(this, "Failed to Check Compatibility", ToastLength.Long).Show(); } }; buttonVerify.Click += async delegate { // Validate the JWS response with Google to ensure it came from them var valid = await attestationResult.ValidateWithGoogle(DEVELOPERS_CONSOLE_API_KEY); if (valid) { Toast.MakeText(this, "Successfully validated response with Google!", ToastLength.Short).Show(); } else { Toast.MakeText(this, "Failed response validation with Google!", ToastLength.Short).Show(); } }; }
public void NonceGeneration() { string nonce = Nonce.Generate(); Assert.IsNotEmpty(nonce); }
public async Task <HealthCheckResult> CheckNow(CancellationToken cancel) { string outcome; Exception exception = null; int? statusCode = null; string contentType = null; long? contentLength = null; string initialContent = null; JToken data = null; var probeId = Nonce.Generate(12); var probedUrl = _bypassHttpCaching ? UrlHelper.AppendParameter(_targetUrl, ProbeIdParameterName, probeId) : _targetUrl; var utcTimestamp = DateTime.UtcNow; var sw = Stopwatch.StartNew(); try { var request = new HttpRequestMessage(HttpMethod.Get, probedUrl); request.Headers.Add("X-Correlation-ID", probeId); if (_bypassHttpCaching) { request.Headers.CacheControl = new CacheControlHeaderValue { NoStore = true } } ; var response = await _httpClient.SendAsync(request, cancel); statusCode = (int)response.StatusCode; contentType = response.Content.Headers.ContentType?.ToString(); contentLength = response.Content.Headers.ContentLength; var content = await response.Content.ReadAsStreamAsync(); (initialContent, data) = await DownloadContent(content, contentType, contentLength); outcome = response.IsSuccessStatusCode ? OutcomeSucceeded : OutcomeFailed; } catch (Exception ex) { outcome = OutcomeFailed; exception = ex; } sw.Stop(); var level = outcome == OutcomeFailed ? "Error" : data == null && _extractor != null ? "Warning" : null; return(new HealthCheckResult( utcTimestamp, _title, "GET", _targetUrl, outcome, probeId, level, sw.Elapsed.TotalMilliseconds, statusCode, contentType, contentLength, initialContent, exception, data, _targetUrl == probedUrl ? null : probedUrl)); }
public void NonceGeneratesCorrectCharacterCount(int count) { var nonce = Nonce.Generate(count); Assert.Equal(count, nonce.Length); }