码迷,mamicode.com
首页 > Windows程序 > 详细

.Net Core Api 授权认证

时间:2018-02-01 17:40:19      阅读:2939      评论:0      收藏:0      [点我收藏+]

标签:odi   auth   metrics   date   返回   text   res   style   mod   

一、所使用到的NuGet:

1. System.IdentityModel.Tokens.Jwt

2. Microsoft.AspNetCore.Authentication.JwtBearer

技术分享图片

技术分享图片

 

二、在Startup.cs 中配置添加如下服务

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication.JwtBearer;

namespace WebApplication1
{
    public class Startup
    {
        

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            
            services.AddMvc();
            //手动高亮
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                  .AddJwtBearer(options => {
                      options.TokenValidationParameters = new TokenValidationParameters
                      {
                          ValidateIssuer = true,//是否验证Issuer
                          ValidateAudience = true,//是否验证Audience
                          ValidateLifetime = true,//是否验证失效时间
                          ValidateIssuerSigningKey = true,//是否验证SecurityKey
                          ValidAudience = "haos.test.com",
                          //山下这两项和签发token时的issuer,Audience一致
                          ValidIssuer = "haos.test.issuer.com",
                          IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("1234567887654321"))//拿到token加密密钥.必须是16个字符
                      };
                  });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            //手动高亮
            app.UseAuthentication();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }
            
            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });
        }
    }
}

三、签发token 添加测试控制器

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Linq;

namespace WebApplication1.Controllers
{
    [Authorize]
    public class TestController:Controller
    {

        public JsonResult Test()
        {
            //获取当前用户信息
            var claims = User.Claims;
            var userName = User.Identity.Name;
            var userId = claims.FirstOrDefault(t => t.Type == "userId");
            var phone = claims.FirstOrDefault(t => t.Type == ClaimTypes.MobilePhone);
            return Json("ok");
        }
        
        /// <summary>
        /// 登录(签发token)
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public JsonResult Login(string name ,string pwd)
        {
            var claims = new[]
               {
                   new Claim(ClaimTypes.Name, "test"),
                   new Claim(ClaimTypes.MobilePhone, "157****7350"),
                   new Claim("userId","value")
               };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("1234567887654321"));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                   issuer: "haos.test.issuer.com",
                   audience: "haos.test.com",
                   claims: claims,
                   expires: DateTime.Now.AddMinutes(30),
                   signingCredentials: creds);
            return Json(new {
                Authorization = $"Bearer {new JwtSecurityTokenHandler().WriteToken(token)}"
            });
        }
    }
}
//返回的token;注:键为authorization,其中必须有Bearer 字样
{"authorization":"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoidGVzdCIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL21vYmlsZXBob25lIjoiMTU3KioqKjczNTAiLCJleHAiOjE1MTc0NjgzNDcsImlzcyI6Imhhb3MudGVzdC5pc3N1ZXIuY29tIiwiYXVkIjoiaGFvcy50ZXN0LmNvbSJ9.Xtrbbz6WF4VreoB-S2nmRL5lx1Vg27WcQYTsek5VPIc"}

四、访问结果

技术分享图片

 

.Net Core Api 授权认证

标签:odi   auth   metrics   date   返回   text   res   style   mod   

原文地址:https://www.cnblogs.com/haosit/p/8399048.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!