Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
Kévin Chalet
@kevinchalet
context.Ticket
James Hancock
@JohnGalt1717
so like this: var ticket = new AuthenticationTicket(
new ClaimsPrincipal(identity),
new AuthenticationProperties(context.Ticket.Properties),
context.Scheme.Name);
(.Items)
Kévin Chalet
@kevinchalet
Yeah.
James Hancock
@JohnGalt1717
Thanks!
Kévin Chalet
@kevinchalet
You're welcome :smile:
BTW, I'm looking for contributors for OpenIddict 3.0 (that will replace ASOS). If you're interested, let me know :smile:
Kim Zhu
@kimz-petsure
For the the implicit grant, which method I can use to add custom claim to the access token?
Is it HandleAuthorizationRequest?
Kévin Chalet
@kevinchalet
If you use the events model to handle authorization requests, yep.
Otherwise, you can do that in your authorization controller, if you use the default passthrough mode.
Kim Zhu
@kimz-petsure
@PinpointTownes ty
Kim Zhu
@kimz-petsure
I have defined the AuthorizationEndpointPath in Startup.cs, but I got 404 error when I passed the response_type, redirect_url, and scope
see below code in "Startup.cs"
        var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(this.Configuration["OAuth:SecurityKey"]));
        services.AddAuthentication(
            options => {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }
            )
            .AddOpenIdConnectServer(options=> {
                options.TokenEndpointPath = "/oauth/token";
                options.AuthorizationEndpointPath = "/oauth/authorize";
                options.SigningCredentials.AddKey(signingKey);

                options.AccessTokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler {
                    OutboundClaimTypeMap = new Dictionary<string, string>()
                };
            options.Provider = new AuthorizationServerProvider();
            options.ApplicationCanDisplayErrors = true;
            options.AllowInsecureHttp = true;
        });
Kévin Chalet
@kevinchalet
Do you handle the authorization request in your event method?
Because by default, authorization requests are pass through.
Kim Zhu
@kimz-petsure

Yes.

here is my

public override async Task HandleAuthorizationRequest(HandleAuthorizationRequestContext context)
{
if (context.Request.IsImplicitFlow())
{
var clientId = context.Request.ClientId;
var rdi = context.Request.RedirectUri;
var state = context.Request.State;
var scope = context.Request.Scope;
if (string.IsNullOrEmpty(clientId))
{
context.Reject(error: OpenIdConnectConstants.Errors.InvalidClient,
description: "client id cannot be null");
return;
}
else if (string.IsNullOrEmpty(rdi))
{
context.Reject(
error: OpenIdConnectConstants.Errors.InvalidClient,
description: "redirect_uri cannot be empty"
);
return;
}
else if (string.IsNullOrEmpty(scope))
{
context.Reject(
error: OpenIdConnectConstants.Errors.InvalidClient,
description: "scope cannot be empty"
);
return;
}

            var identity = new ClaimsIdentity(
                OpenIdConnectServerDefaults.AuthenticationScheme,
                OpenIdConnectConstants.Claims.Name,
                OpenIdConnectConstants.Claims.Role);
            var clientService = context.HttpContext.RequestServices.GetRequiredService<IClientService>();
            var clientService = await partnerService.GetPartnerBrokerAuthClientByClientAccessId(clientId);
            if (clientService == null)
            {
                context.Reject(error: OpenIdConnectConstants.Errors.InvalidClient,
                    description: "client id cannot be found");
                return;
            }


            if (string.IsNullOrEmpty(clientService .AllowedOrigin))
            {
                context.Reject(error: OpenIdConnectConstants.Errors.InvalidClient,
                    description: "The redirect url of the client cannot be null");
                return;
            }
            if (!clientService .AllowedOrigin.Split(',').Any(x => string.Equals(x, rdi, StringComparison.OrdinalIgnoreCase)))
            {
                context.Reject(
                            error: OpenIdConnectConstants.Errors.InvalidClient,
                            description: "The supplied redirect uri is incorrect"
                        );
                return;
            }
            if (clientService .Scopes == null || ( clientService .Scopes != null && clientService .Scopes.Count == 0 ))
            {
                context.Reject(error: OpenIdConnectConstants.Errors.InvalidClient,
                    description: "Ths definition of the client's scopes cannot be null");
                return;
            }

}

            ticket.SetAccessTokenLifetime(TimeSpan.FromSeconds(clientService.AccessTokenLifeTime));
            ticket.SetIdentityTokenLifetime(TimeSpan.FromSeconds(clientService.AccessTokenLifeTime));
            context.Validate(ticket);
Kévin Chalet
@kevinchalet
I suspect you didn't implement ValidateAuthorizationRequest and since you're using options.ApplicationCanDisplayErrors = true, it will allow the rest of the ASP.NET Core pipeline to be invoked. If there's nothing to handle the error, you'll get a 404 response.
Consider moving your validation checks to ValidateAuthorizationRequest and remove options.ApplicationCanDisplayErrors = true.
Kim Zhu
@kimz-petsure
ty
Kim Zhu
@kimz-petsure
I found the issue, it was caused by my error handler middleware. if the request got the "unsupport response type", the "httpContext" would return 404.
I got another question behind this, how can i capture the error (e.g. reject ) in the provider event from httpcontext which is in ErrorMiddleware
Kévin Chalet
@kevinchalet
HttpContext.GetOpenIdConnectResponse()?.Error/ErrorDescription
Kim Zhu
@kimz-petsure
let me try
Kim Zhu
@kimz-petsure
Cannot capture that response in HttpContext in the error middleware, it looks the reject error is run before the error middle ware
Kim Zhu
@kimz-petsure
here is part of code in the middleware
            await this._next(context);
            var openIdConnectResponse = context.GetOpenIdConnectResponse();
            if (openIdConnectResponse != null && !string.IsNullOrEmpty(openIdConnectResponse.Error) && !string.IsNullOrEmpty(openIdConnectResponse.ErrorDescription))
            {
                if (!context.Response.HasStarted)
                {
                    context.Response.Headers.Clear();
                    context.Response.ContentType = "application/json";
                    context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    var result = JsonConvert.SerializeObject(new Infrastructure.Utils.HttpClient.GenericResponse<string>()
                    {
                        Exception = openIdConnectResponse.ErrorDescription ?? openIdConnectResponse.Error,
                        StatusCode = HttpStatusCode.BadRequest
                    });

                    this._logger.LogError("The openIdConnect error with path" + context.Request.Path + ", ##IP:" + context.Connection.RemoteIpAddress + "## result: " + result);
                    await context.Response.WriteAsync(result);
                    return;
                }
            }
Kim Zhu
@kimz-petsure
@PinpointTownes It looks HttpContext.GetOpenIdConnectResponse() is only working in controller
@PinpointTownes not the middleware
Kim Zhu
@kimz-petsure

Found one strange thing

If I trigger the code below in ValidateTokenRequest event, the response contentType is "application/json"; If I trigger the code below in ValidateAuthorizationRequest, the response contentType is "text/plain;charset=UTF-8"

        if (string.IsNullOrEmpty(clientId))
        {
            //context.HttpContext.Response.
            context.Reject(error: OpenIdConnectConstants.Errors.InvalidClient,
                description: "client id cannot be null");
            return;
        }
Kévin Chalet
@kevinchalet
The authorization endpoint is an interactive/browser endpoint, while the token endpoint is an API/headless endpoint, hence the difference :smile:
Kim Zhu
@kimz-petsure
:) ....thx
Bart Calixto
@Bartmax
looks like lot of work recently. How can I help @PinpointTownes ? I'm aware of help-wanted tag, but all looks daunting. Maybe I can take a look at the json one
Kévin Chalet
@kevinchalet
@Bartmax yeah :smile:
You can take a look at the tickets related to unit and functional tests, it's easy to split the tasks.
Bart Calixto
@Bartmax
great, I'll do
Jamaxack
@Jamaxack
Hello all
any ideas please?
Florian
@filoe
Running asp.net core 2.2 on linux docker image. Getting the following error

[18:05:10 Error] AspNet.Security.OAuth.Apple.Internal.DefaultAppleClientSecretGenerator
Failed to generate new client secret for the Apple authentication scheme.
Interop+Crypto+OpenSslCryptographicException: error:0D08303A:asn1 encoding routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error
at Internal.Cryptography.Pal.CertificatePal.FromBlob(Byte[] rawData, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags)
at System.Security.Cryptography.X509Certificates.X509Certificate..ctor(Byte[] rawData, String password, X509KeyStorageFlags keyStorageFlags)
at AspNet.Security.OAuth.Apple.Internal.DefaultAppleClientSecretGenerator.CreateAlgorithmLinuxOrMac(Byte[] keyBlob, String password)
at AspNet.Security.OAuth.Apple.Internal.DefaultAppleClientSecretGenerator.CreateAlgorithm(Byte[] keyBlob, String password)
at AspNet.Security.OAuth.Apple.Internal.DefaultAppleClientSecretGenerator.GenerateNewSecretAsync(AppleGenerateClientSecretContext context)
at AspNet.Security.OAuth.Apple.Internal.DefaultAppleClientSecretGenerator.GenerateAsync(AppleGenerateClientSecretContext context)

[18:05:10 Information] AspNet.Security.OAuth.Apple.AppleAuthenticationHandler
Error from RemoteAuthentication: error:0D08303A:asn1 encoding routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error.

[18:05:10 Error] Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware
An unhandled exception has occurred while executing the request.
System.Exception: An error was encountered while handling the remote login. ---> Interop+Crypto+OpenSslCryptographicException: error:0D08303A:asn1 encoding routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error
at Internal.Cryptography.Pal.CertificatePal.FromBlob(Byte[] rawData, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags)
at System.Security.Cryptography.X509Certificates.X509Certificate..ctor(Byte[] rawData, String password, X509KeyStorageFlags keyStorageFlags)
at AspNet.Security.OAuth.Apple.Internal.DefaultAppleClientSecretGenerator.CreateAlgorithmLinuxOrMac(Byte[] keyBlob, String password)
at AspNet.Security.OAuth.Apple.Internal.DefaultAppleClientSecretGenerator.CreateAlgorithm(Byte[] keyBlob, String password)
at AspNet.Security.OAuth.Apple.Internal.DefaultAppleClientSecretGenerator.GenerateNewSecretAsync(AppleGenerateClientSecretContext context)
at AspNet.Security.OAuth.Apple.Internal.DefaultAppleClientSecretGenerator.GenerateAsync(AppleGenerateClientSecretContext context)
at AspNet.Security.OAuth.Apple.AppleAuthenticationEvents.<>c.<<-ctor>b__10_0>d.MoveNext()

Providing the secret using the UsePrivateKey extension of the apple package. When running it on windows using:

            var bytes = Convert.FromBase64String("base64-string");
            var privateKey = Encoding.UTF8.GetString(bytes);
            if (privateKey.StartsWith("-----BEGIN PRIVATE KEY-----", StringComparison.Ordinal))
            {
                string[] lines = privateKey.Split(new char[1]
                {
                    '\n'
                });
                privateKey = string.Join(string.Empty, lines.Skip(1).Take(lines.Length - 2));
            }
            bytes = Convert.FromBase64String(privateKey);

            var key = CngKey.Import(bytes, CngKeyBlobFormat.Pkcs8PrivateBlob);
            var k = new ECDsaCng(key) { HashAlgorithm = CngAlgorithm.Sha256 };

it works using the same base64 string as in the container

Kévin Chalet
@kevinchalet
@filoe wrong gitter room.
Martin Costello
@martincostello
@filoe There’s inconsistencies in the cryptography APIs in ASP.NET Core 2.2 that made it tricky for certain scenarios. If you can’t update to 3.0 or 3.1, try reading the section about xplat issues in my blog post: https://blog.martincostello.com/sign-in-with-apple-prototype-for-aspnet-core/
rik coleman
@coleman-rik
afternoon everyone.
.Net Framework 4.5.2 Web API project Microsoft OWIN isn't sending 'Access-Control-Allow-Origin' headers? Any ideas where I should look?
Kévin Chalet
@kevinchalet
Hi. Is your question related to Owin.Security.OpenIdConnect.Server or general? :smile:
rik coleman
@coleman-rik
@PinpointTownes Microsoft.Owin.Cors
Kévin Chalet
@kevinchalet
Then it has nothing to do with this Gitter room, right?
rik coleman
@coleman-rik
@PinpointTownes I don't know. This is the only Owin/Cors room I could find here.
Kévin Chalet
@kevinchalet
The topic associated with this room is "OpenID Connect/OAuth2 server framework for OWIN/Katana" so it's definitely not the right place.