Skip to content

Setup Blazor Backend to accept Alexa Skill requests.

Arjun Krishna edited this page Dec 30, 2020 · 4 revisions

Alexa Integration

Code Setup

Server/Controllers/AlexaSkillController.cs

	  [HttpPost("api/AlexaSkill/Request")]
        public IActionResult HandleResponse([FromBody] SkillRequest input)

        {

            var requestType = input.GetRequestType();
            SkillResponse response = null;

            var name = "";
            var jwtEncodedString = input.Session.User.AccessToken;
            if (jwtEncodedString is null)
            {
                response = ResponseBuilder.TellWithLinkAccountCard("You are not currently linked to this skill. Please go into your Alexa app and sign in.");
                response.Response.ShouldEndSession = true;

                return new OkObjectResult(response);
            }


            var token = new JwtSecurityToken(jwtEncodedString: jwtEncodedString);
            var claims = token.Claims;
            name = claims.First(c => c.Type == "name").Value;


            if (requestType == typeof(LaunchRequest))
            {
                response = ResponseBuilder.Tell($"Welcome to Blazor News {name}!");
                response.Response.ShouldEndSession = false;
            }

            // return information from an intent
            else if (requestType == typeof(IntentRequest))
            {
                // do some intent-based stuff
                var intentRequest = input.Request as IntentRequest;
                if (intentRequest.Intent.Name.Equals("news"))
                {
                    // get the pull requests
                    var news = GetNews();

                    if (news == 0)
                        response = ResponseBuilder.Tell("We have no blazor news at this time.");
                    else
                        response = ResponseBuilder.Tell("There are " + news.ToString() + " blazor news articles.");

                    response.Response.ShouldEndSession = false;
                }
                else
                {
                    response = ResponseBuilder.Ask("I don't understand. Can you please try again?", null);
                    response.Response.ShouldEndSession = false;

                }
            }
            else if (requestType == typeof(SessionEndedRequest))
            {
                response = ResponseBuilder.Tell("See you next time!");
                response.Response.ShouldEndSession = true;
            }

            return new OkObjectResult(response);
        }

        private static int GetNews()
        {
            return 3;
        }

Server/Startup.cs

changed made in StartUp.cs

            var alexaVendor = Configuration["Alexa:BlazorNews:VendorId"];
            var alexaSecretText = "AlexaBlazorNewsSecret"; // I use this secret under the Alexa configuration.
            var client = new IdentityServer4.Models.Client
            {
                ClientId = "AlexaBlazorNews",
                ClientName = "AlexaBlazorNews",
                Enabled = true,
                AllowedGrantTypes = GrantTypes.Code,
                AllowAccessTokensViaBrowser = true,
                RequireConsent = false,
                RequirePkce = false,
                RequireClientSecret = true,
                AllowRememberConsent = true,
                ClientSecrets = {new Secret(alexaSecretText.Sha256()) },
                RedirectUris =
                {
                    "https://pitangui.amazon.com/api/skill/link/" + alexaVendor,
                    "https://layla.amazon.com/api/skill/link/" + alexaVendor,
                    "https://alexa.amazon.co.jp/api/skill/link/"+alexaVendor
                },
                PostLogoutRedirectUris =
                {
                    "https://pitangui.amazon.com/api/skill/link/" + alexaVendor,
                    "https://layla.amazon.com/api/skill/link/" + alexaVendor,
                    "https://alexa.amazon.co.jp/api/skill/link/"+alexaVendor
                },
                AllowedScopes =
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    IdentityServerConstants.StandardScopes.Email,
                    IdentityServerConstants.StandardScopes.Phone,
                    "alexa"
                },
                AllowOfflineAccess = true,
                AccessTokenType = AccessTokenType.Jwt,
                
            };

            var clients = new List<IdentityServer4.Models.Client>();
            var configClients = Configuration.GetSection("IdentityServer:Clients")
                .Get<IdentityServer4.Models.Client[]>();

            clients.Add(client);
            clients.AddRange(configClients);
            
            services.AddIdentityServer()
                .AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options =>
                {
                    options.IdentityResources["openid"].UserClaims.Add("role"); // Roles
                    options.ApiResources.Single().UserClaims.Add("role");
                    options.IdentityResources["openid"].UserClaims.Add("email");
                    options.ApiResources.Single().UserClaims.Add("email");
                    options.IdentityResources["openid"].UserClaims.Add("name");
                    options.ApiResources.Single().UserClaims.Add("name");
                    options.Clients.AddRange(clients.ToArray()); 
                });
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("role");
            services.AddTransient<IProfileService, ProfileService>();
            services.AddControllersWithViews().AddNewtonsoftJson(); // newtonsoftjson is needed because alexa.net has not been migrated to Text.Json yet.

NGrok Setup

Download Grok NGrok Token Setup NGROK command NGrok url for forwarding

Alexa Console Setup

Alexa Create New Skill Alexa Choose Template Skill Builder Checklist Skill Invocation Create Intent Utterances

Default Region: https://a9afa2d4182f.ngrok.io/api/AlexaSkill/Request

Endpoint

NGrok url was changed as I had restarted the Ngrok. VendorId is picked from here.

Web Authotization URI: https://a9afa2d4182f.ngrok.io/connect/authorize
Access Token URI: https://a9afa2d4182f.ngrok.io/connect/token
Client ID: AlexaBlazorNews
Your Secret: AlexaBlazorNewsSecret   (this will be used in the code)
Your Authentication Scheme: I changed it to Credentials in request body. Still did not work. Need to read more.

Account Linking

User Secret Setup

VendorId setup User Secret Setup

Blazor WASM

Run Server Solution File from Visual Studio, NGrok will automatically pick it up.

Testing

Request

Test Development

Acount Linking via Alexa App

Linking Screen in Alexa App on iOS

Alexa App

Login Screen in the App

Alexa App Login

Alexa Account Linking Successful

Alexa Linking Successful