美文网首页
Spring Security框架获取access_token

Spring Security框架获取access_token

作者: 私人云笔记_骁勇波波 | 来源:发表于2023-03-14 18:30 被阅读0次

    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);

        }

    相关文章

      网友评论

          本文标题:Spring Security框架获取access_token

          本文链接:https://www.haomeiwen.com/subject/qrjkrdtx.html