Beispiel #1
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultScheme          = CookieAuthenticationDefaults.AuthenticationScheme;
                sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
            .AddCookie()
            .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, "AAD", o =>
            {
                o.ClientId             = ClientId;
                o.ClientSecret         = ClientSecret; // for code flow
                o.Authority            = Authority;
                o.ResponseType         = OpenIdConnectResponseType.CodeIdToken;
                o.SignedOutRedirectUri = "/signed-out";
                // GetClaimsFromUserInfoEndpoint = true,
                o.Events = new OpenIdConnectEvents()
                {
                    OnAuthorizationCodeReceived = async context =>
                    {
                        var request     = context.HttpContext.Request;
                        var currentUri  = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path);
                        var credential  = new ClientCredential(ClientId, ClientSecret);
                        var authContext = new AuthenticationContext(Authority, AuthPropertiesTokenCache.ForCodeRedemption(context.Properties));

                        var result = await authContext.AcquireTokenByAuthorizationCodeAsync(
                            context.ProtocolMessage.Code, new Uri(currentUri), credential, Resource);

                        context.HandleCodeRedemption(result.AccessToken, result.IdToken);
                    }
                };
            });
        }
Beispiel #2
0
        public void Configure(IApplicationBuilder app)
        {
            app.UseDeveloperExceptionPage();

            app.UseAuthentication();

            app.Run(async context =>
            {
                if (context.Request.Path.Equals("/signin"))
                {
                    if (context.User.Identities.Any(identity => identity.IsAuthenticated))
                    {
                        // User has already signed in
                        context.Response.Redirect("/");
                        return;
                    }

                    await context.ChallengeAsync(new AuthenticationProperties {
                        RedirectUri = "/"
                    });
                }
                else if (context.Request.Path.Equals("/signout"))
                {
                    await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                    await WriteHtmlAsync(context.Response,
                                         async response =>
                    {
                        await response.WriteAsync($"<h1>Signed out locally: {HtmlEncode(context.User.Identity.Name)}</h1>");
                        await response.WriteAsync("<a class=\"btn btn-primary\" href=\"/\">Sign In</a>");
                    });
                }
                else if (context.Request.Path.Equals("/signout-remote"))
                {
                    await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                    await context.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);
                }
                else if (context.Request.Path.Equals("/signed-out"))
                {
                    await WriteHtmlAsync(context.Response,
                                         async response =>
                    {
                        await response.WriteAsync($"<h1>You have been signed out.</h1>");
                        await response.WriteAsync("<a class=\"btn btn-primary\" href=\"/signin\">Sign In</a>");
                    });
                }
                else if (context.Request.Path.Equals("/remote-signedout"))
                {
                    await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                    await WriteHtmlAsync(context.Response,
                                         async response =>
                    {
                        await response.WriteAsync($"<h1>Signed out remotely: {HtmlEncode(context.User.Identity.Name)}</h1>");
                        await response.WriteAsync("<a class=\"btn btn-primary\" href=\"/\">Sign In</a>");
                    });
                }
                else
                {
                    if (!context.User.Identities.Any(identity => identity.IsAuthenticated))
                    {
                        await context.ChallengeAsync(new AuthenticationProperties {
                            RedirectUri = "/"
                        });
                        return;
                    }

                    await WriteHtmlAsync(context.Response, async response =>
                    {
                        await response.WriteAsync($"<h1>Hello Authenticated User {HtmlEncode(context.User.Identity.Name)}</h1>");
                        await response.WriteAsync("<a class=\"btn btn-default\" href=\"/signout\">Sign Out Locally</a>");
                        await response.WriteAsync("<a class=\"btn btn-default\" href=\"/signout-remote\">Sign Out Remotely</a>");

                        await response.WriteAsync("<h2>Claims:</h2>");
                        await WriteTableHeader(response, new string[] { "Claim Type", "Value" }, context.User.Claims.Select(c => new string[] { c.Type, c.Value }));

                        await response.WriteAsync("<h2>Tokens:</h2>");
                        try
                        {
                            // Use ADAL to get the right token
                            var authContext     = new AuthenticationContext(Authority, AuthPropertiesTokenCache.ForApiCalls(context, CookieAuthenticationDefaults.AuthenticationScheme));
                            var credential      = new ClientCredential(ClientId, ClientSecret);
                            string userObjectID = context.User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                            var result          = await authContext.AcquireTokenSilentAsync(Resource, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

                            await response.WriteAsync($"<h3>access_token</h3><code>{HtmlEncode(result.AccessToken)}</code><br>");
                        }
                        catch (Exception ex)
                        {
                            await response.WriteAsync($"AcquireToken error: {ex.Message}");
                        }
                    });
                }
            });
        }
Beispiel #3
0
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory)
        {
            loggerfactory.AddConsole(Microsoft.Extensions.Logging.LogLevel.Information);

            // Simple error page
            app.Use(async(context, next) =>
            {
                try
                {
                    await next();
                }
                catch (Exception ex)
                {
                    if (!context.Response.HasStarted)
                    {
                        context.Response.Clear();
                        context.Response.StatusCode = 500;
                        await context.Response.WriteAsync(ex.ToString());
                    }
                    else
                    {
                        throw;
                    }
                }
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            var clientId     = Configuration["oidc:clientid"];
            var clientSecret = Configuration["oidc:clientsecret"];
            var authority    = Configuration["oidc:authority"];
            var resource     = "https://graph.windows.net";

            app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
            {
                ClientId     = clientId,
                ClientSecret = clientSecret, // for code flow
                Authority    = authority,
                ResponseType = OpenIdConnectResponseType.CodeIdToken,
                // GetClaimsFromUserInfoEndpoint = true,
                Events = new OpenIdConnectEvents()
                {
                    OnAuthorizationCodeReceived = async context =>
                    {
                        var request     = context.HttpContext.Request;
                        var currentUri  = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path);
                        var credential  = new ClientCredential(clientId, clientSecret);
                        var authContext = new AuthenticationContext(authority, AuthPropertiesTokenCache.ForCodeRedemption(context.Properties));

                        var result = await authContext.AcquireTokenByAuthorizationCodeAsync(
                            context.ProtocolMessage.Code, new Uri(currentUri), credential, resource);

                        context.HandleCodeRedemption();
                    }
                }
            });

            app.Run(async context =>
            {
                if (context.Request.Path.Equals("/signout"))
                {
                    await context.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                    context.Response.ContentType = "text/html";
                    await context.Response.WriteAsync($"<html><body>Signing out {context.User.Identity.Name}<br>{Environment.NewLine}");
                    await context.Response.WriteAsync("<a href=\"/\">Sign In</a>");
                    await context.Response.WriteAsync($"</body></html>");
                    return;
                }

                if (!context.User.Identities.Any(identity => identity.IsAuthenticated))
                {
                    await context.Authentication.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties {
                        RedirectUri = "/"
                    });
                    return;
                }

                context.Response.ContentType = "text/html";
                await context.Response.WriteAsync($"<html><body>Hello Authenticated User {context.User.Identity.Name}<br>{Environment.NewLine}");
                await context.Response.WriteAsync("Claims:<br>" + Environment.NewLine);
                foreach (var claim in context.User.Claims)
                {
                    await context.Response.WriteAsync($"{claim.Type}: {claim.Value}<br>{Environment.NewLine}");
                }

                await context.Response.WriteAsync("Tokens:<br>" + Environment.NewLine);
                try
                {
                    // Use ADAL to get the right token
                    var authContext     = new AuthenticationContext(authority, AuthPropertiesTokenCache.ForApiCalls(context, CookieAuthenticationDefaults.AuthenticationScheme));
                    var credential      = new ClientCredential(clientId, clientSecret);
                    string userObjectID = context.User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                    var result          = await authContext.AcquireTokenSilentAsync(resource, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

                    await context.Response.WriteAsync($"access_token: {result.AccessToken}<br>{Environment.NewLine}");
                }
                catch (Exception ex)
                {
                    await context.Response.WriteAsync($"AquireToken error: {ex.Message}<br>{Environment.NewLine}");
                }

                await context.Response.WriteAsync("<a href=\"/signout\">Sign Out</a>");
                await context.Response.WriteAsync($"</body></html>");
            });
        }
Beispiel #4
0
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory)
        {
            loggerfactory.AddConsole(LogLevel.Information);

            // Simple error page
            app.Use(async (context, next) =>
            {
                try
                {
                    await next();
                }
                catch (Exception ex)
                {
                    if (!context.Response.HasStarted)
                    {
                        context.Response.Clear();
                        context.Response.StatusCode = 500;
                        await context.Response.WriteAsync(ex.ToString());
                    }
                    else
                    {
                        throw;
                    }
                }
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            var clientId = Configuration["oidc:clientid"];
            var clientSecret = Configuration["oidc:clientsecret"];
            var authority = Configuration["oidc:authority"];
            var resource = "https://graph.windows.net";
            app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
            {
                ClientId = clientId,
                ClientSecret = clientSecret, // for code flow
                Authority = authority,
                ResponseType = OpenIdConnectResponseTypes.CodeIdToken,
                // GetClaimsFromUserInfoEndpoint = true,
                Events = new OpenIdConnectEvents()
                {
                    OnAuthorizationCodeReceived = async context =>
                    {
                        var request = context.HttpContext.Request;
                        var currentUri = UriHelper.Encode(request.Scheme, request.Host, request.PathBase, request.Path);
                        var credential = new ClientCredential(clientId, clientSecret);                                 
                        var authContext = new AuthenticationContext(authority, new AuthPropertiesTokenCache(context.Properties));

                        var result = await authContext.AcquireTokenByAuthorizationCodeAsync(
                            context.ProtocolMessage.Code, new Uri(currentUri), credential, resource);

                        context.HandleCodeRedemption(result.AccessToken, result.IdToken);
                    }
                }
            });

            app.Run(async context =>
            {
                if (context.Request.Path.Equals("/signout"))
                {
                    await context.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                    context.Response.ContentType = "text/html";
                    await context.Response.WriteAsync($"<html><body>Signing out {context.User.Identity.Name}<br>{Environment.NewLine}");
                    await context.Response.WriteAsync("<a href=\"/\">Sign In</a>");
                    await context.Response.WriteAsync($"</body></html>");
                    return;
                }

                if (!context.User.Identities.Any(identity => identity.IsAuthenticated))
                {
                    await context.Authentication.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties { RedirectUri = "/" });
                    return;
                }

                context.Response.ContentType = "text/html";
                await context.Response.WriteAsync($"<html><body>Hello Authenticated User {context.User.Identity.Name}<br>{Environment.NewLine}");
                await context.Response.WriteAsync("Claims:<br>" + Environment.NewLine);
                foreach (var claim in context.User.Claims)
                {
                    await context.Response.WriteAsync($"{claim.Type}: {claim.Value}<br>{Environment.NewLine}");
                }

                await context.Response.WriteAsync("Tokens:<br>" + Environment.NewLine);
                try
                {
                    // Retrieve the auth session with the cached tokens
                    var authenticateContext = new AuthenticateContext(CookieAuthenticationDefaults.AuthenticationScheme);
                    await context.Authentication.AuthenticateAsync(authenticateContext);
                    var authProperties = new AuthenticationProperties(authenticateContext.Properties);
                    var tokenCache = new AuthPropertiesTokenCache(authProperties);

                    // Use ADAL to get the right token
                    var authContext = new AuthenticationContext(authority, tokenCache);
                    var credential = new ClientCredential(clientId, clientSecret);
                    string userObjectID = context.User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                    var result = authContext.AcquireTokenSilent(resource, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

                    // Update the cookie with the modified tokens
                    if (tokenCache.HasCacheChanged)
                    {
                        await context.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, authenticateContext.Principal, authProperties);
                    }

                    await context.Response.WriteAsync($"access_token: {result.AccessToken}<br>{Environment.NewLine}");
                }
                catch (Exception ex)
                {
                    await context.Response.WriteAsync($"AquireToken error: {ex.Message}<br>{Environment.NewLine}");
                }

                await context.Response.WriteAsync("<a href=\"/signout\">Sign Out</a>");
                await context.Response.WriteAsync($"</body></html>");
            });
        }
Beispiel #5
0
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory)
        {
            loggerfactory.AddConsole(Microsoft.Extensions.Logging.LogLevel.Information);

            // Simple error page
            app.Use(async(context, next) =>
            {
                try
                {
                    await next();
                }
                catch (Exception ex)
                {
                    if (!context.Response.HasStarted)
                    {
                        context.Response.Clear();
                        context.Response.StatusCode = 500;
                        await context.Response.WriteAsync(ex.ToString());
                    }
                    else
                    {
                        throw;
                    }
                }
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            var clientId     = "0ec0a7da-117a-40b3-b4df-35d850d3690f";                  //Configuration["oidc:clientid"];
            var clientSecret = "SLy6EyGCo4izbq4NYaJrOqJNylRI/Kdy7WYk88dzt3Q=";          //Configuration["oidc:clientsecret"];
            var authority    = "https://login.windows.net/tkopaczmse3.onmicrosoft.com"; //Configuration["oidc:authority"];
            var resource     = "https://graph.windows.net";

            app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
            {
                ClientId              = clientId,
                ClientSecret          = clientSecret, // for code flow
                Authority             = authority,
                ResponseType          = OpenIdConnectResponseType.CodeIdToken,
                PostLogoutRedirectUri = "/signed-out",
                // GetClaimsFromUserInfoEndpoint = true,
                Events = new OpenIdConnectEvents()
                {
                    OnAuthorizationCodeReceived = async context =>
                    {
                        var request     = context.HttpContext.Request;
                        var currentUri  = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path);
                        var credential  = new ClientCredential(clientId, clientSecret);
                        var authContext = new AuthenticationContext(authority, AuthPropertiesTokenCache.ForCodeRedemption(context.Properties));

                        var result = await authContext.AcquireTokenByAuthorizationCodeAsync(
                            context.ProtocolMessage.Code, new Uri(currentUri), credential, resource);

                        context.HandleCodeRedemption();
                    }
                }
            });

            app.Run(async context =>
            {
                if (context.Request.Path.Equals("/signin"))
                {
                    if (context.User.Identities.Any(identity => identity.IsAuthenticated))
                    {
                        // User has already signed in
                        context.Response.Redirect("/");
                        return;
                    }

                    await context.Authentication.ChallengeAsync(
                        OpenIdConnectDefaults.AuthenticationScheme,
                        new AuthenticationProperties {
                        RedirectUri = "/"
                    });
                }
                else if (context.Request.Path.Equals("/signout"))
                {
                    await context.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                    await WriteHtmlAsync(context.Response,
                                         async response =>
                    {
                        await response.WriteAsync($"<h1>Signed out locally: {HtmlEncode(context.User.Identity.Name)}</h1>");
                        await response.WriteAsync("<a class=\"btn btn-primary\" href=\"/\">Sign In</a>");
                    });
                }
                else if (context.Request.Path.Equals("/signout-remote"))
                {
                    await context.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                    await context.Authentication.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);
                }
                else if (context.Request.Path.Equals("/signed-out"))
                {
                    await WriteHtmlAsync(context.Response,
                                         async response =>
                    {
                        await response.WriteAsync($"<h1>You have been signed out.</h1>");
                        await response.WriteAsync("<a class=\"btn btn-primary\" href=\"/signin\">Sign In</a>");
                    });
                }
                else if (context.Request.Path.Equals("/remote-signedout"))
                {
                    await context.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                    await WriteHtmlAsync(context.Response,
                                         async response =>
                    {
                        await response.WriteAsync($"<h1>Signed out remotely: {HtmlEncode(context.User.Identity.Name)}</h1>");
                        await response.WriteAsync("<a class=\"btn btn-primary\" href=\"/\">Sign In</a>");
                    });
                }
                else
                {
                    if (!context.User.Identities.Any(identity => identity.IsAuthenticated))
                    {
                        await context.Authentication.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties {
                            RedirectUri = "/"
                        });
                        return;
                    }

                    await WriteHtmlAsync(context.Response, async response =>
                    {
                        await response.WriteAsync($"<h1>Hello Authenticated User {HtmlEncode(context.User.Identity.Name)}</h1>");
                        await response.WriteAsync("<a class=\"btn btn-default\" href=\"/signout\">Sign Out Locally</a>");
                        await response.WriteAsync("<a class=\"btn btn-default\" href=\"/signout-remote\">Sign Out Remotely</a>");

                        await response.WriteAsync("<h2>Claims:</h2>");
                        await WriteTableHeader(response, new string[] { "Claim Type", "Value" }, context.User.Claims.Select(c => new string[] { c.Type, c.Value }));

                        await response.WriteAsync("<h2>Tokens:</h2>");
                        try
                        {
                            // Use ADAL to get the right token
                            var authContext     = new AuthenticationContext(authority, AuthPropertiesTokenCache.ForApiCalls(context, CookieAuthenticationDefaults.AuthenticationScheme));
                            var credential      = new ClientCredential(clientId, clientSecret);
                            string userObjectID = context.User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                            var result          = await authContext.AcquireTokenSilentAsync(resource, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

                            await response.WriteAsync($"<h3>access_token</h3><code>{HtmlEncode(result.AccessToken)}</code><br>");
                        }
                        catch (Exception ex)
                        {
                            await response.WriteAsync($"AquireToken error: {ex.Message}");
                        }
                    });
                }
            });
        }