Beispiel #1
0
        public async Task SignInAsync([NotNull] ClaimsPrincipal user, [CanBeNull] AuthenticationProperties properties)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            var transaction = Context.Features.Get <OpenIddictServerAspNetCoreFeature>()?.Transaction ??
                              throw new InvalidOperationException("An unknown error occurred while retrieving the OpenIddict server context.");

            transaction.Properties[typeof(AuthenticationProperties).FullName] = properties ?? new AuthenticationProperties();

            var context = new ProcessSignInContext(transaction)
            {
                Principal = user,
                Response  = new OpenIddictResponse()
            };

            await _dispatcher.DispatchAsync(context);

            if (context.IsRequestHandled || context.IsRequestSkipped)
            {
                return;
            }

            else if (context.IsRejected)
            {
                var notification = new ProcessErrorContext(transaction)
                {
                    Response = new OpenIddictResponse
                    {
                        Error            = context.Error ?? Errors.InvalidRequest,
                        ErrorDescription = context.ErrorDescription,
                        ErrorUri         = context.ErrorUri
                    }
                };

                await _dispatcher.DispatchAsync(notification);

                if (notification.IsRequestHandled || context.IsRequestSkipped)
                {
                    return;
                }

                throw new InvalidOperationException(new StringBuilder()
                                                    .Append("The OpenID Connect response was not correctly processed. This may indicate ")
                                                    .Append("that the event handler responsible of processing OpenID Connect responses ")
                                                    .Append("was not registered or was explicitly removed from the handlers list.")
                                                    .ToString());
            }
        }
Beispiel #2
0
    public string GenerateAccessToken(IServiceProvider sp)
    {
        try
        {
            var claims = new List <Claim>
            {
                new Claim(Claims.Role, Roles.Administrator)
            };
            var identity = new ClaimsIdentity(claims);

            var options = (IOptions <OpenIddictServerOptions>)sp
                          .GetService(typeof(IOptions <OpenIddictServerOptions>));
            var logger = (ILogger <OpenIddictServerDispatcher>)sp
                         .GetService(typeof(ILogger <OpenIddictServerDispatcher>));

            var transaction = new OpenIddictServerTransaction
            {
                Options = options.Value,
                Logger  = logger
            };

            var context = new ProcessSignInContext(transaction)
            {
                Issuer = new Uri("https://localhost:5001/"),
                AccessTokenPrincipal = new ClaimsPrincipal(identity)
            };

            var generator = new GenerateIdentityModelAccessToken();
#pragma warning disable CA2012
            generator.HandleAsync(context).GetAwaiter().GetResult();
#pragma warning restore CA2012

            return(context.AccessToken);
        }
        catch (Exception)
        {
            throw;
        }
    }
Beispiel #3
0
        protected override async Task TeardownCoreAsync()
        {
            // Note: OWIN authentication handlers cannot reliabily write to the response stream
            // from ApplyResponseGrantAsync or ApplyResponseChallengeAsync because these methods
            // are susceptible to be invoked from AuthenticationHandler.OnSendingHeaderCallback,
            // where calling Write or WriteAsync on the response stream may result in a deadlock
            // on hosts using streamed responses. To work around this limitation, this handler
            // doesn't implement ApplyResponseGrantAsync but TeardownCoreAsync, which is never called
            // by AuthenticationHandler.OnSendingHeaderCallback. In theory, this would prevent
            // OpenIddictServerOwinMiddleware from both applying the response grant and allowing
            // the next middleware in the pipeline to alter the response stream but in practice,
            // OpenIddictServerOwinMiddleware is assumed to be the only middleware allowed to write
            // to the response stream when a response grant (sign-in/out or challenge) was applied.

            // Note: unlike the ASP.NET Core host, the OWIN host MUST check whether the status code
            // corresponds to a challenge response, as LookupChallenge() will always return a non-null
            // value when active authentication is used, even if no challenge was actually triggered.
            var challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);

            if (challenge != null && (Response.StatusCode == 401 || Response.StatusCode == 403))
            {
                var transaction = Context.Get <OpenIddictServerTransaction>(typeof(OpenIddictServerTransaction).FullName) ??
                                  throw new InvalidOperationException("An unknown error occurred while retrieving the OpenIddict server context.");

                transaction.Properties[typeof(AuthenticationProperties).FullName] = challenge.Properties ?? new AuthenticationProperties();

                var context = new ProcessChallengeContext(transaction)
                {
                    Response = new OpenIddictResponse()
                };

                await _dispatcher.DispatchAsync(context);

                if (context.IsRequestHandled || context.IsRequestSkipped)
                {
                    return;
                }

                else if (context.IsRejected)
                {
                    var notification = new ProcessErrorContext(transaction)
                    {
                        Response = new OpenIddictResponse
                        {
                            Error            = context.Error ?? Errors.InvalidRequest,
                            ErrorDescription = context.ErrorDescription,
                            ErrorUri         = context.ErrorUri
                        }
                    };

                    await _dispatcher.DispatchAsync(notification);

                    if (notification.IsRequestHandled || context.IsRequestSkipped)
                    {
                        return;
                    }

                    throw new InvalidOperationException(new StringBuilder()
                                                        .Append("The OpenID Connect response was not correctly processed. This may indicate ")
                                                        .Append("that the event handler responsible of processing OpenID Connect responses ")
                                                        .Append("was not registered or was explicitly removed from the handlers list.")
                                                        .ToString());
                }
            }

            var signin = Helper.LookupSignIn(Options.AuthenticationType);

            if (signin != null)
            {
                var transaction = Context.Get <OpenIddictServerTransaction>(typeof(OpenIddictServerTransaction).FullName) ??
                                  throw new InvalidOperationException("An unknown error occurred while retrieving the OpenIddict server context.");

                transaction.Properties[typeof(AuthenticationProperties).FullName] = signin.Properties ?? new AuthenticationProperties();

                var context = new ProcessSignInContext(transaction)
                {
                    Principal = signin.Principal,
                    Response  = new OpenIddictResponse()
                };

                await _dispatcher.DispatchAsync(context);

                if (context.IsRequestHandled || context.IsRequestSkipped)
                {
                    return;
                }

                else if (context.IsRejected)
                {
                    var notification = new ProcessErrorContext(transaction)
                    {
                        Response = new OpenIddictResponse
                        {
                            Error            = context.Error ?? Errors.InvalidRequest,
                            ErrorDescription = context.ErrorDescription,
                            ErrorUri         = context.ErrorUri
                        }
                    };

                    await _dispatcher.DispatchAsync(notification);

                    if (notification.IsRequestHandled || context.IsRequestSkipped)
                    {
                        return;
                    }

                    throw new InvalidOperationException(new StringBuilder()
                                                        .Append("The OpenID Connect response was not correctly processed. This may indicate ")
                                                        .Append("that the event handler responsible of processing OpenID Connect responses ")
                                                        .Append("was not registered or was explicitly removed from the handlers list.")
                                                        .ToString());
                }
            }

            var signout = Helper.LookupSignOut(Options.AuthenticationType, Options.AuthenticationMode);

            if (signout != null)
            {
                var transaction = Context.Get <OpenIddictServerTransaction>(typeof(OpenIddictServerTransaction).FullName) ??
                                  throw new InvalidOperationException("An unknown error occurred while retrieving the OpenIddict server context.");

                transaction.Properties[typeof(AuthenticationProperties).FullName] = signout.Properties ?? new AuthenticationProperties();

                var context = new ProcessSignOutContext(transaction)
                {
                    Response = new OpenIddictResponse()
                };

                await _dispatcher.DispatchAsync(context);

                if (context.IsRequestHandled || context.IsRequestSkipped)
                {
                    return;
                }

                else if (context.IsRejected)
                {
                    var notification = new ProcessErrorContext(transaction)
                    {
                        Response = new OpenIddictResponse
                        {
                            Error            = context.Error ?? Errors.InvalidRequest,
                            ErrorDescription = context.ErrorDescription,
                            ErrorUri         = context.ErrorUri
                        }
                    };

                    await _dispatcher.DispatchAsync(notification);

                    if (notification.IsRequestHandled || context.IsRequestSkipped)
                    {
                        return;
                    }

                    throw new InvalidOperationException(new StringBuilder()
                                                        .Append("The OpenID Connect response was not correctly processed. This may indicate ")
                                                        .Append("that the event handler responsible of processing OpenID Connect responses ")
                                                        .Append("was not registered or was explicitly removed from the handlers list.")
                                                        .ToString());
                }
            }
        }