It is also a pleasure to write a blog while enjoying the peace of the countryside.
I like to write a blog after solving the problem. By expressing it in words, We will deepen our understanding and often have new gains and even find better solutions. It can also be shared with others. How happy is it?
The problem to be solved this time is:How can I verify a user's email address during user registration?
The common solution is to send an activation email to the user's mailbox. However, this method has the following problems:
- From sending an email to receiving an email, there may be a delay.
- Emails may be treated as spam.
- The user may enter the wrong email address. Worse, the user does not know that he or she has entered the wrong email address.
How can I verify the user's Gmail email address?
The solution we use isUse oauth to call Google API to get users' Gmail addresses.
As a result, the problem becomesHow to call Google API through oauth in ASP. NET MVC?
Two Mandatory documents:
Using oauth 2.0 to access Google APIs
Using oauth 2.0 for Web server applications
Our oauth application scenario is Web server applications. The corresponding sequence diagram is as follows:
Briefly describe the entire process:
- You provide a Google oauth logon link on your website.
- The user clicks this link to log on to the Google login page.
- After the user successfully logs on, the authorization page is displayed.
- After the user authorization is successful, Google will automatically redirect to your website page and pass the authorization code to you.
- Use this authorization code to request access_token from the Google oauth server.
- After obtaining the access_token, call the Google API to obtain the user information.
The specific implementation steps are as follows:
1. Go to the Google APIs console, create a project, and create a client ID, such:
Obtain the following information: Client ID, email address, client secret, and redirect Uris.
2. Create an empty ASP. net mvc Project
3. Add the corresponding consumer etting in Web. config to save the Client ID information obtained in step 1.
<appSettings> <add key="ClientID" value=""/> <add key="EmailAddress" value=""/> <add key="ClientSecret" value=""/> <add key="RedirectURI" value=""/> </appSettings>
4. Create the MVC controller oauthcontroller and add the action named googlelogin to redirect to the Google page for logon. The Code is as follows:
Public class oauthcontroller: controller {public actionresult googlelogin () {var url = "https://accounts.google.com/o/oauth2/auth? "+" Scope = {0} & State = {1} & redirect_uri = {2} & response_type = Code & client_id = {3} & approval_prompt = force "; // userinfo. email indicates obtaining the user's email var scope = httputility. urlencode ("https://www.googleapis.com/auth/userinfo.email"); // corresponds to userinfo. email var state = "email"; var redirecturi = httputility. urlencode (configurationmanager. appsettings ["redirecturi"]); var cilentid = httputility. urlencode (configurationmanager. appsettings ["clientid"]); Return redirect (string. format (URL, scope, state, redirecturi, cilentid ));}}
After compilation, access the file through a browser. Assume that the domain name is passport. cnblogs. cc. The access URL is passport. cnblogs. CC/oauth/googlelogin. After accessing, if your Google account is logged on, the authorization page is displayed, for example:
After clicking "Allow access", the page will be redirected back to your website. Here we redirect the URL passport. cnblogs. CC/oauth2callback? State = Email & code = 4/BSCUqsaY6S5GYk9tFR-45-_ uhl4-, the value of the query parameter code is authorization code, followed by the Redirection URL passport. cnblogs. CC/oauth2callback processing (this URL is the Redirect Uris obtained in step 1 ).
5. Add routing rules in global. asax. cs. The Code is as follows:
routes.MapRoute( "oauth2callback", "oauth2callback", new { controller = "OAuth", action = "GoogleCallback", id = UrlParameter.Optional });
6. Add the action named googlecallback to oauthcontroller.
public class OAuthController : Controller{ public ActionResult GoogleCallback() { }}
All subsequent operations are completed in googlecallback.
7. This step is the key to completing two operations:
A) Request access_token from the Google oauth server through authorization code (this is required for every call to the Google API ).
B) after obtaining the access_token, call the Google API to obtain the user information (email here ).
References: https://developers.google.com/accounts/docs/OAuth2WebServer
7.1 The Code flow for obtaining access_token based on the authorization code is:
- Send an http post request to https://accounts.google.com/o/oauth2/tokenand pass the relevant parameters.
- Obtain the server response. The response content is in JSON format.
- Deserializes JSON into an anonymous instance and obtains the access_token.
The Code is as follows:
// Because it is https, it must be converted to httpwebrequestvar webrequest = webrequest. create ("https://accounts.google.com/o/oauth2/token") as httpwebrequest; webrequest. method = "Post"; webrequest. contenttype = "application/X-WWW-form-urlencoded"; // refer to the https://developers.google.com/accounts/docs/OAuth2WebServervar postdata = string. format ("code = {0} & client_id = {1} & client_secret = {2} & redirect_uri = {3}" + "& grant_type = authorization_code", request. querystring ["code"], configurationmanager. appsettings ["clientid"], configurationmanager. appsettings ["clientsecret"], configurationmanager. appsettings ["redirecturi"]); // in the http post request, the parameter using (VAR Sw = new streamwriter (webrequest. getrequeststream () {SW. write (postdata);} // send the request and obtain the server response var resonsejson = ""; using (VAR response = webrequest. getresponse () {using (VAR sr = new streamreader (response. getresponsestream () {resonsejson = sr. readtoend () ;}// use JSON.. Net deserializes the JSON string returned by the server to obtain access_tokenvar accesstoken = jsonconvert. deserializeanonymoustype (resonsejson, new {access_token = ""}). access_token;
7.2 The Code flow for reading user information based on access_token is:
- Send an http get request to https://www.googleapis.com/oauth2/v1/userinfo. the request header contains the access_token information.
- Obtain the response content in JSON format of the server and read the user's email information.
The Code is as follows:
webRequest = WebRequest.Create("https://www.googleapis.com/oauth2/v1/userinfo") as HttpWebRequest;webRequest.Method = "GET";webRequest.Headers.Add("Authorization", "Bearer " + accessToken);using (var response = webRequest.GetResponse()){ using (var sr = new StreamReader(response.GetResponseStream())) { return Content(JsonConvert.DeserializeAnonymousType(sr.ReadToEnd(), new { Email = "" }).Email); }}
Download complete code
Http://files.cnblogs.com/dudu/CNBlogsDemoMvcOAuth.rar