Principal is just an old interface from Java SE 6.
As all interfaces without default implementation it simple defines some methods which are required to be implemented by the class which will implement that interface.
Those methods are
boolean equals(Object another)
Compares this principal to the specified object.
String getName()
Returns the name of this principal.
int hashCode()
Returns a hashcode for this principal.
String toString()
Returns a string representation of this principal.
As the Java Doc states :
This interface represents the abstract notion of a principal, which
can be used to represent any entity, such as an individual, a
corporation, and a login id.
In simple terms it is just used so that the implementer will have to implement this interface in a way that he makes an entity uniquely distingueed between other entities. Also the getName()
will have to return a value by which one specific entity is uniquely identified and does not collide with other entities.
So if the Principal
which is used is of type UserDetails
then the getName()
of Principal
returns the UserName
of UserDetails
.
If we see the implementation that Spring uses for AbstractAuthenticationToken.class
:
public String getName() {
if (this.getPrincipal() instanceof UserDetails) {
return ((UserDetails)this.getPrincipal()).getUsername();
} else if (this.getPrincipal() instanceof AuthenticatedPrincipal) {
return ((AuthenticatedPrincipal)this.getPrincipal()).getName();
} else if (this.getPrincipal() instanceof Principal) {
return ((Principal)this.getPrincipal()).getName();
} else {
return this.getPrincipal() == null ? "" : this.getPrincipal().toString();
}
}
Also is important to mention:
abstract class AbstractAuthenticationToken implements Authentication
and
interface Authentication extends Principal
Principal
Interface also ensures that the implementer will implement equals()
and hashCode()
which makes much sense because the entity of Principal that represents an Organization or a Company or a Person must have some way of being compared with other entities.