使用HttpClient获取oAuth2.0中的code、token及refreshToken

授权服务器使用授权码模式(authorization_code)

添加依赖
        <!--对用户名和密码进行base64加密-->
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.10</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
        <!--解析json数据-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

第一步(获取code)

    public String getCode(String client_id, String response_type, String redirect_uri) {
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 将用户名和密码放入header中
        String plainClientCredentials = "user:user";
        String base64ClientCredentials = new String(Base64.encodeBase64(plainClientCredentials.getBytes()));
        String url = "http://127.0.0.1:8081/authoriza/oauth/authorize?client_id=" + client_id + "&"
                + "response_type=" + response_type + "&" + "redirect_uri=" + redirect_uri;

        RequestConfig config = RequestConfig.custom().setRedirectsEnabled(false).setConnectionRequestTimeout(5000)
                .build();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("Authorization", "Basic " + base64ClientCredentials);
        httpGet.setConfig(config);
        String result = "";
        try {

            HttpResponse response = httpClient.execute(httpGet);
            // 从从定向地址中取得code
            if (response.getStatusLine().getStatusCode() == 302) {
                Header header = response.getFirstHeader("Location");
                String location = header.getValue();
                String code = location.substring(location.indexOf("=") + 1, location.length());
                return code;
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "error";
    }

第二步(获取token及refreshToken)

public AccessToken getToken(String client_id, String grant_type, String code, String redirect_uri,
            String client_secret) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String url = "http://127.0.0.1:8081/authoriza/oauth/token?client_id=" + client_id + "&grant_type="
                + grant_type + "&code=" + code + "&redirect_uri=" + redirect_uri + "&client_secret=" + client_secret;
        HttpPost httpPost = new HttpPost(url);
        HttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String result = "";
        if (response.getStatusLine().getStatusCode() == 200) {
            try {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
                // 解析token的json数据
                JSONObject jsonObject = JSONObject.parseObject(result);
                AccessToken accessToken = new AccessToken();
                accessToken.setAccess_token(jsonObject.getString("access_token"));
                accessToken.setToken_type(jsonObject.getString("token_type"));
                accessToken.setRefresh_token(jsonObject.getString("refresh_token"));
                accessToken.setExpires_in(jsonObject.getString("expires_in"));
                accessToken.setScope(jsonObject.getString("scope"));
                return accessToken;
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return new AccessToken();
    }

源码下载地址:https://download.csdn.net/download/lhc_makefunny/10559161

真的想吐槽一下国内的网络环境,其实真的没有必要把一片博客转来转去的,翻来覆去就一片文章真的解决不了问题;还有有些问题的确是国内搜不到的,还是要懂得科学上网

在 Java 调用 OAuth2 API 接口可以使用一些第三方库,比如 Apache 的 HttpClient,Spring Security OAuth2 等。 下面以 Spring Security OAuth2 为例,介绍一下 Java 调用 OAuth2 API 的步骤: 1. 配置 OAuth2 客户端信息。需要配置客户端 ID、客户端密钥、授权 URL、令牌 URL 等信息。 2. 获取访问令牌。可以通过 OAuth2 客户端信息和用户授权码等信息向授权服务器获取访问令牌。 3. 使用访问令牌调用 API。可以使用访问令牌调用 OAuth2 API 接口,获取用户数据等信息。 以下是一个简单的示例代码: ``` // 创建 OAuth2 客户端信息 ClientDetails clientDetails = new BaseClientDetails( "client_id", // 客户端 ID "resource_id", // 资源 ID "scope", // 客户端范围 "client_secret", // 客户端密钥 "authorization_code,refresh_token", // 授权类型 "http://localhost:8080/auth/callback", // 授权回调 URL 3600, // 令牌有效期 3600, // 刷新令牌有效期 null // 其他属性 ); // 创建 OAuth2 请求 OAuth2Request oAuth2Request = new OAuth2Request( null, // 请求参数 "client_id", // 客户端 ID null, // 范围 true, // 是否批准 null, // 资源 ID null, // 授权类型 null, // 授权回调 URL null, // State 参数 null // 其他属性 ); // 创建 OAuth2 认证令牌 Authentication authentication = new UsernamePasswordAuthenticationToken( "username", // 用户名 "password", // 密码 null // 用户角色 ); // 创建 OAuth2 访问令牌请求 OAuth2AccessTokenRequest oAuth2AccessTokenRequest = new OAuth2AccessTokenRequest( oAuth2Request, // OAuth2 请求 authentication // OAuth2 认证令牌 ); // 创建 OAuth2 客户端 ClientRegistration clientRegistration = ClientRegistration.withRegistrationId("my-client") .clientId("client-id") .clientSecret("client-secret") .clientAuthenticationMethod(ClientAuthenticationMethod.BASIC) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .redirectUriTemplate("http://localhost:8080/login/oauth2/code/{registrationId}") .scope("read") .authorizationUri("https://example.com/oauth2/authorize") .tokenUri("https://example.com/oauth2/token") .userInfoUri("https://example.com/oauth2/userinfo") .userNameAttributeName(IdTokenClaimNames.SUB) .jwkSetUri("https://example.com/oauth2/jwks") .clientName("my-client") .build(); // 创建 OAuth2 访问令牌响应 OAuth2AccessTokenResponse oAuth2AccessTokenResponse = new OAuth2AccessTokenResponse( OAuth2AccessToken.TokenType.BEARER, // 令牌类型 "access-token", // 访问令牌 "refresh-token", // 刷新令牌 3600L, // 令牌有效期 null // 范围 ); // 创建 OAuth2 访问令牌响应实体 OAuth2AccessTokenResponseEntity oAuth2AccessTokenResponseEntity = new OAuth2AccessTokenResponseEntity( oAuth2AccessTokenResponse, // 访问令牌响应 clientRegistration.getProviderDetails().getTokenInfoUri() // 令牌信息 URI ); // 使用访问令牌调用 OAuth2 API 接口 RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setBearerAuth("access-token"); // 设置访问令牌 HttpEntity<String> entity = new HttpEntity<String>("parameters", headers); String result = restTemplate.exchange("http://example.com/api", HttpMethod.GET, entity, String.class).getBody(); ``` 以上示例代码仅供参考,具体实现还需要根据实际情况进行调整。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值