Ejemplo n.º 1
0
        public void Configure(IApplicationBuilder app)
        {
            var options = Options ?? new StormpathOwinOptions();

            options.LibraryUserAgent = "Stormpath.Owin.IntegrationTest";
            options.ViewRenderer     = new PrecompiledViewRenderer(null);

            var stormpathMiddleware = StormpathMiddleware.Create(options);

            Client          = stormpathMiddleware.GetClient();
            ApplicationHref = stormpathMiddleware.Configuration.Application.Href;

            app.UseOwin(addToPipeline =>
            {
                addToPipeline(next =>
                {
                    stormpathMiddleware.Initialize(next);
                    return(stormpathMiddleware.Invoke);
                });
            });

            app.Run(async(context) =>
            {
                if (context.Request.Path == "/")
                {
                    await context.Response.WriteAsync("Hello World!");
                    return;
                }

                context.Response.StatusCode = 404;
            });
        }
        /// <summary>
        /// Adds the Stormpath middleware to the pipeline.
        /// </summary>
        /// <remarks>You must call <see cref="AddStormpath(IServiceCollection, object)"/> before calling this method.</remarks>
        /// <param name="app">The <see cref="IApplicationBuilder" />.</param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        /// <exception cref="InvalidOperationException">The Stormpath services have not been added to the service collection.</exception>
        public static IApplicationBuilder UseStormpath(this IApplicationBuilder app)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            var suppliedConfiguration = app.ApplicationServices.GetRequiredService <UserConfigurationContainer>();
            var logger = app.ApplicationServices.GetRequiredService <SDK.Logging.ILogger>();

            var hostingAssembly = app.GetType().GetTypeInfo().Assembly;

            var viewRenderer = new CompositeViewRenderer(logger,
                                                         new PrecompiledViewRenderer(logger),
                                                         app.ApplicationServices.GetRequiredService <RazorViewRenderer>());

            var stormpathMiddleware = StormpathMiddleware.Create(new StormpathOwinOptions()
            {
                LibraryUserAgent = GetLibraryUserAgent(hostingAssembly),
                Configuration    = suppliedConfiguration.Configuration,
                ViewRenderer     = viewRenderer,
                Logger           = logger
            });

            app.UseOwin(addToPipeline =>
            {
                addToPipeline(next =>
                {
                    stormpathMiddleware.Initialize(next);
                    return(stormpathMiddleware.Invoke);
                });
            });

            app.UseMiddleware <StormpathAuthenticationMiddleware>(Options.Create(new StormpathAuthenticationOptions()
            {
                AuthenticationScheme = "Cookie"
            }), logger);
            app.UseMiddleware <StormpathAuthenticationMiddleware>(Options.Create(new StormpathAuthenticationOptions()
            {
                AuthenticationScheme = "Bearer"
            }), logger);

            return(app);
        }
        public void Configuration(IAppBuilder app)
        {
            var logger = new ConsoleLogger(LogLevel.Trace);

            // Initialize the Stormpath middleware
            var stormpath = StormpathMiddleware.Create(new StormpathOwinOptions()
            {
                LibraryUserAgent       = "nowin/0.22.2",
                ViewRenderer           = new PrecompiledViewRenderer(logger),
                Logger                 = logger,
                PreRegistrationHandler = (ctx, ct) =>
                {
                    ctx.Account.CustomData["source"] = "Nowin";
                    return(Task.FromResult(true));
                },
                PostRegistrationHandler = async(ctx, ct) =>
                {
                    var customData = await ctx.Account.GetCustomDataAsync(ct);
                },
                PreLoginHandler = (ctx, ct) =>
                {
                    return(Task.FromResult(true));
                },
                PostLoginHandler = async(ctx, ct) =>
                {
                    var customData = await ctx.Account.GetCustomDataAsync(ct);
                }
            });

            // Insert it into the OWIN pipeline
            app.Use(stormpath);

            // Add a sample middleware that responds to GET /
            app.Use(new Func <AppFunc, AppFunc>(next => (async env =>
            {
                if (env["owin.RequestPath"] as string != "/")
                {
                    await next.Invoke(env);
                    return;
                }
                using (var writer = new StreamWriter(env["owin.ResponseBody"] as Stream))
                {
                    await writer.WriteAsync("<h1>Hello from OWIN!</h1>");

                    if (!env.ContainsKey(OwinKeys.StormpathUser))
                    {
                        await writer.WriteAsync("<a href=\"/login\">Log in</a> or <a href=\"/register\">Register</a>");
                    }
                    else
                    {
                        var user = env[OwinKeys.StormpathUser] as IAccount;

                        await writer.WriteAsync($"<p>Logged in as {user?.FullName} ({user?.Email})</p>");

                        await writer.WriteAsync(@"
<form action=""/logout"" method=""post"" id=""logout_form"">
  <a onclick=""document.getElementById('logout_form').submit();"" style=""cursor: pointer;"">
    Log Out
  </a>
</form>");
                    }

                    await writer.FlushAsync();
                }
            })));

            // Add a "protected" route
            app.Use(new Func <AppFunc, AppFunc>(next => (async env =>
            {
                if (env["owin.RequestPath"] as string != "/protected")
                {
                    await next.Invoke(env);
                    return;
                }

                if (!env.ContainsKey(OwinKeys.StormpathUser))
                {
                    var deleteCookieAction =
                        new Action <Configuration.Abstractions.Immutable.WebCookieConfiguration>(_ => { }); // TODO
                    var setStatusCodeAction = new Action <int>(code => env["owin.ResponseStatusCode"] = code);
                    var setHeaderAction = new Action <string, string>((name, value) =>
                                                                      (env["owin.ResponseHeaders"] as IDictionary <string, string[]>).SetString(name, value));
                    var redirectAction = new Action <string>(location =>
                    {
                        setStatusCodeAction(302);
                        setHeaderAction("Location", location);
                    });
                    var routeProtector = new RouteProtector(
                        stormpath.GetClient(),
                        stormpath.Configuration,
                        deleteCookieAction,
                        setStatusCodeAction,
                        setHeaderAction,
                        redirectAction,
                        null);
                    routeProtector.OnUnauthorized("text/html", "/protected");
                }
                else
                {
                    using (var writer = new StreamWriter(env["owin.ResponseBody"] as Stream))
                    {
                        await writer.WriteAsync("<p>Zomg secret!</p>");
                        await writer.FlushAsync();
                    }
                }
            })));
        }