All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.dahuatech.icc.oauth.handle.OauthProcessor Maven / Gradle / Ivy

There is a newer version: 1.0.13.7
Show newest version
package com.dahuatech.icc.oauth.handle;

import com.dahuatech.hutool.http.Method;
import com.dahuatech.hutool.json.JSONUtil;
import com.dahuatech.hutool.log.Log;
import com.dahuatech.hutool.log.LogFactory;
import com.dahuatech.icc.exception.ClientException;
import com.dahuatech.icc.exception.ServerException;
import com.dahuatech.icc.oauth.constant.OauthConstant;
import com.dahuatech.icc.oauth.http.*;
import com.dahuatech.icc.oauth.model.v202010.*;
import com.dahuatech.icc.oauth.profile.GrantType;
import com.dahuatech.icc.oauth.profile.IccProfile;
import com.dahuatech.icc.oauth.utils.LogUtils;
import com.dahuatech.icc.util.BeanUtil;
import com.dahuatech.icc.util.SignUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class OauthProcessor {

    private static final Log logger = LogFactory.get();

    public IccTokenResponse.IccToken oauth(OauthConfigBaseInfo oauthConfigBaseInfo) throws ClientException {
        if(oauthConfigBaseInfo.getGrantType() == GrantType.password){//密码模式
            return password((OauthConfigUserPwdInfo)oauthConfigBaseInfo);
        }else{//客户端模式
            throw new ClientException("GrantType [client_credentials] not support");
//            return clientCredentials((OauthConfigClientInfo)oauthConfigBaseInfo);
        }
    }

    /**
     * 密码认证获取token
     *
     * @return IccTokenResponse.IccToken
     * @throws ClientException 客户端异常
     * @throws ServerException 服务端异常
     */
    private IccTokenResponse.IccToken password(OauthConfigUserPwdInfo oauthConfigUserPwdInfo) throws ClientException, ServerException {
        String uuid = UUID.randomUUID().toString();
        IccHttpHttpRequest pubRequest =
                new IccHttpHttpRequest(
                        OauthConstant.url(oauthConfigUserPwdInfo.getHttpConfigInfo(),OauthConstant.OAUTH_URL_PUBLIC_KEY_GET), Method.GET);
        String pubBody = pubRequest.execute();
        LogUtils.printOut(logger,uuid,pubBody);
        OauthPublicKeyResponse keyResp = BeanUtil.toBean(pubBody, OauthPublicKeyResponse.class);
        if (keyResp.getData() == null) {
            logger.error("get public key faiure [{}]", OauthConstant.OAUTH_URL_PUBLIC_KEY_GET);
            throw new ServerException("get public key faiure");
        }
        Map map = new HashMap<>();
        map.put("grant_type", oauthConfigUserPwdInfo.getGrantType().name());
        map.put("username", oauthConfigUserPwdInfo.getUsername());
        map.put("password", SignUtil.encryptRSANew(oauthConfigUserPwdInfo.getPassword(), keyResp.getData().getPublicKey()));
        /*web_client*/
        map.put("client_id", oauthConfigUserPwdInfo.getClientId());
        /*web_client*/
        map.put("client_secret", oauthConfigUserPwdInfo.getClientSecret());
        map.put("public_key", keyResp.getData().getPublicKey());
//        TokenHandlerProcessor.getInstance().getTokenMap().put(enGrantKeyName(GrantType.password.name()), iccToken);
        return oauth(map,oauthConfigUserPwdInfo.getHttpConfigInfo(),uuid);
    }

    /**
     * 客户端认证获取token
     *
     * @return IccTokenResponse.IccToken
     * @throws ClientException 客户端异常
     * @throws ServerException 服务端异常
     */
    private IccTokenResponse.IccToken clientCredentials(OauthConfigClientInfo oauthConfigClientInfo) throws ClientException, ServerException {
        Map map = new HashMap<>();
        map.put("grant_type", "client_credentials");
        map.put("client_id", oauthConfigClientInfo.getClientId());
        map.put("client_secret", oauthConfigClientInfo.getClientSecret());
        return oauth(map,oauthConfigClientInfo.getHttpConfigInfo(),UUID.randomUUID().toString());
    }

    private IccTokenResponse.IccToken oauth(Map map,HttpConfigInfo httpConfigInfo,String uuid) throws ClientException {
        IccHttpHttpRequest pr =
                new IccHttpHttpRequest(
                        OauthConstant.url(httpConfigInfo,OauthConstant.OAUTH_URL_PWD_AUTH_POST),
                        Method.POST,
                        JSONUtil.toJsonStr(map));
        pr.setRequestUniqueCode(uuid);
        LogUtils.printIn(logger,pr);
        String prBody = pr.execute();
        LogUtils.printOut(logger,uuid,prBody);
        IccTokenResponse token = BeanUtil.toBean(prBody, IccTokenResponse.class);
        if (token == null || !token.isSuccess()) {
            logger.error(
                    " auth failure [{}] reason [{}]",
                    OauthConstant.url(httpConfigInfo,OauthConstant.OAUTH_URL_PWD_AUTH_POST),
                    token == null ? "" : token.getErrMsg());
            throw new ClientException(
                    "GrantType [password] username=["
                            + IccProfile.username
                            + "],password=["
                            + IccProfile.password
                            + "] get access_token failure");
        }
        IccTokenResponse.IccToken iccToken = token.getData();
        /** 设置存活时间ttl,其中 expires_in 单位是秒 */
        iccToken.setTtl(System.currentTimeMillis() + (iccToken.getExpires_in() * 1000));
        return iccToken;
    }

    /**
     * 保活接口需要鉴权,需要原始配置信息
     * @param magicId
     * @param type
     * @return
     * @throws ClientException
     */
    public BrmKeepAliveResponse keepAlive(OauthConfigBaseInfo oauthConfigBaseInfo,String magicId,OauthConstant.ClientType type) throws ClientException {
        IClient iClient = new IccClient(oauthConfigBaseInfo);
        BrmKeepAliveRequest request = new BrmKeepAliveRequest(oauthConfigBaseInfo.getHttpConfigInfo());
        request.setMagicId(magicId);
        request.setClientType(type.getClientType());
        LogUtils.printIn(logger,request);
        BrmKeepAliveResponse brmKeepAliveResponse = iClient.doAction(request,request.getResponseClass());
        LogUtils.printOut(logger,request.getRequestUniqueCode(),brmKeepAliveResponse.getResult());
        return brmKeepAliveResponse;
    }

    public OauthRefreshTokenResponse refreshToken(OauthConfigBaseInfo oauthConfigBaseInfo,String refreshToken) throws ClientException {
        IClient iClient = new IccClient(oauthConfigBaseInfo);
        OauthRefreshTokenRequest oauthRefreshTokenRequest = new OauthRefreshTokenRequest(oauthConfigBaseInfo.getHttpConfigInfo());
        oauthRefreshTokenRequest.setClient_id(oauthConfigBaseInfo.getClientId());
        oauthRefreshTokenRequest.setClient_secret(oauthConfigBaseInfo.getClientSecret());
        oauthRefreshTokenRequest.setGrant_type(GrantType.refresh_token.name());
        oauthRefreshTokenRequest.setRefresh_token(refreshToken);
        LogUtils.printIn(logger,oauthRefreshTokenRequest);
        OauthRefreshTokenResponse oauthRefreshTokenResponse = iClient.doAction(oauthRefreshTokenRequest,oauthRefreshTokenRequest.getResponseClass());
        LogUtils.printOut(logger,oauthRefreshTokenRequest.getRequestUniqueCode(),oauthRefreshTokenResponse.getResult());
        return oauthRefreshTokenResponse;
    }

    public static synchronized OauthProcessor getIntance(){
        return SingleHolder.INSTANCE;
    }

    private static class SingleHolder{
        private final static OauthProcessor INSTANCE = new OauthProcessor();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy