谷歌OAuth 2.0 in .NET4 无法在中等信任级别服务器上创建服务帐户
本文关键字:服务器 信任 创建 服务 OAuth in NET4 谷歌 | 更新日期: 2023-09-27 18:32:36
我想在 .NET4.0 网络服务。由于不涉及任何用户,因此我使用了服务帐户授权方法。它在我的本地机器上完美运行。但是当我想在托管服务器上安装它时,我在创建证书时收到权限异常。原因是 Web 服务的中等信任级别。但该级别在托管服务器上很常见。是否有其他方法可以访问在中等信任级别服务器上工作的 api?
这是我的内部服务代码:
public static List<CalendarEventObject> GetEvents( string calendarName, int maxToGet, out string error )
{
string done = "";
error = "";
try
{
// access google api with service account
String serviceAccountEmail = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@developer.gserviceaccount.com";
var p12File = System.Web.HttpContext.Current.Server.MapPath( "./bin/MyAppsServiceAccountFileFromGoogleDeveoperConsole.p12" );
done += "maped certificate: " + p12File;
// this needs System.Security.Permissions.KeyContainerPermission permission,
// that is not inside medium trust (nor inside high trust)
var certificate = new X509Certificate2( p12File
, "notasecret"
, X509KeyStorageFlags.MachineKeySet |
X509KeyStorageFlags.PersistKeySet |
X509KeyStorageFlags.Exportable ); // tried several storage flags with no success
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer( serviceAccountEmail )
{
Scopes = new[] { CalendarService.Scope.Calendar }
}.FromCertificate( certificate ) );
// Create the service.
var service = new CalendarService( new BaseClientService.Initializer( )
{
HttpClientInitializer = credential,
ApplicationName = "MyCalendarReader",
} );
done += "service created ";
// Fetch the list of calendar list
var list = service.CalendarList.List( ).Execute( ).Items;
done += "CalendarList loaded ";
if ( list.Count == 0 ) throw new Exception( "CalendarList returned none" );
bool found = false;
List<string> calendars = new List<string>( );
foreach ( var calendarListEntry in list )
{
calendars.Add( calendarListEntry.Summary );
if ( calendarListEntry.Summary == calendarName )
{
found = true;
return ExtractEvents( service, calendarListEntry, maxToGet );
}
}
if ( !found )
{
throw new Exception( "No matching calendar: " + String.Join( ";", calendars ) );
}
}
catch ( Exception ex )
{
error = String.Format( "'nDone:{0}'n msg:{1}'n inner:{2}'n stack:{3}", done, ex.Message, ex.InnerException != null ? ex.InnerException.Message : "none", ex.StackTrace );
}
return new List<CalendarEventObject>( );
}
我认为除了
更改信任级别之外,没有其他方法可以解决您的问题。
"中等信任级别在托管服务器上很常见"声明,虽然它曾经是正确的 - 但现在不是了。
Medium Trust
已被ASP.NET
团队淘汰。主要原因是反射在过去几年中开始被更多地使用。在中等信任中进行反思几乎是不可能的。
您最好的解决方案,尤其是从长远来看,是告诉您的托管服务提供商,并寻找另一个提供商,以防他们拒绝为您提供完全信任。
PS:ASP.NET 部分信任不保证应用程序隔离