自行保护IdentityServer4 Api

时间:2019-01-25 10:34:55

标签: identityserver4

我们目前正在研究Identityserver4的实现,该实现还将有一些api调用。

仅当用户被授权(带有承载令牌)时,这些api调用才可用。

在Startup.cs中,我们拥有services.AddIdentityServer(),因为它是IdentityServer,并且还添加了AddAuthentication()调用以确保授权端点仅可用于授权连接。

Startup.cs => ConfigureServices():

services.AddIdentityServer();                
services.AddAuthentication("Bearer")
                .AddIdentityServerAuthentication(options =>
                {
                    options.Authority = "http://localhost:9000";
                    options.RequireHttpsMetadata = false;

                    options.ApiName = "identityserver4";
                });

Startup.cs => Configure():

        app.UseAuthentication();

        app.UseIdentityServer();

        //app.UseAuthentication();

在UseIdentityServer()之前或之后使用UseAuthentication()不会更改任何内容。

我在Identityserver中的api调用仍然对所有人可用。 当前正在使用邮递员来测试呼叫。

我需要添加一些东西吗?有什么我想念的吗?

亲切的问候,

沃尔特

编辑1:添加了控制器和完整的startup.cs UserController.cs:

namespace Identity.Controllers
{
    [Authorize]
    [Route("[controller]")]

    public class UserController : ControllerBase
    {
        private readonly ILogger _logger;
        private readonly IUserBusinessLogic _userBusinessLogic;

        public UserController(ILogger<UserController> logger, IUserBusinessLogic userBusinessLogic)
            : base()
        {
            _logger = logger;
            _userBusinessLogic = userBusinessLogic;
        }

        [Route("")]
        [HttpGet]        
        public async Task<ActionResult<IList<UserDto>>> GetAllUsers()
        {
            var users = await _userBusinessLogic.GetAll();
            return users.ToList();
        }
    }
}

Startup.cs:

namespace Identity
{
    public class Startup
    {
        private readonly IConfiguration _configuration;
        private readonly ILogger _logger;

        public Startup(IConfiguration configuration, ILogger<Startup> logger)
            : base()
        {
            _configuration = configuration;
            _logger = logger;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvcCore()
                .AddJsonFormatters()
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
                .AddRazorViewEngine(); 

            services.Configure<ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = context => new ValidationProblemDetailsResult();
            });

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
                .AddIdentityServerAuthentication(options =>
                {
                    options.Authority = "http://localhost:9000";
                    options.RequireHttpsMetadata = false;

                    options.ApiName = "identityserver4";
                });

            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddPersistedGrantStore<PersistedGrantStoreBusinessLogic>()
            .AddResourceStore<ResourceBusinessLogic>()
            .AddClientStore<ClientBusinessLogic>()
            .AddProfileService<ProfileBusinessLogic>()
            .AddCorsPolicyService<CorsPolicyBusinessLogic>();

            services.AddCors(options =>
            {
                options.AddPolicy("default",
                    builder => builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader().Build());
            });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseAuthentication();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseCors("default");
            app.UseIdentityServer();
            app.UseStaticFiles();
            app.ConfigureExceptionHandler(_logger);
            app.UseMvcWithDefaultRoute();
        }
    }
}

2 个答案:

答案 0 :(得分:0)

我只是出于完全相同的目的编写了一些代码,并且遇到了与您相同的问题。

根据Identity Server Doc,请不要忘记在[Authorize]属性中指定身份验证方案。

Startup.cs:

services.AddAuthentication()
        .AddIdentityServerAuthentication("Bearer", options =>
                {
                    options.Authority = "http://localhost:9000";
                    options.RequireHttpsMetadata = false;
                    options.ApiName = "identityserver4";
                });
  

请注意,"Bearer"被赋予AddIdentityServerAuthentication,而不是AddAuthentication

Controller.cs:

[Authorize(AuthenticationSchemes = "Bearer")]
public IActionResult YourControllerAction()
{
}

希望它对您有用!

答案 1 :(得分:0)

发现我的问题! 在我的启动中,我应该使用services.AddMvc()时才使用services.AddMvcCore(),或者只添加services.AddAuthorization,而不会使用services.AddMvcCore()来添加。

在做了一些其他方面的研究之后,我想到了这个解决方案。在我的研究中,我遇到了以下页面:https://offering.solutions/blog/articles/2017/02/07/difference-between-addmvc-addmvcore/

它解释了AddMvc()和AddMvcCore()之间的区别。 因此,在添加services.AddAuthorization()之后,我的问题就解决了,身份服务器中的api得到了保护。

感谢所有试图帮助我的人!