我在配置护照授予时遇到问题。我需要使用用户名和密码(基本身份验证)执行POST请求“身份验证”,并以响应方式返回令牌。 我根据https://docs.spring.io/spring-security/site/docs/current/reference/html5/#oauth2Client-password-grant的看法:
spring:
security:
oauth2:
client:
registration:
lol:
client-id:lol
client-secret: lol
client-authentication-method: basic
authorization-grant-type: password
accessTokenUri: http://lol/token
provider:
lol:
token-uri: lol/token
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.exceptionHandling()
.and()
.oauth2Client()
}
@Bean
public OAuth2AuthorizedClientManager passwordFlowAuthorizedClientManager(
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository
) {
DefaultPasswordTokenResponseClient passwordTokenResponseClient = new DefaultPasswordTokenResponseClient();
RestTemplate restTemplate = new RestTemplate();
restTemplate.setMessageConverters(Arrays.asList(
new FormHttpMessageConverter(),
new OAuth2AccessTokenResponseHttpMessageConverter()
));
restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
passwordTokenResponseClient.setRestOperations(restTemplate);
OAuth2AuthorizedClientProvider authorizedClientProvider =
OAuth2AuthorizedClientProviderBuilder.builder()
.password()
.build();
DefaultOAuth2AuthorizedClientManager authorizedClientManager =
new DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
authorizedClientManager.setContextAttributesMapper(authorizeRequest -> {
Map<String, Object> contextAttributes = new HashMap<>();
String username = authorizeRequest.getAttribute(OAuth2ParameterNames.USERNAME);
String password = authorizeRequest.getAttribute(OAuth2ParameterNames.PASSWORD);
if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
contextAttributes = new HashMap<>();
// `PasswordOAuth2AuthorizedClientProvider` requires both attributes
contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
}
return contextAttributes;
});
return authorizedClientManager;
}
@Bean
WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client =
new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
return WebClient.builder()
.apply(oauth2Client.oauth2Configuration())
.build();
}
}
当我有GET http://localhost:8080/oauth2/authorization/-> 401时。 并且DefaultPasswordTokenResponseClient已初始化,我具有“未找到“ UsernamePasswordAuthentificationToken”的AuthenticationProvider”。
但我想这是PasswordOAuth2AuthorizedClientProvider。
没有任何效果/而且我不知道该怎么办。怎么了?谢谢