【问题标题】:Retrofit 1.9 to consume jhipster oauth the response is not populated改造 1.9 以使用 jhipster oauth 响应未填充
【发布时间】:2015-10-25 01:17:20
【问题描述】:

我遇到了一个奇怪的 Json 转换问题,我有一个基于 jhipster 的实现 oauth 身份验证的 webapp,以及一个简单的 android 应用;我的编程逻辑基于这篇文章jhipster oauth : How can i get the access_token via CURL

对于 android 应用,我有以下代码:

public class RestAdapterManager {

    public static final String API_BASE_URL = "http://192.168.0.102:8080/";

    private static RestAdapter.Builder builder = new RestAdapter.Builder()
            .setEndpoint(API_BASE_URL);
            //.setClient(new OkClient(new OkHttpClient()));

    public static <S> S createService(Class<S> serviceClass) {
        return createService(serviceClass, null, null);
    }

    public static <S> S createService(Class<S> serviceClass, String username, String password) {
        if (username != null && password != null) {
            // concatenate username and password with colon for authentication
            String credentials = username + ":" + password;
            // create Base64 encodet string
            final String basic =
                    "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

            builder.setRequestInterceptor(new RequestInterceptor() {
                @Override
                public void intercept(RequestFacade request) {
                    request.addHeader("Accept", "applicaton/json");
                    request.addHeader("Authorization", basic);
                }
            });
        }

        RestAdapter adapter = builder.setLogLevel(RestAdapter.LogLevel.FULL).build();
        return adapter.create(serviceClass);
    }
}

使用oauth服务本身的接口

public class AuthorizeService {

    private static IAuthorizeService authorizeService;

    public static IAuthorizeService getAuthorizeService() {
        return RestAdapterManager.createService(IAuthorizeService.class, "RikuyWebapp", "mySecretOAuthSecret" );
    }

    /**/

    public interface IAuthorizeService {

        @POST("/oauth/token")
        public void authorize(@Body Object dummy, @Query("username") String userName,
                              @Query("password") String password,
                              @Query("grant_type") String grantType,
                              @Query("scope") String scope,
                              @Query("client_id") String client_id,
                              @Query("client_secret") String client_secret,
                              Callback<UserToken> callback);
    }
}

以及对服务的实际调用:

Button loginButton = (Button) findViewById(R.id.loginbutton);
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AuthorizeService.getAuthorizeService().authorize("", "username",
                        "password", "password", "read", "appId", "appSecret", new Callback<UserToken>() {
                            @Override
                            public void success(UserToken result, Response response) {
                                Log.d("sucees!", result.getAccessToken());
                            }

                            @Override
                            public void failure(RetrofitError error) {
                                Log.d("Fail!", error.getBody().toString());
                            }
                        });

            }
        });

我尝试使用使用http://www.jsonschema2pojo.org/ 生成的此对象以及我从 curl 获得的响应来捕获响应

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
        "access_token",
        "token_type",
        "refresh_token",
        "expires_in",
        "scope"
})
public class UserToken {

    @JsonProperty("access_token")
    private String accessToken;
    @JsonProperty("token_type")
    private String tokenType;
    @JsonProperty("refresh_token")
    private String refreshToken;
    @JsonProperty("expires_in")
    private long expiresIn;
    @JsonProperty("scope")
    private String scope;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    /**
     *
     * @return
     * The accessToken
     */
    @JsonProperty("access_token")
    public String getAccessToken() {
        return accessToken;
    }
..........

从改造日志来看,所有接缝都很好:

10-24 10:54:44.365  29537-29815/mobile.rikuy.com.co.androidoauthclient D/Retrofit﹕ ---> HTTP POST http://192.168.0.102:8080/oauth/token?username=username&password=password&grant_type=password&scope=read&client_id=webappId&client_secret=webAppSecret
10-24 10:54:44.365  29537-29815/mobile.rikuy.com.co.androidoauthclient D/Retrofit﹕ Authorization: Basic UmlrdXlXZWJhcHA6bXlTZWNyZXRPQXV0aFNlY3JldA==
10-24 10:54:44.365  29537-29815/mobile.rikuy.com.co.androidoauthclient D/Retrofit﹕ Content-Type: application/json; charset=UTF-8
10-24 10:54:44.365  29537-29815/mobile.rikuy.com.co.androidoauthclient D/Retrofit﹕ Content-Length: 2
10-24 10:54:44.368  29537-29815/mobile.rikuy.com.co.androidoauthclient D/Retrofit﹕ ""
10-24 10:54:44.368  29537-29815/mobile.rikuy.com.co.androidoauthclient D/Retrofit﹕ ---> END HTTP (2-byte body)
10-24 10:54:44.576  29537-29815/mobile.rikuy.com.co.androidoauthclient D/Retrofit﹕ <--- HTTP 200 http://192.168.0.102:8080/oauth/token?username=username&password=password&grant_type=password&scope=read&client_id=webappId&client_secret=webAppSecret (208ms)
10-24 10:54:44.576  29537-29815/mobile.rikuy.com.co.androidoauthclient D/Retrofit﹕ Server: Apache-Coyote/1.1
10-24 10:54:44.576  29537-29815/mobile.rikuy.com.co.androidoauthclient D/Retrofit﹕ X-Content-Type-Options: nosniff
10-24 10:54:44.576  29537-29815/mobile.rikuy.com.co.androidoauthclient D/Retrofit﹕ X-XSS-Protection: 1; mode=block
10-24 10:54:44.576  29537-29815/mobile.rikuy.com.co.androidoauthclient D/Retrofit﹕ Cache-Control: no-cache, no-store, max-age=0, must-revalidate
10-24 10:54:44.576  29537-29815/mobile.rikuy.com.co.androidoauthclient D/Retrofit﹕ Pragma: no-cache
10-24 10:54:44.576  29537-29815/mobile.rikuy.com.co.androidoauthclient D/Retrofit﹕ Expires: 0
10-24 10:54:44.576  29537-29815/mobile.rikuy.com.co.androidoauthclient D/Retrofit﹕ X-Frame-Options: DENY
10-24 10:54:44.576  29537-29815/mobile.rikuy.com.co.androidoauthclient D/Retrofit﹕ X-Application-Context: application:dev:8080
10-24 10:54:44.576  29537-29815/mobile.rikuy.com.co.androidoauthclient D/Retrofit﹕ Cache-Control: no-store
10-24 10:54:44.577  29537-29815/mobile.rikuy.com.co.androidoauthclient D/Retrofit﹕ Pragma: no-cache
10-24 10:54:44.577  29537-29815/mobile.rikuy.com.co.androidoauthclient D/Retrofit﹕ Content-Type: application/json;charset=UTF-8
10-24 10:54:44.577  29537-29815/mobile.rikuy.com.co.androidoauthclient D/Retrofit﹕ Transfer-Encoding: chunked
10-24 10:54:44.577  29537-29815/mobile.rikuy.com.co.androidoauthclient D/Retrofit﹕ Date: Sat, 24 Oct 2015 15:54:44 GMT
10-24 10:54:44.577  29537-29815/mobile.rikuy.com.co.androidoauthclient D/Retrofit﹕ OkHttp-Selected-Protocol: http/1.1
10-24 10:54:44.577  29537-29815/mobile.rikuy.com.co.androidoauthclient D/Retrofit﹕ OkHttp-Sent-Millis: 1445702084460
10-24 10:54:44.577  29537-29815/mobile.rikuy.com.co.androidoauthclient D/Retrofit﹕ OkHttp-Received-Millis: 1445702084573
10-24 10:54:44.578  29537-29815/mobile.rikuy.com.co.androidoauthclient D/Retrofit﹕ {"access_token":"26eb7fa0-16fc-4a78-8977-19d2d4125e74","token_type":"bearer","refresh_token":"f657059b-c85e-4021-8600-7f8990243a6f","expires_in":1759,"scope":"read"}

但是,当我尝试访问 POJO 中的值时,大多数都是 null,并且只有范围被填充。

【问题讨论】:

    标签: java android oauth-2.0 jhipster


    【解决方案1】:

    经过几天的努力寻找解决方案,我发现不仅@JsonProperty("access_token") 字段与转换过程相关,而且字段和方法名称也很重要,所以当我更改我的来自

    的pojo
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonPropertyOrder({
            "access_token",
            "token_type",
            "refresh_token",
            "expires_in",
            "scope"
    })
    public class UserToken {
    
        @JsonProperty("access_token")
        private String accessToken;
        @JsonProperty("token_type")
        private String tokenType;
        @JsonProperty("refresh_token")
        private String refreshToken;
        @JsonProperty("expires_in")
        private long expiresIn;
        @JsonProperty("scope")
        private String scope;
        @JsonIgnore
        private Map<String, Object> additionalProperties = new HashMap<String, Object>();
    
        /**
         *
         * @return
         * The accessToken
         */
        @JsonProperty("access_token")
        public String getAccessToken() {
            return accessToken;
        }
    ..........
    

    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonPropertyOrder({
            "access_token",
            "token_type",
            "refresh_token",
            "expires_in",
            "scope"
    })
    public class UserToken {
    
        @JsonProperty("access_token")
        private String access_token;
        @JsonProperty("token_type")
        private String token_type;
        @JsonProperty("refresh_token")
        private String refresh_token;
        @JsonProperty("expires_in")
        private long expires_in;
        @JsonProperty("scope")
        private String scope;
        @JsonIgnore
        private Map<String, Object> additionalProperties = new HashMap<String, Object>();
    
        public String getAccess_token() {
            return access_token;
        }
    

    一切都开始按预期运行,请注意,更改是为了将 POJO 字段的名称与我在响应中收到的名称相匹配。

    编辑:

    刚刚发现正确的做法是对元素使用SerializedName,在这里可以找到清晰的解释:http://heriman.net/?p=5

    【讨论】:

      猜你喜欢
      • 2021-07-14
      • 1970-01-01
      • 2019-02-01
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-10
      • 2016-02-14
      相关资源
      最近更新 更多