.net core webapi 使用Authorize身份认证

举报
清雨小竹 发表于 2022/09/13 09:32:42 2022/09/13
【摘要】 1.使用JWT身份认证模式,引入库:IdentityServer4.AccessTokenValidation2.在StartUp.cs中添加加密秘钥串:public static readonly SymmetricSecurityKey symmetricKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("need_to_get...

1.使用JWT身份认证模式,引入库:IdentityServer4.AccessTokenValidation

2.在StartUp.cs中添加加密秘钥串:

public static readonly SymmetricSecurityKey symmetricKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("need_to_get_this_from_enviroment"));

3.在ConfigureServices方法中在services.AddMvc();之前添加代码:

 

           services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(o =>
        {
            o.TokenValidationParameters = new TokenValidationParameters
            {
                NameClaimType = JwtClaimTypes.Name,
                RoleClaimType = JwtClaimTypes.Role,
 
                ValidIssuer = "YFAPICommomCore",
                ValidAudience = "api",
                IssuerSigningKey = symmetricKey
 
 
                /***********************************TokenValidationParameters的参数默认值***********************************/
                // RequireSignedTokens = true,
                // SaveSigninToken = false,
                // ValidateActor = false,
                // 将下面两个参数设置为false,可以不验证Issuer和Audience,但是不建议这样做。
                // ValidateAudience = true,
                // ValidateIssuer = true, 
                // ValidateIssuerSigningKey = false,
                // 是否要求Token的Claims中必须包含Expires
                // RequireExpirationTime = true,
                // 允许的服务器时间偏移量
                // ClockSkew = TimeSpan.FromSeconds(300),
                // 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
                // ValidateLifetime = true
            };
        });


在Configure方法中app.UseMvc();之前添加代码:

app.UseAuthentication();

4.在一个ApiController中增加生成access_token的方法:

       

[HttpPost("authenticate")]
        public IActionResult Authenticate([FromBody]User userDto)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var authTime = DateTime.UtcNow;
            var expiresAt = authTime.AddDays(7);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
            new Claim(JwtClaimTypes.Audience,"api"),
            new Claim(JwtClaimTypes.Issuer,"YFAPICommomCore"),
            new Claim(JwtClaimTypes.Id, "1"),
            new Claim(JwtClaimTypes.Name, "xxx"),
            new Claim(JwtClaimTypes.Email, "xxx@qq.com"),
            new Claim(JwtClaimTypes.PhoneNumber, "13500000000")
                }),
                Expires = expiresAt,
                SigningCredentials = new SigningCredentials(Startup.symmetricKey, SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);
            return Ok(new
            {
                access_token = tokenString,
                token_type = "Bearer",
                profile = new
                {
                    sid = "1",
                    name = "xxxx",
                    auth_time = new DateTimeOffset(authTime).ToUnixTimeSeconds(),
                    expires_at = new DateTimeOffset(expiresAt).ToUnixTimeSeconds()
                }
            });
        }


5.然后就可以在任意ApiController方法中添加 [Authorize] 使用了:

       

 [Authorize]
        [HttpPost]
        [HttpGet]
        public string Test2()
        {
            var identity = (ClaimsIdentity)User.Identity;
            var id = identity.Claims.FirstOrDefault(u=>u.Type== JwtClaimTypes.Id).Value;
            return "test auth";
        }


注意:在ConfigureServices中初始化Swagger的时候,可以加上对auth的支持。

           

 Init Swagger
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title = "WebAPI"
                });
                //启用auth支持
                options.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name = "Authorization",
                    In = "header",
                    Type = "apiKey"
                });
 
                ///Determine base path for the application.  
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath = Path.Combine(basePath, "TestCore.xml");
 
                //var xmlPath = "/opt/zili/gongyeyun/TestCore.xml";
 
                options.IncludeXmlComments(xmlPath);
            }); 

工程git地址:https://github.com/zzzili/YFAPICommonCore

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。