本文介绍了Spotify PKCE。错误无效的客户端密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要完成Authorization Code Flow with Proof Key for Code Exchange。在第4步中,我收到错误400 - bad request {"error":"invalid_request","error_description":"Invalid client secret"}

如果是PKCE,为什么需要客户端机密。我做错了什么?你有什么想法吗?

类似的正文请求

代码验证器示例:xeJ7Sx1lyUr0A_DAomzewuGn8vNS2cd3ZF2odDlqHEqeYKpxjnYYhpHxOohoo7lf22VNImGiOy_PE07owmDn2VmTWvdKKQ

代码挑战示例:N_yPRc_VC8JQJz5dYOuvvM-9cJLdAtEjJ9-lh8Xk_qI

我在请求中也看到了同样的情况。

步骤1

使用PkceUtil

class PkceUtil {

    private static final int PKCE_BASE64_ENCODE_SETTINGS = Base64.NO_WRAP | Base64.NO_PADDING | Base64.URL_SAFE;

    String generateCodeVerifier(){
        SecureRandom random = new SecureRandom();
        byte[] codeVerifier = new byte[40];
        random.nextBytes(codeVerifier);
        return Base64.encodeToString(codeVerifier, PKCE_BASE64_ENCODE_SETTINGS);
    }

    String generateCodeChallenge(String codeVerifier) {
        byte[] bytes = codeVerifier.getBytes(StandardCharsets.UTF_8);
        MessageDigest messageDigest = getMessageDigestInstance();
        if (messageDigest != null) {
            messageDigest.update(bytes);
            byte[] digest = messageDigest.digest();
            return Base64.encodeToString(digest, PKCE_BASE64_ENCODE_SETTINGS);
        }
        return "";
    }

    private MessageDigest getMessageDigestInstance(){
        try {
            return MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}

第2步

使用官方android-sdk auth-lib by Spotify

private AuthorizationRequest getAuthRequestCode() {
    PkceUtil pkceUtil = new PkceUtil();
    codeVerifier = pkceUtil.generateCodeVerifier();
    codeChallenge = pkceUtil.generateCodeChallenge(codeVerifier);
    return new AuthorizationRequest.Builder(CLIENT_ID, AuthorizationResponse.Type.CODE, getRedirectUri())
            .setShowDialog(false)
            .setScopes(SCOPE)
            .setCustomParam("code_challenge_method", "S256")
            .setCustomParam("code_challenge", codeChallenge)
            .build();
}

private String getRedirectUri() {
    return Uri.parse(REDIRECT_URI).toString();
}

步骤3和4

获取代码并发送请求以交换代码

private void onAuthResponse(int resultCode, Intent intent){
    AuthorizationResponse response = AuthorizationClient.getResponse(resultCode, intent);
    switch (response.getType()) {
        case TOKEN:
            break;
        case CODE:
            SpotifyAuthApi api = new SpotifyAuthApi();
            SpotifyAuthService spotify = api.getService();

            Map<String, Object> map = new HashMap<>();
            map.put("client_id", CLIENT_ID);
            map.put("grant_type", "authorization_code");
            map.put("code", response.getCode());
            map.put("redirect_uri", getRedirectUri());
            map.put("code_verifier", codeVerifier);
            spotify.getAccessToken(map, new Callback<AuthorizationResponse>() {
                @Override
                public void success(AuthorizationResponse authorizationResponse, Response response) {
                }

                @Override
                public void failure(RetrofitError error) {
                    // Error 400 - bad request
                }
            });
            break;
        case ERROR:
            break;
        default:
    }
}

要发送请求,请使用自己的AuthApi和带有帮助重新调整的AuthService


public interface SpotifyAuthService {

    @POST("/api/token")
    @FormUrlEncoded
    AuthorizationResponse getAccessToken(@FieldMap Map<String, Object> params);

    @POST("/api/token")
    @FormUrlEncoded
    void getAccessToken(@FieldMap Map<String, Object> params, Callback<AuthorizationResponse> callback);

}

public class SpotifyAuthApi {

    private static final String SPOTIFY_ACCOUNTS_ENDPOINT = "https://accounts.spotify.com/";

    private final SpotifyAuthService mSpotifyAuthService;

    private class WebApiAuthenticator implements RequestInterceptor {
        @Override
        public void intercept(RequestFacade request) {
            request.addHeader("content-type", "application/x-www-form-urlencoded");
        }
    }

    public SpotifyAuthApi() {
        Executor httpExecutor = Executors.newSingleThreadExecutor();
        MainThreadExecutor callbackExecutor = new MainThreadExecutor();
        mSpotifyAuthService = init(httpExecutor, callbackExecutor);
    }

    private SpotifyAuthService init(Executor httpExecutor, Executor callbackExecutor) {
        final RestAdapter restAdapter = new RestAdapter.Builder()
                .setLogLevel(RestAdapter.LogLevel.BASIC)
                .setExecutors(httpExecutor, callbackExecutor)
                .setEndpoint(SPOTIFY_ACCOUNTS_ENDPOINT)
                .setRequestInterceptor(new SpotifyAuthApi.WebApiAuthenticator())
                .build();

        return restAdapter.create(SpotifyAuthService.class);
    }

    public SpotifyAuthService getService() {
        return mSpotifyAuthService;
    }

}

推荐答案

我对Spotify Android SDK库不太熟悉,但从this issue判断,它不支持PKCE鉴权流程,不确定您自定义code_challengecode_challenge_method参数时是否会创建有效的请求。

确保此步骤(2)起作用,否则授权终结点假定您使用正常的授权码流,并期望client_secret(在步骤4中)。

这篇关于Spotify PKCE。错误无效的客户端密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 00:08