ASP.NET Core5.0 WebApi和BlazorWebAssembly 博客后台管理系统(jwt登录校验)

ASP.NET Core5.0 WebApi和BlazorWebAssembly 博客后台管理系统

1,此项目是VS2019,Asp.NetCore5.0,用到Blazor,样式用到了bootstrap,数据库用到的MySQL数据库
项目实例图片,文章后面会**附上项目地址 下载地址

webapi端截图
ASP.NET Core5.0 WebApi和BlazorWebAssembly 博客后台管理系统(jwt登录校验)_第1张图片
Blazor Wasm端截图ASP.NET Core5.0 WebApi和BlazorWebAssembly 博客后台管理系统(jwt登录校验)_第2张图片ASP.NET Core5.0 WebApi和BlazorWebAssembly 博客后台管理系统(jwt登录校验)_第3张图片
2,项目结构和部分代码下(代码较多只粘贴部分,文章最后提供项目下载地址在这里插入代码片
ASP.NET Core5.0 WebApi和BlazorWebAssembly 博客后台管理系统(jwt登录校验)_第4张图片
2.1 webapi端

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            //连接sqlite
            //services.AddDbContext(
            //   options =>
            //   {
            //       options.UseSqlite(@"Data Source=BlzaorApiBlog.db");
            //   });
            //添加app 连接mysql
            services.AddDbContext<MyBlogDbContext>(option =>
            {
                option.UseMySql(Configuration["SqlConn"], MySqlServerVersion.LatestSupportedServerVersion);
            });
            //注入服务
            services.AddScoped<IBlogModesServices, BlogModesServices>();
            services.AddScoped<IBlogTypesServices, BlogTypesServices>();
            services.AddScoped<IWriterInfoServices, WriterInfoServices>();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "Blog.Api", Version = "v1" });
                #region Swagger想要使用鉴权需要注册服务的时候添加以下代码
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    Description = "直接在下框中输入Bearer {token}(注意两者之间是一个空格)",
                    Name = "Authorization",
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                  {
                    new OpenApiSecurityScheme
                    {
                      Reference=new OpenApiReference
                      {
                        Type=ReferenceType.SecurityScheme,
                        Id="Bearer"
                      }
                    },
                    new string[] {}
                  }
                });
                #endregion
            });

            #region 注入jwt
            services.AddCustomJWT();
            #endregion

            #region 注入AutoMapper
            object p = services.AddAutoMapper(typeof(CustomAutoMapperProfile));
            #endregion

            #region 配置跨域请求

            services.AddCors(options =>
            {
                options.AddPolicy("any", builder =>
                {
                    builder.SetIsOriginAllowed(_ => true)
                    .AllowAnyOrigin() //允许任何来源的主机访问
                    .AllowAnyHeader()
                    .AllowAnyMethod(); 
                });
            });

            #endregion

        }

2.2,Wasm端

public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("#app");

            //builder.Services.AddScoped(sp => new HttpClient
            //{
            //    //BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
            //    BaseAddress = new Uri("https://localhost:5001")
            //});

            builder.Services.AddHttpClient<IBlogModeServices, BlogModeServices>
               (client => client.BaseAddress = new Uri("https://localhost:6001"));

            builder.Services.AddHttpClient<IBlogTypeServices, BlogTypeServices>
              (client => client.BaseAddress = new Uri("https://localhost:6001"));

            builder.Services.AddHttpClient<IWriteInfoServices, WriteInfoServices>
              (client => client.BaseAddress = new Uri("https://localhost:6001"));

            builder.Services.AddBlazoredModal(); //modal框
            builder.Services.AddBlazoredLocalStorage(); //localstorage

            //builder.Services.AddAuthorizationCore(); //授权
            var host = builder.Build();
            await host.RunAsync();
        }

2.3 jwt 校验

[Route("api/[controller]")]
    [ApiController]
    public class AuthorizationController : ControllerBase
    {
        private readonly IWriterInfoServices _IwriterInfoSerive;
        public AuthorizationController(IWriterInfoServices iwriterInfoSerive)
        {
            _IwriterInfoSerive = iwriterInfoSerive;
        }

        [Produces("application/json")]
        [HttpPost("Login")]
        public async Task<ApiResult> Login([FromBody] WriterInfo DTouser)
        {
            //Console.WriteLine("dtouser:" + DTouser);
            //加密后的密码  
            //string pwd = DTouser.UserPwd;
            string pwd = MD5Helper.GenerateMD5(DTouser.UserPwd);
            string useraccount = DTouser.UserAccount;
            //数据校验
            var writer = await _IwriterInfoSerive.FindAsync(useraccount, pwd);
            if (writer != null)
            {
                //.登陆成功
                var claims = new Claim[]
                     {
                         //不能发敏感信息
                          //new Claim(ClaimTypes.Name, "张三")
                          new Claim("UserAccount", writer.UserAccount),
                          new Claim ("Id",writer.Id.ToString()),
                          new Claim ("UserName",writer.UserName)
                      };                                                 //密钥
                var key = new SymmetricSecurityKey(
                    Encoding.UTF8.GetBytes("SDMC-CJAS1-SAD-DFSFA-SADHJVF-VF"));
                //issuer代表颁发Token的Web应用程序,audience是Token的受理者
                var token = new JwtSecurityToken(
                    issuer: "http://localhost:5000", //=jwt发布者
                    audience: "http://localhost:6000", //=api使用者
                    claims: claims,
                    notBefore: DateTime.Now,
                    expires: DateTime.Now.AddHours(1),
                    signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
                );
                var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
                // return jwtToken;
                return ApiResultHelper.Success(jwtToken);
            }
            return ApiResultHelper.Error("登录失败-账号密码错误");
        }
    }

3,项目下载地址

你可能感兴趣的:(ASPNETCore,C#,asp.net,后端,microsoft)