.NET exceptions I can throw for Not Authorized or Not Authenticated
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.
You could also use UnauthorizedAccessException for authorization violations
Use the C# AuthenticationException or InvalidCredentialException class.
https://docs.microsoft.com/en-us/dotnet/api/system.security.authentication.authenticationexception
To avoid reinventing the wheel, I'd use PrincipalPermission.Demand or PrincipalPermissionAttribute.
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 System.UnauthorizedAccessException, 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.