RingDotNetfor Ring

Identities and claims

Programs that have users need a way to say who the user is and what the user may do. .NET describes a user with claims — small statements such as a name, an e-mail address and a role. This lesson builds an identity, finds claims, checks roles and writes a permission check.

What you will learn#

ASP.NET Core uses exactly these classes for every login, so what you learn here is what a web program (the tutorial A web service with a database) receives after the user signed in. The tutorial Login, sessions and cookies made a login with a password hash; this lesson is about what happens after the login.

The program#

samples/UsingDotNet/tutorials/ch08_claims.ring
# identities and claims - ClaimsIdentity, ClaimsPrincipal, roles, claim types and a simple permission check
load "dotnet.ring"

using {
	"System"
	"System.Security.Claims"
}

func main

	# A claim is a statement about a user: a type and a value ("Role" = "Admin", "Email" = "ann@example.com").
	# An identity is a list of claims from one source; a principal holds identities. ASP.NET uses these classes for every login.
	oIdentity = new ClaimsIdentity().@New([ :authenticationType = "Password" ])
	oIdentity.AddClaim((new Claim).@New([ :type = "Name", :value = "Ann" ]))
	oIdentity.AddClaim((new Claim).@New([ :type = "Email", :value = "ann@example.com" ]))
	oIdentity.AddClaim((new Claim).@New([ :type = "Role", :value = "Editor" ]))
	oClaim = (new Claim).@New([ :type = "Role", :value = "Reviewer" ])
	oIdentity.AddClaim(oClaim)
	oPrincipal = new ClaimsPrincipal().@New([ :identity = oIdentity ])

	? "1. authentication type: " + oIdentity.AuthenticationType + ", authenticated: " + oIdentity.IsAuthenticated
	? "   claims: " + len(oIdentity.Claims.toList())
	aClaims = oIdentity.Claims.toList()
	for oClaim in aClaims
		? "      " + oClaim.Type + " = " + oClaim.Value
	next

	# 2. Find a claim: FindFirst gives the first claim of a type, FindAll all of them, HasClaim answers yes or no
	? nl + "2. email: " + oPrincipal.FindFirst("Email").Value
	cRoles = ""
	aRoles = oPrincipal.FindAll("Role").toList()
	for oRole in aRoles
		cRoles += oRole.Value + " "
	next
	? "   roles: " + cRoles
	? "   has claim Role=Editor: " + oPrincipal.HasClaim([ :type = "Role", :value = "Editor" ]) + ", has claim Role=Admin: " + oPrincipal.HasClaim([ :type = "Role", :value = "Admin" ])

	# 3. Roles: IsInRole looks at the claims of the role type. A new identity must say which claim type is the role.
	oRoleIdentity = new ClaimsIdentity().@New([ :authenticationType = "Password", :nameType = "Name", :roleType = "Role" ])
	oRoleIdentity.AddClaim((new Claim).@New([ :type = "Name", :value = "Ann" ]))
	oRoleIdentity.AddClaim((new Claim).@New([ :type = "Role", :value = "Editor" ]))
	oRolePrincipal = new ClaimsPrincipal().@New([ :identity = oRoleIdentity ])
	? nl + "3. name: " + oRoleIdentity.Name
	? "   is Editor: " + oRolePrincipal.IsInRole("Editor") + ", is Admin: " + oRolePrincipal.IsInRole("Admin")

	# 4. A permission check in Ring: the rules are data (what a role may do), the claims say who the user is
	aRules = [ :Editor = ["read","write"], :Reviewer = ["read","comment"], :Admin = ["read","write","delete"] ]
	? nl + "4. permissions of the user:"
	for cAction in ["read","write","comment","delete"]
		? "   " + cAction + ": " + mayDo(oPrincipal,aRules,cAction)
	next

# True when one of the roles of the principal allows the action
func mayDo oPrincipal, aRules, cAction

	aRoles = oPrincipal.FindAll("Role").toList()
	for oRole in aRoles
		aAllowed = aRules[lower(oRole.Value)]
		if not islist(aAllowed) loop
		but find(aAllowed,cAction) > 0
			return True
		ok
	next
	return False
Output
1. authentication type: Password, authenticated: 1
   claims: 4
      Name = Ann
      Email = ann@example.com
      Role = Editor
      Role = Reviewer

2. email: ann@example.com
   roles: Editor Reviewer 
   has claim Role=Editor: 1, has claim Role=Admin: 0

3. name: Ann
   is Editor: 1, is Admin: 0

4. permissions of the user:
   read: 1
   write: 1
   comment: 1
   delete: 0
Note

This program uses a generic function (dnNew) where a class cannot be used. The lesson The generic functions explains them.

How it works#

Claims, identities, principals#

A claim is one statement about a user: Name = Ann, Email = ann@example.com, Role = Editor. The type is just a text; .NET has standard names (ClaimTypes.Email is a long address-like text) but your own short names work in your own program. A user can have several claims of the same type, like the two roles here.

An identity is a list of claims that came from one source (a password login, a certificate, a token) together with the name of that source (AuthenticationType). A principal is the user as the program sees them, and can hold several identities. IsAuthenticated is true when the identity has an authentication type.

The constructors have several forms, so an identity is made with named values: new ClaimsIdentity().@New([ :authenticationType = "Password" ]).

Finding claims#

FindFirst(type) returns the first claim of that type (or null), FindAll(type) all of them as a collection (toList() gives a Ring list), and HasClaim answers yes or no. HasClaim has two forms, so it takes a list of names: [ :type = "Role", :value = "Editor" ].

Roles#

IsInRole("Editor") looks for a claim of the role type of the identity. The default role type is a long standard name, so an identity that uses its own type must say which one it is (:roleType = "Role"); the same goes for the type that Name reads (:nameType = "Name"). That is the usual reason for the question "why does IsInRole say no?".

Rules as data#

Step 4 keeps what a role may do in a Ring list (:Editor = ["read", "write"], ...) and the function mayDo asks: does any role of the user allow this action? The user has the roles Editor and Reviewer, so read, write and comment are allowed and delete is not. Rules in a list can be changed, saved (the tutorial Settings) and tested without changing the code, and this is the same idea as the policies of ASP.NET.

Warning

A claim is only as trustworthy as its source. Claims that come from the user (a form field, a cookie that is not signed) prove nothing. Build the identity on the server, from your own database, after you checked the password (the tutorial Login, sessions and cookies) — and check the permission on the server for every action, not only by hiding a button.

What you learned#

Exercises#

  1. Add the claim Department = Sales and write a rule that allows delete only for the Sales department.
  2. Make hasAllRoles(oPrincipal, aRoles).
  3. Serialize the claims of a user to JSON (the tutorial JSON as a tree) and build the identity again from the JSON.
  4. Make an identity with no authentication type and look at IsAuthenticated.

Next#

Rate limiting

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.