.NET exceptions I can throw for Not Authorized or Not Authenticated
C#ExceptionAuthenticationAuthorizationC# 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#
Use the C# AuthenticationException or InvalidCredentialException class.
https://docs.microsoft.com/en-us/dotnet/api/system.security.authentication.authenticationexception
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.