如何通过客户凭证流中的OAuth2authorizedClientservice获取访问令牌?

发布于 2025-01-22 06:09:51 字数 4155 浏览 0 评论 0原文

我创建了一个具有弹簧安全性的客户端。作为授权服务器,我使用KeyCloak。 现在,我想使用参数注释@registeredoauth2authorizedClient(registrationID =“ KeyCloak”)> 我可以访问令牌,但是当我通过oauth2authorizedClientservice时,我只会恢复null,我不明白为什么。

这是我的实现:

application.properties:

spring.security.oauth2.client.registration.keycloak.client-id=test-client
spring.security.oauth2.client.registration.keycloak.client-secret=b466bd4e-8dec-4af2-b90a-ab3fc06009b6
spring.security.oauth2.client.registration.keycloak.authorization-grant-type=client_credentials

spring.security.oauth2.client.provider.keycloak.issuer-uri=http://localhost:8081/auth/realms/master

securityConfiguration.class

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter
{
    @Override
    public void configure(HttpSecurity http) throws Exception
    {
        http.oauth2Client();
    }
}

restController:

@RestController
@RequestMapping("client")
public class ExampleRestController
{
    @Autowired
    private OAuth2AuthorizedClientService authorizedClientService;

    @GetMapping("resource")
    public void runSecure(@RegisteredOAuth2AuthorizedClient(registrationId = "keycloak") OAuth2AuthorizedClient client)
    {
        var serviceClient = authorizedClientService.loadAuthorizedClient("keycloak", "anonymousUser");
        System.out.println(serviceClient.getAccessToken()); // NULL

        System.out.println((client.getAccessToken())); // NOT NULL
    }
}

希望提供帮助,谢谢:)

编辑:

以下是我的解决方案,可以灵活地使用服务:应用程序:应用程序:

应用程序:应用程序:应用程序。属性:

spring.security.oauth2.client.registration.keycloak.client-id=test-client
spring.security.oauth2.client.registration.keycloak.client-secret=b466bd4e-8dec-4af2-b90a-ab3fc06009b6
spring.security.oauth2.client.provider.keycloak.token-uri=http://localhost:8081/auth/realms/master/protocol/openid-connect/token

客户注册:

@Configuration
public class ClientRegistrationConfiguration
{
    private static final String KEYCLOAK = "keycloak";

    @Bean
    public ClientRegistration clientRegistration(OAuth2ClientProperties properties)
    {
        return withRegistrationId(KEYCLOAK)
                .tokenUri(properties.getProvider().get(KEYCLOAK).getTokenUri())
                .clientId(properties.getRegistration().get(KEYCLOAK).getClientId())
                .clientSecret(properties.getRegistration().get(KEYCLOAK).getClientSecret())
                .authorizationGrantType(CLIENT_CREDENTIALS)
                .build();
    }

    @Bean
    public ClientRegistrationRepository clientRegistrationRepository(ClientRegistration clientRegistration)
    {
        return new InMemoryClientRegistrationRepository(clientRegistration);
    }

    @Bean
    public OAuth2AuthorizedClientService oAuth2AuthorizedClientService(ClientRegistrationRepository clientRegistrationRepository)
    {
        return new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository);
    }

    @Bean
    public AuthorizedClientServiceOAuth2AuthorizedClientManager authorizedClientServiceOAuth2AuthorizedClientManager(
            ClientRegistrationRepository clientRegistrationRepository,
            OAuth2AuthorizedClientService authorizedClientService)
    {
        var authorizedClientProvider = builder().clientCredentials().build();
        var authorizedClientManager = new AuthorizedClientServiceOAuth2AuthorizedClientManager(clientRegistrationRepository, authorizedClientService);
        authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
        return authorizedClientManager;
    }
}

我的自定义令牌服务:

@Service
public class DefaultTokenService implements TokenService
{
    @Autowired
    private AuthorizedClientServiceOAuth2AuthorizedClientManager clientManager;

    @Override
    public OAuth2AccessToken getOAuth2AccessToken()
    {
        return Objects.requireNonNull(clientManager.authorize(withClientRegistrationId("keycloak").principal("Keycloak").build())).getAccessToken();
    }
}

I have created a client with Spring Security. As Authorization Server I use Keycloak.
Now I want to gain access to the access token, using the parameter annotation @RegisteredOAuth2AuthorizedClient(registrationId = "keycloak")
I get access to the token, but when I go through the OAuth2AuthorizedClientService I only get back NULL, and I don't understand why.

Here is my implementation:

application.properties:

spring.security.oauth2.client.registration.keycloak.client-id=test-client
spring.security.oauth2.client.registration.keycloak.client-secret=b466bd4e-8dec-4af2-b90a-ab3fc06009b6
spring.security.oauth2.client.registration.keycloak.authorization-grant-type=client_credentials

spring.security.oauth2.client.provider.keycloak.issuer-uri=http://localhost:8081/auth/realms/master

SecurityConfiguration.class

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter
{
    @Override
    public void configure(HttpSecurity http) throws Exception
    {
        http.oauth2Client();
    }
}

RestController:

@RestController
@RequestMapping("client")
public class ExampleRestController
{
    @Autowired
    private OAuth2AuthorizedClientService authorizedClientService;

    @GetMapping("resource")
    public void runSecure(@RegisteredOAuth2AuthorizedClient(registrationId = "keycloak") OAuth2AuthorizedClient client)
    {
        var serviceClient = authorizedClientService.loadAuthorizedClient("keycloak", "anonymousUser");
        System.out.println(serviceClient.getAccessToken()); // NULL

        System.out.println((client.getAccessToken())); // NOT NULL
    }
}

Hope for help, thanks :)

EDIT:

Here is my solution to get a flexible access to the access-token using a service:

application.properties:

spring.security.oauth2.client.registration.keycloak.client-id=test-client
spring.security.oauth2.client.registration.keycloak.client-secret=b466bd4e-8dec-4af2-b90a-ab3fc06009b6
spring.security.oauth2.client.provider.keycloak.token-uri=http://localhost:8081/auth/realms/master/protocol/openid-connect/token

Client registration:

@Configuration
public class ClientRegistrationConfiguration
{
    private static final String KEYCLOAK = "keycloak";

    @Bean
    public ClientRegistration clientRegistration(OAuth2ClientProperties properties)
    {
        return withRegistrationId(KEYCLOAK)
                .tokenUri(properties.getProvider().get(KEYCLOAK).getTokenUri())
                .clientId(properties.getRegistration().get(KEYCLOAK).getClientId())
                .clientSecret(properties.getRegistration().get(KEYCLOAK).getClientSecret())
                .authorizationGrantType(CLIENT_CREDENTIALS)
                .build();
    }

    @Bean
    public ClientRegistrationRepository clientRegistrationRepository(ClientRegistration clientRegistration)
    {
        return new InMemoryClientRegistrationRepository(clientRegistration);
    }

    @Bean
    public OAuth2AuthorizedClientService oAuth2AuthorizedClientService(ClientRegistrationRepository clientRegistrationRepository)
    {
        return new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository);
    }

    @Bean
    public AuthorizedClientServiceOAuth2AuthorizedClientManager authorizedClientServiceOAuth2AuthorizedClientManager(
            ClientRegistrationRepository clientRegistrationRepository,
            OAuth2AuthorizedClientService authorizedClientService)
    {
        var authorizedClientProvider = builder().clientCredentials().build();
        var authorizedClientManager = new AuthorizedClientServiceOAuth2AuthorizedClientManager(clientRegistrationRepository, authorizedClientService);
        authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
        return authorizedClientManager;
    }
}

My custom token service:

@Service
public class DefaultTokenService implements TokenService
{
    @Autowired
    private AuthorizedClientServiceOAuth2AuthorizedClientManager clientManager;

    @Override
    public OAuth2AccessToken getOAuth2AccessToken()
    {
        return Objects.requireNonNull(clientManager.authorize(withClientRegistrationId("keycloak").principal("Keycloak").build())).getAccessToken();
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

jJeQQOZ5 2025-01-29 06:09:51

您需要自动oauth2authorizedclientmanager bean,并明确发送令牌请求:

authorizedClientManager.authorize(request)

请参阅 https://docs.spring.io/spring-security/referenty/servlet/oauth2/client/authorization-grants.html

You need to autowire OAuth2AuthorizedClientManager bean and explicitly send a token request:

authorizedClientManager.authorize(request)

See https://docs.spring.io/spring-security/reference/servlet/oauth2/client/authorization-grants.html

柠檬 2025-01-29 06:09:51

在应用程序中设置infor.yml

config Sercurity

获取访问令牌

Setting infor in application.yml
enter image description here

Config Sercurity
enter image description here

Get access token
enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文