系列目录:

DotNetOpenAuth实践系列(源码在这里)

上一篇我们写了一个OAuth2的认证服务器,我们也获取到access_token,那么这个token怎么使用呢,我们现在就来揭开

一般获取access_token用处就是访问接口资源,不然也用不到怎么大费周章的还要获取个token再去访问资源

而接口有几类:

WCF服务接口,WebApi,还有自己用如ashx,aspx写的接口提供给前端调用的接口

其中WCF接口DotNetOpenAuth.Sample例子中已经做了

这些接口公开对外就需要一个认证的过程才能访问(当然内部或者内网使用的也不用这么麻烦,毕竟认证也是影响性能的)

废话不多说,我们下面开始搭建资源服务器

首先,搭建WCF服务接口的资源认证

一、创建WCF资源服务器项目

DotNetOpenAuth实践之WCF资源服务器配置-LMLPHP

2、添加DotNetOpenAuth到项目中

DotNetOpenAuth实践之WCF资源服务器配置-LMLPHP

3、添加WCF服务,为了方便,我们添加支持ajax的wcf服务

DotNetOpenAuth实践之WCF资源服务器配置-LMLPHP

4、重写ServiceAuthorizationManager

 using System;
using System.Collections.Generic;
using System.IdentityModel.Policy;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Security.Principal;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
using System.ServiceModel.Web;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OAuth2;
using ProtocolException = System.ServiceModel.ProtocolException; namespace WCFRescourcesServer.Code
{
public class IdefavAuthorizationManager : ServiceAuthorizationManager
{
public IdefavAuthorizationManager()
{
} protected override bool CheckAccessCore(OperationContext operationContext)
{
if (!base.CheckAccessCore(operationContext))
{
return false;
} var httpDetails = operationContext.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
var requestUri = operationContext.RequestContext.RequestMessage.Properties.Via; return Task.Run(async delegate
{
ProtocolFaultResponseException exception = null;
try
{
var principal = await VerifyOAuth2Async(
httpDetails,
requestUri,
operationContext.IncomingMessageHeaders.Action ?? operationContext.IncomingMessageHeaders.To.AbsolutePath);
if (principal != null)
{
var policy = new OAuthPrincipalAuthorizationPolicy(principal);
var policies = new List<IAuthorizationPolicy> { policy }; var securityContext = new ServiceSecurityContext(policies.AsReadOnly());
if (operationContext.IncomingMessageProperties.Security != null)
{
operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext;
}
else
{
operationContext.IncomingMessageProperties.Security = new SecurityMessageProperty
{
ServiceSecurityContext = securityContext,
};
} securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> { principal.Identity, }; return true;
}
else
{
return false;
}
}
catch (ProtocolFaultResponseException ex)
{ exception = ex;
}
catch (ProtocolException ex)
{ } if (exception != null)
{ // Return the appropriate unauthorized response to the client.
var outgoingResponse = await exception.CreateErrorResponseAsync(CancellationToken.None);
if (WebOperationContext.Current != null)
this.Respond(WebOperationContext.Current.OutgoingResponse, outgoingResponse);
} return false;
}).GetAwaiter().GetResult();
} private static async Task<IPrincipal> VerifyOAuth2Async(HttpRequestMessageProperty httpDetails, Uri requestUri, params string[] requiredScopes)
{
var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer((RSACryptoServiceProvider)Common.Configuration.SigningCertificate.PublicKey.Key, (RSACryptoServiceProvider)Common.Configuration.EncryptionCertificate.PrivateKey));
return await resourceServer.GetPrincipalAsync(httpDetails, requestUri, requiredScopes: requiredScopes);
} private void Respond(OutgoingWebResponseContext responseContext, HttpResponseMessage responseMessage)
{
responseContext.StatusCode = responseMessage.StatusCode;
responseContext.SuppressEntityBody = true;
foreach (var header in responseMessage.Headers)
{
responseContext.Headers[header.Key] = header.Value.First();
}
}
}
}

5、实现OAuthPrincipalAuthorizationPolicy接口

 namespace OAuthResourceServer.Code {
using System;
using System.Collections.Generic;
using System.IdentityModel.Claims;
using System.IdentityModel.Policy;
using System.Linq;
using System.Security.Principal;
using System.Web; public class OAuthPrincipalAuthorizationPolicy : IAuthorizationPolicy {
private readonly Guid uniqueId = Guid.NewGuid();
private readonly IPrincipal principal; /// <summary>
/// Initializes a new instance of the <see cref="OAuthPrincipalAuthorizationPolicy"/> class.
/// </summary>
/// <param name="principal">The principal.</param>
public OAuthPrincipalAuthorizationPolicy(IPrincipal principal) {
this.principal = principal;
} #region IAuthorizationComponent Members /// <summary>
/// Gets a unique ID for this instance.
/// </summary>
public string Id {
get { return this.uniqueId.ToString(); }
} #endregion #region IAuthorizationPolicy Members public ClaimSet Issuer {
get { return ClaimSet.System; }
} public bool Evaluate(EvaluationContext evaluationContext, ref object state) {
evaluationContext.AddClaimSet(this, new DefaultClaimSet(Claim.CreateNameClaim(this.principal.Identity.Name)));
evaluationContext.Properties["Principal"] = this.principal;
return true;
} #endregion
}
}

6、配置WCF

<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_OpenApi" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="" maxReceivedMessageSize="" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
<readerQuotas maxDepth="" maxStringContentLength="" maxArrayLength="" maxBytesPerRead="" maxNameTableCharCount="" />
<reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" />
<security mode="Message">
<transport clientCredentialType="Windows" proxyCredentialType="None" realm="" />
<message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="WCFRescourcesServer.OpenApiAspNetAjaxBehavior">
<enableWebScript />
</behavior>
<behavior name="WCFRescourcesServer.Services1Behavior"> </behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="myS">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
<serviceAuthorization serviceAuthorizationManagerType="WCFRescourcesServer.Code.IdefavAuthorizationManager, WCFRescourcesServer" principalPermissionMode="Custom" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<services>
<service name="WCFRescourcesServer.Service1" behaviorConfiguration="myS">
<endpoint address="" behaviorConfiguration="WCFRescourcesServer.Services1Behavior" binding="wsHttpBinding" contract="WCFRescourcesServer.IService1" />
</service>
</services>
</system.serviceModel>

下面这段是关键的一句,配置WCF访问验证

<serviceAuthorization serviceAuthorizationManagerType="WCFRescourcesServer.Code.IdefavAuthorizationManager, WCFRescourcesServer" principalPermissionMode="Custom"/>

二、创建WCFClient访问WCF服务

创建一个IdefavOAuth2Client的Asp.net项目然后添加服务器引用

DotNetOpenAuth实践之WCF资源服务器配置-LMLPHP

访问WCF代码如下:

 protected async void Button1_Click(object sender, EventArgs e)
{
var authServer = new AuthorizationServerDescription()
{ TokenEndpoint = new Uri("http://localhost:53022/OAuth/token "),
ProtocolVersion = ProtocolVersion.V20
};
//var wcf= new UserAgentClient(authServer, "idefav", "1");
WebServerClient Client= new WebServerClient(authServer, "idefav", ""); var code =await Client.GetClientAccessTokenAsync(new string[] { "http://localhost:55044/IService1/DoWork" });
string token = code.AccessToken;
Service1Reference.Service1Client service1Client=new Service1Client();
var httpRequest = (HttpWebRequest)WebRequest.Create(service1Client.Endpoint.Address.Uri);
ClientBase.AuthorizeRequest(httpRequest,token);
var httpDetails = new HttpRequestMessageProperty();
httpDetails.Headers[HttpRequestHeader.Authorization] = httpRequest.Headers[HttpRequestHeader.Authorization]; using (var scope = new OperationContextScope(service1Client.InnerChannel))
{ if (OperationContext.Current.OutgoingMessageProperties.ContainsKey(HttpRequestMessageProperty.Name))
{
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpDetails;
}
else
{
OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpDetails);
} Button1.Text= service1Client.DoWork();
} }

注意:

DotNetOpenAuth实践之WCF资源服务器配置-LMLPHP

标示的地方是可以从服务引用生成的代码上面看的到

DotNetOpenAuth实践之WCF资源服务器配置-LMLPHP

当然这个Scope可以在WCF中配置

DotNetOpenAuth实践之WCF资源服务器配置-LMLPHP

如果这里客户端和资源服务器不一致也会拒绝访问

我们来测试一下,把端口改成55045然后运行项目

DotNetOpenAuth实践之WCF资源服务器配置-LMLPHP

结果:

DotNetOpenAuth实践之WCF资源服务器配置-LMLPHP

最后,还有个注意点

DotNetOpenAuth v5.0.0-alpha3 从Nuget上面安装的有Bug,需要去github下载源代码然后编译成dll替换掉Nuget的dll

DotNetOpenAuth实践之WCF资源服务器配置-LMLPHP

我已经编译好了一份,百度网盘:

链接:http://pan.baidu.com/s/1jGlMZye 密码:hw2o

这里的是WCF资源服务器以及客户端访问

下篇将会讲WebAPI形式的资源服务器

04-15 06:47
查看更多