使用 Asp.net 4.0 实施 OAuth2

Implement OAuth2 with Asp.net 4.0

我有一个 .NET 4.0 应用程序,我需要添加具有第三层的 OAuth2 身份验证。我有点困惑(很难找到 .NET 4.0 的示例和文档)。

我可以将 Microsoft.AspNet.Membership.OpenAuth (OAuth 2.0) 与 Asp.net 4.0 (.NET 4.0) 一起使用吗?

我的另一个选择是使用 DotNetOpenAuth,但我很难找到 .NET 4.0 中的 Webforms 回调示例。

根据我的理解,我应该有一个身份验证页面(登录页面):

var medOK = new WebServerClient(GetAuthServerDescription(), clientIdentifier: "some client id");
medOK.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter("some secret code");

// CallBack
var state = new AuthorizationState();
var uri = Request.Url.AbsoluteUri;
uri = RemoveQueryStringFromUri(uri);
state.Callback = new Uri(uri); 
var accessTokenResponse = medOK.ProcessUserAuthorization();
if (accessTokenResponse != null){
    //If you have accesstoek then do something 
} else if (this.AccessToken == null) {
    // If we don't yet have access, immediately request it.
    medOK.PrepareRequestUserAuthorization(state);
    medOK.RequestUserAuthorization();
}

还有一个回调页面(假设是一个 ashx 页面):

var medOK = new WebServerClient(GetAuthServerDescription(), clientIdentifier: "some client id");
medOK.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter("some secret code");
var response = medOK.GetClientAccessToken();

// Then I get claims

明白吗? (我尽量简明扼要,没有写出我尝试过的所有内容,但如果需要我可以提供更多信息)

如果您使用的是 4.5 或更高版本,请按照许多网站博客中的描述使用 Owinpost,如果您使用 Visual Studio 2013+ 模板创建一个 Asp.net 项目,您将有一个示例如何实现,like mentioned here. Or you can use IdentityModel使用起来很简单

对于.NET 4.0,我结束了使用DotNetOpenAuth,它不是一个简单的方法来找到如何调用库,所以我会分享我的发现,第一步id获得用户授权。

var client = new WebServerClient(GetAuthServerDescription(), clientIdentifier: "client id");
client.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter("secrete");

// CallBack
uri = RemoveQueryStringFromUri(callBack);
state.Callback = new Uri(uri);
var accessTokenResponse = client.ProcessUserAuthorization();
if (accessTokenResponse != null){
    //If you have accesstoek then do something 
} else {
    // If we don't yet have access, immediately request it.
    client.PrepareRequestUserAuthorization(state).Send();
}

使用 GetAuthServerDescription 构建 AuthorizationServerDescription

回调方法 url 是一个简单的 post(获取令牌),因为我没有找到如何发送我需要发送给我的提供商的确切参数。