public AlexaResponse ProcessAlexaRequest(AlexaRequestPayload alexaRequestPayload) { // validate request time stamp and app id // note that there is custom validation in the AlexaRequestValidationHandler SpeechletRequestValidationResult validationResult = _alexaRequestValidationService.ValidateAlexaRequest(alexaRequestPayload); if (validationResult == SpeechletRequestValidationResult.OK) { try { // transform request AlexaRequest alexaRequest = _alexaRequestMapper.MapAlexaRequest(alexaRequestPayload); // persist request and member _alexaRequestPersistenceService.PersistAlexaRequestAndMember(alexaRequest); // create a request handler strategy from the alexarequest IAlexaRequestHandlerStrategy alexaRequestHandlerStrategy = _alexaRequestHandlerStrategyFactory.CreateAlexaRequestHandlerStrategy(alexaRequestPayload); // use the handlerstrategy to process the request and generate a response AlexaResponse alexaResponse = alexaRequestHandlerStrategy.HandleAlexaRequest(alexaRequestPayload); // return response return(alexaResponse); } catch (Exception exception) { // todo: log the error return(new AlexaResponse("There was an error " + exception.Message)); //return new AlexaWordErrorResponse().GenerateCustomError(); } } return(null); }
/// <summary> /// TODO: Turn request validation back on before going live. /// </summary> public override bool OnRequestValidation( SpeechletRequestValidationResult result, DateTime referenceTimeUtc, SpeechletRequestEnvelope requestEnvelope) { return(true); }
public override bool OnRequestValidation(SpeechletRequestValidationResult result, DateTime referenceTimeUtc, SpeechletRequestEnvelope requestEnvelope) { if (requestEnvelope?.Session?.Application?.Id?.Equals("amzn1.ask.skill.052afe5d-6417-4e89-b6aa-b4ee3c0bb75a") == false) { return(false); } return(base.OnRequestValidation(result, referenceTimeUtc, requestEnvelope)); }
public override bool OnRequestValidation(SpeechletRequestValidationResult result, DateTime referenceTimeUtc, SpeechletRequestEnvelope requestEnvelope) { if (SkipValidation) { return(true); } return(base.OnRequestValidation(result, referenceTimeUtc, requestEnvelope)); }
public override bool OnRequestValidation(SpeechletRequestValidationResult result, DateTime referenceTimeUtc, SpeechletRequestEnvelope requestEnvelope) { //if (requestEnvelope?.Session?.Application?.Id?.Equals("<your Alexa skill's application id here>") == false) //{ // //WebApiApplication.telemetry.TrackEvent("Request envelope does not contain the appid"); // return false; //} return(base.OnRequestValidation(0, referenceTimeUtc, requestEnvelope)); }
public override bool OnRequestValidation(SpeechletRequestValidationResult result, DateTime referenceTimeUtc, SpeechletRequestEnvelope requestEnvelope) { if (requestEnvelope?.Session?.Application?.Id?.Equals("amzn1.ask.skill.77ffa04a-699d-452d-b8d5-4c128079a1b2") == false) { WebApiApplication.telemetry.TrackEvent("Request envelope does not contain the appid"); return(false); } return(base.OnRequestValidation(result, referenceTimeUtc, requestEnvelope)); }
public void RequestWithInvalidTimestampTest() { const string TestDataFile = @"TestData\RequestWithInvalidTimestamp.json"; SpeechletRequestValidationResult validationResult = SpeechletRequestValidationResult.OK; SpeechletRequestEnvelope alexaRequest = null; var alexaContent = File.ReadAllText(TestDataFile); try { alexaRequest = SpeechletRequestEnvelope.FromJson(alexaContent); } catch (Exception ex) when(ex is Newtonsoft.Json.JsonReaderException || ex is InvalidCastException || ex is FormatException) { validationResult = validationResult | SpeechletRequestValidationResult.InvalidJson; } Assert.True(validationResult == SpeechletRequestValidationResult.InvalidJson); }
/// <summary> /// Check to verify request headers and certificates per Amazon's validation requirements /// Note this method does not apply in debug mode /// </summary> /// <param name="httpRequest"></param> /// <param name="cancellationToken"></param> /// <returns></returns> protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage httpRequest, CancellationToken cancellationToken) { string buildMode = ConfigurationSettings.AppSettings["Mode"]; if (!buildMode.Equals("Debug")) { SpeechletRequestValidationResult validationResult = SpeechletRequestValidationResult.OK; string chainUrl = null; if (!httpRequest.Headers.Contains(AlexaSdk.SIGNATURE_CERT_URL_REQUEST_HEADER) || String.IsNullOrEmpty(chainUrl = httpRequest.Headers.GetValues(AlexaSdk.SIGNATURE_CERT_URL_REQUEST_HEADER).First())) { validationResult = validationResult | SpeechletRequestValidationResult.NoCertHeader; } string signature = null; if (!httpRequest.Headers.Contains(AlexaSdk.SIGNATURE_REQUEST_HEADER) || String.IsNullOrEmpty(signature = httpRequest.Headers.GetValues(AlexaSdk.SIGNATURE_REQUEST_HEADER).First())) { validationResult = validationResult | SpeechletRequestValidationResult.NoSignatureHeader; } var alexaBytes = AsyncHelpers.RunSync <byte[]>(() => httpRequest.Content.ReadAsByteArrayAsync()); // attempt to verify signature only if we were able to locate certificate and signature headers if (validationResult == SpeechletRequestValidationResult.OK) { if (!AlexaRequestSignatureVerifierService.VerifyRequestSignature(alexaBytes, signature, chainUrl)) { validationResult = validationResult | SpeechletRequestValidationResult.InvalidSignature; } } if (validationResult != SpeechletRequestValidationResult.OK) { throw new Exception("VALIDATION"); } } return(await base.SendAsync(httpRequest, cancellationToken)); }
public override bool OnRequestValidation(SpeechletRequestValidationResult result, DateTime referenceTimeUtc, SpeechletRequestEnvelope requestEnvelope) { return(true); if (result != SpeechletRequestValidationResult.OK) { if (result.HasFlag(SpeechletRequestValidationResult.NoSignatureHeader)) { //Debug.WriteLine("Alexa request is missing signature header, rejecting."); return(false); } if (result.HasFlag(SpeechletRequestValidationResult.NoCertHeader)) { //Debug.WriteLine("Alexa request is missing certificate header, rejecting."); return(false); } if (result.HasFlag(SpeechletRequestValidationResult.InvalidSignature)) { //Debug.WriteLine("Alexa request signature is invalid, rejecting."); return(false); } else { if (result.HasFlag(SpeechletRequestValidationResult.InvalidTimestamp)) { var diff = referenceTimeUtc - requestEnvelope.Request.Timestamp; //Debug.WriteLine("Alexa request timestamped '{0:0.00}' seconds ago making timestamp invalid, but continue processing.",diff.TotalSeconds); } return(true); } } else { var diff = referenceTimeUtc - requestEnvelope.Request.Timestamp; //Debug.WriteLine("Alexa request timestamped '{0:0.00}' seconds ago.", diff.TotalSeconds); return(true); } }
public SpeechletRequestValidationResult ValidateAlexaRequest(AlexaRequestPayload alexaRequest) { SpeechletRequestValidationResult validationResult = SpeechletRequestValidationResult.OK; if (!ConfigurationSettings.AppSettings["Mode"].Equals("Debug")) { // check timestamp if (!VerifyRequestTimestamp(alexaRequest, DateTime.UtcNow)) { validationResult = SpeechletRequestValidationResult.InvalidTimestamp; throw new Exception(validationResult.ToString()); } // check app id if (!VerifyApplicationIdHeader(alexaRequest)) { validationResult = SpeechletRequestValidationResult.InvalidAppId; throw new Exception(validationResult.ToString()); } } return(validationResult); }
public SpeechletRequestValidationResult ValidateAlexaRequest(SkillRequest alexaRequest) { SpeechletRequestValidationResult validationResult = SpeechletRequestValidationResult.OK; if (AlexaConstants.BuildMode == "PROD") { // check timestamp if (!VerifyRequestTimestamp(alexaRequest, DateTime.UtcNow)) { validationResult = SpeechletRequestValidationResult.InvalidTimestamp; throw new Exception(validationResult.ToString()); } // check app id if (!VerifyApplicationIdHeader(alexaRequest)) { validationResult = SpeechletRequestValidationResult.InvalidAppId; throw new Exception(validationResult.ToString()); } } return(validationResult); }
public SpeechletValidationException(SpeechletRequestValidationResult validationResult, string message, Exception cause) : base(message, cause) { ValidationResult = validationResult; }
public SkillResponse HandleResponse(SkillRequest alexaRequestInput) { AlexaRequestValidationService validator = new AlexaRequestValidationService(); SpeechletRequestValidationResult validationResult = validator.ValidateAlexaRequest(alexaRequestInput); if (validationResult != SpeechletRequestValidationResult.OK) { logger.Debug("validation error: " + validationResult.ToString()); new Exception("Invalid Request"); } SkillResponse response = new SkillResponse(); response.Version = "1.0"; logger.Debug("Request:" + JsonConvert.SerializeObject(alexaRequestInput.Request)); CaseInfo caseInfo = Helpers.GetCaseInfo(alexaRequestInput.Context.System.User.UserId); if (caseInfo.profile == null) { caseInfo.profile = Helpers.GetUserProfile(alexaRequestInput); } switch (alexaRequestInput.Request.Type) { case "LaunchRequest": logger.Debug("Launch request in"); response.Response = new ResponseBody(); response.Response.Card = new SimpleCard() { Content = "Hello " + caseInfo.profile.name + ". Welcome to your Benefind dashboard. Say: \"Check case summary\", \"Check my pending documents\" or \"Schedule an appointment\"", Title = "Benifind Dashboard" }; response.Response.OutputSpeech = new PlainTextOutputSpeech() { Text = "Hello " + caseInfo.profile.name + ". Welcome to your Beni-find dashboard. You don't have any new notifications. You can now say, Check case summary, or Check my pending documents, Or say Schedule an appointment \"" }; //response.Response.OutputSpeech = new PlainTextOutputSpeech() { Text = "Hello!! say, \"I am ready!\"" }; response.Response.ShouldEndSession = false; logger.Debug("Launch request out"); break; case "SessionEndedRequest": response.Response = new ResponseBody(); response.Response.Card = new SimpleCard() { Content = "Goodbye, have a good day!", Title = "Welcome!!" }; response.Response.OutputSpeech = new PlainTextOutputSpeech() { Text = "Goodbye, have a good day!" }; response.Response.ShouldEndSession = true; return(response); case "IntentRequest": try { IntentRequest intentRequest = (IntentRequest)(alexaRequestInput.Request); if (intentRequest.Intent.Name == "casesummary") { string text = "Hello <Name>, I see your SNAP case is active and ongoing. The SNAP case will be up for renewal for March 31st 2019. Your child care case is pending for an RFI. Please say \"Check my RFI\" to know more."; response.Response = Helpers.GetPlainTextResponseBody(text.Replace("<Name>", caseInfo.profile.name), true, "Case Summary"); response.Response.ShouldEndSession = false;; } if (intentRequest.Intent.Name == "rfi") { string text = "Hello <Name>, you have a household composition RFI, due by January 31st 2019. You can upload documents on our self service portal or return documents to our offices. P.A.F.S 76 is a supported document for this RFI."; response.Response = Helpers.GetPlainTextResponseBody(text.Replace("<Name>", caseInfo.profile.name), true, "RFI Details"); response.Response.ShouldEndSession = false;; } if (intentRequest.Intent.Name == "schedule") { string text = ""; if (intentRequest.Intent.ConfirmationStatus == "CONFIRMED") { var date = intentRequest.Intent.Slots["date"].Value; var time = intentRequest.Intent.Slots["time"].Value; text = "All set, your appointment is scheduled for the selected time. I have also sent you this information on your email."; Helpers.SendEmailAsync(caseInfo.profile.email, caseInfo.profile.name, date, time); } else { text = "Ok, Roger that!! Request cancelled!"; } response.Response = Helpers.GetPlainTextResponseBody(text.Replace("<Name>", caseInfo.profile.name), true, "Appointments"); response.Response.ShouldEndSession = true;; } if (intentRequest.Intent.Name == "AMAZON.StopIntent") { var stophandler = new AMAZON_StopIntent(); var skillresponse = stophandler.HandleIntent(null, null, null, null, logger); skillresponse.Version = "1.0"; return(skillresponse); } if (intentRequest.Intent.Name == "AMAZON.FallbackIntent") { var fallbackhandler = new AMAZON_FallbackIntent(); var fallbackresponse = fallbackhandler.HandleIntent(null, null, null, null, logger); fallbackresponse.Version = "1.0"; return(fallbackresponse); } if (intentRequest.Intent.Name == "AMAZON.CancelIntent") { var cancelhandler = new AMAZON_CancelIntent(); var cancellresponse = cancelhandler.HandleIntent(null, null, null, null, logger); cancellresponse.Version = "1.0"; return(cancellresponse); } //if (intentRequest.Intent.Name == "AMAZON.HelpIntent") //{ // var helphandler = new AMAZON_HelpIntent(); // var helplresponse = helphandler.HandleIntent(null, null, null, null, logger); // helplresponse.Version = "1.0"; // helplresponse.Response.ShouldEndSession = false; // return helplresponse; //} break; } catch (Exception e) { response.Response = Helpers.GetPlainTextResponseBody("Aaargh, the application encountered an error. Please try again later. Sorry for the inconvenience", true, "Error", e.Message); response.Response.ShouldEndSession = true; logger.Debug(e.StackTrace); } break; } logger.Debug("Response:" + JsonConvert.SerializeObject(response.Response)); return(response); }
/// <summary> /// Processes Alexa request AND validates request signature /// </summary> /// <param name="httpRequest"></param> /// <returns></returns> public virtual HttpResponseMessage GetResponse(HttpRequestMessage httpRequest) { SpeechletRequestValidationResult validationResult = SpeechletRequestValidationResult.OK; DateTime now = DateTime.UtcNow; // reference time for this request string chainUrl = null; if (!httpRequest.Headers.Contains(Sdk.SIGNATURE_CERT_URL_REQUEST_HEADER) || String.IsNullOrEmpty(chainUrl = httpRequest.Headers.GetValues(Sdk.SIGNATURE_CERT_URL_REQUEST_HEADER).First())) { validationResult = validationResult | SpeechletRequestValidationResult.NoCertHeader; } string signature = null; if (!httpRequest.Headers.Contains(Sdk.SIGNATURE_REQUEST_HEADER) || String.IsNullOrEmpty(signature = httpRequest.Headers.GetValues(Sdk.SIGNATURE_REQUEST_HEADER).First())) { validationResult = validationResult | SpeechletRequestValidationResult.NoSignatureHeader; } var alexaBytes = AsyncHelpers.RunSync <byte[]>(() => httpRequest.Content.ReadAsByteArrayAsync()); Debug.WriteLine(httpRequest.ToLogString()); // attempt to verify signature only if we were able to locate certificate and signature headers if (validationResult == SpeechletRequestValidationResult.OK) { if (!SpeechletRequestSignatureVerifier.VerifyRequestSignature(alexaBytes, signature, chainUrl)) { validationResult = validationResult | SpeechletRequestValidationResult.InvalidSignature; } } SpeechletRequestEnvelope alexaRequest = null; try { var alexaContent = UTF8Encoding.UTF8.GetString(alexaBytes); alexaRequest = SpeechletRequestEnvelope.FromJson(alexaContent); } catch (Newtonsoft.Json.JsonReaderException) { validationResult = validationResult | SpeechletRequestValidationResult.InvalidJson; } catch (InvalidCastException) { validationResult = validationResult | SpeechletRequestValidationResult.InvalidJson; } // attempt to verify timestamp only if we were able to parse request body if (alexaRequest != null) { if (!SpeechletRequestTimestampVerifier.VerifyRequestTimestamp(alexaRequest, now)) { validationResult = validationResult | SpeechletRequestValidationResult.InvalidTimestamp; } } if (alexaRequest == null || !OnRequestValidation(validationResult, now, alexaRequest)) { return(new HttpResponseMessage(HttpStatusCode.BadRequest) { ReasonPhrase = validationResult.ToString() }); } string alexaResponse = DoProcessRequest(alexaRequest); HttpResponseMessage httpResponse; if (alexaResponse != null) { httpResponse = new HttpResponseMessage(HttpStatusCode.OK); httpResponse.Content = new StringContent(alexaResponse, Encoding.UTF8, "application/json"); // Debug.WriteLine(httpResponse.ToLogString()); } else { httpResponse = new HttpResponseMessage(HttpStatusCode.InternalServerError); } return(httpResponse); }
public SpeechletValidationException(SpeechletRequestValidationResult validationResult) : base() { ValidationResult = validationResult; }
/// <summary> /// Opportunity to set policy for handling requests with invalid signatures and/or timestamps /// </summary> /// <returns>true if request processing should continue, otherwise false</returns> public virtual bool OnRequestValidation( SpeechletRequestValidationResult result, DateTime referenceTimeUtc, SpeechletRequestEnvelope requestEnvelope) { return result == SpeechletRequestValidationResult.OK; }
/// <summary> /// Opportunity to set policy for handling requests with invalid signatures and/or timestamps /// </summary> /// <returns>true if request processing should continue, otherwise false</returns> public virtual bool OnRequestValidation( SpeechletRequestValidationResult result, DateTime referenceTimeUtc, SpeechletRequestEnvelope requestEnvelope) { return(result == SpeechletRequestValidationResult.OK); }
public SkillResponse Prescreen(SkillRequest alexaRequestInput) { AlexaRequestValidationService validator = new AlexaRequestValidationService(); SpeechletRequestValidationResult validationResult = validator.ValidateAlexaRequest(alexaRequestInput); if (validationResult != SpeechletRequestValidationResult.OK) { logger.Debug("validation error: " + validationResult.ToString()); new Exception("Invalid Request"); } SkillResponse response = new SkillResponse(); response.Version = "1.0"; logger.Debug("Request:" + JsonConvert.SerializeObject(alexaRequestInput.Request)); switch (alexaRequestInput.Request.Type) { case "LaunchRequest": // logger.Debug("Launch request in"); response.Response = new ResponseBody(); response.Response.Card = new SimpleCard() { Content = "Hello!! Welcome to the Kentucky Health eligibility finder! Lets answer a few questions together to see the benefits you could have through the Kentucky HEALTH program. Say \"I am ready\" when ready to start.", Title = "Welcome!!" }; response.Response.OutputSpeech = new PlainTextOutputSpeech() { Text = "Hello!! Welcome to Kentucky Health eligibility finder! Lets answer a few questions together and see what types of requirements and benefits you may have through the Kentucky HEALTH program. When ready, say, \"I am ready!\"" }; //response.Response.OutputSpeech = new PlainTextOutputSpeech() { Text = "Hello!! say, \"I am ready!\"" }; response.Response.Reprompt = new Reprompt("Please say, I am ready."); response.Response.ShouldEndSession = false; // logger.Debug("Launch request out"); break; case "SessionEndedRequest": response.Response = new ResponseBody(); response.Response.Card = new SimpleCard() { Content = "Goodbye, have a good day!", Title = "Welcome!!" }; response.Response.OutputSpeech = new PlainTextOutputSpeech() { Text = "Goodbye, have a good day!" }; response.Response.ShouldEndSession = true; return(response); case "IntentRequest": try { CaseInfo caseInfo = Helpers.GetCaseInfo(alexaRequestInput.Session.SessionId); IntentRequest intentRequest = (IntentRequest)alexaRequestInput.Request; //if (intentRequest.Intent.Name == "repeat") //{ // response.Response = GetResponseForSlot(caseInfo.LastAskedSlot, caseInfo.ChildName, caseInfo.EligibilityGroup); // response.Version = "1.0"; // response.Response.ShouldEndSession = false; //} if (intentRequest.Intent.Name == "PreScreen") { UpdateModel(caseInfo, intentRequest.Intent); string slot = GetNextSlot(caseInfo); ResponseBody body = GetResponseForSlot(slot, caseInfo.ChildName, caseInfo.EligibilityGroup); if (slot.Contains("EG_")) { caseInfo.EligibilityGroup = slot; slot = "conclude"; } caseInfo.LastAskedSlot = slot; response.Response = body; if (body.ShouldEndSession == true) { Helpers.RemoveCaseInfo(alexaRequestInput.Session.SessionId); } } if (intentRequest.Intent.Name == "AMAZON.StopIntent") { var stophandler = new AMAZON_StopIntent(); var skillresponse = stophandler.HandleIntent(null, null, null, null, logger); skillresponse.Version = "1.0"; return(skillresponse); } if (intentRequest.Intent.Name == "AMAZON.FallbackIntent") { var fallbackhandler = new AMAZON_FallbackIntent(); var fallbackresponse = fallbackhandler.HandleIntent(null, null, null, null, logger); fallbackresponse.Version = "1.0"; return(fallbackresponse); } if (intentRequest.Intent.Name == "AMAZON.CancelIntent") { var cancelhandler = new AMAZON_CancelIntent(); var cancellresponse = cancelhandler.HandleIntent(null, null, null, null, logger); cancellresponse.Version = "1.0"; return(cancellresponse); } //if (intentRequest.Intent.Name == "AMAZON.HelpIntent") //{ // var helphandler = new AMAZON_HelpIntent(); // var helplresponse = helphandler.HandleIntent(null, null, null, null, logger); // helplresponse.Version = "1.0"; // helplresponse.Response.ShouldEndSession = false; // return helplresponse; //} break; } catch (Exception e) { response.Response = Helpers.GetPlainTextResponseBody("Aaargh, the application encountered an error. Please try again later. Sorry for the inconvenience", true, "Error", e.Message); response.Response.ShouldEndSession = true; logger.Debug(e.StackTrace); } break; } logger.Debug("Response:" + JsonConvert.SerializeObject(response.Response)); return(response); }
public SkillResponse Prescreen(SkillRequest alexaRequestInput) { AlexaRequestValidationService validator = new AlexaRequestValidationService(); SpeechletRequestValidationResult validationResult = validator.ValidateAlexaRequest(alexaRequestInput); if (validationResult != SpeechletRequestValidationResult.OK) { logger.Debug("validation error: " + validationResult.ToString()); new Exception("Invalid Request"); } SkillResponse response = new SkillResponse(); response.Version = "1.0"; // logger.Debug("Request:" + JsonConvert.SerializeObject(alexaRequestInput.Request)); switch (alexaRequestInput.Request.Type) { case "LaunchRequest": // logger.Debug("Launch request in"); response.Response = new ResponseBody(); response.Response.Card = new SimpleCard() { // Content = "Hello! Enjoy your game while I keep the scores. You can tell me to start a game or ask for the score of your current game.", Content = "Hello!! Welcome to Childcare pre-screening! Please note: This is a demo skill to demonstrate voice driven pre-screening process. Outcomes have no real world significance.", Title = "Welcome!!" }; response.Response.OutputSpeech = new PlainTextOutputSpeech() { Text = "Hello!! welcome to Childcare pre-screening! You can now say, check my eligibility" }; response.Response.ShouldEndSession = false; // logger.Debug("Launch request out"); break; case "SessionEndedRequest": response.Response = new ResponseBody(); response.Response.Card = new SimpleCard() { // Content = "Hello! Enjoy your game while I keep the scores. You can tell me to start a game or ask for the score of your current game.", Content = "Goodbye, have a good day!", Title = "Welcome!!" }; response.Response.OutputSpeech = new PlainTextOutputSpeech() { Text = "Goodbye, have a good day!" }; response.Response.ShouldEndSession = true; return(response); case "IntentRequest": try { CaseInfo caseInfo = Helpers.GetCaseInfo(alexaRequestInput.Session.SessionId); IntentRequest intentRequest = (IntentRequest)alexaRequestInput.Request; if (intentRequest.Intent.Name == "PreScreen") { UpdateModel(caseInfo, intentRequest.Intent); string slot = GetNextSlot(caseInfo); ResponseBody body = GetResponseForSlot(slot, caseInfo.ChildName); caseInfo.LastAskedSlot = slot; response.Response = body; if (body.ShouldEndSession == true) { Helpers.RemoveCaseInfo(alexaRequestInput.Session.SessionId); } } if (intentRequest.Intent.Name == "AMAZON.StopIntent") { var stophandler = new AMAZON_StopIntent(); var skillresponse = stophandler.HandleIntent(null, null, null, null, logger); skillresponse.Version = "1.0"; return(skillresponse); } if (intentRequest.Intent.Name == "AMAZON.FallbackIntent") { var fallbackhandler = new AMAZON_FallbackIntent(); var fallbackresponse = fallbackhandler.HandleIntent(null, null, null, null, logger); fallbackresponse.Version = "1.0"; return(fallbackresponse); } if (intentRequest.Intent.Name == "AMAZON.CancelIntent") { var cancelhandler = new AMAZON_CancelIntent(); var cancellresponse = cancelhandler.HandleIntent(null, null, null, null, logger); cancellresponse.Version = "1.0"; return(cancellresponse); } if (intentRequest.Intent.Name == "AMAZON.HelpIntent") { var helphandler = new AMAZON_HelpIntent(); var helplresponse = helphandler.HandleIntent(null, null, null, null, logger); helplresponse.Version = "1.0"; helplresponse.Response.ShouldEndSession = false; return(helplresponse); } break; }catch (Exception e) { response.Response = Helpers.GetPlainTextResponseBody("Aaargh, the application encountered an error. Please try again later. Sorry for the inconvenience", true, "Error", e.Message); response.Response.ShouldEndSession = true; logger.Debug(e.StackTrace); } break; } // logger.Debug("Response:" + JsonConvert.SerializeObject(response.Response)); response.Response.Reprompt = new Reprompt("Sorry, I didn't hear you, can you repeat that?"); return(response); }
public override bool OnRequestValidation( SpeechletRequestValidationResult result, DateTime referenceTimeUtc, SpeechletRequestEnvelope requestEnvelope) { return(true); //alexa simulator would fail from time to time if this is not set as true }
/// <summary> /// Processes Alexa request AND validates request signature /// </summary> /// <returns></returns> public virtual string GetResponse(Dictionary <string, string[]> Headers, byte[] Content, out HttpStatusCode HttpStatusCode) { SpeechletRequestValidationResult validationResult = SpeechletRequestValidationResult.OK; DateTime now = DateTime.UtcNow; // reference time for this request string chainUrl = null; if (!Headers.ContainsKey(Sdk.SIGNATURE_CERT_URL_REQUEST_HEADER) || String.IsNullOrEmpty(chainUrl = Headers[Sdk.SIGNATURE_CERT_URL_REQUEST_HEADER].First())) { validationResult = validationResult | SpeechletRequestValidationResult.NoCertHeader; } string signature = null; if (!Headers.ContainsKey(Sdk.SIGNATURE_REQUEST_HEADER) || String.IsNullOrEmpty(signature = Headers[Sdk.SIGNATURE_REQUEST_HEADER].First())) { validationResult = validationResult | SpeechletRequestValidationResult.NoSignatureHeader; } // attempt to verify signature only if we were able to locate certificate and signature headers if (validationResult == SpeechletRequestValidationResult.OK) { if (!SpeechletRequestSignatureVerifier.VerifyRequestSignature(Content, signature, chainUrl)) { validationResult = validationResult | SpeechletRequestValidationResult.InvalidSignature; } } SpeechletRequestEnvelope alexaRequest = null; try { var alexaContent = UTF8Encoding.UTF8.GetString(Content); alexaRequest = SpeechletRequestEnvelope.FromJson(alexaContent); } catch (Newtonsoft.Json.JsonReaderException) { validationResult = validationResult | SpeechletRequestValidationResult.InvalidJson; } catch (InvalidCastException) { validationResult = validationResult | SpeechletRequestValidationResult.InvalidJson; } // attempt to verify timestamp only if we were able to parse request body if (alexaRequest != null) { if (!SpeechletRequestTimestampVerifier.VerifyRequestTimestamp(alexaRequest, now)) { validationResult = validationResult | SpeechletRequestValidationResult.InvalidTimestamp; } } if (alexaRequest == null || !OnRequestValidation(validationResult, now, alexaRequest)) { HttpStatusCode = HttpStatusCode.BadRequest; return(validationResult.ToString()); } string alexaResponse = DoProcessRequest(alexaRequest); if (alexaResponse == null) { HttpStatusCode = HttpStatusCode.InternalServerError; return(null); } else { HttpStatusCode = HttpStatusCode.OK; return(alexaResponse); } }
/// <summary> /// Opportunity to set policy for handling requests with invalid signatures and/or timestamps /// </summary> /// <returns>true if request processing should continue, otherwise false</returns> public virtual bool OnRequestValidation(RequestHeader header, SpeechletRequestValidationResult result) { return(result == SpeechletRequestValidationResult.OK); }
public bool OnRequestValidation( SpeechletRequestValidationResult result, DateTime referenceTimeUtc, SpeechletRequestEnvelope requestEnvelope) { return(speechlet.OnRequestValidation(result, referenceTimeUtc, requestEnvelope)); }
public async Task Invoke(HttpContext context) { try { // Do something with context near the beginning of request processing. if (AlexaConstants.BuildMode == "PROD") { SpeechletRequestValidationResult validationResult = SpeechletRequestValidationResult.OK; string chainUrl = null; if (!context.Request.Headers.Keys.Contains(AlexaConstants.SIGNATURE_CERT_URL_REQUEST_HEADER) || String.IsNullOrEmpty(chainUrl = context.Request.Headers.First(p => p.Key == AlexaConstants.SIGNATURE_CERT_URL_REQUEST_HEADER).Value)) { logger.Debug("No cert url header"); validationResult = validationResult | SpeechletRequestValidationResult.NoCertHeader; } string signature = null; if (!context.Request.Headers.Keys.Contains(AlexaConstants.SIGNATURE_REQUEST_HEADER) || String.IsNullOrEmpty(signature = context.Request.Headers.First(p => p.Key == AlexaConstants.SIGNATURE_REQUEST_HEADER).Value)) { logger.Debug("No signature request header"); validationResult = validationResult | SpeechletRequestValidationResult.NoSignatureHeader; } MemoryStream ms = new MemoryStream(); context.Request.EnableRewind(); context.Request.Body.CopyTo(ms); //// If you need it... byte[] alexaBytes = ms.ToArray(); context.Request.Body.Seek(0, SeekOrigin.Begin); //HttpRequestStream // attempt to verify signature only if we were able to locate certificate and signature headers if (validationResult == SpeechletRequestValidationResult.OK) { if (!AlexaRequestSignatureVerifierService.VerifyRequestSignature(alexaBytes, signature, chainUrl, logger)) { logger.Debug("Verify signature failed"); validationResult = validationResult | SpeechletRequestValidationResult.InvalidSignature; } } if (validationResult != SpeechletRequestValidationResult.OK) { logger.Debug(validationResult.ToString()); throw new Exception("VALIDATION"); } } } catch (Exception e) { logger.Debug(e.StackTrace); throw (e); } await _next.Invoke(context); // Clean up. }