[英]Google OAuth 2.0 in .NET4 fails to create ServiceAccount on medium trust level server
我想閱讀.NET4.0 Web服務中的一些日歷事件。 因為沒有用戶參與,所以我使用了服務帳戶授權方法。 它在我的本地計算機上完美運行。 但是,當我要將其安裝在托管服務器上時,在創建證書時會遇到權限異常。 原因是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>( );
}
除了更改信任級別,我認為沒有其他解決方案。
“中等信任級別在托管服務器上很常見”聲明,盡管它曾經是真實的,但現在已經不復存在了。
ASP.NET
團隊已淘汰了Medium Trust
。 主要原因是最近幾年開始越來越多地使用反射。 在“中等信任度”中進行反思幾乎是不可能的。
您最好的解決方案,尤其是從長遠來看,是將其告知您的托管服務提供商,並尋找另一個提供商,以防他們拒絕為您提供完全信任。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.