Add Google authentication method to existing ASP.NET WebAPI project











up vote
0
down vote

favorite












I have existsing C# ASP.NET WebAPI 2.0 project with a few methods for another website. This WebAPI project has no any authentication and returns JSON data. The first method takes two parameters from website: Email and Password then checks it in MS SQL table and returns JSON (success or wrong): if success then i create some token and add token with user_id to another MS SQL table. This method returns token if everything is ok.



    [HttpPost]
[Route("api/v1/auth/email-login")]
[ActionName("EmailLogin")]
public IHttpActionResult Postpipeline_EmailLogin([FromBody] PostAuthItem postAuthItem)
{
try
{
int? userId = db.USERS_GetUserId(postAuthItem.Email, postAuthItem.Password).FirstOrDefault();
if (userId == null)
{
return Ok(new
{
Error = "Wrong email or password!"
});
}
else
{
string token = this.GetToken(40);

db.TOKENS_Add(userId, token);
db.SaveChanges();

return Ok(new
{
Token = token
});
}
}
catch (Exception ex)
{
return new System.Web.Http.Results.ResponseMessageResult(Request.CreateErrorResponse((HttpStatusCode)400, new HttpError("Http error! " + ex.Message + " " + ex.InnerException.Message)));
}
}


Now authorization via Google has been added to the website. So i need to add new method, that will check success or wrong authentication via Google. Website developer send me only access_token like this:



Request:
{
"access_token": "ya47.Kdd_KeQ0mQiTzom20dQ6M83742KMYQpkCUqCZv0UbU2CjhMIuxIT5ugRXwIrOUcV-TGbUztMiRDRPzh0INrGgh7gqXyaIfyQAnNMmP0GhXRc6bbanEiPxV7fK9ss"
}


If there is possibility to check valid Google user with this request?










share|improve this question


























    up vote
    0
    down vote

    favorite












    I have existsing C# ASP.NET WebAPI 2.0 project with a few methods for another website. This WebAPI project has no any authentication and returns JSON data. The first method takes two parameters from website: Email and Password then checks it in MS SQL table and returns JSON (success or wrong): if success then i create some token and add token with user_id to another MS SQL table. This method returns token if everything is ok.



        [HttpPost]
    [Route("api/v1/auth/email-login")]
    [ActionName("EmailLogin")]
    public IHttpActionResult Postpipeline_EmailLogin([FromBody] PostAuthItem postAuthItem)
    {
    try
    {
    int? userId = db.USERS_GetUserId(postAuthItem.Email, postAuthItem.Password).FirstOrDefault();
    if (userId == null)
    {
    return Ok(new
    {
    Error = "Wrong email or password!"
    });
    }
    else
    {
    string token = this.GetToken(40);

    db.TOKENS_Add(userId, token);
    db.SaveChanges();

    return Ok(new
    {
    Token = token
    });
    }
    }
    catch (Exception ex)
    {
    return new System.Web.Http.Results.ResponseMessageResult(Request.CreateErrorResponse((HttpStatusCode)400, new HttpError("Http error! " + ex.Message + " " + ex.InnerException.Message)));
    }
    }


    Now authorization via Google has been added to the website. So i need to add new method, that will check success or wrong authentication via Google. Website developer send me only access_token like this:



    Request:
    {
    "access_token": "ya47.Kdd_KeQ0mQiTzom20dQ6M83742KMYQpkCUqCZv0UbU2CjhMIuxIT5ugRXwIrOUcV-TGbUztMiRDRPzh0INrGgh7gqXyaIfyQAnNMmP0GhXRc6bbanEiPxV7fK9ss"
    }


    If there is possibility to check valid Google user with this request?










    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I have existsing C# ASP.NET WebAPI 2.0 project with a few methods for another website. This WebAPI project has no any authentication and returns JSON data. The first method takes two parameters from website: Email and Password then checks it in MS SQL table and returns JSON (success or wrong): if success then i create some token and add token with user_id to another MS SQL table. This method returns token if everything is ok.



          [HttpPost]
      [Route("api/v1/auth/email-login")]
      [ActionName("EmailLogin")]
      public IHttpActionResult Postpipeline_EmailLogin([FromBody] PostAuthItem postAuthItem)
      {
      try
      {
      int? userId = db.USERS_GetUserId(postAuthItem.Email, postAuthItem.Password).FirstOrDefault();
      if (userId == null)
      {
      return Ok(new
      {
      Error = "Wrong email or password!"
      });
      }
      else
      {
      string token = this.GetToken(40);

      db.TOKENS_Add(userId, token);
      db.SaveChanges();

      return Ok(new
      {
      Token = token
      });
      }
      }
      catch (Exception ex)
      {
      return new System.Web.Http.Results.ResponseMessageResult(Request.CreateErrorResponse((HttpStatusCode)400, new HttpError("Http error! " + ex.Message + " " + ex.InnerException.Message)));
      }
      }


      Now authorization via Google has been added to the website. So i need to add new method, that will check success or wrong authentication via Google. Website developer send me only access_token like this:



      Request:
      {
      "access_token": "ya47.Kdd_KeQ0mQiTzom20dQ6M83742KMYQpkCUqCZv0UbU2CjhMIuxIT5ugRXwIrOUcV-TGbUztMiRDRPzh0INrGgh7gqXyaIfyQAnNMmP0GhXRc6bbanEiPxV7fK9ss"
      }


      If there is possibility to check valid Google user with this request?










      share|improve this question













      I have existsing C# ASP.NET WebAPI 2.0 project with a few methods for another website. This WebAPI project has no any authentication and returns JSON data. The first method takes two parameters from website: Email and Password then checks it in MS SQL table and returns JSON (success or wrong): if success then i create some token and add token with user_id to another MS SQL table. This method returns token if everything is ok.



          [HttpPost]
      [Route("api/v1/auth/email-login")]
      [ActionName("EmailLogin")]
      public IHttpActionResult Postpipeline_EmailLogin([FromBody] PostAuthItem postAuthItem)
      {
      try
      {
      int? userId = db.USERS_GetUserId(postAuthItem.Email, postAuthItem.Password).FirstOrDefault();
      if (userId == null)
      {
      return Ok(new
      {
      Error = "Wrong email or password!"
      });
      }
      else
      {
      string token = this.GetToken(40);

      db.TOKENS_Add(userId, token);
      db.SaveChanges();

      return Ok(new
      {
      Token = token
      });
      }
      }
      catch (Exception ex)
      {
      return new System.Web.Http.Results.ResponseMessageResult(Request.CreateErrorResponse((HttpStatusCode)400, new HttpError("Http error! " + ex.Message + " " + ex.InnerException.Message)));
      }
      }


      Now authorization via Google has been added to the website. So i need to add new method, that will check success or wrong authentication via Google. Website developer send me only access_token like this:



      Request:
      {
      "access_token": "ya47.Kdd_KeQ0mQiTzom20dQ6M83742KMYQpkCUqCZv0UbU2CjhMIuxIT5ugRXwIrOUcV-TGbUztMiRDRPzh0INrGgh7gqXyaIfyQAnNMmP0GhXRc6bbanEiPxV7fK9ss"
      }


      If there is possibility to check valid Google user with this request?







      c# asp.net-web-api asp.net-identity google-oauth






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 22 at 9:48









      Konstantin

      67911027




      67911027
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          You can go directly though the Userinfo endpoint



          GET /userinfo/v2/me HTTP/1.1
          Host: www.googleapis.com
          Content-length: 0
          Authorization: Bearer 29.GltcBsh3Q-qbIEslOBcifBKlRh2GfE0-P11tDMgBx_WdWdH1TG6iWkDtzj0e_zIERaDyq6b_oseOIiSpG3iO0LIeQuAAyn5VVDe50WVmdtWhrMiN27wTsUJY0jxP


          This will return infomation about the user in question



          {
          "picture": "https://lh5.googleusercontent.com/-a1CWlFnA5xE/AAAAAAAAAAI/AAAAAAAAl1I/UcwPajZOuN4/photo.jpg",
          "name": "Linda Lawton",
          "family_name": "Lawton",
          "locale": "en",
          "gender": "female",
          "link": "https://plus.google.com/+LindaLawton",
          "given_name": "Linda",
          "id": "117200475532672775346"
          }





          share|improve this answer

















          • 1




            Remember that you are only going to be able to get information back about a user if you had requested one of the profile scopes. How are you authorizing this user?
            – DaImTo
            Nov 22 at 10:56










          • Solved! Thank you very much, Linda!
            – Konstantin
            Nov 22 at 14:46


















          up vote
          0
          down vote













          After a user successfully signs in, get the user's ID token:



          function onSignIn(googleUser) {
          var id_token = googleUser.getAuthResponse().id_token;
          ...
          }


          Then, send the ID token to your server with an HTTPS POST request:



          var xhr = new XMLHttpRequest();
          xhr.open('POST', 'https://yourbackend.example.com/tokensignin');
          xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
          xhr.onload = function() {
          console.log('Signed in as: ' + xhr.responseText);
          };
          xhr.send('idtoken=' + id_token);


          You can view the complete documentation in:
          Authenticate with a backend server






          share|improve this answer

















          • 1




            The question only mentions access token not Id token. I am not sure this answers the question asked.
            – DaImTo
            Nov 22 at 10:39











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53428070%2fadd-google-authentication-method-to-existing-asp-net-webapi-project%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          1
          down vote



          accepted










          You can go directly though the Userinfo endpoint



          GET /userinfo/v2/me HTTP/1.1
          Host: www.googleapis.com
          Content-length: 0
          Authorization: Bearer 29.GltcBsh3Q-qbIEslOBcifBKlRh2GfE0-P11tDMgBx_WdWdH1TG6iWkDtzj0e_zIERaDyq6b_oseOIiSpG3iO0LIeQuAAyn5VVDe50WVmdtWhrMiN27wTsUJY0jxP


          This will return infomation about the user in question



          {
          "picture": "https://lh5.googleusercontent.com/-a1CWlFnA5xE/AAAAAAAAAAI/AAAAAAAAl1I/UcwPajZOuN4/photo.jpg",
          "name": "Linda Lawton",
          "family_name": "Lawton",
          "locale": "en",
          "gender": "female",
          "link": "https://plus.google.com/+LindaLawton",
          "given_name": "Linda",
          "id": "117200475532672775346"
          }





          share|improve this answer

















          • 1




            Remember that you are only going to be able to get information back about a user if you had requested one of the profile scopes. How are you authorizing this user?
            – DaImTo
            Nov 22 at 10:56










          • Solved! Thank you very much, Linda!
            – Konstantin
            Nov 22 at 14:46















          up vote
          1
          down vote



          accepted










          You can go directly though the Userinfo endpoint



          GET /userinfo/v2/me HTTP/1.1
          Host: www.googleapis.com
          Content-length: 0
          Authorization: Bearer 29.GltcBsh3Q-qbIEslOBcifBKlRh2GfE0-P11tDMgBx_WdWdH1TG6iWkDtzj0e_zIERaDyq6b_oseOIiSpG3iO0LIeQuAAyn5VVDe50WVmdtWhrMiN27wTsUJY0jxP


          This will return infomation about the user in question



          {
          "picture": "https://lh5.googleusercontent.com/-a1CWlFnA5xE/AAAAAAAAAAI/AAAAAAAAl1I/UcwPajZOuN4/photo.jpg",
          "name": "Linda Lawton",
          "family_name": "Lawton",
          "locale": "en",
          "gender": "female",
          "link": "https://plus.google.com/+LindaLawton",
          "given_name": "Linda",
          "id": "117200475532672775346"
          }





          share|improve this answer

















          • 1




            Remember that you are only going to be able to get information back about a user if you had requested one of the profile scopes. How are you authorizing this user?
            – DaImTo
            Nov 22 at 10:56










          • Solved! Thank you very much, Linda!
            – Konstantin
            Nov 22 at 14:46













          up vote
          1
          down vote



          accepted







          up vote
          1
          down vote



          accepted






          You can go directly though the Userinfo endpoint



          GET /userinfo/v2/me HTTP/1.1
          Host: www.googleapis.com
          Content-length: 0
          Authorization: Bearer 29.GltcBsh3Q-qbIEslOBcifBKlRh2GfE0-P11tDMgBx_WdWdH1TG6iWkDtzj0e_zIERaDyq6b_oseOIiSpG3iO0LIeQuAAyn5VVDe50WVmdtWhrMiN27wTsUJY0jxP


          This will return infomation about the user in question



          {
          "picture": "https://lh5.googleusercontent.com/-a1CWlFnA5xE/AAAAAAAAAAI/AAAAAAAAl1I/UcwPajZOuN4/photo.jpg",
          "name": "Linda Lawton",
          "family_name": "Lawton",
          "locale": "en",
          "gender": "female",
          "link": "https://plus.google.com/+LindaLawton",
          "given_name": "Linda",
          "id": "117200475532672775346"
          }





          share|improve this answer












          You can go directly though the Userinfo endpoint



          GET /userinfo/v2/me HTTP/1.1
          Host: www.googleapis.com
          Content-length: 0
          Authorization: Bearer 29.GltcBsh3Q-qbIEslOBcifBKlRh2GfE0-P11tDMgBx_WdWdH1TG6iWkDtzj0e_zIERaDyq6b_oseOIiSpG3iO0LIeQuAAyn5VVDe50WVmdtWhrMiN27wTsUJY0jxP


          This will return infomation about the user in question



          {
          "picture": "https://lh5.googleusercontent.com/-a1CWlFnA5xE/AAAAAAAAAAI/AAAAAAAAl1I/UcwPajZOuN4/photo.jpg",
          "name": "Linda Lawton",
          "family_name": "Lawton",
          "locale": "en",
          "gender": "female",
          "link": "https://plus.google.com/+LindaLawton",
          "given_name": "Linda",
          "id": "117200475532672775346"
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 22 at 10:38









          DaImTo

          41.8k1056232




          41.8k1056232








          • 1




            Remember that you are only going to be able to get information back about a user if you had requested one of the profile scopes. How are you authorizing this user?
            – DaImTo
            Nov 22 at 10:56










          • Solved! Thank you very much, Linda!
            – Konstantin
            Nov 22 at 14:46














          • 1




            Remember that you are only going to be able to get information back about a user if you had requested one of the profile scopes. How are you authorizing this user?
            – DaImTo
            Nov 22 at 10:56










          • Solved! Thank you very much, Linda!
            – Konstantin
            Nov 22 at 14:46








          1




          1




          Remember that you are only going to be able to get information back about a user if you had requested one of the profile scopes. How are you authorizing this user?
          – DaImTo
          Nov 22 at 10:56




          Remember that you are only going to be able to get information back about a user if you had requested one of the profile scopes. How are you authorizing this user?
          – DaImTo
          Nov 22 at 10:56












          Solved! Thank you very much, Linda!
          – Konstantin
          Nov 22 at 14:46




          Solved! Thank you very much, Linda!
          – Konstantin
          Nov 22 at 14:46












          up vote
          0
          down vote













          After a user successfully signs in, get the user's ID token:



          function onSignIn(googleUser) {
          var id_token = googleUser.getAuthResponse().id_token;
          ...
          }


          Then, send the ID token to your server with an HTTPS POST request:



          var xhr = new XMLHttpRequest();
          xhr.open('POST', 'https://yourbackend.example.com/tokensignin');
          xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
          xhr.onload = function() {
          console.log('Signed in as: ' + xhr.responseText);
          };
          xhr.send('idtoken=' + id_token);


          You can view the complete documentation in:
          Authenticate with a backend server






          share|improve this answer

















          • 1




            The question only mentions access token not Id token. I am not sure this answers the question asked.
            – DaImTo
            Nov 22 at 10:39















          up vote
          0
          down vote













          After a user successfully signs in, get the user's ID token:



          function onSignIn(googleUser) {
          var id_token = googleUser.getAuthResponse().id_token;
          ...
          }


          Then, send the ID token to your server with an HTTPS POST request:



          var xhr = new XMLHttpRequest();
          xhr.open('POST', 'https://yourbackend.example.com/tokensignin');
          xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
          xhr.onload = function() {
          console.log('Signed in as: ' + xhr.responseText);
          };
          xhr.send('idtoken=' + id_token);


          You can view the complete documentation in:
          Authenticate with a backend server






          share|improve this answer

















          • 1




            The question only mentions access token not Id token. I am not sure this answers the question asked.
            – DaImTo
            Nov 22 at 10:39













          up vote
          0
          down vote










          up vote
          0
          down vote









          After a user successfully signs in, get the user's ID token:



          function onSignIn(googleUser) {
          var id_token = googleUser.getAuthResponse().id_token;
          ...
          }


          Then, send the ID token to your server with an HTTPS POST request:



          var xhr = new XMLHttpRequest();
          xhr.open('POST', 'https://yourbackend.example.com/tokensignin');
          xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
          xhr.onload = function() {
          console.log('Signed in as: ' + xhr.responseText);
          };
          xhr.send('idtoken=' + id_token);


          You can view the complete documentation in:
          Authenticate with a backend server






          share|improve this answer












          After a user successfully signs in, get the user's ID token:



          function onSignIn(googleUser) {
          var id_token = googleUser.getAuthResponse().id_token;
          ...
          }


          Then, send the ID token to your server with an HTTPS POST request:



          var xhr = new XMLHttpRequest();
          xhr.open('POST', 'https://yourbackend.example.com/tokensignin');
          xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
          xhr.onload = function() {
          console.log('Signed in as: ' + xhr.responseText);
          };
          xhr.send('idtoken=' + id_token);


          You can view the complete documentation in:
          Authenticate with a backend server







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 22 at 10:19









          Vahid Borandeh

          62




          62








          • 1




            The question only mentions access token not Id token. I am not sure this answers the question asked.
            – DaImTo
            Nov 22 at 10:39














          • 1




            The question only mentions access token not Id token. I am not sure this answers the question asked.
            – DaImTo
            Nov 22 at 10:39








          1




          1




          The question only mentions access token not Id token. I am not sure this answers the question asked.
          – DaImTo
          Nov 22 at 10:39




          The question only mentions access token not Id token. I am not sure this answers the question asked.
          – DaImTo
          Nov 22 at 10:39


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53428070%2fadd-google-authentication-method-to-existing-asp-net-webapi-project%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Trompette piccolo

          Slow SSRS Report in dynamic grouping and multiple parameters

          Simon Yates (cyclisme)