我正在使用Keycloak admin API创建新用户。 在创建用户之前,如何检查给定的密码确实符合领域密码策略?
我正在使用以下代码:
const locations=[{id:1,name:"Western province",parent_region_id:null},{id:2,name:"Southern province",parent_region_id:null},{id:3,name:"Central province",parent_region_id:null},{id:4,name:"Colombo district",parent_region_id:1},{id:5,name:"Galle district",parent_region_id:2},{id:6,name:"Kandy district",parent_region_id:3},{id:7,name:"Maharagama",parent_region_id:4},{id:8,name:"Nugegoda",parent_region_id:4},{id:9,name:"Peradeniya",parent_region_id:6},]
const res = locations
.filter(({parent_region_id})=>parent_region_id!==null)
.filter(({parent_region_id},i,a)=>{
return a.findIndex(l=>l.id === parent_region_id) > -1;
});
console.log(res);
上述代码的问题是,如果给定的密码不符合密码策略,则方法“ resetPassword”将失败,但是此时用户已经在密钥斗篷中创建,因此我必须删除它,因为没有办法“回滚”。
另一个选项是在创建用户之前检查密码是否正确。但是我该怎么办?
答案 0 :(得分:0)
UserResource具有getUsers()方法,用于按用户名查找用户并检查其属性。 如果resetPassword失败,则可以找到用户,并根据需要应用检查,然后再次进行resetPassword。
答案 1 :(得分:0)
您将获得验证失败消息,如JSON Object
{"error":"invalidPasswordMinLengthMessage","error_description":"Invalid password: minimum length 8."}
我使用以下代码从ClientErrorException
读取验证失败消息
public void resetUserInvalidPassword() {
String userId = createUser("user1", "user1@localhost");
try {
CredentialRepresentation cred = new CredentialRepresentation();
cred.setType(CredentialRepresentation.PASSWORD);
cred.setValue(" ");
cred.setTemporary(false);
realm.users().get(userId).resetPassword(cred);
} catch (ClientErrorException e) {
Response response = e.getResponse();
System.out.println(getErrorMessage(response));
response.close();
}
}
private String getErrorMessage(Response response) {
Object entity = response.getEntity();
String errorMessage = "(none)";
if (entity instanceof ErrorRepresentation)
errorMessage = ((ErrorRepresentation) entity).getErrorMessage();
else if (entity instanceof InputStream)
errorMessage = new BufferedReader(new InputStreamReader((InputStream)entity)).lines().collect(Collectors.joining("\n"));
else if (entity != null)
errorMessage = entity.toString();
return errorMessage;
}