1. 注册百度开发者账号
1.注册:百度Passport
2.登录百度开发者中心:百度开发者中心
2. 创建第三方授权应用
进入百度开发者控制台应用管理页面“创建工程”,开始创建应用。
3. 获取百度应用令牌
记录以下三个信息:API Key、Secret Key和应用回调地址,后面我们会用到。
4. 应用系统集成
下载
**JustAuth-demo**工程,gitee或github均可。git clone https://gitee.com/justauth/JustAuth-demo.git
修改配置参数。
- application.properties
根据实际情况修改端口、Redis等配置信息。
server.port=8443spring.thymeleaf.cache=falsespring.devtools.restart.additional-paths=src/main/javaspring.devtools.restart.exclude=static/**,public/**# Redis配置spring.redis.database=0spring.redis.host=localhostspring.redis.port=6379spring.redis.password=
- me.zhyd.justauth.RestAuthController
将获取的码云应用令牌信息(Client ID -> API Key、Client Secret -> Secret Key)更新至控制器,同时需要确保在开发者后台配置的回调地址与“redirectUri”保持一致。
/*** 根据具体的授权来源,获取授权请求工具类*/private AuthRequest getAuthRequest(String source) {AuthRequest authRequest = null;switch (source.toLowerCase()) {case "baidu":authRequest = new AuthBaiduRequest(AuthConfig.builder().clientId("${Client ID}").clientSecret("${Client Secret}").redirectUri("http://localhost:8443/oauth/callback/baidu").scopes(Arrays.asList(AuthBaiduScope.BASIC.getScope(),AuthBaiduScope.SUPER_MSG.getScope(),AuthBaiduScope.NETDISK.getScope())).build());break;// ....default:break;}if (null == authRequest) {throw new AuthException("未获取到有效的Auth配置");}return authRequest;}
扫描登录处理逻辑,需根据实际需要进行修改,此处示例登录成功后跳转至第三方站点。
@RequestMapping("/callback/{source}")public ModelAndView login(@PathVariable("source") String source, AuthCallback callback, HttpServletRequest request) {AuthRequest authRequest = getAuthRequest(source);AuthResponse<AuthUser> response = authRequest.login(callback);log.info(JSONObject.toJSONString(response));if (response.ok()) {userService.save(response.getData());// 示例:登录成功后跳转至第三方站点return new ModelAndView("redirect:http://localhost:8089/bcm-szx-sati/index.html#/home");}Map<String, Object> map = new HashMap<>(1);map.put("errorMsg", response.getMsg());return new ModelAndView("error", map);}
- 启动工程,选择“百度”,手机扫描二维码,进行验证。

- 响应消息。
根据响应消息,可获取**token**(包含:**accessToken**),之后通过这些信息可获取扫描用户更多授权信息。
{"code":2000,"data":{"avatar":"http://himg.bdimg.com/sys/portrait/item/1ea2e5878cxxxe4b8bf4882.jpg","gender":"MALE","nickname":"凌***丿","rawUserInfo":{"birthday":"2009-04-05","openid":"oD0ag_m52Xxxxxx6wWP2Dbm1X","sex":"1","is_realname":"1","portrait":"1ea2e5878cxxx4b8bf4882","is_bind_mobile":"1","blood":"2","username":"凌***丿"},"source":"BAIDU","token":{"accessToken":"121.7f063a00b80xxxP8H6YxcJqD.C3r33w","expireIn":2592000,"refreshToken":"122.b8cff99fe00cbxxxxZt-xSF906TGkEmPvdEn.IUdj0g","scope":"basic"},"username":"凌***丿","uuid":"oD0ag_m52xxxWP2Dbm1X"}}
参考
JustAuth:集成第三方企业平台指南-百度登录
https://justauth.wiki/guide/oauth/baidu/
