当前位置: 首页 > 工具软件 > java-saml > 使用案例 >

Java 通过SAML2.0调用接口

印辉
2023-12-01
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class  SamlTest {
    private static final Logger logger = LoggerFactory.getLogger(SamlTest.class);

    private static final HttpUrl HSH_GET_USER_URL =   Objects.requireNonNull(HttpUrl.parse("http://10.19.23.84:90/sso-core/ssoservlet"));


    public static final MediaType JSONTYPE = MediaType.parse("application/json;charset=utf-8");

    public static  JSONObject getUserInfoByToken(String ticket) {
        StringBuffer params = new StringBuffer();
        params.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        params.append("<samlp:ArtifactResolve xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" xmlns:saml=\"urn:oasis:names:tc:SAML:2.0:assertion\"");
        String id = UUID.randomUUID().toString().replace("-", "").substring(0, 32).toUpperCase();
        params.append(" Id=");
        params.append("\"");
        params.append(id);
        params.append("\"");
        params.append("  Version=\"2.0\" ");
        params.append(" IssueInstant=");
        params.append("\"");
        params.append(new Date());
        params.append("\">");
        String url = "http://12.17.22.2/sso-core/queryapp";
        params.append("<saml:Issuer>").append(url).append("</saml:Issuer>");
        params.append("<samlp:Artifact>").append(ticket).append("</samlp:Artifact>");
        params.append("</samlp:ArtifactResolve>");
        logger.info("获取用户信息入参{}", JSON.toJSON(params));
        RequestBody requestBody = RequestBody.create(JSONTYPE, params.toString());
        Request req = new Request.Builder()
                .url(HSH_GET_USER_URL)
                .post(requestBody)
                .build();
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .connectTimeout(100,TimeUnit.SECONDS)
                .readTimeout(100, TimeUnit.SECONDS)
                .build();
        try {
            Response response = httpClient.newCall(req).execute();
            if (response.isSuccessful()) {
                String resultXml = Objects.requireNonNull(response.body()).string();
                System.out.println("Converted AuthRequest: " + resultXml);
                if(!StringUtils.isEmpty(resultXml)){

                    logger.info("获取用户信息入参2222", resultXml);
                    JSONObject jsonObject = JsonXmlUtil.xml2Json(resultXml);
                    logger.info("jsonObject2+==============="+ jsonObject.toString());

                    if(jsonObject!=null){
                        if("Success".equals(String.valueOf(jsonObject.get("Status")))){
                            logger.info("调用和生活接口:请求被成功处理");

                            return jsonObject;
                        }else if("Requester".equals(String.valueOf(jsonObject.get("Status")))){
                            logger.error("调用和生活接口:请求因为请求者的原因未能成功处理");
                        }else if("Responder".equals(String.valueOf(jsonObject.get("Status")))){
                            logger.error("调用和生活接口:请求因为响应者的原因未能成功处理");
                        }else {
                            logger.error("调用和生活接口请求:获取用户信息失败");
                        }
                    }
                }
                return null;
            } else {
                logger.error("请求失败{}", JSON.toJSON(response));
               /* throw new IOException();*/
            }

        } catch (Exception e) {
            logger.error("调用和生活接口获取用户信息失败{}", JSON.toJSON(e.getMessage()));
            return null;
        }
        return null ;
    }

}

maven 引入

<dependency>
   <groupId>org.opensaml</groupId>
   <artifactId>opensaml</artifactId>
   <version>2.6.4</version>
</dependency>
<dependency>
   <groupId>com.squareup.okhttp3</groupId>
   <artifactId>okhttp</artifactId>
   <version>3.6.0</version>
</dependency>
<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.1.41</version>
</dependency>
 
 类似资料: