Code:
/ FX-1434 / FX-1434 / 1.0 / untmp / whidbey / REDBITS / ndp / clr / src / BCL / System / Security / Principal / WindowsImpersonationContext.cs / 1 / WindowsImpersonationContext.cs
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//
// WindowsImpersonationContext.cs
//
// Representation of an impersonation context.
//
namespace System.Security.Principal
{
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Runtime.ConstrainedExecution;
[System.Runtime.InteropServices.ComVisible(true)]
public class WindowsImpersonationContext : IDisposable {
private SafeTokenHandle m_safeTokenHandle = SafeTokenHandle.InvalidHandle;
private WindowsIdentity m_wi;
private FrameSecurityDescriptor m_fsd;
private WindowsImpersonationContext () {}
internal WindowsImpersonationContext (SafeTokenHandle safeTokenHandle, WindowsIdentity wi, bool isImpersonating, FrameSecurityDescriptor fsd) {
// make this a no-op on Win98 so calling code does not have to special case down-level platforms.
if (WindowsIdentity.RunningOnWin2K) {
if (safeTokenHandle.IsInvalid)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidImpersonationToken"));
if (isImpersonating) {
if (!Win32Native.DuplicateHandle(Win32Native.GetCurrentProcess(),
safeTokenHandle,
Win32Native.GetCurrentProcess(),
ref m_safeTokenHandle,
0,
true,
Win32Native.DUPLICATE_SAME_ACCESS))
throw new SecurityException(Win32Native.GetMessage(Marshal.GetLastWin32Error()));
m_wi = wi;
}
m_fsd = fsd;
}
}
// Revert to previous impersonation (the only public method).
public void Undo () {
// make this a no-op on Win98 so calling code does not have to special case down-level platforms.
if (!WindowsIdentity.RunningOnWin2K)
return;
int hr = 0;
if (m_safeTokenHandle.IsInvalid) { // the thread was not initially impersonating
hr = Win32.RevertToSelf();
if (hr < 0)
throw new SecurityException(Win32Native.GetMessage(hr));
} else {
hr = Win32.RevertToSelf();
if (hr < 0)
throw new SecurityException(Win32Native.GetMessage(hr));
hr = Win32.ImpersonateLoggedOnUser(m_safeTokenHandle);
if (hr < 0)
throw new SecurityException(Win32Native.GetMessage(hr));
}
WindowsIdentity.UpdateThreadWI(m_wi);
if (m_fsd != null)
m_fsd.SetTokenHandles(null, null);
}
// Non-throwing version that does not new any exception objects. To be called when reliability matters
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal bool UndoNoThrow()
{
bool bRet = false;
try{
// make this a no-op on Win98 so calling code does not have to special case down-level platforms.
if (!WindowsIdentity.RunningOnWin2K)
return true;
int hr = 0;
if (m_safeTokenHandle.IsInvalid)
{ // the thread was not initially impersonating
hr = Win32.RevertToSelf();
}
else
{
hr = Win32.RevertToSelf();
if (hr >= 0)
hr = Win32.ImpersonateLoggedOnUser(m_safeTokenHandle);
}
bRet = (hr >= 0);
if (m_fsd != null)
m_fsd.SetTokenHandles(null,null);
}
catch
{
bRet = false;
}
return bRet;
}
//
// IDisposable interface.
//
[ComVisible(false)]
protected virtual void Dispose(bool disposing) {
if (disposing) {
if (m_safeTokenHandle != null && !m_safeTokenHandle.IsClosed) {
Undo();
m_safeTokenHandle.Dispose();
}
}
}
[ComVisible(false)]
public void Dispose () {
Dispose(true);
}
}
}
Link Menu

This book is available now!
Buy at Amazon US or
Buy at Amazon UK
- CodeCommentStatementCollection.cs
- CorePropertiesFilter.cs
- GenericTextProperties.cs
- GrabHandleGlyph.cs
- DbConnectionPoolGroup.cs
- WebPartsPersonalization.cs
- DbProviderServices.cs
- HtmlInputHidden.cs
- MetadataArtifactLoaderResource.cs
- ScrollBar.cs
- HttpStaticObjectsCollectionBase.cs
- EncoderBestFitFallback.cs
- WorkflowStateRollbackService.cs
- DataGridViewColumnCollection.cs
- ObjectMemberMapping.cs
- SelectionChangedEventArgs.cs
- ExpressionEvaluator.cs
- Style.cs
- DownloadProgressEventArgs.cs
- UshortList2.cs
- RectAnimation.cs
- XPathPatternParser.cs
- RelationshipConverter.cs
- ToolboxComponentsCreatedEventArgs.cs
- PropertyNames.cs
- FileRecordSequenceCompletedAsyncResult.cs
- TextBoxBase.cs
- XsltArgumentList.cs
- WebColorConverter.cs
- PointCollection.cs
- DataGridCaption.cs
- XmlLinkedNode.cs
- ContainerUIElement3D.cs
- SessionPageStatePersister.cs
- BoundField.cs
- EditableLabelControl.cs
- XpsDocumentEvent.cs
- ImplicitInputBrush.cs
- Buffer.cs
- QilStrConcat.cs
- MdImport.cs
- RawTextInputReport.cs
- ChannelPool.cs
- TypeUsageBuilder.cs
- DelegatingChannelListener.cs
- CompilerCollection.cs
- SQLInt64Storage.cs
- InternalConfigHost.cs
- OptimisticConcurrencyException.cs
- MasterPageParser.cs
- SingleStorage.cs
- BoolLiteral.cs
- TcpSocketManager.cs
- HttpsTransportBindingElement.cs
- ContainerFilterService.cs
- ArgumentOutOfRangeException.cs
- SiteMapNodeCollection.cs
- SmiEventSink_DeferedProcessing.cs
- BrowserDefinition.cs
- XPathQilFactory.cs
- HeaderedContentControl.cs
- ExtensionQuery.cs
- EmbeddedMailObject.cs
- HtmlTitle.cs
- Component.cs
- DataGridView.cs
- ScrollBar.cs
- PriorityBinding.cs
- SourceFileBuildProvider.cs
- ProxyGenerationError.cs
- SmtpSection.cs
- ChildTable.cs
- GridViewHeaderRowPresenter.cs
- ExtensionSurface.cs
- MemoryMappedFile.cs
- BooleanFacetDescriptionElement.cs
- ArrangedElementCollection.cs
- UrlPropertyAttribute.cs
- BitArray.cs
- HttpRuntime.cs
- QueueProcessor.cs
- Line.cs
- InstanceStoreQueryResult.cs
- PathTooLongException.cs
- Constraint.cs
- login.cs
- DrawingGroupDrawingContext.cs
- StylusShape.cs
- InertiaTranslationBehavior.cs
- EntityDataSourceWrapperPropertyDescriptor.cs
- BindingOperations.cs
- TextParaLineResult.cs
- GroupBox.cs
- WebPartExportVerb.cs
- WebResourceUtil.cs
- FilterElement.cs
- backend.cs
- AssemblyInfo.cs
- MemberInfoSerializationHolder.cs
- MobileListItem.cs