参考地址
VsCode
1.创建WebApi
创建 webApi项目
dotnet new weiapi
2.安装 identityserver4 包
dotnet add package IdentityServer4
3.配置一个 IdentityServerConfig.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 修改
- 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/";
options.RequireHttpsMetadata = false;
options.Audience = "identity";
});
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地址:https://localhost:5001/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]
此时访问报错,暂时不知道怎么解决,待定