azure服务器_没有IDE的Azure中5分钟无服务器功能

azure服务器

Microsoft Azure makes it incredibly easy to get a basic API/microservice up and running quickly! If you are unfamiliar with building serverless architectures in the Microsoft ecosystem, using Azure Functions has become a quick way to get back-end code up and running that is easy to understand and usable for anyone.

Microsoft Azure使快速启动和运行基本API /微服务变得异常容易! 如果您不熟悉在Microsoft生态系统中构建无服务器体系结构,则使用Azure Functions已成为获取并运行易于理解且对任何人都可用的后端代码的快速方法。

In this tutorial, we will set-up an API endpoint using the HTTP Trigger invocation that you can use with any front-end site. I use this approach all the time when I am on the go or am on a computer that doesn't have Visual Studio installed. It's super powerful for hackathons, quick proof of concepts, and shareable across diverse programming teams with almost no friction. I think you’re going to like the results, so let’s get started!

在本教程中,我们将使用可与任何前端站点一起使用的HTTP触发器调用来设置API端点。 在旅途中或未安装Visual Studio的计算机上,我始终使用这种方法。 它对于黑客马拉松,概念的快速证明非常强大,并且可以在几乎没有冲突的情况下在不同的编程团队中共享。 我认为您会喜欢结果,所以让我们开始吧!

什么是Azure Function HTTP触发器? ( What is an Azure Function HTTP trigger? )

The HTTP trigger lets you invoke a function with an HTTP request. You can use an HTTP trigger to build serverless APIs and respond to webhooks.

HTTP触发器使您可以使用HTTP请求来调用函数。 您可以使用HTTP触发器来构建无服务器API并响应Webhooks。

By default, an HTTP trigger returns HTTP 200 OK with an empty body in Functions 1.x, or HTTP 204 No Content with an empty body in Functions 2.x. Several languages are supported for Azure Functions such as JavaScript, Python, F# and Java. While this tutorial will be created in C#, more specifically .NET Core, the basic process is still applicable to any developer.

默认情况下,HTTP触发器在函数1.x中返回带有空主体的HTTP 200 OK,或者在函数2.x中返回带有空主体的HTTP 204 No Content。 Azure函数支持多种语言,例如JavaScript,Python,F#和Java。 虽然本教程将使用C#(更具体地说是.NET Core)创建,但基本过程仍然适用于任何开发人员。

在Azure中开始使用您的功能 ( Get your Function Started in Azure )

If you don't have an Azure subscription, create an account before you begin. After logging in, select the Create a resource button, type Function App into the search field then select it.

如果您没有Azure订阅 ,请在开始之前创建一个帐户。 登录后,选择“ 创建资源”按钮,在搜索字段中键入Function App ,然后选择它。

Enter a name for your function, adjust the rest of the settings as seen in the screenshot below and select Create.

输入功能的名称,调整其余设置,如下面的屏幕截图所示,然后选择创建

Look at the bell icon to check notifications when the provisioning has been completed for your function.

当您的功能配置完成后,请查看响铃图标以查看通知。

Once it has successfully been deployed, click Go to resource to view your new function app. You can also select Pin to dashboard to make it easier to return to it from your dashboard for subsequent portal logins.

成功部署后,单击“ 转到资源”以查看您的新功能应用程序。 您还可以选择“ 固定到仪表板” ,以使其更容易从仪表板返回以进行后续门户登录。

在新功能应用程序内创建功能 ( Create a Function Inside of your New Function App )

Now it's time to add some code! Click the + sign next to Functions on the left-hand side menu, select New Function and leave the default naming for now. Click Create to get started. This function will run whenever it receives an HTTP request.

现在是时候添加一些代码了! 单击左侧菜单上“ 功能 ”旁边的+号,选择“ 新功能”并保留默认名称。 单击创建开始。 每当收到HTTP请求时,该函数就会运行。

Your base function has been generated with some default code.

您的基本函数已使用一些默认代码生成。

In your new function, click </>** Get function URL** at the top right, leave the drop-down set to default **(Function key**) and copy it. Paste the URL in another tab in your browser to test it out. You should see a response asking for a name to be passed in the query string.

在新功能中,点击</ > **获取右上角的功能URL **,将下拉菜单设置为默认值**(功能键**)并复制。 将URL粘贴到浏览器的另一个选项卡中进行测试。 您应该看到一个响应,要求在查询字符串中传递名称。

通过添加身份管理来保护无服务器HTTP触发器的安全 ( Secure your Serverless HTTP Trigger by Adding Identity Management )

Now that your function has been created, you might not want just anyone accessing it. Identity management can be a mess to set-up, but Okta (a developer API service focused on providing user management) makes it really painless! Let's say you would like to assign client credentials that you control to a server that calls your API, gets validated, then delivers authenticated results from your Azure Function. Follow the steps below to secure this HTTP trigger.

现在已经创建了函数,您可能不希望任何人访问它。 身份管理的设置很麻烦,但是Okta(专注于提供用户管理的开发人员API服务)使它变得非常轻松! 假设您想将控制的客户端凭据分配给调用您的API的服务器,进行验证,然后从Azure函数提供经过身份验证的结果。 请按照以下步骤保护此HTTP触发器。

To integrate Okta's Identity Cloud for user authentication, you'll need to sign-up for a forever-free developer account first. Once logged in, navigate to Applications > ** Add Application.** Select the Service flow for Machine-to-Machine and click Next.

要集成Okta的身份云进行用户身份验证,您需要首先注册一个永久免费的开发者帐户。 登录后,导航至应用程序 > **添加应用程序。**选择机器到机器的服务流程,然后单击下一步

Name the application "API Sample App" and click Done.

将应用程序命名为“ API Sample App”,然后单击“完成”

On the API Sample App's general settings, you will see the Client Credentials box with the client ID and client secret in it. You will use these to authenticate a client wishing to call your API.

在API Sample App的常规设置上,您会看到“ 客户端凭据”框,其中包含客户端ID和客户端密码。 您将使用它们来认证希望调用您的API的客户端。

For each client that you want to have access to the API, you'll need to create an Okta application for it and give it the Client ID and Client Secret. If you are interested in learning more about using ASP.NET Core with client credentials in Okta, check out this post on the Okta developer blog.

对于要访问该API的每个客户端,都需要为其创建一个Okta应用程序,并为其提供客户端ID和客户端密钥。 如果您有兴趣了解更多关于使用ASP.NET的核心,在1563客户端凭证,检查出这个帖子在1563开发者博客。

This approach is for use cases where Okta is the authorization server for your resource server. For example, an application or API that you have created (i.e. you want Okta to act as the user store for your application, but Okta is invisible to your users). This kind of authorization server is called a Custom Authorization Server, and your full URL looks like this:

此方法适用于Okta是资源服务器的授权服务器的用例。 例如,您创建的一个应用程序或API(即,您希望Okta充当您的应用程序的用户存储,但是Okta对您的用户不可见)。 这种授权服务器称为“ 自定义授权服务器” ,您的完整URL如下所示:

https://{yourOktaDomain}/oauth2/${authServerId}/v1/authorize

https:// {yourOktaDomain} / oauth2 / $ {authServerId} / v1 / authorize

If you have a free Okta developer account, you can use the default authorization server that was created along with your account, in which case the full URL looks like this:

如果您有免费的Okta开发人员帐户,则可以使用与帐户一起创建的默认授权服务器,在这种情况下,完整的URL如下所示:

https://{yourOktaDomain}/oauth2/default/v1/authorize

https:// {yourOktaDomain} / oauth2 / default / v1 / authorize

Lastly, you will need to add a custom scope for the client credential flow. To do this, go to your default Authentication server and add a scope called api_scope. Your client will use this scope type when they call Okta's token endpoint in a later step.

最后,您将需要为客户端凭证流添加一个自定义范围。 为此,请转到默认的身份验证服务器并添加一个名为api _ scope的范围 。 您的客户端在后续步骤中调用Okta的令牌终结点时将使用此范围类型。

配置您的Azure功能以使用Okta客户端凭据 ( Configure your Azure Function to Use Okta Client Credentials )

Go to your function and select Integrate underneath it. Uncheck the POST checkbox, change the Authorization Level to Annonymous and click Save.

转到您的功能,然后选择其下方的“ 积分” 。 取消选中POST复选框,将Authorization Level更改为Anonymous ,然后单击Save

You will notice that users will not be prompted to log in because we set the access level to anonymous. Since you will be getting users from a 3rd party identity provider, you will handle the Okta token validation call from within your Azure function code. There are several ways to validate the access token generated by Okta. In this post, you will use the Introspection API endpoint.

您会注意到,由于我们将访问级别设置为匿名,因此不会提示用户登录。 由于您将从第三方身份提供商那里获取用户,因此您将在Azure函数代码中处理Okta令牌验证调用。 有几种方法可以验证Okta生成的访问令牌。 在本文中,您将使用Introspection API端点。

Click on the name of your HTTP trigger and copy and paste the following code, replacing {yourOktaDomain} with the actual domain assigned on your Okta account.

单击您的HTTP触发器的名称,然后复制并粘贴以下代码,将{yourOktaDomain}替换为在Okta帐户上分配的实际域。

#r "Newtonsoft.Json"

using System.Net;

using Microsoft.AspNetCore.Mvc;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)

{

   log.LogInformation("C# HTTP trigger function processed a request.");



   //Pull out the header values passed into the request

   var headers = req.Headers;

   if(!headers.TryGetValue("token", out var token))

   {

       return new BadRequestResult();

   }

   if(!headers.TryGetValue("client_id", out var client_id))

   {

       return new BadRequestResult();

   }

   if(!headers.TryGetValue("client_secret", out var client_secret))

   {

       return new BadRequestResult();

   }

   var accessToken = token.First();

   var clientId = client_id.First();

   var clientSecret = client_secret.First();

   //Call the Okta introspection API to validate the token.

   var baseUrl = "https://dev-414346.okta.com/oauth2/default/v1/introspect";

   var content = new FormUrlEncodedContent(new[]

   {

       new KeyValuePair<string, string>("token", accessToken),

       new KeyValuePair<string, string>("token_type_hint", "access_token"),

       new KeyValuePair<string, string>("client_id", clientId),

       new KeyValuePair<string, string>("client_secret", clientSecret)

   });

   var _httpClient = new HttpClient();

   var response = await _httpClient.PostAsync(baseUrl, content);

   var result = await response.Content.ReadAsStringAsync();

   log.LogInformation("C# HTTP trigger function processed an external API call to Okta.");

   //Based on the token validation from Okta, return a response

   if(response.IsSuccessStatusCode)

   {

       return new OkObjectResult("Hello, you have access to this API");

   }

   else

   {

       return new UnauthorizedResult();

   }

}

Save it and make sure there are no errors!

保存并确保没有错误!

客户端如何使用安全的无服务器API ( How a Client Would Consume your Secured Serverless API )

Now it's time to test out what you've created from the perspective of someone who would be consuming your Azure Function as a REST API!

现在是时候从一个将您的Azure Function用作REST API的人的角度测试您创建的内容了!

After you give the client their client ID and client secret, they would use a testing tool like Postman to call Okta's token endpoint to request an access token to use for calling your API. Okta's documentation guides the client on how to make that call and quickly retrieve a usable token. Here is an example of a call to get that token using Postman.

在为客户提供其客户ID客户机密后 ,他们将使用诸如Postman之类的测试工具来调用Okta的令牌端点,以请求访问令牌以用于调用您的API。 Okta的文档指导客户如何进行呼叫并快速检索可用令牌。 这是使用Postman获取该令牌的调用示例。

Then, the client uses that info when calling your endpoint. The client_id, client_secret and token all need to be passed as header values when calling your Azure Function HTTP Trigger. You should see a 200 OK success message.

然后,客户端在呼叫端点时使用该信息。 调用Azure函数HTTP触发器时,都必须将客户端 _ id客户端 _ 密钥令牌作为标头值传递。 您应该看到200 OK成功消息。

That's it! Pretty fast, and no IDE required.

而已! 相当快,不需要IDE。

了解有关无服务器,.NET和身份验证的更多信息 ( Learn more about Serverless, .NET, and Authentication )

This post only scratches the surface of the awesome things you can do with serverless in .NET! Check out these other fantastic posts.

这篇文章仅涉及您可以在.NET中使用无服务器完成的出色工作! 查看其他精彩的帖子。

You can find the complete project source code on GitHub. Happy coding!

您可以在GitHub上找到完整的项目源代码。 编码愉快!

翻译自: https://scotch.io/tutorials/5-minute-serverless-functions-in-azure-without-an-ide

azure服务器

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值