Spring Security框架获取access_token 的java方法

public AuthToken applyToken(String username, String password, String clientId, String clientSecret) {

        StringBuffer stringBuffer=new StringBuffer();

        stringBuffer.append("grant_type=password&scope=read write");

        stringBuffer.append("&client_id=" + clientId);

        stringBuffer.append("&client_secret="+clientSecret);

        stringBuffer.append("&username=" + username);

        stringBuffer.append("&password=" + password);

        //申请令牌的url

        String authUrl = httpUrl + "/oauth/token?" + stringBuffer.toString();

        //        authUrl = authUrl.replaceAll(" ","%20");  //实践不需要替换空格,restTemplate能识别

        log.info("-----------------authUrl:" + authUrl);

        //定义header

        LinkedMultiValueMap<String, String> header = new LinkedMultiValueMap<>();

        String httpBasic = getHttpBasic(clientId, clientSecret);

        header.add("Authorization",httpBasic);

        //定义body,用body会报错

        LinkedMultiValueMap<String, String> body = new LinkedMultiValueMap<>();

//        body.add("grant_type","password");

//        body.add("username",username);

//        body.add("password",password);

        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(body, header);

        //String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables

        //设置restTemplate远程调用时候,对400和401不让报错,正确返回数据

        restTemplate.setErrorHandler(new DefaultResponseErrorHandler(){

            @Override

            public void handleError(ClientHttpResponse response) throws IOException {

                if(response.getRawStatusCode()!=400 && response.getRawStatusCode()!=401){

                    super.handleError(response);

                }

            }

        });

        ResponseEntity<Map> exchange = restTemplate.exchange(authUrl, HttpMethod.POST, httpEntity, Map.class);

        //申请令牌信息

        Map bodyMap = exchange.getBody();

        if (bodyMap == null ||

                bodyMap.get("access_token") == null ||

                bodyMap.get("refresh_token") == null ||

                bodyMap.get("jti") == null) {

            //解析spring security返回的错误信息

            if (bodyMap != null && bodyMap.get("error_description") != null) {

                String error_description = (String) bodyMap.get("error_description");

                if (error_description.indexOf("UserDetailsService returned null") >= 0) {

//                    ExceptionCast.cast(AuthCode.AUTH_ACCOUNT_NOTEXISTS);

                } else if (error_description.indexOf("坏的凭证") >= 0) {

//                    ExceptionCast.cast(AuthCode.AUTH_CREDENTIAL_ERROR);

                }

            }

            return null;

        }

       AuthToken authToken = new AuthToken();

        authToken.setAccess_token((String) bodyMap.get("jti"));//用户身份令牌

        authToken.setRefresh_token((String) bodyMap.get("refresh_token"));//刷新令牌

        authToken.setJwt_token((String) bodyMap.get("access_token"));//jwt令牌

        return authToken;

    }

    //获取httpbasic的串

    private String getHttpBasic(String clientId, String clientSecret) {

        String string = clientId + ":" + clientSecret;

        //将串进行base64编码

        byte[] encode = Base64Utils.encode(string.getBytes());

        return "Basic " + new String(encode);

    }

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容