【问题标题】:OpenID Connect server with ASOS, .NET Core pipeline带有 ASOS、.NET Core 管道的 OpenID Connect 服务器
【发布时间】:2016-12-18 21:49:23
【问题描述】:

我已经开始通过实现资源所有者密码凭证授予来使用带有 ASOS 的 OpenID Connect 服务器。但是,当我使用邮递员对其进行测试时,我收到了一般的 500 内部服务器错误。

这是我的代码,供您调试。感谢您的反馈。

谢谢

-比鲁克

这是我的Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.

        services.AddAuthentication(options => {
            options.SignInScheme = "ServerCookie";
        });


        services.AddApplicationInsightsTelemetry(Configuration);

        services.AddMvc();

        services.AddSession(options => {
            options.IdleTimeout = TimeSpan.FromMinutes(30);
        });
    }




    public void Configure(IApplicationBuilder app, IHostingEnvironment env, LoggerFactory loggerFactory)
    {

        app.UseOAuthValidation();


        app.UseOpenIdConnectServer(options => {
            // Create your own authorization provider by subclassing
            // the OpenIdConnectServerProvider base class.
            options.Provider = new AuthorizationProvider();

            // Enable the authorization and token endpoints.
           // options.AuthorizationEndpointPath = "/connect/authorize";
            options.TokenEndpointPath = "/connect/token";

            // During development, you can set AllowInsecureHttp
            // to true to disable the HTTPS requirement.
            options.ApplicationCanDisplayErrors = true;
            options.AllowInsecureHttp = true;

            // Note: uncomment this line to issue JWT tokens.
            // options.AccessTokenHandler = new JwtSecurityTokenHandler();
        });

        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseApplicationInsightsRequestTelemetry();

        app.UseApplicationInsightsExceptionTelemetry();

        app.UseMvc();
    }

这是我的AuthorizationProvider.cs

public sealed class AuthorizationProvider : OpenIdConnectServerProvider
{
    public Task<User> GetUser()
    {

        return Task.Run(()=> new User { UserName = "biruk60", Password = "adminUser123" });
    }
    // Implement OnValidateAuthorizationRequest to support interactive flows (code/implicit/hybrid).
    public override Task ValidateTokenRequest(ValidateTokenRequestContext context)
    {
        // Reject the token request that don't use grant_type=password or grant_type=refresh_token.
        if (!context.Request.IsPasswordGrantType() && !context.Request.IsRefreshTokenGrantType())
        {
            context.Reject(
                error: OpenIdConnectConstants.Errors.UnsupportedGrantType,
                description: "Only resource owner password credentials and refresh token " +
                             "are accepted by this authorization server");

            return Task.FromResult(0);
        }

        // Since there's only one application and since it's a public client
        // (i.e a client that cannot keep its credentials private), call Skip()
        // to inform the server the request should be accepted without 
        // enforcing client authentication.
        context.Skip();

        return Task.FromResult(0);
    }



    public override async Task HandleTokenRequest(HandleTokenRequestContext context)
    {
        //// Resolve ASP.NET Core Identity's user manager from the DI container.
        //var manager = context.HttpContext.RequestServices.GetRequiredService<UserManager<ApplicationUser>>();

        // Only handle grant_type=password requests and let ASOS
        // process grant_type=refresh_token requests automatically.
        if (context.Request.IsPasswordGrantType())
        {
            // var user = await manager.FindByNameAsync(context.Request.Username);

            var user = await GetUser();//new { userName = "briuk60@gmail.com", password = "adminUser123" };
            if (user == null)
            {
                context.Reject(
                    error: OpenIdConnectConstants.Errors.InvalidGrant,
                    description: "Invalid credentials.");

                return;
            }

            if (user != null && (user.Password == context.Request.Password))
            {




                var identity = new ClaimsIdentity(context.Options.AuthenticationScheme);

                // Note: the name identifier is always included in both identity and
                // access tokens, even if an explicit destination is not specified.
               // identity.AddClaim(ClaimTypes.NameIdentifier, await manager.GetUserId(user));

                // When adding custom claims, you MUST specify one or more destinations.
                // Read "part 7" for more information about custom claims and scopes.
                identity.AddClaim("username", "biruk60",
                    OpenIdConnectConstants.Destinations.AccessToken,
                    OpenIdConnectConstants.Destinations.IdentityToken);

                // Create a new authentication ticket holding the user identity.
                var ticket = new AuthenticationTicket(
                    new ClaimsPrincipal(identity),
                    new AuthenticationProperties(),
                    context.Options.AuthenticationScheme);

                // Set the list of scopes granted to the client application.
                ticket.SetScopes(
                    /* openid: */ OpenIdConnectConstants.Scopes.OpenId,
                    /* email: */ OpenIdConnectConstants.Scopes.Email,
                    /* profile: */ OpenIdConnectConstants.Scopes.Profile);

                // Set the resource servers the access token should be issued for.
               // ticket.SetResources("resource_server");

                context.Validate(ticket);
            }
        }
    }


}

我做错了什么。我可以将它置于调试模式并单步执行它而不会出现任何错误,它只是提琴手和邮递员中的 500 内部服务器错误。

【问题讨论】:

    标签: oauth-2.0 asp.net-core openid-connect aspnet-contrib


    【解决方案1】:

    您可能会看到以下异常:

    System.InvalidOperationException:找不到唯一标识符来生成“子”声明:确保添加“ClaimTypes.NameIdentifier”声明。

    添加ClaimTypes.NameIdentifier 声明,它应该可以工作。

    【讨论】:

    • 做到了。谢谢凯文!
    • @Kiran 你的问题与这个问题完全无关,恐怕。您可能应该联系 Microsoft 并询问他们是否可以为您构建一个小样本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-08
    • 1970-01-01
    • 2016-12-18
    • 2016-11-19
    相关资源
    最近更新 更多