Startup.Auth.cs不接受环境变量

时间:2015-04-07 18:41:41

标签: c# asp.net azure environment-variables

这是任何有兴趣的人的完整资源: https://github.com/josephmcasey/me/blob/master/JosephMCasey/App_Start/Startup.Auth.cs

我正在使用ASP.Net和C#建立个人网站组合。目前我收到以下错误,我知道这些错误与我的Startup.Auth.cs类文件有关。

    [ArgumentException: The 'ClientId' option must be provided.]
    Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationMiddleware..ctor(OwinMiddleware next, IAppBuilder app, GoogleOAuth2AuthenticationOptions options) +280
   lambda_method(Closure , OwinMiddleware , IAppBuilder , GoogleOAuth2AuthenticationOptions ) +83
    [TargetInvocationException: Exception has been thrown by the target of an invocation.]
    [HttpException (0x80004005): Exception has been thrown by the target of an invocation.]

如何从azure应用程序的设置中正确调用这些客户端密码字符串,而无需手动将其键入源代码?

        app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
        {
            ClientId = Environment.GetEnvironmentVariable("APPSETTING_Google-clientId"),
            ClientSecret = Environment.GetEnvironmentVariable("APPSETTING_Google-clientSecret")
        });

2 个答案:

答案 0 :(得分:1)

要详细说明已接受的答案,但未解释此问题 - 您的开发人员客户端ID需要作为中间件身份验证设置的一部分添加。

(我在Facebook身份验证方面遇到了同样的问题,刚刚意识到我在使用新机器时忘记设置密钥了。)

根据接受的配置使用答案,提醒密钥不应该是硬编码的,所以要么使用 CloudConfigurationManager ,要么通过 Microsoft.Extensions.SecretManager

使用秘密管理器的一个很好的演练是: http://docs.asp.net/en/latest/security/authentication/sociallogins.html

答案 1 :(得分:0)

固定来源

using System;
using Microsoft.Azure;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.DataProtection;
using Owin.Security.Providers.Yahoo;
using Owin.Security.Providers.LinkedIn;
using Owin.Security.Providers.GitHub;
using Owin.Security.Providers.Steam;
using Owin.Security.Providers.StackExchange;
using Microsoft.Owin.Security.Google;
using Microsoft.Owin.Security.OAuth;
using Owin;
using JosephMCasey.Models;
using JosephMCasey.Providers;
using Microsoft.WindowsAzure.Management;

namespace JosephMCasey
{
    public partial class Startup
    {
        // Enable the application to use OAuthAuthorization. You can then secure your Web APIs
        static Startup()
        {
            PublicClientId = "web";

            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                AuthorizeEndpointPath = new PathString("/Account/Authorize"),
                Provider = new ApplicationOAuthProvider(PublicClientId),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                AllowInsecureHttp = true
            };
        }

        public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

        public static string PublicClientId { get; private set; }

        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.  
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(20),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);

            // Uncomment the following lines to enable logging in with third party login providers

            app.UseMicrosoftAccountAuthentication(
                clientId: CloudConfigurationManager.GetSetting("Microsoft-clientId"),
                clientSecret: CloudConfigurationManager.GetSetting("Microsoft-clientSecret"));

            app.UseTwitterAuthentication(
                consumerKey: CloudConfigurationManager.GetSetting("Twitter-consumerKey"),
                consumerSecret: CloudConfigurationManager.GetSetting("Twitter-consumerSecret"));

            app.UseFacebookAuthentication(
                appId: CloudConfigurationManager.GetSetting("Facebook-appId"),
                appSecret: CloudConfigurationManager.GetSetting("Facebook-appSecret"));

            app.UseYahooAuthentication(
                CloudConfigurationManager.GetSetting("Yahoo-clientId"),
                CloudConfigurationManager.GetSetting("Yahoo-clientSecret"));

            app.UseGitHubAuthentication(
            clientId: CloudConfigurationManager.GetSetting("Github-clientId"),
            clientSecret: CloudConfigurationManager.GetSetting("Github-clientSecret"));

            app.UseLinkedInAuthentication(CloudConfigurationManager.GetSetting("LinkedIn-clientId"), CloudConfigurationManager.GetSetting("LinkedIn-clientSecret"));

            app.UseSteamAuthentication(CloudConfigurationManager.GetSetting("Steam-key"));

            app.UseStackExchangeAuthentication(
            clientId: CloudConfigurationManager.GetSetting("StackExchange-clientId"),
            clientSecret: CloudConfigurationManager.GetSetting("StackExchange-clientSecret"),
            key: CloudConfigurationManager.GetSetting("StackExchange-key"));

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = CloudConfigurationManager.GetSetting("Google-clientId"),
                ClientSecret = CloudConfigurationManager.GetSetting("Google-clientSecret")
            });
        }
    }
}
相关问题