zoukankan      html  css  js  c++  java
  • Blazor client-side + webapi (.net core 3.1) 添加jwt验证流程(非host)第二步 添加Identity

     

    添加Identity数据上下文

    安装nuget包:Microsoft.AspNetCore.Identity.EntityFrameworkCore

    创建ApplicationDbContext类

    创建一个Data文件夹,并创建一个新类,添加以下内容

        public class ApplicationDbContext : IdentityDbContext
        {
            public ApplicationDbContext(DbContextOptions options) : base(options)
            {
            }
        }

    这个是一个默认Identity上下文,继承于DbContext,包含了一些默认的表(Dbset)包括用户,权限身份等等。

    注册数据库和数据上下文

    添加以下代码到ConfigureServices中

                services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
                services.AddIdentity<IdentityUser,IdentityRole>()
              .AddEntityFrameworkStores<ApplicationDbContext>();

    在.net core 3.1中,AddDefaultIdentity() 被删除了,所以这里用了AddIdentity()。

    如果你需要使用SqlServer或者localdb的话,就安装nuget:Microsoft.EntityFrameworkCore.SqlServer ,我自己是使用的Mysql,使用的nuget包是:Pomelo.EntityFrameworkCore.MySql。

    这两个包都会自动安装EFCore包。

    添加链接字符串到appsettings.json

    localdb

      "ConnectionStrings": {
        "DefaultConnection": "Server=(localdb)\MSSQLLocalDB;Database=AuthApiAndBlazor;Trusted_Connection=True;MultipleActiveResultSets=true"
      },

    Mysql

      "ConnectionStrings": {
        "DefaultConnection": "Server=localhost;database=AuthApiAndBlazor;uid=root;pwd=password;charset=utf8;sslMode=None",
      },

    打开包管理器(或.Net CLI),添加迁移。

    使用包管理员

    PM> Add-Migration Init

    使用命令行

    C:UsersAdministratorsource
    eposAuthApiAndBlazorserver> dotnet ef migrations add init

    当然,在3.1.2中,你可能会遇到错误,需要安装 Microsoft.EntityFrameworkCore.Design包

    Your startup project 'server' doesn't reference Microsoft.EntityFrameworkCore.Design. This package is required for the Entity Framework Core Tools to work. Ensure your startup project is correct, install the package, and try again.

    检查迁移文件,无误后更新到服务器

    包管理器

    PM> Update-Database

    命令行

    C:UsersAdministratorsource
    eposAuthApiAndBlazorserver> dotnet ef database update

    添加用户验证到管道(Configure method)中

                app.UseAuthorization(); //验证用户可以做什么
                app.UseAuthentication(); //用户身份的验证

    为你的api 控制器添加授权验证(用户验证)来测试我们的用户成功了

        [Authorize] //添加特性
        public class WeatherForecastController : ControllerBase

    生成后运行,这时候再访问WeatherForecast的api就会跳转到https://localhost:5002/Account/Login?ReturnUrl=%2FWeatherForecast Login操作的页面上,这是Identity的预设链接,也是MVC标识(Identity)基架的默认页面,在MVC下这会被自动创建,但是由于我们是手动添加到WebApi中的,所以需要更改,我们也只需要它返回401状态码即可,实际登陆应该由前端进行操作。

    设置JWT

    首先需要安装Nuget包:Microsoft.AspNetCore.Authentication.JwtBearer

    添加代码到ConfigureServices method中

                services.AddAuthentication((opts =>
                {
                    opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    opts.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;  //如果不加这行,将会跳转到/Account/Login,也就是说你可以用视图来处理未登录
                })) //设置验证方式为常量Bearer,即JWTBearer
                    .AddJwtBearer(options =>
                    {
                        options.TokenValidationParameters = new TokenValidationParameters
                        {
                            ValidateIssuer = true, //验证发行方
                            ValidateAudience = true, //验证听众api
                            ValidateLifetime = true, //验证生存时间
                            ValidateIssuerSigningKey = true, //验证发行方密钥
                            ValidIssuer = Configuration["JwtIssuer"], //发行方
                            ValidAudience = Configuration["JwtAudience"], //听众
                            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtSecurityKey"])) //对称密钥
                        };
                    });

    这里的写法是将JwtIssuer 、 JwtAudience 和 JwtSecurityKey 都放到appsettings.json文件中,你可以自己选择,我没有试过AddJwtBearer是单例还是怎样,即它可能不是实时可修改的。

    它在appsettings.json的样子:

      "JwtSecurityKey": "RANDOM_KEY_MUST_NOT_BE_SHARED", //密钥
      "JwtIssuer": "https://localhost:5002", //server的域名
      "JwtAudience": "http://localhost:5001", //client (Blazor的域名)
      "JwtExpiryInDays": 1 //过期时间

    添加Register和Login控制器

    在server中生成两个api控制器,一个用于注册,一个用来做登陆。

    RegisterController:

        [Route("api/[controller]")]
        [ApiController]
        public class AccountsController : ControllerBase
        {
            private readonly UserManager<IdentityUser> _userManager;
    
            public AccountsController(UserManager<IdentityUser> userManager)
            {
                _userManager = userManager;
            }
    
            [HttpPost]
            public async Task<IActionResult> Post([FromBody]RegisterModel model)
            {
                //创建用户,实际运用中我们一般会将IdentityUser更换为我们自定义的用户
                var newUser = new IdentityUser { UserName = model.Email, Email = model.Email };
    
                var result = await _userManager.CreateAsync(newUser, model.Password);
    
                if (!result.Succeeded)
                {
                    var errors = result.Errors.Select(x => x.Description);
                    //提示失败
                    return Ok(new RegisterResult { Successful = false, Errors = errors });
                }
                //提示成功,让前端做跳转
                return Ok(new RegisterResult { Successful = true });
            }
        }

    所需模型: (tips:这里因为我们前后端都是使用.net core 去实现,所以实际上我们可以将这些前后端都需要的模型,做成一个共享类库,即保证了同步性,又节省了代码量,如果你不这么做的话,你接下来还需要再添加一次这些模型到client项目)

    RegisterModel(用于接收注册前端参数)

        public class RegisterModel
        {
            [Required]
            [EmailAddress]
            [Display(Name = "Email")]
            public string Email { get; set; }
    
            [Required]
            [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
            [DataType(DataType.Password)]
            [Display(Name = "Password")]
            public string Password { get; set; }
    
            [DataType(DataType.Password)]
            [Display(Name = "Confirm password")]
            [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
            public string ConfirmPassword { get; set; }
        }

    RegisterResult (用于回传注册状态)

        public class RegisterResult
        {
            public bool Successful { get; set; }
            public IEnumerable<string> Errors { get; set; }
        }

    为了方便,我们这里一次性也把登陆的模型都添加进去

    LoginModel

        public class LoginModel
        {
            [Required]
            public string Email { get; set; }
    
            [Required]
            public string Password { get; set; }
    
            public bool RememberMe { get; set; }
        }

    LoginResult

        public class LoginResult
        {
            public bool Successful { get; set; }
            public string Error { get; set; }
            public string Token { get; set; } //最终token
        }

    UserModel

        public class UserModel
        {
            public string Email { get; set; }
            public bool IsAuthenticated { get; set; }
        }

    LoginController的代码:

        [Route("api/[controller]")]
        [ApiController]
        public class LoginController : ControllerBase
        {
            private readonly IConfiguration _configuration;
            private readonly SignInManager<IdentityUser> _signInManager;
    
            public LoginController(IConfiguration configuration,
                                   SignInManager<IdentityUser> signInManager)
            {
                _configuration = configuration;
                _signInManager = signInManager;
            }
    
            //api/login (GET)
            [HttpPost]
            public async Task<IActionResult> Login([FromBody] LoginModel login)
            {
                //尝试登陆
                var result = await _signInManager.PasswordSignInAsync(login.Email, login.Password, false, false);
    
                if (!result.Succeeded) return BadRequest(new LoginResult { Successful = false, Error = "Username and password are invalid." }); //如果登陆失败
    
    
                //payload
                var claims = new[]
                {
                    new Claim(ClaimTypes.Name, login.Email)
                };
    
                //对称密钥
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtSecurityKey"]));
                //密钥做签名
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                //过期时间
                var expiry = DateTime.Now.AddDays(Convert.ToInt32(_configuration["JwtExpiryInDays"]));
    
                //生成token
                var token = new JwtSecurityToken(
                    _configuration["JwtIssuer"],
                    _configuration["JwtAudience"],
                    claims,
                    expires: expiry,
                    signingCredentials: creds
                );
    
                return Ok(new LoginResult { Successful = true, Token = new JwtSecurityTokenHandler().WriteToken(token) });
            }
        }

    下面我们可以自己找个方法验证下,这里就省略。 如果正确的话,你的WeatherForecast控制器应该是401未授权的。

    当然我在实际运行中试过并不返回401而是302跳转到了/Account/Login这个默认的登陆页面,由于我们将全部内容都交由前端处理,并不打算用mvc方式处理登陆注册,所以我们必须返回401以供前端识别。

    使用postman做测试,首先WeatherForecast控制器是401返回(GET)

    其次来试验/api/register 注册控制器

    首先设置Content-Type为application/json

    接着把json字符串放入body,经过实验,提交的json中对象名称可以首字母小写也可以首字母大写,跟实际类名相同都可,但是Blazor提交的json是会自动将首字母变小写,但是后面的其他的大写字母都不会变。当在使用blazor对接其他后端的时候要小心,因为如果要更改这个已经做好的过程,稍微有点麻烦

    接下来可以获得Response

    {
        "successful": false,
        "errors": [
            "User name 'jiangsimpler@gmail.com' is already taken."
        ]
    }

    到此本章就结束了,下一章将开始处理client前端的注册登陆和登出以及查询授权api数据

  • 相关阅读:
    离散数学随笔2
    离散数学随笔1
    java多线程实现线程同步
    c语言细节
    堆的简单实现和应用
    快速排序分析
    ORACLE PRAGMA AUTONOMOUS_TRANSACTION 自治事务 单独提交某一段操作
    System.out.println() 输出 快捷键
    最全最新🇨🇳中国【省、市、区县、乡镇街道】json,csv,sql数据
    使用 js 设置组合快捷键,支持多个组合键定义,还支持 React
  • 原文地址:https://www.cnblogs.com/Simplerjiang/p/12343341.html
Copyright © 2011-2022 走看看