当前位置: 首页>>代码示例>>C#>>正文


C# IApplicationBuilder.UseOAuthAuthentication方法代码示例

本文整理汇总了C#中IApplicationBuilder.UseOAuthAuthentication方法的典型用法代码示例。如果您正苦于以下问题:C# IApplicationBuilder.UseOAuthAuthentication方法的具体用法?C# IApplicationBuilder.UseOAuthAuthentication怎么用?C# IApplicationBuilder.UseOAuthAuthentication使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IApplicationBuilder的用法示例。


在下文中一共展示了IApplicationBuilder.UseOAuthAuthentication方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Configure

        public void Configure(IApplicationBuilder app)
        {
            app.UseCookieAuthentication(options =>
            {
                options.AutomaticAuthentication = true;
                options.LoginPath = new PathString("/");
            });

            app.UseOAuthAuthentication("GitHub-AccessToken", options =>
            {
                options.ClientId = _configuration.Get("GitHub:ClientId");
                options.ClientSecret = _configuration.Get("GitHub:Secret");
                options.CallbackPath = new PathString("/signin-github");
                options.AuthorizationEndpoint = "https://github.com/login/oauth/authorize";
                options.TokenEndpoint = "https://github.com/login/oauth/access_token";
                options.SaveTokensAsClaims = true;
                options.Scope.Add("read:org");
                options.Scope.Add("repo");
            });

            app.Use(async (context, next) =>
            {
                if (!context.User.Identities.Any(identity => identity.IsAuthenticated))
                {
                    await context.Authentication.ChallengeAsync("GitHub-AccessToken", new AuthenticationProperties() { RedirectUri = context.Request.Path.ToString() });
                    return;
                }
                await next();
            });

            app.UseMvcWithDefaultRoute();
        }
开发者ID:glennc,项目名称:GHUtils,代码行数:32,代码来源:Startup.cs

示例2: Configure

        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddDebug(LogLevel.Debug);
            loggerFactory.AddConsole(LogLevel.Debug);

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            app.UseIISPlatformHandler();

            app.UseCookieAuthentication(options =>
            {
                options.AutomaticAuthenticate = true;
                options.AutomaticChallenge = true;
                options.AuthenticationScheme = "Cookies";
            });

            app.UseOAuthAuthentication(options =>
            {
                options.AutomaticChallenge = true;
                options.AuthenticationScheme = "DSAUTH";
                options.DisplayName = "DSAUTH";
                options.SignInScheme = "Cookies";

                options.ClientId = "clientid1";
                options.ClientSecret = "xoxoxo";
                options.CallbackPath = new PathString("/login/oauthcallback");

                //options.AuthorizationEndpoint = "http://ds.transvec.com/oauth/authorize";
                //options.TokenEndpoint = "http://ds.transvec.com/oauth/token";
                options.AuthorizationEndpoint = "http://localhost:8080/oauth/authorize";
                options.TokenEndpoint = "http://localhost:8080/oauth/token";
                options.Scope.Add("email");
            });

            app.UseDeveloperExceptionPage();
            app.UseMvcWithDefaultRoute();
        }
开发者ID:brollins90,项目名称:dsOauthClient,代码行数:37,代码来源:Startup.cs

示例3: Configure

        public void Configure(IApplicationBuilder app)
        {
            app.UseErrorPage();

            app.UseCookieAuthentication(options =>
                {
                    options.LoginPath = new PathString("/login");
                });

            // https://developers.facebook.com/apps/
            app.UseFacebookAuthentication(options =>
            {
                options.AppId = "569522623154478";
                options.AppSecret = "a124463c4719c94b4228d9a240e5dc1a";
            });

            app.UseOAuthAuthentication("Google-AccessToken", options =>
            {
                options.ClientId = "560027070069-37ldt4kfuohhu3m495hk2j4pjp92d382.apps.googleusercontent.com";
                options.ClientSecret = "n2Q-GEw9RQjzcRbU3qhfTj8f";
                options.CallbackPath = new PathString("/signin-google-token");
                options.AuthorizationEndpoint = GoogleAuthenticationDefaults.AuthorizationEndpoint;
                options.TokenEndpoint = GoogleAuthenticationDefaults.TokenEndpoint;
                options.Scope.Add("openid");
                options.Scope.Add("profile");
                options.Scope.Add("email");
            });

            // https://console.developers.google.com/project
            app.UseGoogleAuthentication(options =>
            {
                options.ClientId = "560027070069-37ldt4kfuohhu3m495hk2j4pjp92d382.apps.googleusercontent.com";
                options.ClientSecret = "n2Q-GEw9RQjzcRbU3qhfTj8f";
            });

            // https://apps.twitter.com/
            app.UseTwitterAuthentication(options =>
            {
                options.ConsumerKey = "6XaCTaLbMqfj6ww3zvZ5g";
                options.ConsumerSecret = "Il2eFzGIrYhz6BWjYhVXBPQSfZuS4xoHpSSyD9PI";
            });

            /* https://account.live.com/developers/applications
            The MicrosoftAccount service has restrictions that prevent the use of http://localhost:54540/ for test applications.
            As such, here is how to change this sample to uses http://mssecsample.localhost.this:54540/ instead.

            Edit the Project.json file and replace http://localhost:54540/ with http://mssecsample.localhost.this:54540/.

            From an admin command console first enter:
             notepad C:\Windows\System32\drivers\etc\hosts
            and add this to the file, save, and exit (and reboot?):
             127.0.0.1 MsSecSample.localhost.this

            Then you can choose to run the app as admin (see below) or add the following ACL as admin:
             netsh http add urlacl url=http://mssecsample.localhost.this:54540/ user=[domain\user]

            The sample app can then be run via:
             dnx . web
            */
            app.UseOAuthAuthentication("Microsoft-AccessToken", options =>
            {
                options.Caption = "MicrosoftAccount-AccessToken - Requires project changes";
                options.ClientId = "00000000480FF62E";
                options.ClientSecret = "bLw2JIvf8Y1TaToipPEqxTVlOeJwCUsr";
                options.CallbackPath = new PathString("/signin-microsoft-token");
                options.AuthorizationEndpoint = MicrosoftAccountAuthenticationDefaults.AuthorizationEndpoint;
                options.TokenEndpoint = MicrosoftAccountAuthenticationDefaults.TokenEndpoint;
                options.Scope.Add("wl.basic");
            });

            app.UseMicrosoftAccountAuthentication(options =>
            {
                options.Caption = "MicrosoftAccount - Requires project changes";
                options.ClientId = "00000000480FF62E";
                options.ClientSecret = "bLw2JIvf8Y1TaToipPEqxTVlOeJwCUsr";
            });

            // https://github.com/settings/applications/
            app.UseOAuthAuthentication("GitHub-AccessToken", options =>
            {
                options.ClientId = "8c0c5a572abe8fe89588";
                options.ClientSecret = "e1d95eaf03461d27acd6f49d4fc7bf19d6ac8cda";
                options.CallbackPath = new PathString("/signin-github-token");
                options.AuthorizationEndpoint = "https://github.com/login/oauth/authorize";
                options.TokenEndpoint = "https://github.com/login/oauth/access_token";
            });

            app.UseOAuthAuthentication("GitHub", options =>
            {
                options.ClientId = "49e302895d8b09ea5656";
                options.ClientSecret = "98f1bf028608901e9df91d64ee61536fe562064b";
                options.CallbackPath = new PathString("/signin-github");
                options.AuthorizationEndpoint = "https://github.com/login/oauth/authorize";
                options.TokenEndpoint = "https://github.com/login/oauth/access_token";
                options.UserInformationEndpoint = "https://api.github.com/user";
                options.ClaimsIssuer = "OAuth2-Github";
                // Retrieving user information is unique to each provider.
                options.Notifications = new OAuthAuthenticationNotifications()
                {
                    OnGetUserInformationAsync = async (context) =>
//.........这里部分代码省略.........
开发者ID:SacmaIslerOfisi,项目名称:Security,代码行数:101,代码来源:Startup.cs

示例4: Configure

        public void Configure(IApplicationBuilder app)
        {
            app.UseCookieAuthentication(options =>
            {
                options.LoginPath = new PathString("/login");
            });

            // Configure GitHub
            app.UseOAuthAuthentication("GitHub", options =>
            {
                options.ClientId = "a643223e6e429ee091d1";
                options.ClientSecret = "673d832c4b8cd8932aa4444e319cc20bff7bf590";
                options.CallbackPath = new PathString("/signin-github");
                options.AuthorizationEndpoint = "https://github.com/login/oauth/authorize";
                options.TokenEndpoint = "https://github.com/login/oauth/access_token";
                options.UserInformationEndpoint = "https://api.github.com/user";
                options.Notifications = new OAuthAuthenticationNotifications
                {
                    OnGetUserInformationAsync = async context =>
                    {
                        // Get the GitHub user
                        HttpRequestMessage userRequest = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
                        userRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
                        userRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        HttpResponseMessage userResponse = await context.Backchannel.SendAsync(userRequest, context.HttpContext.RequestAborted);
                        userResponse.EnsureSuccessStatusCode();
                        var text = await userResponse.Content.ReadAsStringAsync();
                        JObject user = JObject.Parse(text);

                        var identity = new ClaimsIdentity(
                            context.Options.AuthenticationType,
                            ClaimsIdentity.DefaultNameClaimType,
                            ClaimsIdentity.DefaultRoleClaimType);

                        JToken value;
                        var id = user.TryGetValue("id", out value) ? value.ToString() : null;
                        if (!string.IsNullOrEmpty(id))
                        {
                            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, id, ClaimValueTypes.String, context.Options.AuthenticationType));
                        }
                        var userName = user.TryGetValue("login", out value) ? value.ToString() : null;
                        if (!string.IsNullOrEmpty(userName))
                        {
                            identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, userName, ClaimValueTypes.String, context.Options.AuthenticationType));
                        }
                        var name = user.TryGetValue("name", out value) ? value.ToString() : null;
                        if (!string.IsNullOrEmpty(name))
                        {
                            identity.AddClaim(new Claim("urn:github:name", name, ClaimValueTypes.String, context.Options.AuthenticationType));
                        }
                        var link = user.TryGetValue("url", out value) ? value.ToString() : null;
                        if (!string.IsNullOrEmpty(link))
                        {
                            identity.AddClaim(new Claim("urn:github:url", link, ClaimValueTypes.String, context.Options.AuthenticationType));
                        }

                        context.Identity = identity;
                    }
                };
            });

            // Choose an authentication type
            app.Map("/login", socialApp =>
            {
                socialApp.Run(async context =>
                {
                    string authType = context.Request.Query["authtype"];
                    if (!string.IsNullOrEmpty(authType))
                    {
                        context.Response.Challenge(new AuthenticationProperties() { RedirectUri = "/" }, authType);
                        return;
                    }

                    context.Response.ContentType = "text/html";
                    await context.Response.WriteAsync("<html><body>");
                    await context.Response.WriteAsync("Choose an authentication type: <br>");
                    foreach (var type in context.GetAuthenticationTypes())
                    {
                        await context.Response.WriteAsync("<a href=\"?authtype=" + type.AuthenticationType + "\">" + (type.Caption ?? "(suppressed)") + "</a><br>");
                    }
                    await context.Response.WriteAsync("</body></html>");
                });
            });

            // Sign-out to remove the user cookie.
            app.Map("/logout", socialApp =>
            {
                socialApp.Run(async context =>
                {
                    context.Response.SignOut(CookieAuthenticationDefaults.AuthenticationType);
                    context.Response.ContentType = "text/html";
                    await context.Response.WriteAsync("<html><body>");
                    await context.Response.WriteAsync("You have been logged out. Goodbye " + context.User.Identity.Name + "<br>");
                    await context.Response.WriteAsync("<a href=\"/\">Home</a>");
                    await context.Response.WriteAsync("</body></html>");
                });
            });

            // Deny anonymous request beyond this point.
            app.Use(async (context, next) =>
//.........这里部分代码省略.........
开发者ID:niranjanramalingam,项目名称:ASPNET5GenericOAuthProvider,代码行数:101,代码来源:Startup.cs

示例5: Configure

        // Configure is called after ConfigureServices is called.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IUserRepository userRepository, InatorConstraint inatorConstraint)
        {
            loggerFactory.MinimumLevel = LogLevel.Information;
            loggerFactory.AddConsole();
            loggerFactory.AddDebug();

            // Configure the HTTP request pipeline.

            // Add the following to the request pipeline only in development environment.
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll);
            }
            else
            {
                // Add Error handling middleware which catches all application specific errors and
                // sends the request to the following path or controller action.
                app.UseExceptionHandler("/Home/Error");
            }

            // Add the platform handler to the request pipeline.
            app.UseIISPlatformHandler();

            // Add static files to the request pipeline.
            app.UseStaticFiles();

            app.UseCookieAuthentication(options => {
                options.AutomaticAuthentication = true;
                //options.AutomaticChallenge = true;
                options.LoginPath = new PathString("/login");
            });

            string githubClientId = this.Configuration["GitHubClientId"];
            string githubClientSecret = this.Configuration["GitHubClientSecret"];

            // Add GitHub Authentication
            // http://www.jerriepelser.com/blog/introduction-to-aspnet5-generic-oauth-provider
            // https://github.com/aspnet/Security/blob/dev/samples/SocialSample/Startup.cs
            app.UseOAuthAuthentication(new OAuthOptions {
                AuthenticationScheme = "GitHub",
                DisplayName = "Github",
                ClientId = githubClientId,
                ClientSecret = githubClientSecret,
                CallbackPath = new PathString("/signin-github"),
                AuthorizationEndpoint = "https://github.com/login/oauth/authorize",
                TokenEndpoint = "https://github.com/login/oauth/access_token",
                SaveTokensAsClaims = false,
                UserInformationEndpoint = "https://api.github.com/user",
                // Retrieving user information is unique to each provider.
                Events = new OAuthEvents {
                    OnCreatingTicket = async context => {
                        // Get the GitHub user

                        var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
                        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
                        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                        var response = await context.Backchannel.SendAsync(request, context.HttpContext.RequestAborted);
                        response.EnsureSuccessStatusCode();

                        var githubUser = JObject.Parse(await response.Content.ReadAsStringAsync());

                        var id = githubUser.Value<int>("id");
                        if (id < 1) {
                            throw new ArgumentNullException("id");
                        }
                        var login = githubUser.Value<string>("login");
                        var name = githubUser.Value<string>("name");
                        var avitarUrl = githubUser.Value<string>("avatar_url");

                        User user = userRepository.GetByGitHubId(id) ?? new User { GitHubId = id };
                        user.Login = login;
                        user.Name = name;
                        user.AvitarUrl = avitarUrl;
                        userRepository.Save(user);

                        context.Identity.AddClaim(new Claim(
                            ClaimTypes.NameIdentifier, user.UserId.ToString()
                        ));

                        if (!string.IsNullOrEmpty(name)) {
                            context.Identity.AddClaim(new Claim(
                                "urn:github:name", name,
                                ClaimValueTypes.String, context.Options.ClaimsIssuer
                            ));
                        }
                        if (!string.IsNullOrEmpty(avitarUrl)) {
                            context.Identity.AddClaim(new Claim(
                                "urn:github:avitar", avitarUrl,
                                ClaimValueTypes.String, context.Options.ClaimsIssuer
                            ));
                        }

                        if (user.IsAdmin) {
                            context.Identity.AddClaim(new Claim(
                                ClaimTypes.Role, "admin"
                            ));
//.........这里部分代码省略.........
开发者ID:robrich,项目名称:api-inator,代码行数:101,代码来源:Startup.cs

示例6: Configure

        public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory)
        {
            loggerfactory.AddConsole(LogLevel.Information);

            // Simple error page to avoid a repo dependency.
            app.Use(async (context, next) =>
            {
                try
                {
                    await next();
                }
                catch (Exception ex)
                {
                    if (context.Response.HasStarted)
                    {
                        throw;
                    }
                    context.Response.StatusCode = 500;
                    await context.Response.WriteAsync(ex.ToString());
                }
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                LoginPath = new PathString("/login")
            });

            // You must first create an app with facebook and add it's ID and Secret to your config.json or user-secrets.
            // https://developers.facebook.com/apps/
            app.UseFacebookAuthentication(new FacebookOptions
            {
                AppId = Configuration["facebook:appid"],
                AppSecret = Configuration["facebook:appsecret"],
                Scope = { "email" },
                Fields = { "name", "email" },
                SaveTokens = true,
            });

            // See config.json
            app.UseOAuthAuthentication(new OAuthOptions
            {
                AuthenticationScheme = "Google-AccessToken",
                DisplayName = "Google-AccessToken",
                ClientId = Configuration["google:clientid"],
                ClientSecret = Configuration["google:clientsecret"],
                CallbackPath = new PathString("/signin-google-token"),
                AuthorizationEndpoint = GoogleDefaults.AuthorizationEndpoint,
                TokenEndpoint = GoogleDefaults.TokenEndpoint,
                Scope = { "openid", "profile", "email" },
                SaveTokens = true
            });

            // See config.json
            // https://console.developers.google.com/project
            app.UseGoogleAuthentication(new GoogleOptions
            {
                ClientId = Configuration["google:clientid"],
                ClientSecret = Configuration["google:clientsecret"],
                SaveTokens = true,
                Events = new OAuthEvents()
                {
                    OnRemoteFailure = ctx =>
                    {
                        ctx.Response.Redirect("/error?FailureMessage=" + UrlEncoder.Default.Encode(ctx.Failure.Message));
                        ctx.HandleResponse();
                        return Task.FromResult(0);
                    }
                }
            });

            // See config.json
            // https://apps.twitter.com/
            app.UseTwitterAuthentication(new TwitterOptions
            {
                ConsumerKey = Configuration["twitter:consumerkey"],
                ConsumerSecret = Configuration["twitter:consumersecret"],
                SaveTokens = true,
                Events = new TwitterEvents()
                {
                    OnRemoteFailure = ctx =>
                    {
                        ctx.Response.Redirect("/error?FailureMessage=" + UrlEncoder.Default.Encode(ctx.Failure.Message));
                        ctx.HandleResponse();
                        return Task.FromResult(0);
                    }
                }
            });

            /* Azure AD app model v2 has restrictions that prevent the use of plain HTTP for redirect URLs.
               Therefore, to authenticate through microsoft accounts, tryout the sample using the following URL:
               https://localhost:54541/
            */
            // See config.json
            // https://apps.dev.microsoft.com/
            app.UseOAuthAuthentication(new OAuthOptions
            {
                AuthenticationScheme = "Microsoft-AccessToken",
                DisplayName = "MicrosoftAccount-AccessToken",
//.........这里部分代码省略.........
开发者ID:cemalshukriev,项目名称:Security,代码行数:101,代码来源:Startup.cs


注:本文中的IApplicationBuilder.UseOAuthAuthentication方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。