(i) Authentication and authorization
The two basic pillars of security are authentication and authorization. Authentication is the process of identifying a user, and authorization is performed after verifying that the identified user can access the attribute resource.
1. Identification and Principal
Use identity to validate the user running the application. Principal is an object that contains the user's identity and the role that the user belongs to.
AppDomain.CurrentDomain.SetPrincipalPolicy (principalpolicy.windowsprincipal);varPrincipal = Windowsprincipal.current asWindowsPrincipal;varIdentity = Principal. Identity asWindowsIdentity; Console.WriteLine ("identity type: {0}", identity. ToString ()); Console.WriteLine ("name: {0}", identity. Name); Console.WriteLine ("whether the role is user: {0}", Principal. IsInRole (Windowsbuiltinrole.user)); Console.WriteLine ("whether the role is super administrator: {0}", Principal. IsInRole (Windowsbuiltinrole.administrator)); Console.WriteLine ("authentication: {0}", identity. isauthenticated); Console.WriteLine ("Authentication type: {0}", identity. AuthenticationType); Console.WriteLine ("anonymous: {0}", identity. isanonymous); Console.WriteLine ("account tag: {0}", identity. Token);
2. Role
Role-based security can be a good solution to resource access issues.
3. Declaring role-based security
If you run the following code with an account in a non-local user group, the ShowMessage () method throws an exception.
Static voidMain (string[] args) {AppDomain.CurrentDomain.SetPrincipalPolicy (Principalpolicy.windowsprincipal); Try{showmessage (); } Catch(SecurityException exception) {Console.WriteLine ("Catch Security Exception: ({0})", exception. Message); Console.WriteLine ("The current principal should be placed in the local user group"); } console.readkey ();} [PrincipalPermission (Securityaction.demand,role="builtin\\users")]Private Static voidShowMessage () {Console.WriteLine ("The current principal is logged on locally"); Console.WriteLine ("(Member in local user group is)");}
4. Claims
In addition to using roles, you can use claims to access user information. The ability to describe an entity in relation to an entity. An entity is usually a user, or it can be an application. Capabilities describe the actions that an entity allows to perform. This claim is much more flexible than the character model.
varPrincipal = Windowsprincipal.current asClaimsPrincipal; Console.WriteLine (); Console.WriteLine ("gets a collection that contains all the claims that are derived from the claims identifier associated with this claim principal. ");foreach(varClaiminchprincipal. Claims) {Console.WriteLine ("subject: {0}", claim. Subject) Console.WriteLine ("issuer: {0}", claim. Issuer); Console.WriteLine ("claim type: {0}", claim. Type); Console.WriteLine ("value type: {0}", claim. ValueType); Console.WriteLine ("value: {0}", claim. Value); foreach(varPropinchclaim. Properties) {Console.WriteLine ("\ t property: {0} {1}", Prop. Key, Prop. Value); } Console.WriteLine ();}
5. Client Application Services
Code too long not posted in the article
Server Source: Download
Client Source: Download
Before you run it, be aware that the Client App. Config is modifying the connection location for the Serviceuri to run on the server, example: Serviceuri in source code is serviceuri= "http://localhost:59514/ Role_json_appservice.axd ", to modify the link address (assuming http://localhost:9999/) plus role_json_appservice.axd for you to run the site later, the final serviceuri=" Http://localhost:9999/Role_JSON_Appservice.axd ".
(ii) encryption
1. Signature
1 Internal StaticCngKey alicekeysignature;2 Internal Static byte[] Alicepubkeyblob;3 Static voidMain (string[] args)4 {5 Createkeys ();6 7 byte[] Alicedata = Encoding.UTF8.GetBytes ("Alice");8 byte[] Alicesignature =createsignatrue (alicedata,alicekeysignature);9 TenConsole.WriteLine ("Alice created the signature: {0}", Convert.tobase64string (alicesignature)); One A if(VerifySignature (ALICEDATA,ALICESIGNATURE,ALICEPUBKEYBLOB)) - { -Console.WriteLine ("Alice's signature verification succeeded"); the } - - Console.readkey (); - } + - Private Static BOOLVerifySignature (byte[] Data,byte[] Signature,byte[] pubkey) + { A BOOLRetValue =false; at using(CngKey key =Cngkey.import (PubKey, Cngkeyblobformat.genericpublicblob)) - using(varSigningalg =NewECDsaCng (key)) - { -RetValue =signingalg.verifydata (data, signature); - signingalg.clear (); - } in returnRetValue; - } to + Private Static byte[] Createsignatrue (byte[] data, CngKey key) - { the byte[] signature; * using(varsigningalg=NewECDsaCng (key)) $ {Panax NotoginsengSignature =signingalg.signdata (data); - signingalg.clear (); the } + returnsignature; A } the + - Private Static voidCreatekeys () $ { $Alicekeysignature =cngkey.create (cngalgorithm.ecdiffiehellmanp256); -Alicepubkeyblob =Alicekeysignature.export (CNGKEYBLOBFORMAT.GENERICPUBLICBLOB); -}
2. Exchange secret key and secure transmission
Use the Diffiehellman algorithm to exchange a symmetric secret key for secure transmission.
(iii) Access control of resources
In the operating system, resources are protected using access control lists (ACLs). The resource has an associated security descriptor. The security descriptor contains information about the resource owner and references two access control lists: A discretionary access control list (DACL, which determines who has access), and a system access control list (SACL, which determines the audit rules for the security event log). ACLs contain a list of access control entries (Aces, containing types, security identifiers, and permissions). In a DACL, the type of ACE can be either allow access or deny access. The permissions that can be set and obtained with the file are create, read, write, delete, modify, change the license, and obtain permission.
Get a list of access controls for a file:
Static voidMain (string[] args) { stringFileName =@"C:\Users\Administrator\Desktop\1.txt"; using(FileStream fs=File.Open (Filename,filemode.open)) {filesecurity SecurityDescriptor=FS. GetAccessControl (); Authorizationrulecollection rules= Securitydescriptor.getaccessrules (true,true,typeof(NTAccount)); foreach(AuthorizationRule ruleinchrules) { varfilerule = Rule asFileSystemAccessRule; Console.WriteLine ("access type: {0}", Filerule.accesscontroltype); Console.WriteLine ("permissions: {0}", filerule.filesystemrights); Console.WriteLine ("identity: {0}", FileRule.IdentityReference.Value); Console.WriteLine (); } }}
Modify access Rights reference:http://www.cnblogs.com/wolf-sun/p/4591734.html
(v) Code access security
In role-based security, you can define what the user is allowed to do. In code-based security, you can specify what the code can do.
1.2nd Level Safety Transparency
Use the Securityrules attribute to annotate the assembly and set Securityruleset.level2 to apply the. NET4 new level.
[Assembly:securityrules (Securityruleset.level2)]
2. Permissions
If the code is running in a sandbox, the sandbox can be defined. NET permissions to define the actions that the code allows to perform. Permissions are actions that allow (or disallow) the execution of each code group (for example: reading a file from a file system) ... NET permissions are independent of operating system permissions. NET permissions are only validated by the CLR.
(1) Permission set
A permission set is a collection of permissions.
(2) require permission by programming
Assemblies can require permissions in a declarative or programmatic manner.
(3) Using the sandbox API to include unauthorized code
(v) Publishing code using certificates
You can use a digital certificate to sign an assembly so that the consumer of the software verifies the identity of the software publisher.
"Reading notes" C # Advanced Programming Chapter 22nd Security