一、创建一个空的api项目

添加identityserver4的nuget包

配置config文件

public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new IdentityResource[]
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
};
}
/// <summary>
/// API信息
/// </summary>
/// <returns></returns>
public static IEnumerable<ApiResource> GetApis()
{
return new[]
{
new ApiResource(IdentityServerConstants.LocalApi.ScopeName),
new ApiResource("manageApi", "Demo API with Swagger")
};
}
/// <summary>
/// 客服端信息
/// </summary>
/// <returns></returns>
public static IEnumerable<Client> GetClients()
{
return new[]
{
new Client
{
ClientId = "clientId",//客服端名称
ClientName = "Swagger UI for demo_api",//描述
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword ,//指定允许的授权类型(AuthorizationCode,Implicit,Hybrid,ResourceOwner,ClientCredentials的合法组合)。
AllowAccessTokensViaBrowser = true,//是否通过浏览器为此客户端传输访问令牌
AccessTokenLifetime = 3600*24,
AuthorizationCodeLifetime=3600*24,
ClientSecrets ={new Secret("secret".Sha256())},
//RedirectUris =
//{
// "http://localhost:59152/oauth2-redirect.html"
//},
AllowedCorsOrigins = new string[]{ "http://localhost:9012", "http://101.133.234.110:21004", "http://115.159.83.179:21004" },
AllowedScopes = { "manageApi", IdentityServerConstants.LocalApi.ScopeName }//指定客户端请求的api作用域。 如果为空,则客户端无法访问
}
};
}

在Startup.cs中注入IdentityServer服务并使用中间件

 //配置身份服务器与内存中的存储,密钥,客户端和资源
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(config.GetApis())//添加api资源
.AddInMemoryClients(config.GetClients())//添加客户端
.AddInMemoryIdentityResources(config.GetIdentityResources())//添加对OpenID Connect的支持
//使用自定义验证
.AddResourceOwnerValidator<CustomResourceOwnerPasswordValidator>()
.AddProfileService<ProfileService>();
//启用IdentityServer
app.UseIdentityServer();

接下来,我们去实现CustomResourceOwnerPasswordValidator这个类

创建一个CustomResourceOwnerPasswordValidator类,继承IResourceOwnerPasswordValidator

 public class CustomResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
{
public Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
{
throw new NotImplementedException();
}
}

接下来,我们就是些验证了

我们创建一个服务,去获取数据库里面的用户,验证是否有当前登录的用户

这里我们创建了一个userservice来验证我们的输入用户是否存在

  public class UserService : IUserService
{
public async Task<TestPhoneUser> ValidateCredentials(string nameorphone, string password)
{
var dto= TestUser.FirstOrDefault(c => c.Phone == nameorphone && password == c.PassWord);
if (dto != null)
return dto;
else
return null;
}
public class TestPhoneUser
{
/// <summary>
/// 唯一标识
/// </summary>
public int Id { get; set; }
/// <summary>
/// 手机号
/// </summary>
public string Phone { get; set; }
/// <summary>
/// 密码
/// </summary>
public string PassWord { get; set; }
}
public List<TestPhoneUser> TestUser = new List<TestPhoneUser>
{
new TestPhoneUser
{
Id=1,
Phone="12345678911",
PassWord="123qwe"
},new TestPhoneUser
{
Id=2,
Phone="123",
PassWord="123qwe"
}
}; }

现在,我们去完善CustomResourceOwnerPasswordValidator

public class CustomResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
{
private readonly IUserService _userService; public CustomResourceOwnerPasswordValidator(IUserService userService)
{
_userService = userService;
}
public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
{
var dto = await _userService.ValidateCredentials(context.UserName, context.Password);
if (dto!=null)
{
context.Result = new GrantValidationResult(
dto.Id.ToString(),
"pwd",
DateTime.Now);
}
else
{
//验证失败
context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "用户名密码错误");
}
}
}

再要配置profile

 public class ProfileService:IProfileService
{
public Task GetProfileDataAsync(ProfileDataRequestContext context)
{
context.IssuedClaims = context.Subject.Claims.ToList();
return Task.CompletedTask;
} public Task IsActiveAsync(IsActiveContext context)
{
context.IsActive = true; return Task.CompletedTask;
}
}

注入刚刚添加的服务

 services.AddScoped<IUserService, UserService>();
services.AddScoped<IProfileService, ProfileService>();

在Startup.cs中加入identityServer验证

 //用户校验
services.AddLocalApiAuthentication(); services.AddAuthorization(options =>
{
options.AddPolicy(IdentityServerConstants.LocalApi.PolicyName, policy =>
{
policy.AddAuthenticationSchemes(IdentityServerConstants.LocalApi.AuthenticationScheme);
policy.RequireAuthenticatedUser();
});
});
            app.UseAuthentication();

postman测试

反复验证了很多遍,都没有问题(因为我之前core2.x的时候就是这样写的)

最后去identityserver官网,找到了问题所在

现在的资源都换成了apiscope

然后,我把ApiResource都换成了ApiScope然后再运行

ok,完美!!!(这个坑,坑了我一下午)

最后再给api添加验证就行了

[Authorize(LocalApi.PolicyName)]

访问api

访问成功

参考文献:https://identityserver4.readthedocs.io/en/latest/quickstarts/1_client_credentials.html#defining-an-api-scope

IdentityServer4与API单项目整合(net core 3.X)的更多相关文章

  1. IdentityServer4实战 - 与API单项目整合

    一.前言 我们在实际使用 IdentityServer4 的时候,可能会在使用 IdentityServer4 项目添加一些API,比如 找回密码.用户注册.修改用户资料等,这些API与Identit ...

  2. ssm单项目整合

    目录 前言 创建maven项目 添加依赖 配置文件 总览 jdbc配置 mybatis配置 dao层配置 service层配置 事务配置 controller配置 web.xml 使用 前言 spri ...

  3. Swagger与SpringMVC项目整合

    Swagger与SpringMVC项目整合 来源:http://www.2cto.com/kf/201502/376959.html 为了方便的管理项目中API接口,在网上找了好多关于API接口管理的 ...

  4. 企业项目实战 .Net Core + Vue/Angular 分库分表日志系统 | 简单的分库分表设计

    前言 项目涉及到了一些设计模式,如果你看的不是很明白,没有关系坚持下来,写完之后去思考去品,你就会有一种突拨开云雾的感觉,所以请不要在半途感觉自己看不懂选择放弃,如果我哪里写的详细,或者需要修正请联系 ...

  5. 企业项目实战 .Net Core + Vue/Angular 分库分表日志系统二 | 简单的分库分表设计

    教程预览 01 | 前言 02 | 简单的分库分表设计 03 | 控制反转搭配简单业务 04 | 强化设计方案 05 | 完善业务自动创建数据库 06 | 最终篇-通过AOP自动连接数据库-完成日志业 ...

  6. SSM项目整合基本步骤

    SSM项目整合 1.基本概念 1.1.Spring Spring 是一个开源框架, Spring 是于 2003  年兴起的一个轻量级的 Java  开发框架,由 Rod Johnson  在其著作  ...

  7. 基于aws api gateway的asp.net core验证

    本文是介绍aws 作为api gateway,用asp.net core用web应用,.net core作为aws lambda function. api gateway和asp.net core的 ...

  8. Discuz3.2与Java 项目整合单点登陆

    JAVA WEB项目与Discuz 论坛整合的详细步骤完全版目前未有看到,最近遇到有人在问,想到这个整个不是一时半会也解释不清楚.便把整个整合过程以及后续碰到的问题解决方案写下,以供参考. 原理 Di ...

  9. SSM 框架 ---项目整合

    一.SSM框架理解 Spring(业务层) Spring就像是整个项目中装配bean的大工厂,在配置文件中可以指定使用特定的参数去调用实体类的构造方法来实例化对象. Spring的核心思想是IoC(控 ...

随机推荐

  1. (转)mybatis一级缓存二级缓存

    一级缓存 Mybatis对缓存提供支持,但是在没有配置的默认情况下,它只开启一级缓存,一级缓存只是相对于同一个SqlSession而言.所以在参数和SQL完全一样的情况下,我们使用同一个SqlSess ...

  2. 安卓手机没有twrp的情况,如何下刷入magisk并获得root权限.

    安装adb工具 https://dl.google.com/android/repository/platform-tools_r29.0.6-windows.zip 从以上地址下载,然后解压到任意目 ...

  3. in文件注意事项及详细解释(转载)

    转载自:https://www.cnblogs.com/sysu/p/10817315.html  和   https://www.cnblogs.com/panscience/p/4953940.h ...

  4. 面试:为了进阿里,死磕了ThreadLocal内存泄露原因

    前言 在分析ThreadLocal导致的内存泄露前,需要普及了解一下内存泄露.强引用与弱引用以及GC回收机制,这样才能更好的分析为什么ThreadLocal会导致内存泄露呢?更重要的是知道该如何避免这 ...

  5. samba使用过程中遇到的问题

    1 环境说明 Linux系统版本:Linux version 2.6.32-431.el6.x86_64 (mockbuild@x86-023.build.eng.bos.redhat.com) (g ...

  6. 揭秘日活千万腾讯会议全量云原生化上TKE技术实践

    腾讯会议,一款联合国都Pick的线上会议解决方案,提供完美会议品质和灵活协作空间,广泛应用在政府.医疗.教育.企业等各个行业.大家从文章8天扩容100万核,腾讯会议是如何做到的?都知道腾讯会议背后的计 ...

  7. 由mv命令引发的对inode的思考

    一场机器迁移引起的思考 最近团队一台机器老化了,准备做全量迁移,一不小心,就把100多个G的/data目录放到了新机器的/data/data目录下,上愁了,怎么削减一层data目录呢?难倒像Windo ...

  8. Python开发的入门教程(九)-列表生成式

    介绍 本文主要介绍Python中列表生成式的基本知识和使用 生成列表 要生成list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],我们可以用range(1, 11): >&g ...

  9. 初级知识六——C#事件通知系统实现(观察者模式运用)

    观察者模式,绝对是游戏中十分重要的一种模式,运用这种模式,可以让游戏模块间的通信变得简单,耦合度也会大大降低,下面讲解如何利用C#实现事件通知系统. 补充,首先说下这个系统的实现原理,不然一头扎进去就 ...

  10. 听过N次还是不会之:浏览器输入url后到底经历了什么

    有没有这种场景:当你被问起某一项知识点时,你大脑里想起经常看到过这样的问题,可是具体是怎么样就是说不清楚. 好吧,我就是这样的,于是整理一下,实在记不住,以后找起来也方便. 当你在浏览器地址栏里输入一 ...