.Net Core 创建webApi,Token以及 IdentityServer4

参考地址

VsCode

1.创建WebApi

创建 webApi项目

dotnet new weiapi

2.安装 identityserver4 包,目的是为了获取token

dotnet add package IdentityServer4

3.安装 IdentityServer4.AccessTokenValidation 包,目的是为了权限验证

dotnet add package IdentityServer4.AccessTokenValidation

3.配置一个 IdentityServerConfig.cs 文件 (这边配置放在根目录下面)。目的是为了在startup.cs引用

using IdentityServer4.Models;
using System.Collections.Generic;

namespace IdentityServer4Test.IndntityConfig
{
    public class IdentityServerConfig
    {
        /// <summary>
        /// 添加api资源
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<ApiResource> GetResources()
        {
            return new List<ApiResource>
            {
          
                new ApiResource("api1","My Api")
            };
        }
        /// <summary>
        /// 添加客户端,定义一个可以访问此api的客户端
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<Client> GetClients()
        {
            return new List<Client>
                {
                    new Client
                    {
                        ///
                        ClientId = "client",

                        // 没有交互性用户,使用 客户端模式 进行身份验证。
                        AllowedGrantTypes = GrantTypes.ClientCredentials,
                       
                        // 用于认证的密码
                        ClientSecrets =
                        {
                            new Secret("1234554".Sha256())
                        },
                        // 客户端有权访问的范围(Scopes)
                        AllowedScopes = { "api1" }
                    }
 
                };

        }
    }
}

4.Startup.cs 修改

  1. ConfigureServices方法里面 修改为如下
       services.AddControllers();

            services.AddIdentityServer()
            .AddInMemoryApiResources(IdentityServerConfig.GetResources())//添加配置的api资源
            .AddInMemoryClients(IdentityServerConfig.GetClients())//添加客户端,定义一个可以访问此api的客户端
            .AddDeveloperSigningCredential();

            services.AddAuthentication("Bearer")
       .AddJwtBearer("Bearer", options =>
       {
           options.Authority = "http://localhost:5000/"; //权限验证url
           options.RequireHttpsMetadata = false;//是否开启https
           options.Audience = "api1";
       });

2.Configure方法 修改为如下

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseIdentityServer();//开启Token  配置ASP.NET Core管道
                                    //  //添加authentication中间件到http管道
            app.UseAuthentication();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

5.PostMan测试

post测试,使用http好一点,https在权限认证报错
https地址:https://localhost:5001/connect/token
http地址:http://localhost:5000/connect/token  

form-data参数:
grant_type:client_credentials
client_id:client
client_secret:1234554


请求后会获取到如下大致内容:
{
    "access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6Ill2VmdnbDFUamppQWpFS1VmR2NZYlEiLCJ0eXAiOiJhdCtqd3QifQ.eyJuYmYiOjE1ODUwMzk0NDUsImV4cCI6MTU4NTA0MzA0NSwiaXNzIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6NTAwMSIsImF1ZCI6ImFwaTEiLCJjbGllbnRfaWQiOiJjbGllbnQiLCJzY29wZSI6WyJhcGkxIl19.jV10uH5uo2Ubd2eaqbN521utFc8N7zevgm46tQ9Ka9lIeC-hqOx10bI1BZbWwQjxHla6RAkqwJ0QlyaCZTUk3BVnbFmwnRdW3e08fwSLVY7s2fFuKPJC0bCh3ggLGyoMZgX5cIgpyvyRvI_DIq6vI-6Gpv0aVsPiAfFh5-zLHNfgc5qJ8soG4iP5E33n-SdglICUWuosA2TuF2V7sJaES363emQqa0QnLZQQNgztjlJc2tZViUjOvHa1lk8US_FaHQ6lG6CIRrutQaMnYKSrCcXUBfkAY1b3gnNJ-j_OxeatxuFX7l2uzzKIMEhB2IGg4oej6YYbsCheeOW1ZBoRRw",
    "expires_in": 3600,
    "token_type": "Bearer",
    "scope": "api1"
}

6.权限测试。 API控制器增加 [Authorize]。首先需要安装 IdentityServer4.AccessTokenValidation 。

API控制器

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;

[Route("identity/[action]")]
public class IdentityController : ControllerBase
{
    [HttpGet]
    [Authorize]
    public string Get()
    {
        return "有权限get成功";
    }

      [HttpGet]
    public string Get2()
    {
        return "无权限get成功";
    }
}

采用postman请求测试。不带token请求get直接报错401。
权限测试地址

VS studio

跟着这个做大致一样

原文地址:https://www.cnblogs.com/Alex-Mercer/p/12553594.html