OAuth对接实践 - Linux应用
本章结合Demo代码,介绍单租户托管型应用免登及用户信息获取的相关流程。开发之前,请务必参考详细的对接专题文档,以便对OAuth对接有全面的了解。注:本Demo代码,基于Springboot框架开发,下载链接请参考文章底部的“示例Demo”。
1 获取oauthcode
根据环境变量获取到的appkey与请求头获取跳转地址拼接鉴权URL并访问该URL。示例代码如下:
//-----要先进行部署上线获取到appkey和appSecret-------//
private static Logger logger = LoggerFactory.getLogger(Oauth2Controller.class);
/**
* 注意: //-----要先进行部署上线获取到appkey和appSecret-------
* //环境变量获取appkey和appSecret也可能为iot_hosting_appKey和iot_hosting_appSecret;需要和终端查看的保持一致
*/
public static final String OAUTH_CLIENT_ID = System.getenv("iot.hosting.appKey");
public static final String OAUTH_CLIENT_SECRET = System.getenv("iot.hosting.appSecret");
private static String response_type = "code";
private static String redirectUrlPage = "\"http://\" + request.getHeader(\"Host\")";//是跳转自己系统应用的访问入口,可通过请求头获取
public static final String OAUTH_CLIENT_AUTHORIZE = System.getenv("iot.host.oauth.domain");
public static final String REDIRECT_URL = System.getenv("iot.hosting.api.domain");
/**
* 第一次请求:返回为callback地址和code值
* <p>
* 拼接示例:https://account.iot.aliyun.com/oauth2/auth?&&redirect_uri=http://47.95.191.3:8***&client_id=2768****&response_type=code
*
* @throws Exception
*/
@RequestMapping("/redirectToRequestAuthorizationCodeURL")
public String redirectToRequestAuthorizationCodeURL(HttpServletRequest request) throws Exception {
// accessTokenRequest 是用来描述请求对象的,描述了请求地址,和请求参数
OAuthClientRequest accessTokenRequest = OAuthClientRequest.authorizationLocation(OAUTH_CLIENT_AUTHORIZE)
.setResponseType(response_type).setClientId(OAUTH_CLIENT_ID).setRedirectURI(redirectUrlPage).buildQueryMessage();
return "redirect:" + accessTokenRequest.getLocationUri();
}
鉴权URL会连接到IoT平台进行相关验证,成功后会根据{ redirectUrl }中的地址进行跳转并携带code参数。该参数就是我们后续用到OAuthCode参数。示例代码如下:
http://39.97.129.***:****/?code=b27baa5b367baf46d6625989cadc87e7
⚠️注意格式为:请求头(http)+外部暴露的端口IP+请求appkey后获取的返回code值。
另外,一般我们的应用入口是登录页面与OAuth免登中的回调跳转地址共用一个地址,所以可以通过是否有code参数判断是否是OAuth回调跳转,原有的登录页面也应该保留。
/**
* 返回授权码
*
* @param request
* @return
* @throws Exception
*/
@RequestMapping("/getAuthorizationCode")
public Object getAuthorizationCode(HttpServletRequest request) throws Exception {
OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(request);
String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);
String authorizationCode = oauthRequest.getParam(OAuth.OAUTH_CODE);
//把 state 写到一个 重定向的响应
OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse.authorizationResponse(request, HttpServletResponse.SC_FOUND);
builder.setCode(authorizationCode);
OAuthResponse response = builder.location(redirectURI).buildQueryMessage();
return "redirect:" + response.getLocationUri();
}
2 获取access_token
在调用getAccessTokenByAuthCode接口获取access_token。示例代码如下:
/**
* 发送请求返回
* 根据authcode来获取accesstoken
* <p>
* api: getAccessTokenByAuthCode
*
* @param request
* @return
* @throws Exception
*/
@RequestMapping("/getAccessTokenByAuthCode")
public Object getAccessTokenByAuthCode(HttpServletRequest request) throws Exception {
String code = "835d5af7a835239a9566a1f9078d83a0";//测试使用 request.getHeader("code")
IoTApiClientBuilderParams IoTApiClientBuilderParams =
new IoTApiClientBuilderParams();
IoTApiClientBuilderParams.setAppKey("2776****");
IoTApiClientBuilderParams.setAppSecret("9ca6b2b12aa35b4549659b9****");
SyncApiClient syncClient = new SyncApiClient(IoTApiClientBuilderParams);
IoTApiRequest request1 = new IoTApiRequest();
//设置api的版本
request1.setApiVer("1.0.1");
request1.putParam("code", code);
request1.putParam("grant_type", "code");
request1.putParam("redirect_uri", "http://39.97.129.***:****");
request1.putParam("client_id", "2776****");
//请求参数域名、path、request
ApiResponse response = syncClient.postBody(REDIRECT_URL,
"/user/oauth2/token/get", request1, true);
System.out.println("response code = " + response.getCode()
+ " response = " + new String(response.getBody(), "UTF-8"));
return "redirect:requestResourcePage?accessToken=" + response.getMessage();
}
3 获取用户信息
在调用getUserInfoByAccessToken接口获取access_token。示例代码如下:
/**
* 发送请求返回
* oauth2的授权,根据accesstoken获取用户信息
* <p>
* api: getUserInfoByAccessToken
*
* @param
* @return
* @throws Exception
*/
@RequestMapping("/getUserInfoByAccessToken")
public Object getUserInfoByAccessToken() throws Exception {
String token = "e171cd3d7c71ed189afb8ef5950adb58";
IoTApiClientBuilderParams IoTApiClientBuilderParams =
new IoTApiClientBuilderParams();
IoTApiClientBuilderParams.setAppKey("2776****");
IoTApiClientBuilderParams.setAppSecret("9ca6b2b12aa35b4549659b9****");
SyncApiClient syncClient = new SyncApiClient(IoTApiClientBuilderParams);
IoTApiRequest request1 = new IoTApiRequest();
//设置api的版本
request1.setApiVer("1.0.2");
request1.putParam("access_token", token);
//请求参数域名、path、request
ApiResponse response = syncClient.postBody(REDIRECT_URL,
"/user/oauth2/userinfo/get", request1, true);
System.out.println("response code = " + response.getCode()
+ " response = " + new String(response.getBody(), "UTF-8"));
return "redirect:requestResourcePage?userInfo=" + response.getMessage();
}
4 实现免登
按照上面操作完成后,系统会按照这个逻辑判断用户是否需要免登,我们拿到了IoT平台用户的相关信息,在系统应用中就可以判断该用户是否存在,是否是第一次登入系统等,来实现免登逻辑:a、如果用户是首次登录,则可以根据获取到的IoT用户信息在系统内创建账号密码与初始化账户相关的信息。b、如果用户是首次登录且需要收集用户额外的信息,比如所属企业信息,还可以展示一个收集信息的页面,收集信息后再创建用户账户信息。c、如果用户是首次登录,可以创建随机的,让用户登入系统后提示其再修改密码。也可以计算一个一段时间内有效的sign签名实现免登。
5 示例Demo
下载地址:OAuth Demo for Linux