direct grant我們把它理解爲通過rest接口直接認證,這是oauth2裏的密碼認證方式,即grant_type=password
,它不需要走授權碼這種複雜的流程,相當於傳統的表單認證;keycloak事實上爲我們準備了一個direct grant,只不過它只能使用username和password進行認證,如果你希望使用email,phoneNumber來進行密碼認證,則需要另外去開發,下面就是開發的步驟:
- 添加provider和providerFactory
你的SelfDirectGrantAuthenticator需要繼承ValidatePassword ,當然繼承AbstractDirectGrantAuthenticator也是可以的,ValidatePassword是AbstractDirectGrantAuthenticator的一個子類,都是在直接授權時使用的,它的作用是校驗用戶的密碼,KC的這種設計有利於程序的解耦,例如除了ValidatePassword還有ValidateUsername等。
/**
* 直接繼承了驗證密碼功能的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); //驗證密碼
}
}
-
註冊到org.keycloak.authentication.AuthenticatorFactory
-
keycloak管理平臺,添加驗證,可以從默認的direct grant上覆制
-
將直接認證流程改成剛剛建立的
-
現在就可以在postman裏,脫離瀏覽器,進行認證了,並直接返回access_token