尝试使用Feign登录Spring OAuth2服务器

时间:2016-11-08 09:25:34

标签: java spring spring-security spring-security-oauth2 netflix-feign

我希望通过Feign向Spring OAuth2服务器进行grant_type = password登录。我做了正常的REST调用后,确认OAuth2服务器正常工作。但是在尝试使用Feign时,它失败了。

在我的服务中,我有:

@Component
@Scope("prototype")
@FeignClient(url = "http://localhost:9999/uaa")
public interface AuthClient {

    @RequestMapping(value="/oauth/token", method=RequestMethod.POST)
    @Headers({"Authorization: Basic some_base64encoded_client_secret_here=="})
    public LoginResponse login(
            @Param("username") String username, @Param("password") String password, @Param("grant_type") String grantType);

}

我收到此错误: java.lang.ClassCastException: Cannot cast com.sun.proxy.$Proxy129 to org.springframework.web.bind.annotation.RequestMapping

我发现的大多数示例都展示了如何拦截Feign以使用OAuth标头/等。并假设访问令牌已存在。但这不是我的问题。我还没有访问令牌,因为我试图通过登录来获取访问令牌。有关如何使用Feign登录的任何想法?

1 个答案:

答案 0 :(得分:0)

您可以像这样映射自己的回复:

@Component
@FeignClient(name = "authClient", url = "http://localhost:8080")
public interface AuthClient {

    @RequestMapping(value="/oauth/token", method= RequestMethod.POST)
    AuthResponse login(@RequestParam("grant_type") String grantType, @RequestParam("username") String username,
                   @RequestParam("password") String password, @RequestParam("scope") String scope);

    @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
    class AuthResponse {
        String access_token;
        String token_type;
        String refresh_token;
        String expires_in;
    }
}

public class AuthService {

    private final AuthClient authClient;

    public AuthService(AuthClient authClient) {
        this.authClient = authClient;
    }

    public AuthClient.AuthResponse authenticate(String login, String password, String scopes) {
        return this.authClient.login("password", "admin", "admin", "read+write");
    }
}

您可以注册请求拦截器,以便在每次请求时添加授权标头:

@Bean
public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
    return new BasicAuthRequestInterceptor("clientId", "clientSecret");
}

此代码适用于示例Spring Security OAuth2服务器。