c# - get user information into database in google authentication -
using system; using system.collections.generic; using system.linq; using system.web; using system.web.ui; using system.web.ui.webcontrols; using system.globalization; using system.net; using system.security.cryptography; using system.text; using system.io; using newtonsoft.json; using system.net.http; public partial class _default : system.web.ui.page { protected string googleplus_client_id = "clientid"; protected string googleplus_client_sceret = "id"; protected string googleplus_redirect_url="http://localhost"; // replace redirect url; redirect url developer.google application should match url. protected string parameters; protected void page_load(object sender, eventargs e) { if (session.contents.count > 0) { if (session["loginwith"] != null) { if (session["loginwith"].tostring() == "google") { try { var url = request.url.query; if (url != "") { string querystring = url.tostring(); char[] delimiterchars = { '=' }; string[] words = querystring.split(delimiterchars); string code = words[1]; if (code != null) { //get 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 post data 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); if (serstatus != null) { string accesstoken = string.empty; accesstoken = serstatus.access_token; if (!string.isnullorempty(accesstoken)) { // getgoogleplususerdataser(accesstoken); } else { } } else { } } else { } } } catch (exception ex) { //throw new exception(ex.message, ex); response.redirect("index.aspx"); } } } } } protected void button1_click(object sender, eventargs e) { var googleurl = "https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=" + googleplus_redirect_url + "&scope=https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile&client_id=" + googleplus_client_id; session["loginwith"] = "google"; response.redirect(googleurl); } 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; } } private async void getgoogleplususerdataser(string access_token) { try { httpclient client = new httpclient(); var urlprofile = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + access_token; client.cancelpendingrequests(); httpresponsemessage output = await client.getasync(urlprofile); if (output.issuccessstatuscode) { string outputdata = await output.content.readasstringasync(); googleuseroutputdata serstatus = jsonconvert.deserializeobject<googleuseroutputdata>(outputdata); if (serstatus != null) { // user information here. } } } catch (exception ex) { //catching exception } } } 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; } }
i don't know can store user information in table, don't know google authentication , find ths=is code on stackoverflow
i want store information in table , if user logged in first time page should redirected new user page , if user old user page should redirect welcome page
to start with, agree google's documentation murky business.
there couple of different ways in can validate integrity of id token on server side (btw this page you're looking for):
- "manually" - download google's public keys, verify signature , each , every field, including
iss
one; main advantage (albeit small 1 in opinion) see here can minimize number of requests sent google). - "automatically" - on google's endpoint verify token
https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={0}
- using google api client library - official one.
here's how look:
private const string googleapitokeninfourl = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={0}"; public provideruserdetails getuserdetails(string providertoken) { var httpclient = new monitoredhttpclient(); var requesturi = new uri(string.format(googleapitokeninfourl, providertoken)); httpresponsemessage httpresponsemessage; try { httpresponsemessage = httpclient.getasync(requesturi).result; } catch (exception ex) { return null; } if (httpresponsemessage.statuscode != httpstatuscode.ok) { return null; } var response = httpresponsemessage.content.readasstringasync().result; var googleapitokeninfo = jsonconvert.deserializeobject<googleapitokeninfo>(response); if (!supportedclientsids.contains(googleapitokeninfo.aud)) { log.warnformat("google api token info aud field ({0}) not containing required client id", googleapitokeninfo.aud); return null; } return new provideruserdetails { email = googleapitokeninfo.email, firstname = googleapitokeninfo.given_name, lastname = googleapitokeninfo.family_name, locale = googleapitokeninfo.locale, name = googleapitokeninfo.name, provideruserid = googleapitokeninfo.sub }; }
Comments
Post a Comment