将OAuth2身份验证添加到现有的ASP.NET MVC 5应用程序

时间:2020-01-09 08:05:09

标签: c# asp.net asp.net-mvc oauth oauth-2.0

我们有一个ASP.NET MVC 5应用,需要使用以下信息通过组织对用户进行身份验证:

重定向Uri,客户端ID,秘密密钥,token_uri,resource_uri。

有一些教程对此进行了说明,例如How to implement oauth2 server in ASP.NET MVC 5 and WEB API 2Create an ASP.NET MVC 5 App with Facebook, Twitter, LinkedIn and Google OAuth2 Sign-on (C#),但大多数使用AzureWeb API,但我不想使用APIAzure。那么,如何实现此OAuth2 Authentication

更新:

这是我使用@WiktorZychla的教程编写的代码。但是id似乎不起作用:(


web.config:

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

视图:

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

控制器:

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");
}

0 个答案:

没有答案