Spring Authorization Server with Password Grant Type

Finally, spring-authorization-server got custom grant type support with version 1.0.0. Let’s see what implementations we need to do for grant-type:password. PasswordGrantAuthenticationConverter The following example shows a sample implementation of the AuthenticationConverter. public class PasswordGrantAuthenticationConverter implements AuthenticationConverter { public static final String PASSWORD = "password"; @Nullable @Override public Authentication convert(HttpServletRequest request) { // grant_type (REQUIRED) String grantType = request.getParameter(OAuth2ParameterNames.GRANT_TYPE); if (!PASSWORD.equals(grantType)) { return null; } Authentication clientPrincipal = SecurityContextHolder.getContext().getAuthentication(); MultiValueMap<String, String> parameters = getParameters(request); // username and password (REQUIRED) String username = parameters.getFirst(OAuth2ParameterNames.USERNAME); String password = parameters.getFirst(OAuth2ParameterNames.PASSWORD); if (!StringUtils.hasText(username) || !StringUtils.hasText(password) || parameters.get(OAuth2ParameterNames.USERNAME).size() != 1 || parameters.get(OAuth2ParameterNames.PASSWORD).size() != 1) { throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST); } Map<String, Object> additionalParameters = new HashMap<>(); parameters.forEach((key, value) -> { if (!key.equals(OAuth2ParameterNames.GRANT_TYPE) && !key.equals(OAuth2ParameterNames.CLIENT_ID)) { additionalParameters.put(key, value.get(0)); } }); return new PasswordGrantAuthenticationToken(username, password, clientPrincipal, additionalParameters); } private static MultiValueMap<String, String> getParameters(HttpServletRequest request) { Map<String, String[]> parameterMap = request.getParameterMap(); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(parameterMap.size()); parameterMap.forEach((key, values) -> { for (String value : values) { parameters.add(key, value); } }); return parameters; } } PasswordGrantAuthenticationProvider AuthenticationProvider is responsible for validating the authorization grant. The following example shows a sample implementation. ...

August 22, 2023 · 4 min · 850 words · Me