记录下IdentityService4学习
新建两个项目 Identity.Server认证服务,Identity.UserApiService为Api服务,目的来实现通过认证服务认证后才能调用Api服务
在Identity.Server中安装IdentityServer库
创建ApiResource和Client两个资源文件
public class ApiResourceData {
/// <summary>
/// 获取ApiResource
/// </summary>
/// <returns></returns>
public static IEnumerable<ApiResource> GetApiResources() {
List<ApiResource> list = new List<ApiResource>();
list.Add(new ApiResource(OAuthConfig.UserApi.ApiName, OAuthConfig.UserApi.ApiName));
return list;
}
}
public static IEnumerable<Client> GetClients() {
List<Client> list = new List<Client>();
list.Add(new Client() {
ClientId = OAuthConfig.UserApi.ClientId,
AllowedGrantTypes = new List<string>() {
GrantType.ResourceOwnerPassword,//密码模式需要输入用户名和密码
GrantType.ClientCredentials,//凭证式
},
ClientSecrets = { new Secret(OAuthConfig.UserApi.Secret.Sha256()) },
AllowedScopes = {OAuthConfig.UserApi.ApiName},
AccessTokenLifetime=36000
});
return list;
}
在Startup中配置ConfigureServices
#region 内存模式
services.AddIdentityServer()
.AddDeveloperSigningCredential()//默认的开发者证书
.AddInMemoryApiResources(ApiResourceData.GetApiResources())//IEnumerable的Api资源
.AddInMemoryClients(ApiClientData.GetClients())
.AddTestUsers(TestUserData.GetTestUsers());
#endregion
在Configure中加入
app.UseIdentityServer();
这样就完成了认证服务了。
我们配置了两种模式,password模式如下
凭证模式如下
这样就可以获取到access_token了,这里要注意传入参数的名称。
接下来在项目Identity.UserApiService中安装IdentityServer4. AccessTokenValidation
在Startup中配置
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().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddAuthorization();
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options => {
options.Authority = "http://localhost:5000"; //配置Identityserver的授权地址
options.RequireHttpsMetadata = false; //不需要https
options.ApiName = OAuthConfig.UserApi.ApiName; //api的name,需要和config的名称相同
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();//开启认证
app.UseMvc();
}
}
然后建立一个api控制器并对其加上Authorize特性进行验证
[Route("api/[controller]/[action]")]
[ApiController]
public class TestController : ControllerBase
{
[HttpGet]
[Authorize]//加上认证
public IActionResult GetUser(string id) {
var msg = $"this id is:{id}";
return Content(msg);
}
}
此时我们可以来测试下,在没加token的情况下访问返回的是401错误
我们在headers的Authorization加入token,就能正常返回值了,注意token前需加上"Bearer token"才可以被认证通过