问题
I'm trying to consume a rest web service in spring integration project. This web service is secured with oauth2 (authorization code).Any idea how to achieve this?
I tried using OAuth2RestTemplate but it gave me an error:
org.springframework.security.oauth2.client.resource.UserRedirectRequiredException: A redirect is required to get the users approval
Below is my code.
import java.util.Arrays;
import org.springframework.security.oauth2.client.token.AccessTokenRequest;
import org.springframework.security.oauth2.client.token.DefaultAccessTokenRequest;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails;
public class OAuth2Client1 {
public static void main(String[] args) {
AuthorizationCodeResourceDetails resource = new AuthorizationCodeResourceDetails();
resource.setId("My Developer");
resource.setClientId("xxxxxx");
resource.setClientSecret("xxxxxx");
resource.setAccessTokenUri("https://api.infusionsoft.com/token");
resource.setUserAuthorizationUri("https://signin.infusionsoft.com/app/oauth/authorize");
resource.setPreEstablishedRedirectUri("https://myapps.com:8181/my_work");
resource.setScope(Arrays.asList("full"));
try {
AuthorizationCodeAccessTokenProvider authProvider =
new AuthorizationCodeAccessTokenProvider();
AccessTokenRequest request = new DefaultAccessTokenRequest();
String str = authProvider.obtainAuthorizationCode(resource, request);
System.out.println(str);
} catch (Exception e) {
e.printStackTrace();
}
}
}
回答1:
Authorization Code flow is used to authenticate user in web browser through redirect. It requires user authentication by username and password.
Your case is about communication between two services, also called as M2M (machine-to-machine). Service is not allowed to store user credentials by itself due security reasons. You should use Client Credentials flow that requred only client id and client secret for authentication. So then you'll able to use OAuth2RestTemplate.
回答2:
If the service is secured with oAuth2, you must play with oAuth rules in order to get to the resource server. It means your app needs to register and get clientID and client-secret, then the users of your app can use it to oAuth-connect...
It does not matter HOW you invoke the call, you have to use oAuth. OAuth2RestTemplate
is just a Spring's RestTemplate
implementation for oAuth developers, that abstracts some logic that is relevant for oAuth...
来源:https://stackoverflow.com/questions/48358028/consume-oauth2-authorization-code-rest-api-with-spring-rest-template