如何对自己的IdentityServer进行身份验证和授权?

时间:2020-04-21 10:22:28

标签: authentication asp.net-core asp.net-web-api2 asp.net-identity identityserver4

我有一个名称为MyApi的Api,并且我将另一个带Identityserver4的asp.net核心应用程序用于保护MyApi,现在,我在MyApi中没有任何问题,但是,我想保存用户的NationalCode,所以我应该将其保存在我的IdentityServer数据库中,但是无法在我的IdentityServer项目中获取UserId(带有User.Identity.Name),我之前的问题中也遇到了同样的问题

User.Identity.Name is null in my ASP.NET Core Web API

现在我的IdentityServer4项目中存在这个问题,所以

我可以使用MyApi令牌吗?还是应该获得一个新的令牌以向idenittyserver4项目发送请求?

如果我可以使用MyAPI令牌,应该如何添加配置以解决该问题?

如果我应该为IdentityServer4项目获取新令牌,我是否需要让用户再次登录?!!

修改

我在下面的链接中找到了一条tutorail,但我的问题尚未解决。

http://docs.identityserver.io/en/latest/topics/add_apis.html

我使用以下方法播种了IdentityDatabase


public async Task AddIdenityServerApiToResources(IApplicationBuilder app)
        {
            using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
            {
                serviceScope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();
                var ccontext = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
                ccontext.Database.Migrate();
                //=============================================================
                ccontext.ApiResources.Add(new ApiResource(IdentityServerConstants.LocalApi.ScopeName) {
                    UserClaims =
                    {
                        JwtClaimTypes.Name,
                        JwtClaimTypes.Subject,
                        JwtClaimTypes.Role,
                    }
                }.ToEntity());
                //Add ApiResource To Client's Scope
                var Clients = ccontext.Clients.Include(e => e.AllowedScopes);
                foreach (var item in Clients)
                {
                    item.AllowedScopes.Add(new IdentityServer4.EntityFramework.Entities.ClientScope() { Scope = IdentityServerConstants.LocalApi.ScopeName });
                }
                var Count = await ccontext.SaveChangesAsync();
                if (Count > 0)
                {
                }
            }
        }

2 个答案:

答案 0 :(得分:0)

在IdentityServer4 startup.cs ConfigureServices中

您应该将api视为需要由idserver4保护的任何其他api一样。

含义:使用AddAuthentication和AddJWTToken:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.Authority = "https:// idserver4 ";
            options.RequireHttpsMetadata = true;
            options.Audience = "api name";
            options.TokenValidationParameters = new TokenValidationParameters
            {
                NameClaimType = "name",
                RoleClaimType = "role"
            };
        });

在API控制器中:

使用Authorize Attirbute并按照以下方式确定身份验证方案:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

答案 1 :(得分:0)

我通过以下链接解决了问题:

http://docs.identityserver.io/en/latest/topics/add_apis.html

但是问题是我没有在我的控制器上使用Authorize策略的地方LocalApi.PolicyName

[Route("localApi")]
[Authorize(LocalApi.PolicyName)]
public class LocalApiController : ControllerBase
{
    public IActionResult Get()
    {
        // omitted
    }
}

解决了问题之后