.netcore 跨域+jwt+log4net

跨域

1
2
3
4
5
6
7
8
9
10
11
12
#region CORS 跨域
 
           services.AddCors(options =>
           {
               options.AddPolicy("any", builder =>
               {
                   builder
                     .AllowAnyHeader()
                     .AllowAnyMethod()
                     .AllowAnyOrigin();
               });
           });

 

1
2
// 允许所有跨域,cors是在ConfigureServices方法中配置的跨域策略名称
app.UseCors("any");<br>app.UseFileServer();<br>app.UseStaticFiles();<br>app.UseRouting();<br>app.UseAuthentication();<br>app.UseAuthorization();

  

 

 jwt

安装 包 Microsoft.AspNetCore.Authentication.JwtBearer(5.0.17)

    Microsoft.AspNetCore.Mvc.NewtonsoftJson(5.0.17)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#region Jwt配置
           // 注册JWT服务
           services.AddAuthentication(options =>
           {
               options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
           })
           .AddJwtBearer(options =>
           {
               options.TokenValidationParameters = new TokenValidationParameters()
               {
                   ValidateIssuer = true, //是否验证Issuer
                   ValidIssuer = Configuration["Jwt:Issuer"], //发行人Issuer
                   ValidateAudience = true, //是否验证Audience
                   ValidAudience = Configuration["Jwt:Audience"], //订阅人Audience
                   ValidateIssuerSigningKey = true, //是否验证SecurityKey
                   IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"])), //SecurityKey
                   ValidateLifetime = true, //是否验证失效时间
                   ClockSkew = TimeSpan.FromSeconds(30), //过期时间容错值,解决服务器端时间不同步问题(秒)
                   RequireExpirationTime = true,
               };
           });               //设置日期格式       services.AddControllers()
             .AddNewtonsoftJson(op =>
             { //Newtonsoft.Json
                 op.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                 op.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
             });
 
           services.AddSingleton(new JwtHelper(Configuration));            #endregion

  新建一个类     JwtHelper

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class JwtHelper
   {
       private readonly IConfiguration _configuration;
       public JwtHelper(IConfiguration configuration)
       {
           _configuration = configuration;
       }
       public string CreateToken()
       {
           // 1. 定义需要使用到的Claims
           var claims = new[]
           {
           new Claim(ClaimTypes.Name, "u_admin"), //HttpContext.User.Identity.Name
           new Claim(ClaimTypes.Role, "r_admin"), //HttpContext.User.IsInRole("r_admin")
           new Claim(JwtRegisteredClaimNames.Jti, "admin"),
           new Claim("Username", "Admin"),
           new Claim("Name", "超级管理员")
       };
           // 2. 从 appsettings.json 中读取SecretKey
           var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"]));
           // 3. 选择加密算法
           var algorithm = SecurityAlgorithms.HmacSha256;
           // 4. 生成Credentials
           var signingCredentials = new SigningCredentials(secretKey, algorithm);
           // 5. 根据以上,生成token
           var jwtSecurityToken = new JwtSecurityToken(
               _configuration["Jwt:Issuer"],     //Issuer
               _configuration["Jwt:Audience"],   //Audience
               claims,                          //Claims,
               DateTime.Now,                    //notBefore
               DateTime.Now.AddSeconds(30),    //expires
               signingCredentials               //Credentials
           );
           // 6. 将token变为string
           var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
           return token;
       }
 
   }

  在appsetting.json中添加

1
2
3
4
5
"Jwt": {
    "SecretKey": "745058532@qq.com",
    "Issuer": "WebAppIssuer",
    "Audience": "WebAppAudience"
  }

  log4net

在program文件中加入

1
2
3
4
5
6
7
8
9
10
public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureLogging(loggingBuilder =>
            {
                loggingBuilder.AddLog4Net("log4net.config");
            })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

  

创建log4net.config文件

安装 包 Microsoft.Extensions.Logging.Log4Net.AspNetCore(6.13)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?xml version="1.0" encoding="utf-8"?>
<log4net>
  <!-- Define some output appenders -->
  <appender name="rollingAppender" type="log4net.Appender.RollingFileAppender">
    <file value="log\log.txt" />
    <!--追加日志内容-->
    <appendToFile value="true" />
 
    <!--防止多线程时不能写Log,官方说线程非安全-->
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
 
    <!--可以为:Once|Size|Date|Composite-->
    <!--Composite为Size和Date的组合-->
    <rollingStyle value="Composite" />
 
    <!--当备份文件时,为文件名加的后缀-->
    <datePattern value="yyyyMMdd.TXT" />
 
    <!--日志最大个数,都是最新的-->
    <!--rollingStyle节点为Size时,只能有value个日志-->
    <!--rollingStyle节点为Composite时,每天有value个日志-->
    <maxSizeRollBackups value="20" />
 
    <!--可用的单位:KB|MB|GB-->
    <maximumFileSize value="3MB" />
 
    <!--置为true,当前最新日志文件名永远为file节中的名字-->
    <staticLogFileName value="true" />
 
    <!--输出级别在INFO和ERROR之间的日志-->
    <filter type="log4net.Filter.LevelRangeFilter">
      <param name="LevelMin" value="ALL" />
      <param name="LevelMax" value="FATAL" />
    </filter>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
    </layout>
  </appender>
  <root>
    <priority value="ALL"/>
    <level value="ALL"/>
    <appender-ref ref="rollingAppender" />
  </root>
</log4net>

  

posted @   贾平凡  阅读(65)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示