Spring实战第6版第8章 OAuth2 客户端跑不起来

2023-12-14 18:13:09

使用的SpringBoot 2.6.11,按照教程写的代码,就是跑不起来,一直报下面的错误:

no suitable httpmessageconverter found for response type [java.util.map<java.lang.string, java.lang.object>]

?后来看了配套资源的代码,在授权服务器的?AuthorizationServerConfig 中添加一个 Bean 解决了:

@Bean
public ProviderSettings providerSettings() {
    return ProviderSettings.builder().issuer("http://authserver:9000").build();
}

如果跑起来了,但是登陆后显示错误页面,可以参考这里的代码替换自动化配置:Completely Override the Auto-configuration

具体代码如下:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.context.annotation.RequestScope;

import static org.springframework.security.config.Customizer.withDefaults;


@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorize -> authorize
                        .anyRequest().authenticated()
                )
                .oauth2Login(withDefaults());
        return http.build();
    }

    @Bean
    public ClientRegistrationRepository clientRegistrationRepository() {
        return new InMemoryClientRegistrationRepository(this.tacoClientRegistration());
    }

    private ClientRegistration tacoClientRegistration() {
        return ClientRegistration.withRegistrationId("taco-admin-client")
                .clientId("taco-admin-client")
                .clientSecret("secret")
                .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
                .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
                .redirectUri("http://127.0.0.1:9090/login/oauth2/code/{registrationId}")
                .scope("openid", "writeIngredients", "deleteIngredients")
                .authorizationUri("http://authserver:9000/oauth2/authorize")
                .tokenUri("http://authserver:9000/oauth2/token")
                .userInfoUri("http://authserver:9000/userinfo")
                .userNameAttributeName(IdTokenClaimNames.SUB)
                .jwkSetUri("http://authserver:9000/oauth2/jwks")
//                .clientName("")
                .build();
    }

    @Bean
    @RequestScope
    public IngredientService ingredientService(
                OAuth2AuthorizedClientService clientService) {
    Authentication authentication =
            SecurityContextHolder.getContext().getAuthentication();

    String accessToken = null;

    if (authentication.getClass()
              .isAssignableFrom(OAuth2AuthenticationToken.class)) {
      OAuth2AuthenticationToken oauthToken =
              (OAuth2AuthenticationToken) authentication;
      String clientRegistrationId =
              oauthToken.getAuthorizedClientRegistrationId();
      if ("taco-admin-client".equals(clientRegistrationId)) {
        OAuth2AuthorizedClient client =
            clientService.loadAuthorizedClient(
                clientRegistrationId, oauthToken.getName());
        accessToken = client.getAccessToken().getTokenValue();
      }
    }
    return new RestIngredientService(accessToken);
  }
}

文章来源:https://blog.csdn.net/jjf19891208/article/details/134997566
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。