У нас есть приложение ASP.NET MVC 5
, и мы должны аутентифицировать пользователей через организацию, используя следующую информацию:
URI перенаправления, идентификатор клиента, секретный ключ, token_uri, resource_uri.
Там Есть несколько уроков, объясняющих это, например: Как реализовать сервер oauth2 в ASP. NET MVC 5 и WEB API 2 и Создание ASP. NET MVC 5 Приложение с Facebook, Twitter, LinkedIn и Google OAuth2 Sign-on (C#) , но большинство из них использует Azure
или Web API
, но я не хочу использовать API
или Azure
. Итак, как я могу реализовать это 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");
}