天天看点

IdentityServer4学习(一)定义身份资源

IdentityServer4学习(一)定义身份资源

Posted on

2021-04-09 08:32 

RefineYJ 

阅读(0) 

评论(0) 

编辑 

收藏

定义资源(IdentityResource)

两种基本资源

1.身份资源:代表有关用户的声明,例如用户ID,显示名称,电子邮件地址等

2.Api资源 代表客户端想要访问的功能

IResourceStore 可以实现这个接口 做到从数据存储中定义资源 (官网示例文档是从内存中加载资源)

public static IEnumerable<IdentityResource> GetIdentityResources()
{
    return new List<IdentityResource>
    {
        new IdentityResource(
            name: "openid",
            userClaims: new[] { "sub" },
            displayName: "Your user identifier")
    };
}
      

  

简写:

public static IEnumerable<IdentityResource> GetIdentityResources()
{
    return new List<IdentityResource>
    {
        new IdentityResources.OpenId()
    };
}      

(从内存中获取)

public class ResourceStore : IResourceStore
 {
        /// <summary>
        /// The DbContext.
        /// </summary>
        protected readonly IConfigurationDbContext Context;

        /// <summary>
        /// The logger.
        /// </summary>
        protected readonly ILogger<ResourceStore> Logger;

        /// <summary>
        /// Initializes a new instance of the <see cref="ResourceStore"/> class.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="logger">The logger.</param>
        /// <exception cref="ArgumentNullException">context</exception>
        public ResourceStore(IConfigurationDbContext context, ILogger<ResourceStore> logger)
        {
            Context = context ?? throw new ArgumentNullException(nameof(context));
            Logger = logger;
        }
        ...
 }      

(从数据库获取资源)

自定义身份资源

定义一个名称为profile自定义身份资源

public static IEnumerable<IdentityResource> GetIdentityResources()
{
    return new List<IdentityResource>
    {
        new IdentityResource(
            name: "profile",
            userClaims: new[] { "name", "email", "website" },
            displayName: "Your profile data")
    };
}      

定义资源后,可以通过AllowedScopes 将访问权限授予客户端

var client = new Client
{
    ClientId = "client",

    AllowedScopes = { "openid", "profile" }
};      

客户端可以使用scope参数请求资源

例如 使用vue + oidc-client

constructor () {
    super({
      authority: 'http://localhost:5000/',
      client_id: 'vuejs',
      redirect_uri: 'http://192.168.1.26:8081/callback',
      response_type: 'id_token token',
      scope: 'openid profile roles ',
      post_logout_redirect_uri: 'http://192.168.1.26:8081'
    })
  }      

https://http://localhost:5000/connect/authorize?client_id=client&scope=openid profile

Next(Api资源定义)