使用Asp.net 4.0实现OAuth2

时间:2016-02-10 21:20:19

标签: c# .net-4.0 oauth-2.0 owin dotnetopenauth

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

我可以在Asp.net 4.0(.NET 4.0)中使用Microsoft.AspNet.Membership.OpenAuth(OAuth 2.0)吗?

我的另一个选择是使用DotNetOpenAuth,但是我在.NET 4.0中找到一个回调for 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

制造敏感? (我试着简明扼要,不要写下我尝试的所有内容,但如果需要,我可以提供更多信息)

2 个答案:

答案 0 :(得分:3)

如果您使用4.5或更高版本使用Owin,如许多网站blogpost中所述,如果您使用Visual Studio 2013+模板创建Asp.net项目,您将获得如何实现它的示例like mentioned here。或者您可以使用易于使用的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

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

答案 1 :(得分:-5)

您应该阅读我的stackoverflow question以获取有用的指示。