You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring Boot1.5.9中实现无需用户登录的OAuth2.0密码模式客户端?

Solution for Spring Boot 1.5.9 OAuth2 Client (Resource Owner Password Credentials Grant)

Got it, let's walk through exactly how to build your proxy REST endpoint that handles OAuth2 token fetching and calls the remote protected service on behalf of your users—no login page required. Since you already have valid credentials and confirmed they work in Postman, we can focus on wiring this up smoothly in Spring Boot.

Step 1: Add Required Dependencies

First, make sure your pom.xml (for Maven) includes the necessary OAuth2 and web starters tailored to Spring Boot 1.5.9:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth</groupId>
        <artifactId>spring-security-oauth2</artifactId>
    </dependency>
</dependencies>

Step 2: Configure OAuth2 Client Properties

Add these settings to your application.properties (convert to YAML if you prefer) and fill in your actual authorization server/resource details:

# OAuth2 Client Configuration
security.oauth2.client.client-id=your-registered-client-id
security.oauth2.client.client-secret=your-client-secret
security.oauth2.client.access-token-uri=https://your-auth-server-domain/oauth/token
security.oauth2.client.grant-type=password

# Remote Protected Resource Details
remote.resource.base-url=https://your-protected-service-domain/api
remote.resource.owner-username=your-preconfigured-user-username
remote.resource.owner-password=your-preconfigured-user-password

Step 3: Create OAuth2 Client Configuration Class

This class sets up the OAuth2RestTemplate—the core component that handles token management and requests to the remote service. We'll configure it specifically for the Resource Owner Password Grant:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails;
import org.springframework.security.oauth2.common.AuthenticationScheme;

@Configuration
public class OAuth2ClientConfig {

    @Value("${security.oauth2.client.client-id}")
    private String clientId;

    @Value("${security.oauth2.client.client-secret}")
    private String clientSecret;

    @Value("${security.oauth2.client.access-token-uri}")
    private String accessTokenUri;

    @Value("${remote.resource.owner-username}")
    private String resourceOwnerUsername;

    @Value("${remote.resource.owner-password}")
    private String resourceOwnerPassword;

    @Bean
    public ResourceOwnerPasswordResourceDetails passwordResourceDetails() {
        ResourceOwnerPasswordResourceDetails details = new ResourceOwnerPasswordResourceDetails();
        details.setClientId(clientId);
        details.setClientSecret(clientSecret);
        details.setAccessTokenUri(accessTokenUri);
        details.setUsername(resourceOwnerUsername);
        details.setPassword(resourceOwnerPassword);
        details.setGrantType("password");
        // Use header-based auth for client authentication (adjust if your server uses form params)
        details.setClientAuthenticationScheme(AuthenticationScheme.header);
        return details;
    }

    @Bean
    public OAuth2RestTemplate oAuth2RestTemplate() {
        return new OAuth2RestTemplate(passwordResourceDetails(), new DefaultOAuth2ClientContext());
    }
}

The OAuth2RestTemplate will automatically handle fetching access tokens, caching them, and refreshing expired tokens—so you don't have to manage token lifecycle manually.

Step 4: Build Your Proxy REST Endpoint

Create a controller that exposes your own REST interface, which uses the OAuth2RestTemplate to proxy calls to the remote protected service:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;

@RestController
public class ProxyResourceController {

    @Autowired
    private OAuth2RestTemplate oAuth2RestTemplate;

    @Value("${remote.resource.base-url}")
    private String remoteResourceBaseUrl;

    // Example: Proxy a GET request to the remote service's "/protected/user-info" endpoint
    @GetMapping("/api/proxy/user-info")
    public ResponseEntity<?> getRemoteUserInfo() {
        String remoteEndpoint = remoteResourceBaseUrl + "/protected/user-info";
        ResponseEntity<String> remoteResponse = oAuth2RestTemplate.getForEntity(remoteEndpoint, String.class);
        // Pass the remote service's response directly to your caller
        return ResponseEntity.status(remoteResponse.getStatusCode()).body(remoteResponse.getBody());
    }

    // Example: Proxy a POST request with a request body
    @PostMapping("/api/proxy/submit-data")
    public ResponseEntity<?> submitDataToRemoteService(@RequestBody Object requestBody) {
        String remoteEndpoint = remoteResourceBaseUrl + "/protected/submit";
        ResponseEntity<String> remoteResponse = oAuth2RestTemplate.postForEntity(remoteEndpoint, requestBody, String.class);
        return ResponseEntity.status(remoteResponse.getStatusCode()).body(remoteResponse.getBody());
    }
}

Adjust the HTTP methods and endpoints to match your actual remote service requirements.

Step 5: Test Your Setup

  1. Start your Spring Boot application
  2. Call your proxy endpoint (e.g., GET http://localhost:8080/api/proxy/user-info)
  3. Your endpoint will automatically fetch the OAuth2 token using your pre-configured credentials, call the remote protected service, and return the response to you—just like your Postman test, but wrapped in your own API.

Key Notes

  • For production, add security to your proxy endpoint (e.g., API key validation or Spring Security) to restrict access to authorized callers.
  • If your remote service requires custom headers or request formatting, use the exchange method on OAuth2RestTemplate for full control over request details.
  • Stick to Spring Boot 1.5.9-compatible dependencies to avoid version conflicts.

内容的提问来源于stack exchange,提问作者Aliasghar Yaghoobzadeh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:33:09