keycloak~自定義directgrant直接認(rèn)證
direct grant我們把它理解為通過rest接口直接認(rèn)證,這是oauth2里的密碼認(rèn)證方式,即grant_type=password,它不需要走授權(quán)碼這種復(fù)雜的流程,相當(dāng)于傳統(tǒng)的表單認(rèn)證;keycloak事實(shí)上為我們準(zhǔn)備了一個direct grant,只不過它只能使用username和password進(jìn)行認(rèn)證,如果你希望使用email,phoneNumber來進(jìn)行密碼認(rèn)證,則需要另外去開發(fā),下面就是開發(fā)的步驟:
- 添加provider和providerFactory
你的SelfDirectGrantAuthenticator需要繼承ValidatePassword ,當(dāng)然繼承AbstractDirectGrantAuthenticator也是可以的,ValidatePassword是AbstractDirectGrantAuthenticator的一個子類,都是在直接授權(quán)時使用的,它的作用是校驗(yàn)用戶的密碼,KC的這種設(shè)計有利于程序的解耦,例如除了ValidatePassword還有ValidateUsername等。
/**
* 直接繼承了驗(yàn)證密碼功能的direct grant流.
*/
public class TestDirectGrantAuthenticator extends ValidatePassword {
KeycloakSession session;
public V6DirectGrantAuthenticator(KeycloakSession session) {
this.session = session;
}
@Override
public void authenticate(AuthenticationFlowContext context) {
String username = Optional.ofNullable(context.getHttpRequest().getDecodedFormParameters().getFirst("username"))
.orElse(context.getHttpRequest().getDecodedFormParameters().getFirst("username"));
String password = Optional.ofNullable(context.getHttpRequest().getDecodedFormParameters().getFirst("password"))
.orElse(context.getHttpRequest().getDecodedFormParameters().getFirst("password"));
MultivaluedMap<String, String> inputData = new MultivaluedMapImpl<>();
inputData.add(KeycloakUtil.FIELD_EMAIL_PHONE, username);
inputData.add(KeycloakUtil.PASSWORD, password);
if (KeycloakUtil.passwordLogin(this, context, session.getProvider(JpaConnectionProvider.class).getEntityManager(), session, inputData)) {
super.authenticate(context); //驗(yàn)證密碼
}
}
-
注冊到org.keycloak.authentication.AuthenticatorFactory

-
keycloak管理平臺,添加驗(yàn)證,可以從默認(rèn)的direct grant上復(fù)制

-
將直接認(rèn)證流程改成剛剛建立的

-
現(xiàn)在就可以在postman里,脫離瀏覽器,進(jìn)行認(rèn)證了,并直接返回access_token

浙公網(wǎng)安備 33010602011771號