.NET exceptions I can throw for Not Authorized or Not Authenticated

C#ExceptionAuthenticationAuthorization

C# Problem Overview


I have parts of code where I want to throw an Exception whenever a user is not authenticated/not authorized.

So instead of writing my own NotAuthenticatedException and NotAuthorizedException, I was wondering if there are not already some C# standards for these.

I can imagine a lot of programs throw similar Exceptions, and it would not be very useful if everyone 'writes their own wheel' again.

C# Solutions


Solution 1 - C#

You could also use UnauthorizedAccessException for authorization violations

Solution 2 - C#

Solution 3 - C#

To avoid reinventing the wheel, I'd use http://msdn.microsoft.com/en-us/library/system.security.permissions.principalpermission.demand.aspx">PrincipalPermission.Demand</a> or http://msdn.microsoft.com/en-us/library/system.security.permissions.principalpermissionattribute.aspx">PrincipalPermissionAttribute</a>;.

A SecurityException will be thrown for you if the demand fails.

If you do want to explicitly throw an exception rather than using PrincipalPermission.Demand, you could consider reusing the existing type http://msdn.microsoft.com/en-us/library/system.unauthorizedaccessexception.aspx">System.UnauthorizedAccessException</a>;, which is described in MSDN as:

> The exception that is thrown when the operating system denies access because of an I/O error or a specific type of security error.

It's your app rather than the OS that's denying access, but perhaps close enough.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDirk BoerView Question on Stackoverflow
Solution 1 - C#Gruff BunnyView Answer on Stackoverflow
Solution 2 - C#DarrenView Answer on Stackoverflow
Solution 3 - C#JoeView Answer on Stackoverflow