Asp.net 使用OpenOAuthProvider与Google进行身份验证
我在Visual Studio中创建了默认的ASP.NET项目模板,并转到Asp.net 使用OpenOAuthProvider与Google进行身份验证,asp.net,dotnetopenauth,Asp.net,Dotnetopenauth,我在Visual Studio中创建了默认的ASP.NET项目模板,并转到App\u Start文件夹中的AuthConfig。然后我取消了以下行的注释: OpenAuth.AuthenticationClients.AddGoogle(); 我得到了谷歌登录的按钮,如下所示: 当我点击谷歌按钮时,我发现以下错误: An exception of type 'DotNetOpenAuth.Messaging.ProtocolException' occurred in DotNetOpen
App\u Start
文件夹中的AuthConfig
。然后我取消了以下行的注释:
OpenAuth.AuthenticationClients.AddGoogle();
我得到了谷歌登录的按钮,如下所示:
当我点击谷歌按钮时,我发现以下错误:
An exception of type 'DotNetOpenAuth.Messaging.ProtocolException'
occurred in DotNetOpenAuth.OpenId.RelyingParty.dll but was not handled in user code
Additional information: No OpenID endpoint found.
WE.config文件
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<pages>
<namespaces>
<add namespace="System.Web.Optimization" />
</namespaces>
<controls>
<add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
</controls></pages>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" defaultUrl="~/" />
</authentication>
<profile defaultProvider="DefaultProfileProvider">
<providers>
<add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</profile>
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<roleManager defaultProvider="DefaultRoleProvider">
<providers>
<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</roleManager>
<sessionState mode="InProc" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
</providers>
</sessionState>
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780ccd10d57b246" />
<bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="DotNetOpenAuth.AspNet" publicKeyToken="2780ccd10d57b246" />
<bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
</configuration>
请帮帮我。我缺少什么?实际上,这种实现(OpenId)是。如果可能,您应该更改为MVC5。在MVC5中,它非常简单。这一解决方案仍然有效。如果不能,则需要编写此文件或使用第三方组件,该组件使用OAuth2与Google通信。有关不推荐使用的功能的更多信息,请参阅。通过添加以下代码,您可能会丢失Google身份验证的ConfigureAuth:
app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
ClientId = "*****************.googleusercontent.com",
ClientSecret = "********************"
});
启动时。Auth.cs
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
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
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(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
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);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
//app.UseTwitterAuthentication(
// consumerKey: "",
// consumerSecret: "");
//app.UseFacebookAuthentication(
// appId: "",
// appSecret: "");
// The same with Facebook, Twitter, MicrosoftAccount
app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
ClientId = "*****************.googleusercontent.com",
ClientSecret = "********************"
});
public void ConfigureAuth(IAppBuilder应用程序)
{
//将数据库上下文、用户管理器和登录管理器配置为每个请求使用一个实例
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext(ApplicationUserManager.Create);
app.CreatePerOwinContext(ApplicationSignInManager.Create);
//使应用程序能够使用cookie存储登录用户的信息
//以及使用cookie临时存储用户登录第三方登录提供商的信息
//配置登录cookie
app.UseCookieAuthentication(新的CookieAuthenticationOptions
{
AuthenticationType=DefaultAuthenticationTypes.ApplicationOkie,
LoginPath=新路径字符串(“/Account/Login”),
Provider=新CookieAuthenticationProvider
{
//允许应用程序在用户登录时验证安全戳。
//这是一种安全功能,在您更改密码或向帐户添加外部登录时使用。
OnValidateIdentity=SecurityStampValidator.OnValidateIdentity(
validateInterval:TimeSpan.FromMinutes(30),
regenerateIdentity:(管理器,用户)=>user.GenerateUserIdentityAsync(管理器))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
//允许应用程序在验证双因素身份验证过程中的第二个因素时临时存储用户信息。
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie,TimeSpan.FromMinutes(5));
//使应用程序能够记住第二个登录验证因素,如电话或电子邮件。
//选中此选项后,登录过程中的第二步验证将在您登录的设备上被记住。
//这类似于登录时的RememberMe选项。
app.useTowFactoryMemberBrowserCookie(DefaultAuthenticationTypes.TwoFactoryRememberBrowserCookie);
//取消注释以下行以启用使用第三方登录提供程序登录
//app.UseMicrosoftAccountAuthentication(
//客户ID:“,
//客户机密:);
//app.UseTwitterAuthentication(
//消费市场:“,
//消费者信用:”;
//app.UseFacebookAuthentication(
//appId:“”,
//appSecret:”;
//Facebook、Twitter、MicrosoftAccount也是如此
app.UseGoogleAuthentication(新的GoogleOAuth2AuthenticationOptions()
{
ClientId=“***************.googleusercontent.com”,
ClientSecret=“********************”
});
正如您在聊天评论中提到的,使用Web表单应用程序
。点击谷歌
的事件
protected void lnkbtngplus_Click(object sender, EventArgs e)
{
try
{
var Googleurl = "https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=" + ConfigurationManager.AppSettings["googleplus_redirect_url"] + "&scope=googleapis.com/auth/…" + ConfigurationManager.AppSettings["googleplus_client_id"];
Session["loginWith"] = "google";
Response.Redirect(Googleurl);
}
catch (Exception ex)
{
Master.Messages(ex.Message);
}
}
在重定向url上可以收集如下所示的参数值
try
{
var url = Request.Url.Query;
if (url != "")
{
string queryString = url.ToString();
char[] delimiterChars = { '=' };
string[] words = queryString.Split(delimiterChars);
string code = words[1];
SocialNetwork.GoogleUserOutputData json_data = SocialNetwork.Googlemethod(code);
String email = String.Empty;
String id = String.Empty;
email = json_data.email;
id = json_data.given_name;
if (email != null && email != "")
{
txtFname.Text = id;
txtemail.Text = email;
}
}
}
catch (Exception ex)
{
}
在社交网络类文件中,我有以下方法
#region Google
protected static string Parameters;
public static GoogleUserOutputData Googlemethod(string code)
{
GoogleUserOutputData serStatus1 = new GoogleUserOutputData();
string json_data = string.Empty;
if (code != null)
{
//get the access token
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
webRequest.Method = "POST";
Parameters = "code=" + code + "&client_id=" + googleplus_client_id + "&client_secret=" + googleplus_client_sceret + "&redirect_uri=" + googleplus_redirect_url + "&grant_type=authorization_code";
byte[] byteArray = Encoding.UTF8.GetBytes(Parameters);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
Stream postStream = webRequest.GetRequestStream();
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
WebResponse response = webRequest.GetResponse();
postStream = response.GetResponseStream();
StreamReader reader = new StreamReader(postStream);
string responseFromServer = reader.ReadToEnd();
GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject<GooglePlusAccessToken>(responseFromServer);//JsonConvert.DeserializeObject<GooglePlusAccessToken>(responseFromServer);
//GooglePlusAccessToken serStatus = new GooglePlusAccessToken();
if (serStatus != null)
{
string accessToken = string.Empty;
accessToken = serStatus.access_token;
if (!string.IsNullOrEmpty(accessToken))
{
using (var w = new WebClient())
{
json_data = w.DownloadString("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + accessToken);
serStatus1 = JsonConvert.DeserializeObject<GoogleUserOutputData>(json_data);
}
}
else
{ }
}
else
{ }
}
return serStatus1;
}
public class GoogleUserOutputData
{
public string id { get; set; }
public string name { get; set; }
public string given_name { get; set; }
public string email { get; set; }
public string picture { get; set; }
}
public class GooglePlusAccessToken
{
public string access_token { get; set; }
public string token_type { get; set; }
public int expires_in { get; set; }
public string id_token { get; set; }
public string refresh_token { get; set; }
}
#endregion
#谷歌地区
受保护的静态字符串参数;
公共静态GoogleUserOutputData Googlemethod(字符串代码)
{
GoogleUserOutputData serStatus1=新的GoogleUserOutputData();
string json_data=string.Empty;
如果(代码!=null)
{
//获取访问令牌
HttpWebRequest webRequest=(HttpWebRequest)webRequest.Create(“https://accounts.google.com/o/oauth2/token");
webRequest.Method=“POST”;
Parameters=“code=“+code+”&client\u id=“+googleplus\u client\u id+”&client\u secret=“+googleplus\u client\u sceret+”&redirect\u uri=“+googleplus\u redirect\u url+”&grant\u type=authorization\u code”;
byte[]byteArray=Encoding.UTF8.GetBytes(参数);
webRequest.ContentType=“application/x-www-form-urlencoded”;
webRequest.ContentLength=byteArray.Length;
Stream postStream=webRequest.GetRequestStream();
//将post数据添加到web请求
Write(byteArray,0,byteArray.Length);
postStream.Close();
WebResponse=webRequest.GetResponse();
postStream=response.GetResponseStream();
StreamReader=新的StreamReader(postStream);
字符串responseFromServer=reader.ReadToEnd();
GooglePlusAccessToken serStatus=JsonConvert.Deseria