Password Policy
From Sense/Net Wiki
Revision as of 22:05, 27 January 2012 by Dobsonl (Talk | contribs) (→Customizing Field validation messages)
- draft
- 6.0.8
- Enterprise
- Community
Planned
Overview
Sense/Net provides means for developers to define custom password-checking rules, password policies. It is possible to fully customize password validation on server-side.
Details
To customize password validation rules, you have to create a custom PasswordFieldSetting class and set it in the CTD for the User type:
<Field name="Password" type="Password"> <DisplayName>Password</DisplayName> <Description>User password</Description> <Bind property="PasswordHash"></Bind> <Configuration handler="SenseNet.ContentRepository.Fields.MyPasswordFieldSetting"> <Compulsory>true</Compulsory> </Configuration> </Field>
To implement the custom logic simply derive from PasswordFieldSetting and override the CheckPassword method. Incoming parameters are current password and the list of old passwords with password modification dates. Your method should return a PasswordCheckResult object with the following properties:
- Valid: a bool indicating weather the password is accepted or not,
- Message: a message to be displayed in case the password is not accepted,
- Score: an optional integer value indicating the strength of the password.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SenseNet.ContentRepository.Fields { public class MyPasswordFieldSetting : PasswordFieldSetting { public override PasswordCheckResult CheckPassword(string password, List<PasswordField.OldPasswordData> oldPasswords) { return new PasswordCheckResult { Message = "Never good.", Valid = false }; } } }
Examples
Checking previous passwords
public virtual PasswordCheckResult CheckPassword(string password, List<PasswordField.OldPasswordData> oldPasswords) { var hashed = User.EncodePassword(password); var passwords = oldPasswords.OrderBy(k => k.ModificationDate).ToList(); if (passwords[passwords.Count - 1].Hash == hashed || passwords[passwords.Count - 2].Hash == hashed) return new PasswordCheckResult { Valid = false, Message = "Password cannot be the same as one of the previous 2 passwords!" }; // default password check: every password is considered valid return new PasswordCheckResult { Valid = true }; }
Customizing Field validation messages
Override the ShowErrorMessage function in your custom Field Control in order to display Score data next to the password:
protected override void ShowErrorMessage() { var c = this.FindControlRecursive("ErrorPlaceHolder") as PlaceHolder; if (c == null) return; var validationResult = this.Field.ValidationResult as PasswordFieldValidationResult; var checkResult = validationResult.CheckResult; c.Visible = true; var errorMessageControl = this.FindControlRecursive("ErrorLabel") as Label; if (errorMessageControl != null) errorMessageControl.Text = ErrorMessage + " Score: " + checkResult.Score.ToString(); }