2

We have an ASP.NET MVC 5 app and need to authenticate users via an organization by using the following info:

Redirect Uri, Client Id, Secret Key, token_uri, resource_uri.

There are several tutorials explaining this e.g. How to implement oauth2 server in ASP.NET MVC 5 and WEB API 2 and Create an ASP.NET MVC 5 App with Facebook, Twitter, LinkedIn and Google OAuth2 Sign-on (C#) but most of them use Azure or Web API, but I do not want to use API or Azure. So, how can I implement this OAuth2 Authentication?

Update:

Here is my code using @WiktorZychla's tutorial. But id does not seem to work :(


web.config:

<system.web>
    <authentication mode="Forms">
      <forms name=".DemoAuthCookie" loginUrl="~/Account/Login" timeout="30" 
          slidingExpiration="true" protection="All" />
    </authentication>
</system.web>

View:

<button type="button" onclick="location.href='@Url.Action("Authorize", "Account")';
    return false;" />Login</button>

Controller:

public readonly GoogleClient gClient = new GoogleClient
{
    AuthorizationTracker = new MyAuthorizationTracker(),
    ClientIdentifier = "x...", //client id
    ClientCredentialApplicator = ClientCredentialApplicator.PostParameter("x...") //secret
};

[AllowAnonymous]
public ActionResult Authorize()
{
    IAuthorizationState authorization = gClient.ProcessUserAuthorization();

    // Is this a response from the Identity Provider
    if (authorization == null)
    {
        // no

        // Google will redirect back here
        Uri uri = new Uri("http://localhost:53105/Account/Login");

        // Kick off authorization request with OAuth2 scopes
        gClient.RequestUserAuthorization(returnTo: uri,
            scope: new[] { GoogleClient.OpenId, 
                GoogleClient.ProfileScope, GoogleClient.EmailScope });
    }
    else
    {
        // yes

        var request = WebRequest.Create(GoogleClient.ProfileEndpoint);

        // add an OAuth2 authorization header
        // if you get 403 here, turn ON Google+ API on your app settings page
        request.Headers.Add(
             HttpRequestHeader.Authorization,
             string.Format("Bearer {0}", Uri.EscapeDataString(authorization.AccessToken)));

        // Go to the profile API
        using (var response = request.GetResponse())
        {
            using (var responseStream = response.GetResponseStream())
            {
                var profile = GoogleProfileAPI.Deserialize(responseStream);
                if (profile != null &&
                    !string.IsNullOrEmpty(profile.email))
                    FormsAuthentication.RedirectFromLoginPage(profile.email, false);
            }
        }
    }

    return RedirectToAction("Index", "Home");
}
Jack
  • 1
  • 21
  • 118
  • 236
  • 1
    I wrote a [tutorial](https://www.wiktorzychla.com/2014/11/simple-oauth2-federated-authentication.html) years ago, it's still ok to do Oauth2 this way in a classic mvc5 app. – Wiktor Zychla Jan 09 '20 at 08:09
  • @WiktorZychla Thanks Wiktor, I also have seen some outdated tutorials. But if there is not any difference or update, I can use them. Is it good idea to use them or should I have a look at an updated version written for the last 1-2- years? – Jack Jan 09 '20 at 08:11
  • @WiktorZychla On the other hand, your code seems to be written for ASP.NET and I am not sure if it works for ASP.NET MVC. Any idea? – Jack Jan 09 '20 at 08:12
  • @DaImTo I think you directly voted down without reading the question title. I am looking for an implementation to the **existing** ASP.NET MVC project that may be a default MVC project given on the beginner tutorials. So, there is no need to post all of the unnecessary code here, right? – Jack Jan 09 '20 at 08:20
  • @WiktorZychla Any helps please? – Jack Jan 09 '20 at 08:23
  • @DaImTo What about this [How to implement custom authentication in ASP.NET MVC 5](https://stackoverflow.com/questions/31584506/how-to-implement-custom-authentication-in-asp-net-mvc-5)??? – Jack Jan 09 '20 at 08:37
  • this will work with MVC as well. Just think in terms of controllers/actions rather than pages and the code is the same. You redirect anonymous requests to a controller/action that does authentication where you copy-paste the code I show. We use this in multiple MVC apps. – Wiktor Zychla Jan 09 '20 at 08:44
  • @WiktorZychla If you would not mind, could you pls post the code on that page by modifying for ASP.NET MVC? – Jack Jan 09 '20 at 08:46
  • @DaImTo What about my last update? – Jack Jan 09 '20 at 09:30
  • I need to use custom API instead of Google API. How can I define a custom API in the code above? Maybe I need another definition instead of **GoogleClient**. – Jack Jan 09 '20 at 09:40
  • I think I need to use OWIN and make some changes i.e. adding Startup.Auth.cs file. Any idea? – Jack Jan 09 '20 at 09:59
  • Yes, you definitely need a custom definition of the OAuth2 client. – Wiktor Zychla Jan 09 '20 at 10:10
  • Yes, but how??? I encountered **'IAppBuilder' does not contain a definition for 'UseMicrosoftAccountAuthentication' and no accessible extension method 'UseMicrosoftAccountAuthentication' accepting a first argument of type 'IAppBuilder' could be found** error when using **app.UseMicrosoftAccountAuthentication** :( – Jack Jan 09 '20 at 11:14

0 Answers0