实现钉钉扫码登陆

在钉钉开放平台查看:实现登录第三方网站 - 钉钉开放平台

1、在开发者后台创建应用,创建完应用之后,拿到应用的AppKey和AppSecret。

2、添加接口权限

3、配置frp内网穿透:(当第四步使用回调域名的重定向地址时,这一步可以省略)

使用frp内网穿透工具生成一个公网域名用于教程测试

内网穿透:让内网或私有网络的服务能够被公网访问

FRP:帮助内网中的服务通过公网服务器进行转发,实现内网穿透。

4、在应用中的分享设置中,通过设置第三方网站的回调域名,设置一下重定向的地址

5、官网上说是搭建后端服务,我前端就没看,忽略

6、实现登录第三方网站,我是使用钉钉提供的页面进行登录授权的,根据钉钉提供的第三方网站访问地址来登录。
https://login.dingtalk.com/oauth2/auth?
redirect_uri=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwww.aaaaa.com%2Fauth
&response_type=code        //固定值为code,授权通过后返回authCode
&client_id=dingxxxxxxx   //应用的AppKey 
&scope=openid   //此处的openId保持不变,授权后可获得用户userid
&state=dddd
&prompt=consent


代码实现:

实现思路:1、设置根据钉钉提供的第三方网站访问地址定义的重定向地址,得到浏览器网址,

2、然后获取地址栏的参数authcode,然后把authcode作为参数调用后端接口,从而获取数据res,

3、并且把数据存储在localstorage中。

1、首先根据钉钉提供的第三方网站访问地址,设置重定向的地址,(这部分是钉钉提供的固定部分)。得到浏览器网址,并且赋值给浏览器
//获取要重定向的地址
redirectToDingTalk() {
      var redirectUrl =
        'https://login.dingtalk.com/oauth2/challenge.htm?                
         redirect_uri=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttp%2F127.0.0.1%3A8080%2F%23%2F
         &response_type=code
         &client_id=dinglyjekzn80ebnlyge
         &scope=openid
         &state=dddd
         &prompt=consent'
//在浏览器中进行页面重定向
      window.location.href = redirectUrl
    },

 

2、定义一个获取地址栏参数的方法,用于拿到调用接口所需要的数据authCode
    // 获取地址栏参数
    getUrlParam(name) {
      var temp = window.location.href.split('?')[1]
      var pram = new URLSearchParams('?' + temp)
      return pram.get(name)
    },
3、给定一个按钮,绑定点击事件scanLogin()
// 扫码登陆
    scanLogin() {
      //获取充定向的地址
      this.redirectToDingTalk();

      // 获取地址栏参数
      let authCode = this.getUrlParam('authCode')
      if (authCode) {
        // 调用跳转接口
        reqRedirect(authCode).then((res) => {
          if (res.code == 0) {
            console.log(res, '扫码登陆')
            localStorage.setItem('authCode', authCode)
            localStorage.setItem('name', res.data.name)
            //把token也进行存储
            localStorage.setItem('token',res.data.auth_token)
            this.$router.push('/home/robotManage')
          } else {
            window.location.href = 'http://localhost:8080/#/'
          }
        })
      }
    }

### 使用 Spring Boot 实现钉钉登录 为了实现基于 Spring Boot 的钉钉登录功能,需遵循一系列开发步骤并集成必要的依赖项。具体而言,在应用程序中集成了钉钉 SDK 后,还需完成钉钉开放平台上的应用注册流程以获得 `AppId` 和 `AppSecret`[^1]。 #### 准备工作 - **引入依赖** 在项目的 `pom.xml` 文件内加入如下 Maven 依赖: ```xml <dependency> <groupId>com.dingtalk</groupId> <artifactId>dingtalk-open-client-sdk</artifactId> <version>LATEST_VERSION</version> </dependency> ``` 请注意替换 `LATEST_VERSION` 为最新版本号。 - **配置文件设置** 编辑 `application.properties` 或者 `application.yml` 来存储从钉钉开发者后台得到的应用凭证信息: ```yaml spring: dingtalk: app-id: YOUR_APP_ID app-secret: YOUR_APP_SECRET redirect-uri: http://yourdomain.com/callback/dingtalk ``` 其中 `YOUR_APP_ID`, `YOUR_APP_SECRET` 是之前提到的必要参数;而 `redirect-uri` 则指定了用户同意授权后的跳转地址[^3]。 #### 编写控制器逻辑 创建一个新的 Controller 类用于处理来自 DingTalk OAuth2 流程中的请求: ```java @RestController @RequestMapping("/auth") public class AuthController { @Value("${spring.dingtalk.app-id}") private String appId; @Value("${spring.dingtalk.redirect-uri}") private String redirectUri; /** * 获取钉钉授权链接. */ @GetMapping("/login") public ResponseEntity<String> getDingTalkAuthUrl() { StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append("https://oapi.dingtalk.com/connect/qrconnect?"); try { Map<String, Object> params = Maps.newHashMap(); params.put("appid", URLEncoder.encode(appId, StandardCharsets.UTF_8.toString())); params.put("response_type", "code"); params.put("scope", "snsapi_login"); params.put("state", UUID.randomUUID().toString()); params.put("redirect_uri", URLEncoder.encode(redirectUri, StandardCharsets.UTF_8.toString())); for (Map.Entry<String, Object> entry : params.entrySet()) { urlBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&"); } // 去掉最后一个多余的 & if (urlBuilder.length() > 0) { urlBuilder.setLength(urlBuilder.length() - 1); } return ResponseEntity.ok(urlBuilder.toString()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } } } ``` 此段代实现了生成钉钉授权 URL 并返回给前端页面调用的功能。当用户点击该链接时会被引导至钉钉进行身份验证操作。 #### 处理回调响应 定义另一个方法用来接收由钉钉服务器发送过来的身份认证成功之后的数据包,并从中解析出用户的唯一标识符(即 `userId`),以便后续业务逻辑使用: ```java /** * 授权回调接口. */ @PostMapping("/callback/dingtalk") @ResponseBody public void handleCallback(@RequestParam(value="code") String code, HttpServletResponse response){ // 构建获取 access_token 请求体... MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add("grant_type","authorization_code"); formData.add("client_id",appId); formData.add("client_secret",appSecret); formData.add("code",code); RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData,headers); ResponseEntity<Map> exchangeResult = restTemplate.exchange( "https://oapi.dingtalk.com/sns/gettoken", HttpMethod.POST,requestEntity,new ParameterizedTypeReference<Map>() {}); Map body = exchangeResult.getBody(); String accessToken = (String)body.get("access_token"); // ...继续构建查询 userId 请求... // 将 userId 存储到 session 或数据库中供其他服务访问 } ``` 上述片段展示了如何通过 POST 方法捕获回调路径 `/callback/dingtalk` 上携带的临时授权 (`code`) ,进而换取正式的 `accessToken` 及最终的目标——用户 ID(`userId`) 。这些数据可以被保存下来作为识别已登录状态下的个体依据。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值