学习009-07-01 Configure the JWT Authentication for the Web API(为Web API配置JWT身份验证)

Configure the JWT Authentication for the Web API(为Web API配置JWT身份验证)

Enable Authentication in a New Project(在新项目中启用身份验证)

Use the Solution Wizard to create a Web API project with the JWT authentication. If you choose Standard authentication on the Choose Security page, the wizard generates JWT authentication scaffolding code.
使用解决方案向导创建具有JWT身份验证的Web API项目。如果您在选择安全页面上选择标准身份验证,向导会生成JWT身份验证脚手架代码。
在这里插入图片描述

You can replace the autogenerated IssuerSigningKey value with your JWT signing key and change other JWT settings in the appsettings.json file. We recommend that you use the Secret Manager tool to store the signing key. You can store it in the appsettings.json file for testing purposes only.
您可以将自动生成的IssuerSigningKey值替换为您的JWT签名密钥,并更改appsetings. json文件中的其他JWT设置。我们建议您使用秘密管理器工具来存储签名密钥。您可以将其存储在appsetings.json文件中,仅用于测试目的。

File: MySolution.WebApi\appsettings.json (MySolution.Blazor.Server\appsettings.json)

JSON

// ...
"Authentication": {
    "Jwt": {
    "Issuer": "My",
    "Audience": "http://localhost:4200",
    "IssuerSigningKey": "c1d2e0a7-405b-40be-9b36-fa93469b673a"
    }
}    
// ...

See the following section for information on how to test the JWT authentication: Use the Swagger UI to Test the JWT Authentication.
有关如何测试JWT身份验证的信息,请参阅以下部分:使用Swagger UI测试JWT身份验证。

*Enable Authentication in an Existing Project(*在现有项目中启用身份验证)

To add the JWT authentication to an existing Web API or Blazor Server project, follow the steps below.
要将JWT身份验证添加到现有的Web API或Blazor Server项目,请执行以下步骤。

Step 1. Install the Required NuGet Packages(安装所需的NuGet包)

Install the following NuGet packages to the MySolution.WebApi (MySolution.Blazor.Server) and MySolution.Module projects:
将以下NuGet包安装到MySolutions. WebApi(MySolutions.Blazor.Server)和MySolutions.Module项目:

  • DevExpress.ExpressApp.Security.AspNetCore
  • Microsoft.AspNetCore.Authentication.JwtBearer
  • DevExpress.ExpressApp.Security.Xpo - in XPO applications
  • DevExpress.EntityFrameworkCore.Security - in EF Core applications

See the following topic for details: Choose Between Offline and Online DevExpress NuGet Feeds.
有关详细信息,请参阅以下主题:在离线和在线DevExpress NuGet Feeds之间进行选择。

Step 2. Modify appsettings.json(修改appset. json)

Add the Jwt option to the Authentication section in the appsettings.json file.
将Jwt选项添加到appset. json文件中的身份验证部分。

File: MySolution.WebApi\appsettings.json (MySolution.Blazor.Server\appsettings.json)

JSON

// ...
"Authentication": {
    "Jwt": {
    "Issuer": "My",
    "Audience": "http://localhost:4200",
    "IssuerSigningKey": "c1d2e0a7-405b-40be-9b36-fa93469b673a"
    }
},    
// ...

The IssuerSigningKey value is an autogenerated key. You can replace it with your JWT signing key. You can store it in the appsettings.json file for testing purposes only. We recommend that you use the Secret Manager tool to store the signing key.
IssuerSigningKey值是自动生成的密钥。您可以将其替换为JWT签名密钥。您可以将其存储在appset. json文件中,仅用于测试目的。我们建议您使用秘密管理器工具来存储签名密钥。

Step 3. Modify Startup.cs(修改Startup. cs)

Add the following code to the ConfigureServices method to enable authentication:
将以下代码添加到配置服务方法以启用身份验证:

File: MySolution.WebApi\Startup.cs (MySolution.Blazor.Server\Startup.cs)

C#

using DevExpress.ExpressApp.Security;
using DevExpress.Persistent.BaseImpl.PermissionPolicy;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.DependencyInjection;
// ...
public void ConfigureServices(IServiceCollection services) {
    //...
    services.AddXafAspNetCoreSecurity(Configuration, options => {
        options.RoleType = typeof(PermissionPolicyRole);
        options.UserType = typeof(MySolution.Module.BusinessObjects.ApplicationUser);
        options.UserLoginInfoType = typeof(MySolution.Module.BusinessObjects.ApplicationUserLoginInfo);
        // in XPO applications, uncomment the following line
        // options.Events.OnSecurityStrategyCreated = securityStrategy => ((SecurityStrategy)securityStrategy).RegisterXPOAdapterProviders();
        options.SupportNavigationPermissionsForTypes = false;
    })
    .AddAuthenticationStandard(options => {
        options.IsSupportChangePassword = true;
    });
    var authentication = services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme);
    // The AddJwtBearer method adds JWT credentials to the XAF authentication.
    authentication
        .AddJwtBearer(options => {
            options.TokenValidationParameters = new TokenValidationParameters() {
                ValidIssuer = Configuration["Authentication:Jwt:Issuer"],
                ValidAudience = Configuration["Authentication:Jwt:Audience"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Authentication:Jwt:IssuerSigningKey"]))
            };
        });
    services.AddAuthorization(options => {
        options.DefaultPolicy = new AuthorizationPolicyBuilder(
            JwtBearerDefaults.AuthenticationScheme)
                .RequireAuthenticatedUser()
                .RequireXafAuthentication()
                .Build();
    });
    // ...
    services.AddSwaggerGen(c => {
        c.EnableAnnotations();
        c.SwaggerDoc("v1", new OpenApiInfo {
            Title = "MySolution API",
            Version = "v1",
            Description = @"Use AddXafWebApi(Configuration, options) in the MySolution.WebApi\Startup.cs file to make Business Objects available in the Web API."
        });
        // The AddSecurityDefinition and AddSecurityRequirement methods enable the JWT authentication for the Swagger UI.
        c.AddSecurityDefinition("JWT", new OpenApiSecurityScheme() {
            Type = SecuritySchemeType.Http,
            Name = "Bearer",
            Scheme = "bearer",
            BearerFormat = "JWT",
            In = ParameterLocation.Header
        });
        c.AddSecurityRequirement(new OpenApiSecurityRequirement()
            {
                {
                    new OpenApiSecurityScheme() {
                        Reference = new OpenApiReference() {
                            Type = Microsoft.OpenApi.Models.ReferenceType.SecurityScheme,
                            Id = "JWT"
                        }
                    },
                    new string[0]
                },
        });
    });

Step 4. Add a JWT Authentication Service(添加JWT身份验证服务)

You can implement your own JWT service, or use the JWT service that the Solution Wizard generates. You can find the auto-generated service code below. To use this JWT service, create the JWT folder in the MySolution.WebApi (MySolution.Blazor.Server) project and add the AuthenticationController.cs file to this folder.
您可以实现自己的JWT服务,或使用解决方案向导生成的JWT服务。您可以在下面找到自动生成的服务代码。要使用此JWT服务,请在MySolutions. WebApi(MySolutions.Blazor.Server)项目中创建JWT文件夹,并将AuthenticationController.cs文件添加到此文件夹中。

File: MySolution.WebApi\JWT\AuthenticationController.cs (MySolution.Blazor.Server\JWT\AuthenticationController.cs)

C#

using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using DevExpress.ExpressApp.Security;
using DevExpress.ExpressApp.Security.Authentication;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;


namespace MySolution.WebApi.JWT {
    [ApiController]
    [Route("api/[controller]")]
    public class AuthenticationController : ControllerBase {
        readonly IStandardAuthenticationService securityAuthenticationService;
        readonly IConfiguration configuration;


        public AuthenticationController(IStandardAuthenticationService securityAuthenticationService, IConfiguration configuration) {
            this.securityAuthenticationService = securityAuthenticationService;
            this.configuration = configuration;
        }
        [HttpPost("Authenticate")]
        public IActionResult Authenticate(
            [FromBody]
            [SwaggerRequestBody(@"For example: <br /> { ""userName"": ""Admin"", ""password"": """" }")]
            AuthenticationStandardLogonParameters logonParameters
        ) {
            ClaimsPrincipal user = securityAuthenticationService.Authenticate(logonParameters);


            if(user != null) {
                var issuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Authentication:Jwt:IssuerSigningKey"]));
                var token = new JwtSecurityToken(
                    issuer: configuration["Authentication:Jwt:Issuer"],
                    audience: configuration["Authentication:Jwt:Audience"],
                    claims: user.Claims,
                    expires: DateTime.Now.AddHours(2),
                    signingCredentials: new SigningCredentials(issuerSigningKey, SecurityAlgorithms.HmacSha256)
                    );
                return Ok(new JwtSecurityTokenHandler().WriteToken(token));
            }
            return Unauthorized("User name or password is incorrect.");
        }
    }
}

Step 5. Add the ApplicationUser and ApplicationUserLoginInfo Business Objects(添加Application和ApplicationUserLoginInfo业务对象)

XAF requires the ApplicationUser and ApplicationUserLoginInfo business objects to store user information. Add these business objects to the MySolution.Module project as described in the following topic: Use the Security System.
XAF需要Application ationUser和ApplicationUserLoginInfo业务对象来存储用户信息。将这些业务对象添加到MySolutions. Module项目中,如以下主题中所述:使用安全系统。

Use the Swagger UI to Test the JWT Authentication(使用Swagger UI测试JWT身份验证)

1.If your solution includes a Web API project, right-click the project in the Solution Explorer and choose Debug | Start new instance to run the Web API project. A browser displays the page with the available endpoints.
如果您的解决方案包含Web API项目,请在解决方案资源管理器中右键单击该项目并选择调试|启动新实例以运行Web API项目。浏览器会显示包含可用端点的页面。

If your solution includes a startup Blazor Server project with the Web API, run the application. Add /swagger to the application address (for example, https://localhost:44318/swagger ) and press Enter to display a page with available endpoints.
如果您的解决方案包含带有Web API的启动Blazor Server项目,请运行应用程序。将 /swagger添加到应用程序地址(例如,https://localhost:44318/swagger),然后按Enter显示包含可用端点的页面。

Refer to the following link for more information on the page’s UI: Swagger UI.
有关页面UI的更多信息,请参阅以下链接:Swagger UI。

2.Expand the Post Authentication endpoint and click the Try it out button.
展开发布身份验证终结点并单击试用按钮。

3.In the displayed form, enter the userName and password for an authorized user. In a template application, use Admin as the user name and an empty string as the password.
在显示的表单中,输入授权用户的用户名和密码。在模板应用程序中,使用Admin作为用户名,使用空字符串作为密码。

4.Copy the public key from the Response body, click the Authorize button Authorize button to open the Available authorizations form, and paste the public key in the Value editor to enable the JWT authentication.
从Response正文中复制公钥,单击Authorize按钮Authorize按钮打开可用授权表单,然后将公钥粘贴到Value编辑器中以启用JWT身份验证。
在这里插入图片描述

Refer to the following topic for information on how to create Web API endpoints: Create Endpoints and Test the Web API.
有关如何创建Web API端点的信息,请参阅以下主题:创建端点和测试Web API。

  • 22
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

汤姆•猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值