介绍
现在互联网项目中,在个人主页也经常出现绑定了哪些社交账号,或者要解绑哪个账号。spring social也提供了一些方法,我们只需要该些配置即可实现该功能。
实现功能
社交账号绑定解绑功能
实现步骤
接着上一章的源码补充代码
查看某个账号绑定了哪些社交账号
/**
* @author lvhaibao
* @description 查看某个账号绑定了哪些社交账号
* @date 2019/1/7 0007 14:39
*/
@Component("connect/status")
public class MyConnectionStatusView extends AbstractView {
@Autowired
private ObjectMapper objectMapper;
@SuppressWarnings("unchecked")
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
HttpServletResponse response) throws Exception {
Map<String, List<Connection<?>>> connections = (Map<String, List<Connection<?>>>) model.get("connectionMap");
Map<String, Boolean> result = new HashMap<>();
for (String key : connections.keySet()) {
result.put(key, CollectionUtils.isNotEmpty(connections.get(key)));
}
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(objectMapper.writeValueAsString(result));
}
}
绑定解绑之后的提示
/**
* @author lvhaibao
* @description 绑定解绑页面提示
* @date 2019/1/7 0007 15:05
*/
@Slf4j
public class MyConnectView extends AbstractView {
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
HttpServletResponse response) throws Exception {
response.setContentType("text/html;charset=UTF-8");
if (model.get("connections") == null) {
log.info("解绑成功");
response.getWriter().write("<h3>解绑成功</h3>");
} else {
log.info("绑定成功");
response.getWriter().write("<h3>绑定成功</h3>");
}
}
}
配置绑定解绑
/**
* @author lvhaibao
* @description
* @date 2019/1/4 0004 9:58
*/
@Configuration
@ConditionalOnProperty(prefix = "system.social.weixin", name = "app-id")
public class WeixinAutoConfiguration extends SocialAutoConfigurerAdapter {
@Autowired
private SecurityProperties securityProperties;
@Override
protected ConnectionFactory<?> createConnectionFactory() {
WeixinProperties weixinConfig = securityProperties.getSocial().getWeixin();
return new WeixinConnectionFactory(weixinConfig.getProviderId(), weixinConfig.getAppId(),
weixinConfig.getAppSecret());
}
@Bean({"connect/weixinConnect", "connect/weixinConnected"})
@ConditionalOnMissingBean(name = "weixinConnectedView")
public View weixinConnectedView() {
return new MyConnectView();
}
}
配置绑定页面
@GetMapping("/social/binding")
public String binding(){
return "/demo-binding";
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>登录</title>
</head>
<body>
<h2>Demo绑定页</h2>
<!--connectw为固定值,weixin为providerId-->
<form action="/connect/weixin" method="post">
<button type="submit">绑定微信</button>
</form>
</body>
</html>
测试
首先在user表中添加一个账号,该账号没社交信息数据。
访问 URI为:/connect。即可出现:
然后访问绑定微信页面URI:/social/binding。然后点击帮绑定登录微信即可。此时在数据库后台中出现了该用户的社交账号。
再继续访问URI:/connect。即可出现:
项目源码
https://gitee.com/lvhaibao/spring-lhbauth/tree/469f822d3af964c470c69723c154964c133ef1b6/