Добавление идентификаторов ломает OpenIddict - PullRequest
0 голосов
/ 23 февраля 2019

Я следую точному примеру из примера OpenIddict здесь: https://github.com/openiddict/openiddict-core. Все работает, пока я не использую часть AddIdentity.Мне действительно нужно использовать идентичность.Закомментирование части Identity будет работать, если она не закомментирована, тогда я получу 404 на метод Get в контроллере теста, потому что он не авторизуется.Я использую .Net Core 2.x

Startup.cs:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddDbContext<XXIdentityContext>(options =>
        {
            options.UseSqlServer(config["default:connectionString"]);
            options.UseOpenIddict();
        });

        services.AddIdentity<AspUser, IdentityRole>()
            .AddEntityFrameworkStores<XXIdentityContext>()
            .AddDefaultTokenProviders();

        services.AddOpenIddict()
            .AddCore(options =>
            {
                options.UseEntityFrameworkCore()
                               .UseDbContext<XXIdentityContext>();
            })

            .AddServer(options =>
            {
                options.UseMvc();
                options.EnableTokenEndpoint("/connect/token");
                options.AllowPasswordFlow();
                options.DisableHttpsRequirement();
                options.AcceptAnonymousClients();
            })
            .AddValidation();
    }

    public void Configure(IApplicationBuilder app,
                          IHostingEnvironment env,
                          ILoggerFactory loggerFactory)
    {
        app.UseAuthentication();
        app.UseMvc();
    }

AspUser.cs:

public class AspUser : IdentityUser
{
}

XXIdentityContext.cs:

public class XXIdentityContext: IdentityDbContext<AspUser>
{
    private IConfiguration config;
    public XXIdentityContext(DbContextOptions<XXIdentityContext> options, IConfiguration config) : base(options)
    {
        this.config = config;
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }
}

TestController.cs:

public class TestController : Controller
{
    [HttpPost("~/connect/token"), Produces("application/json")]
    public IActionResult Exchange(OpenIdConnectRequest request)
    {
        var claims = new List<Claim>
        {
            new Claim(ClaimsConstants.Id, "bob"),
            new Claim(ClaimsConstants.Temp, 5.ToString()),
            new Claim(OpenIdConnectConstants.Claims.Subject, "Testing")
        };

        foreach (var claim in claims)
            claim.SetDestinations(OpenIdConnectConstants.Destinations.AccessToken);

        var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "OpenIddict"));

        return SignIn(principal, OpenIddictServerDefaults.AuthenticationScheme);
    }

    [Authorize, HttpGet("~/api/test")]
    public IActionResult GetMessage()
    {
        return Json(new
        {
            Subject = User.GetClaim(OpenIdConnectConstants.Claims.Subject),
            Id = User.GetClaim(ClaimsConstants.Id),
            Temp= User.GetClaim(ClaimsConstants.Temp)
        });
    }
}

1 Ответ

0 голосов
/ 25 февраля 2019

Добавление следующих строк кода в конце метода ConfigureServices решило проблему:

services.AddAuthentication(o =>
{
     o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...