ASP.NET MVC WEB API OAuth2Authorize

using System ;
using System.Net ;
using System.Security.Cryptography ;
using System.Security.Cryptography.X509Certificates ;
using System.Security.Principal ;
using System.ServiceModel.Channels ;
using System.Threading ;
using System.Web.Http ;
using System.Web.Http.Controllers ;
using System.Web.Http.Filters ;
using DotNetOpenAuth.OAuth2 ;
 
namespace ProjectName.Web.Controllers.ActionFilters
{
/// <summary>
/// ActionFilter to authorize requests using OAuth2
/// </summary>
public class OAuth2Authorize : AuthorizationFilterAttribute
{
/// <summary>
/// Called when [authorization].
/// </summary>
/// <param name="actionContext">The action context.</param>
public override void OnAuthorization ( HttpActionContext actionContext )
{
// get public / private key from certificate
var store = new X509Store ( StoreLocation . LocalMachine );
store . Open ( OpenFlags . ReadOnly );
var certCollection = store . Certificates ;
var currentCerts = certCollection . Find ( X509FindType . FindByTimeValid , DateTime . Now , false );
var signingCert = currentCerts . Find ( X509FindType . FindBySubjectDistinguishedName , "CN=*.yourdomain.com, OU=Domain Control Validated, O=*.yourdomain.com" , false );
var cert = signingCert [ 0 ];
store . Close ();
 
var publicKey = ( RSACryptoServiceProvider ) cert . PublicKey . Key ;
var privateKey = ( RSACryptoServiceProvider ) cert . PrivateKey ;
 
using ( var signing = publicKey )
using ( var encrypting = privateKey )
{
base . OnAuthorization ( actionContext );
 
// TODO FIXME dnoa doesn't support HttpRequestMessage - manually creating HttpRequestMessageProperty until they do
var request = new HttpRequestMessageProperty ();
request . Headers [ HttpRequestHeader . Authorization ] = actionContext . Request . Headers . Authorization . ToString ();
var requestUri = actionContext . Request . RequestUri ;
 
var resourceServer = new ResourceServer ( new StandardAccessTokenAnalyzer ( signing , encrypting ));
IPrincipal result ;
 
var response = resourceServer . VerifyAccess ( request , requestUri , out result );
 
if ( response != null )
{
actionContext . Response = actionContext . ControllerContext . Request . CreateResponse ( HttpStatusCode . Forbidden );
return ;
}
 
var principal = null ; // create your principal using result.Identity.Name if needed
Thread . CurrentPrincipal = principal ;
}
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值