springsecurity+oauth2整合微信登录

1.首先是找到 微信登录的文档

2.准备工作申请appid和secret(或者找黑马/尚硅谷的)

3.了解主要流程:

4.生成二维码:首先根据微信开发提供的JS生成二维码:两个重要参数:appid,redirect_uri:重定向地址至我们后端微信服务接口

 var obj = new WxLogin({
 self_redirect:true,
 id:"login_container", 
 appid: "", 
 scope: "", 
 redirect_uri: "",
  state: "",
 style: "",
 href: ""
 });

5.在微信登录服务接口中我们主要进行以下操作:申请access_token,通过access_token获取用户信息,如果是新用户则将用户信息保存至数据库,是老用户则直接登录

即图中的重定向,授权码————>>自动登录

    @RequestMapping("/wxLogin")
    public String wxLogin(String code, String state) throws IOException {
        log.debug("微信扫码回调,code:{},state:{}",code,state);
        //请求微信申请令牌,拿到令牌查询用户信息,将用户信息写入本项目数据库
        XcUser xcUser = wxAuthService.wxAuth(code);
        if(xcUser==null){
            return "redirect:http://localhost/error.html";
        }
        String username = xcUser.getUsername();
        return "redirect:http://localhost/sign.html?username="+username+"&authType=wx";
    }
}

申请令牌环节需要我们对接第三方服务,这里我们使用了restTemplate

    @Bean
    RestTemplate restTemplate(){
        RestTemplate restTemplate = new RestTemplate(new OkHttp3ClientHttpRequestFactory());
        return restTemplate;
    }

下面我们以授权码申请token为例(在书写规范的前提下一定要记得写&,这里我使用的JDK8,没有JDK16的代码块功能,appid和secret尽量不要硬编码)

    private Map<String,String>getAccessToken(String code){
        String wxUrl_template="https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=appid&" +
                "secret=secret&" +
                String.format("code=%s&", code)+
                "grant_type=authorization_code";
        ResponseEntity<String> exchange = restTemplate.exchange(wxUrl_template, HttpMethod.GET, null, String.class);
        String body = exchange.getBody();
        return JSON.parseObject(body,Map.class);
    }

微信登录的主要环节后端就是这么一个链:授权码申请token-->token+openid申请用户信息-->用户信息比对数据库是否存在,不存在则写入。

  # 值得注意的一点是:微信规定,用户信息的UnionID用于区别。openId是普通用户的表示,他只对当前开发者账号唯一

6.执行完return后我们debug的环境就进入到UserDetailsService(也就是说这里我们提交了用户名与密码)接下来进行的是springsecurity的一套流程:封装出一个authentication对象,通过DaoAuthenticationProvider传给UserDetailsService,然后再回调验证 springsecurity流程梳理与总结

7.在前文中我们通过策略模式实现了多登录 springsecurity通过策略模式设置统一认证接口

8.在实现WxAuthService的execute中,我们就不需要再像那样大费周章验证验证码,只需要查出User和其具体的Role,把他返回就好了。

关于User和Role的联系

posted @ 2024-07-29 23:36  天启A  阅读(783)  评论(0)    收藏  举报