• 认证服务------功能实现逻辑


    认证服务分为两种,一种是社交登录,一种是单点登录,都交给认证中心(OAuth2.0)来处理,用一个专门的服务来作这个认证中心,所有的登录注册都是由这个认证中心来处理的,由于注册要发短信,短信又是调用了阿里云的接口, 这个发验证码短信的组件放到了第三方服务中,所以又需要调用第三方服务来发短信,最终的登录注册实现是写在用户服务里的,所以还需要远程调用用户服务

    单点登录注册

    一、用户注册功能(登录和注册都是以表单提交发的请求)

    1、实现发送手机验证码功能(手机验证码是存到Redis缓存中)

    (1)前端实现发送短信后倒计时效果和发送请求/sms/sendCode给后端处理

    1. <div class="register-box">
    2. <label class="other_label">验 证 码:
    3. <input name="code" maxlength="20" type="text" class="caa">
    4. </label>
    5. <a id="sendCode" class=""> 发送验证码 </a>
    6. </div>
    1. /**
    2. * 发送验证码请求给后端
    3. */
    4. $(function () {
    5. $("#sendCode").click(function () {
    6. //2、倒计时
    7. //只有class里有disabled就表示还在倒计时中,什么都不干(用于防止在倒计时期间重复发送验证码)
    8. if($(this).hasClass("disabled")) {
    9. //正在倒计时中
    10. } else {
    11. //1、给指定手机号发送验证码
    12. $.get("/sms/sendCode?phone=" + $("#phoneNum").val(),function (data) {
    13. if(data.code != 0) {
    14. alert(data.msg);
    15. }
    16. });
    17. timeoutChangeStyle();
    18. }
    19. });
    20. });
    21. /**
    22. * 实现验证码倒计时效果
    23. * @type {number}
    24. */
    25. var num = 60; //倒计时60s
    26. function timeoutChangeStyle() {
    27. //点击发送验证码后就设置其class为disabled(用于防止在倒计时期间重复发送验证码)
    28. $("#sendCode").attr("class","disabled");
    29. //倒计时结束
    30. if(num == 0) {
    31. $("#sendCode").text("发送验证码");
    32. num = 60;
    33. //清空前面加的class
    34. $("#sendCode").attr("class","");
    35. } else {
    36. var str = num + "s 后再次发送";
    37. $("#sendCode").text(str);
    38. //1s后再调用自身方法来实现倒计时
    39. setTimeout("timeoutChangeStyle()",1000);
    40. }
    41. num --;
    42. }

    (2)在认证服务的LoginController来处理请求/sms/sendCode(发短信验证码)

    分流程:(其实就是把短信验证码以下面的格式存到缓存再真正发送短信验证码

    Redis缓存中验证码的格式sms:code:123456789->123456_1646981054661 ,123456789是手机号,123456表示验证码,1646981054661表示存入缓存的时间

    1>判断Redis缓存里有没有这个手机号对应的验证码信息

    2>如果Redis缓存中有这个验证码信息那就要判断时间合法性(其实就是验证码有没有过期)

    3>创建验证码并且拼装成存入Redis缓存中的value值格式

    4>调用第三方服务来真正发送验证码

    1. /**
    2. * 短信验证码
    3. * @param phone
    4. * @return
    5. */
    6. @ResponseBody
    7. @GetMapping(value = "/sms/sendCode")
    8. public R sendCode(@RequestParam("phone") String phone) {
    9. /**
    10. * 接口防刷
    11. */
    12. //把验证码从缓存中提取出来
    13. //(缓存中验证码的格式sms:code:123456789->123456_1646981054661 ,123456789是手机号,123456表示验证码,1646981054661表示存入缓存的时间)
    14. String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
    15. if (!StringUtils.isEmpty(redisCode)) {
    16. //把存入缓存的验证码的值给提取出来(格式是123456_1646981054661 ,123456表示验证码,1646981054661表示存入缓存的时间)
    17. long currentTime = Long.parseLong(redisCode.split("_")[1]);
    18. //活动存入redis的时间,用当前时间减去存入redis的时间,判断用户手机号是否在60s内发送验证码
    19. if (System.currentTimeMillis() - currentTime < 60000) {
    20. //60s内不能再发
    21. // BizCodeEnum.SMS_CODE_EXCEPTION=10002 BizCodeEnum.SMS_CODE_EXCEPTION = 10002
    22. return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(),BizCodeEnum.SMS_CODE_EXCEPTION.getMessage());
    23. }
    24. }
    25. /**
    26. * 2、创建验证码存入redis.存key-phone,value-code
    27. */
    28. int code = (int) ((Math.random() * 9 + 1) * 100000);
    29. String codeNum = String.valueOf(code);
    30. //存入缓存的验证码格式是123456_1646981054661 加系统时间是为了防止多次刷新验证码
    31. String redisStorage = codeNum + "_" + System.currentTimeMillis();
    32. //存入redis,防止同一个手机号在60秒内再次发送验证码(存入缓存的格式sms:code:123456789->123456 ,其中123456789是手机号,123456是验证码)
    33. stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,
    34. redisStorage,10, TimeUnit.MINUTES);//AuthServerConstant.SMS_CODE_CACHE_PREFIX = sms:code:
    35. // String codeNum = UUID.randomUUID().toString().substring(0,6);
    36. thirdPartFeignService.sendCode(phone, codeNum);
    37. return R.ok();
    38. }

    注意:这里的短信验证码不是第三方服务发送的,具体短信验证码的内容是上面的sendCode方法随机生成的,这个验证码甚至可以自定义为666666,所以这个验证码的内容在上面sendCode方法就已经存到Redis缓存中,方便后面进行验证码校验

    (3)远程调用第三方服务来真正发送验证码

    1. package com.saodai.saodaimall.auth.feign;
    2. import com.saodai.common.utils.R;
    3. import org.springframework.cloud.openfeign.FeignClient;
    4. import org.springframework.web.bind.annotation.GetMapping;
    5. import org.springframework.web.bind.annotation.RequestParam;
    6. /**
    7. * 远程调用第三方服务来发送验证码
    8. **/
    9. @FeignClient("saodaimall-third-party")
    10. public interface ThirdPartFeignService {
    11. @GetMapping(value = "/sms/sendCode")
    12. R sendCode(@RequestParam("phone") String phone, @RequestParam("code") String code);
    13. }
    14. package com.saodai.saodaimall.thirdparty.controller;
    15. import com.saodai.common.utils.R;
    16. import com.saodai.saodaimall.thirdparty.component.SmsComponent;
    17. import org.springframework.web.bind.annotation.GetMapping;
    18. import org.springframework.web.bind.annotation.RequestMapping;
    19. import org.springframework.web.bind.annotation.RequestParam;
    20. import org.springframework.web.bind.annotation.RestController;
    21. import javax.annotation.Resource;
    22. /**
    23. * 短信验证码的控制器
    24. **/
    25. @RestController
    26. @RequestMapping(value = "/sms")
    27. public class SmsSendController {
    28. @Resource
    29. private SmsComponent smsComponent;
    30. /**
    31. * 提供给别的服务进行调用
    32. * @param phone
    33. * @param code
    34. * @return
    35. */
    36. @GetMapping(value = "/sendCode")
    37. public R sendCode(@RequestParam("phone") String phone, @RequestParam("code") String code) {
    38. //发送验证码
    39. smsComponent.sendCode(phone,code);
    40. return R.ok();
    41. }
    42. }
    43. package com.saodai.saodaimall.thirdparty.component;
    44. import com.saodai.saodaimall.thirdparty.util.HttpUtils;
    45. import lombok.Data;
    46. import org.apache.http.HttpResponse;
    47. import org.springframework.boot.context.properties.ConfigurationProperties;
    48. import org.springframework.stereotype.Component;
    49. import java.util.HashMap;
    50. import java.util.Map;
    51. /**
    52. * 短信验证码发送的组件类(提供发送短信验证码的接口)
    53. **/
    54. @ConfigurationProperties(prefix = "spring.cloud.alicloud.sms")
    55. @Data
    56. @Component
    57. public class SmsComponent {
    58. private String host;
    59. private String path;
    60. private String appcode;
    61. public void sendCode(String phone,String code) {
    62. String method = "POST";
    63. Map<String, String> headers = new HashMap<String, String>();
    64. //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
    65. headers.put("Authorization", "APPCODE " + appcode);
    66. //根据API的要求,定义相对应的Content-Type
    67. headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    68. Map<String, String> querys = new HashMap<String, String>();
    69. Map<String, String> bodys = new HashMap<String, String>();
    70. //注意这里的"code:"是必须要有的,正确的格式是"code:6666",没加code:就会报400错误,expire_at:6表示验证码有效时间为6分钟
    71. bodys.put("content", "code:"+code+",expire_at:6");
    72. bodys.put("phone_number", phone);
    73. //使用的是自定义的模板(content需要两个参数)
    74. bodys.put("template_id", "TPL_09229");
    75. try {
    76. HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
    77. System.out.println(response.toString());
    78. //获取response的body
    79. //System.out.println(EntityUtils.toString(response.getEntity()));
    80. } catch (Exception e) {
    81. e.printStackTrace();
    82. }
    83. }
    84. }
    1. package com.saodai.saodaimall.thirdparty.util;
    2. import org.apache.commons.lang.StringUtils;
    3. import org.apache.http.HttpResponse;
    4. import org.apache.http.NameValuePair;
    5. import org.apache.http.client.HttpClient;
    6. import org.apache.http.client.entity.UrlEncodedFormEntity;
    7. import org.apache.http.client.methods.HttpDelete;
    8. import org.apache.http.client.methods.HttpGet;
    9. import org.apache.http.client.methods.HttpPost;
    10. import org.apache.http.client.methods.HttpPut;
    11. import org.apache.http.conn.ClientConnectionManager;
    12. import org.apache.http.conn.scheme.Scheme;
    13. import org.apache.http.conn.scheme.SchemeRegistry;
    14. import org.apache.http.conn.ssl.SSLSocketFactory;
    15. import org.apache.http.entity.ByteArrayEntity;
    16. import org.apache.http.entity.StringEntity;
    17. import org.apache.http.impl.client.DefaultHttpClient;
    18. import org.apache.http.message.BasicNameValuePair;
    19. import javax.net.ssl.SSLContext;
    20. import javax.net.ssl.TrustManager;
    21. import javax.net.ssl.X509TrustManager;
    22. import java.io.UnsupportedEncodingException;
    23. import java.net.URLEncoder;
    24. import java.security.KeyManagementException;
    25. import java.security.NoSuchAlgorithmException;
    26. import java.security.cert.X509Certificate;
    27. import java.util.ArrayList;
    28. import java.util.List;
    29. import java.util.Map;
    30. /**
    31. * 阿里云短信验证码接口要用的工具类
    32. */
    33. public class HttpUtils {
    34. /**
    35. * get
    36. *
    37. * @param host
    38. * @param path
    39. * @param method
    40. * @param headers
    41. * @param querys
    42. * @return
    43. * @throws Exception
    44. */
    45. public static HttpResponse doGet(String host, String path, String method,
    46. Map<String, String> headers,
    47. Map<String, String> querys)
    48. throws Exception {
    49. HttpClient httpClient = wrapClient(host);
    50. HttpGet request = new HttpGet(buildUrl(host, path, querys));
    51. for (Map.Entry<String, String> e : headers.entrySet()) {
    52. request.addHeader(e.getKey(), e.getValue());
    53. }
    54. return httpClient.execute(request);
    55. }
    56. /**
    57. * post form
    58. *
    59. * @param host
    60. * @param path
    61. * @param method
    62. * @param headers
    63. * @param querys
    64. * @param bodys
    65. * @return
    66. * @throws Exception
    67. */
    68. public static HttpResponse doPost(String host, String path, String method,
    69. Map<String, String> headers,
    70. Map<String, String> querys,
    71. Map<String, String> bodys)
    72. throws Exception {
    73. HttpClient httpClient = wrapClient(host);
    74. HttpPost request = new HttpPost(buildUrl(host, path, querys));
    75. for (Map.Entry<String, String> e : headers.entrySet()) {
    76. request.addHeader(e.getKey(), e.getValue());
    77. }
    78. if (bodys != null) {
    79. List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
    80. for (String key : bodys.keySet()) {
    81. nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
    82. }
    83. UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
    84. formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
    85. request.setEntity(formEntity);
    86. }
    87. return httpClient.execute(request);
    88. }
    89. /**
    90. * Post String
    91. *
    92. * @param host
    93. * @param path
    94. * @param method
    95. * @param headers
    96. * @param querys
    97. * @param body
    98. * @return
    99. * @throws Exception
    100. */
    101. public static HttpResponse doPost(String host, String path, String method,
    102. Map<String, String> headers,
    103. Map<String, String> querys,
    104. String body)
    105. throws Exception {
    106. HttpClient httpClient = wrapClient(host);
    107. HttpPost request = new HttpPost(buildUrl(host, path, querys));
    108. for (Map.Entry<String, String> e : headers.entrySet()) {
    109. request.addHeader(e.getKey(), e.getValue());
    110. }
    111. if (StringUtils.isNotBlank(body)) {
    112. request.setEntity(new StringEntity(body, "utf-8"));
    113. }
    114. return httpClient.execute(request);
    115. }
    116. /**
    117. * Post stream
    118. *
    119. * @param host
    120. * @param path
    121. * @param method
    122. * @param headers
    123. * @param querys
    124. * @param body
    125. * @return
    126. * @throws Exception
    127. */
    128. public static HttpResponse doPost(String host, String path, String method,
    129. Map<String, String> headers,
    130. Map<String, String> querys,
    131. byte[] body)
    132. throws Exception {
    133. HttpClient httpClient = wrapClient(host);
    134. HttpPost request = new HttpPost(buildUrl(host, path, querys));
    135. for (Map.Entry<String, String> e : headers.entrySet()) {
    136. request.addHeader(e.getKey(), e.getValue());
    137. }
    138. if (body != null) {
    139. request.setEntity(new ByteArrayEntity(body));
    140. }
    141. return httpClient.execute(request);
    142. }
    143. /**
    144. * Put String
    145. * @param host
    146. * @param path
    147. * @param method
    148. * @param headers
    149. * @param querys
    150. * @param body
    151. * @return
    152. * @throws Exception
    153. */
    154. public static HttpResponse doPut(String host, String path, String method,
    155. Map<String, String> headers,
    156. Map<String, String> querys,
    157. String body)
    158. throws Exception {
    159. HttpClient httpClient = wrapClient(host);
    160. HttpPut request = new HttpPut(buildUrl(host, path, querys));
    161. for (Map.Entry<String, String> e : headers.entrySet()) {
    162. request.addHeader(e.getKey(), e.getValue());
    163. }
    164. if (StringUtils.isNotBlank(body)) {
    165. request.setEntity(new StringEntity(body, "utf-8"));
    166. }
    167. return httpClient.execute(request);
    168. }
    169. /**
    170. * Put stream
    171. * @param host
    172. * @param path
    173. * @param method
    174. * @param headers
    175. * @param querys
    176. * @param body
    177. * @return
    178. * @throws Exception
    179. */
    180. public static HttpResponse doPut(String host, String path, String method,
    181. Map<String, String> headers,
    182. Map<String, String> querys,
    183. byte[] body)
    184. throws Exception {
    185. HttpClient httpClient = wrapClient(host);
    186. HttpPut request = new HttpPut(buildUrl(host, path, querys));
    187. for (Map.Entry<String, String> e : headers.entrySet()) {
    188. request.addHeader(e.getKey(), e.getValue());
    189. }
    190. if (body != null) {
    191. request.setEntity(new ByteArrayEntity(body));
    192. }
    193. return httpClient.execute(request);
    194. }
    195. /**
    196. * Delete
    197. *
    198. * @param host
    199. * @param path
    200. * @param method
    201. * @param headers
    202. * @param querys
    203. * @return
    204. * @throws Exception
    205. */
    206. public static HttpResponse doDelete(String host, String path, String method,
    207. Map<String, String> headers,
    208. Map<String, String> querys)
    209. throws Exception {
    210. HttpClient httpClient = wrapClient(host);
    211. HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
    212. for (Map.Entry<String, String> e : headers.entrySet()) {
    213. request.addHeader(e.getKey(), e.getValue());
    214. }
    215. return httpClient.execute(request);
    216. }
    217. private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
    218. StringBuilder sbUrl = new StringBuilder();
    219. sbUrl.append(host);
    220. if (!StringUtils.isBlank(path)) {
    221. sbUrl.append(path);
    222. }
    223. if (null != querys) {
    224. StringBuilder sbQuery = new StringBuilder();
    225. for (Map.Entry<String, String> query : querys.entrySet()) {
    226. if (0 < sbQuery.length()) {
    227. sbQuery.append("&");
    228. }
    229. if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
    230. sbQuery.append(query.getValue());
    231. }
    232. if (!StringUtils.isBlank(query.getKey())) {
    233. sbQuery.append(query.getKey());
    234. if (!StringUtils.isBlank(query.getValue())) {
    235. sbQuery.append("=");
    236. sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
    237. }
    238. }
    239. }
    240. if (0 < sbQuery.length()) {
    241. sbUrl.append("?").append(sbQuery);
    242. }
    243. }
    244. return sbUrl.toString();
    245. }
    246. private static HttpClient wrapClient(String host) {
    247. HttpClient httpClient = new DefaultHttpClient();
    248. if (host.startsWith("https://")) {
    249. sslClient(httpClient);
    250. }
    251. return httpClient;
    252. }
    253. private static void sslClient(HttpClient httpClient) {
    254. try {
    255. SSLContext ctx = SSLContext.getInstance("TLS");
    256. X509TrustManager tm = new X509TrustManager() {
    257. public X509Certificate[] getAcceptedIssuers() {
    258. return null;
    259. }
    260. public void checkClientTrusted(X509Certificate[] xcs, String str) {
    261. }
    262. public void checkServerTrusted(X509Certificate[] xcs, String str) {
    263. }
    264. };
    265. ctx.init(null, new TrustManager[] { tm }, null);
    266. SSLSocketFactory ssf = new SSLSocketFactory(ctx);
    267. ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    268. ClientConnectionManager ccm = httpClient.getConnectionManager();
    269. SchemeRegistry registry = ccm.getSchemeRegistry();
    270. registry.register(new Scheme("https", 443, ssf));
    271. } catch (KeyManagementException ex) {
    272. throw new RuntimeException(ex);
    273. } catch (NoSuchAlgorithmException ex) {
    274. throw new RuntimeException(ex);
    275. }
    276. }
    277. }
    1. <!-- 阿里云对象存储,用于上传文件-->
    2. <dependency>
    3. <groupId>com.alibaba.cloud</groupId>
    4. <artifactId>spring-cloud-starter-alicloud-oss</artifactId>
    5. <version>2.2.0.RELEASE</version>
    6. </dependency>
    1. spring:
    2. cloud:
    3. alicloud:
    4. #短信验证码的配置
    5. sms:
    6. host: https://dfsns.market.alicloudapi.com
    7. path: /data/send_sms
    8. appcode: dbc663defb63426caefc7be0a8fe8cdf

    整个配置文件里就只有appcode是自己购买短信服务后唯一的码,其他的都是固定配置

    AppCode获取地址:阿里云登录 - 欢迎登录阿里云,安全稳定的云计算服务平台

    2、注册用户

    (1)前端以表单的形式发送请求/register给后端

    1. <form action="/register" method="post" class="one">
    2. <!-- <div style="color: red" th:text="${errors != null ? (#maps.containsKey(errors, 'msg') ? errors.msg : '') : ''}">-->
    3. <div class="register-box">
    4. <label class="username_label">用 户 名:
    5. <input name="userName" maxlength="20" type="text" >
    6. </label>
    7. <!-- #maps.containsKey(errors, 'userName')表示errors这个map里包含userName的话就取出报错信息,没有的话就输出空字符串-->
    8. <div class="tips" style="color: red" th:text="${errors != null ? (#maps.containsKey(errors, 'userName') ? errors.userName : '') : ''}">
    9. 错误提示区域,如果出错了就会从后端获取报错信息
    10. </div>
    11. </div>
    12. <div class="register-box">
    13. <label class="other_label">设 置 密 码:
    14. <input name="password" maxlength="20" type="password" >
    15. </label>
    16. <div class="tips" style="color: red" th:text="${errors != null ? (#maps.containsKey(errors, 'password') ? errors.password : '') : ''}">
    17. </div>
    18. </div>
    19. <div class="register-box">
    20. <label class="other_label">确 认 密 码:
    21. <input maxlength="20" type="password" >
    22. </label>
    23. <div class="tips">
    24. </div>
    25. </div>
    26. <div class="register-box">
    27. <label class="other_label">
    28. <span>中国 0086</span>
    29. <input name="phone" class="phone" id="phoneNum" maxlength="20" type="text" >
    30. </label>
    31. <div class="tips" style="color: red" th:text="${errors != null ? (#maps.containsKey(errors, 'phone') ? errors.phone : '') : ''}">
    32. </div>
    33. </div>
    34. <div class="register-box">
    35. <label class="other_label">验 证 码:
    36. <input name="code" maxlength="20" type="text" class="caa">
    37. </label>
    38. <a id="sendCode" class=""> 发送验证码 </a>
    39. </div>
    40. <div class="arguement">
    41. <input type="checkbox" id="xieyi"> 阅读并同意
    42. <a href="/static/reg/#">《谷粒商城用户注册协议》</a>
    43. <a href="/static/reg/#">《隐私政策》</a>
    44. <div class="tips" style="color: red" th:text="${errors != null ? (#maps.containsKey(errors, 'code') ? errors.code : '') : ''}">
    45. </div>
    46. <br/>
    47. <div class="submit_btn">
    48. <button type="submit" id="submit_btn">立 即 注 册</button>
    49. </div>
    50. </div>
    51. </form>

    (2)在认证服务的LoginController来处理请求/register

    分流程:

    1>获取用户输入的验证码和缓存里的验证码(这里要判断缓存中验证码为不为空)进行比较,看是否相同

    2>验证码相同就立马删除验证码(令牌机制),验证码不同报错同时重定向到注册界面

    3>远程调用会员服务进行真正的用户注册

    4>远程调用成功就重定向到首页,失败就把错误消息封装成map同时重定向到注册界面

    1. /**
    2. * 用户注册
    3. * TODO: 重定向携带数据:利用session原理,将数据放在session中。
    4. * TODO:只要跳转到下一个页面取出这个数据以后,session里面的数据就会删掉
    5. * TODO:分布下session问题
    6. * RedirectAttributes:重定向也可以保留数据,不会丢失
    7. *
    8. * @return
    9. */
    10. @PostMapping(value = "/register")
    11. public String register(@Valid UserRegisterVo vos, BindingResult result,
    12. RedirectAttributes attributes) {
    13. //1、效验验证码
    14. String code = vos.getCode();
    15. //获取存入Redis里的验证码(redisCode的格式是123456_1646981054661 ,123456表示验证码,1646981054661表示存入缓存的时间)
    16. String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone());
    17. //判断redis的对应的验证码是否为空
    18. if (!StringUtils.isEmpty(redisCode)) {
    19. //判断验证码是否相同
    20. if (code.equals(redisCode.split("_")[0])) {
    21. //删除验证码;令牌机制
    22. stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX+vos.getPhone());
    23. //验证码通过,真正注册,调用远程服务进行注册
    24. R register = memberFeignService.register(vos);
    25. //register.getCode() == 0表示远程调用成功
    26. if (register.getCode() == 0) {
    27. //成功
    28. return "redirect:http://saodaimall.com";
    29. } else {
    30. //失败
    31. Map<String, String> errors = new HashMap<>();
    32. errors.put("msg", register.getData("msg",new TypeReference<String>(){}));
    33. attributes.addFlashAttribute("errors",errors);
    34. return "redirect:http://auth.saodaimall.com/reg.html";
    35. }
    36. } else {
    37. //效验出错回到注册页面
    38. Map<String, String> errors = new HashMap<>();
    39. errors.put("code","验证码错误");
    40. attributes.addFlashAttribute("errors",errors);
    41. return "redirect:http://auth.saodaimall.com/reg.html";
    42. }
    43. } else {
    44. //redis的对应的验证码为空表示效验出错回到注册页面
    45. Map<String, String> errors = new HashMap<>();
    46. errors.put("code","验证码错误");
    47. attributes.addFlashAttribute("errors",errors);
    48. return "redirect:http://auth.saodaimall.com/reg.html";
    49. }
    50. }
    1. package com.saodai.saodaimall.auth.vo;
    2. import lombok.Data;
    3. import org.hibernate.validator.constraints.Length;
    4. import javax.validation.constraints.NotEmpty;
    5. import javax.validation.constraints.Pattern;
    6. /**
    7. * 用户注册信息封装类
    8. **/
    9. @Data
    10. public class UserRegisterVo {
    11. @NotEmpty(message = "用户名不能为空")
    12. @Length(min = 6, max = 19, message="用户名长度在6-18字符")
    13. private String userName;
    14. @NotEmpty(message = "密码必须填写")
    15. @Length(min = 6,max = 18,message = "密码必须是6—18位字符")
    16. private String password;
    17. @NotEmpty(message = "手机号不能为空")
    18. @Pattern(regexp = "^[1]([3-9])[0-9]{9}$", message = "手机号格式不正确")
    19. private String phone;
    20. @NotEmpty(message = "验证码不能为空")
    21. private String code;
    22. }

    (3)远程调用会员服务来实现真正的注册

    1. /**
    2. * 会员注册功能
    3. * @param vo
    4. * @return
    5. */
    6. @PostMapping(value = "/register")
    7. public R register(@RequestBody MemberUserRegisterVo vo) {
    8. try {
    9. memberService.register(vo);
    10. } catch (PhoneException e) {
    11. //BizCodeEnum.PHONE_EXIST_EXCEPTION=存在相同的手机号 15002
    12. return R.error(BizCodeEnum.PHONE_EXIST_EXCEPTION.getCode(),BizCodeEnum.PHONE_EXIST_EXCEPTION.getMessage());
    13. } catch (UsernameException e) {
    14. //BizCodeEnum.USER_EXIST_EXCEPTION=商品库存不足 21000
    15. return R.error(BizCodeEnum.USER_EXIST_EXCEPTION.getCode(),BizCodeEnum.USER_EXIST_EXCEPTION.getMessage());
    16. }
    17. return R.ok();
    18. }
    19. /**
    20. * 会员注册
    21. */
    22. @Override
    23. public void register(MemberUserRegisterVo vo) {
    24. MemberEntity memberEntity = new MemberEntity();
    25. //设置默认等级
    26. MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
    27. memberEntity.setLevelId(levelEntity.getId());
    28. //设置其它的默认信息
    29. //检查用户名和手机号是否唯一。感知异常,异常机制(异常机制就是问题就抛出具体异常,没问题就继续执行下面的语句)
    30. checkPhoneUnique(vo.getPhone());
    31. checkUserNameUnique(vo.getUserName());
    32. memberEntity.setNickname(vo.getUserName());
    33. memberEntity.setUsername(vo.getUserName());
    34. //密码进行MD5盐值加密(盐值加密同一个数据的每次加密结果是不一样的,通过match方法来密码校验)
    35. // (注意这里不能用md5直接加密放数据库,因为彩虹表可以破解md5,所谓彩虹表就是通过大量的md5数据反向退出md5
    36. // 注意MD5是不可逆,但是可暴力通过彩虹表破解)
    37. BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
    38. String encode = bCryptPasswordEncoder.encode(vo.getPassword());
    39. memberEntity.setPassword(encode);
    40. memberEntity.setMobile(vo.getPhone());
    41. memberEntity.setGender(0);
    42. memberEntity.setCreateTime(new Date());
    43. //保存数据
    44. this.baseMapper.insert(memberEntity);
    45. }
    46. /**
    47. * 检查手机号是否重复的异常机制方法
    48. * @param phone
    49. * @throws PhoneException
    50. */
    51. @Override
    52. public void checkPhoneUnique(String phone) throws PhoneException {
    53. Long phoneCount = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
    54. //usernameCount > 0表示手机号已经存在
    55. if (phoneCount > 0) {
    56. throw new PhoneException();
    57. }
    58. }
    59. /**
    60. * 检查用户名是否重复的异常机制方法
    61. * @param userName
    62. * @throws UsernameException
    63. */
    64. @Override
    65. public void checkUserNameUnique(String userName) throws UsernameException {
    66. Long usernameCount = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
    67. //usernameCount > 0表示用户名已经存在
    68. if (usernameCount > 0) {
    69. throw new UsernameException();
    70. }
    71. }

    分流程:(封装MemberEntity对象)

    1>设置默认等级

    1. package com.saodai.saodaimall.member.entity;
    2. import com.baomidou.mybatisplus.annotation.TableId;
    3. import com.baomidou.mybatisplus.annotation.TableName;
    4. import lombok.Data;
    5. import java.io.Serializable;
    6. import java.math.BigDecimal;
    7. /**
    8. * 会员等级
    9. */
    10. @Data
    11. @TableName("ums_member_level")
    12. public class MemberLevelEntity implements Serializable {
    13. private static final long serialVersionUID = 1L;
    14. /**
    15. * id
    16. */
    17. @TableId
    18. private Long id;
    19. /**
    20. * 等级名称
    21. */
    22. private String name;
    23. /**
    24. * 等级需要的成长值
    25. */
    26. private Integer growthPoint;
    27. /**
    28. * 是否为默认等级[0->不是;1->是]
    29. */
    30. private Integer defaultStatus;
    31. /**
    32. * 免运费标准
    33. */
    34. private BigDecimal freeFreightPoint;
    35. /**
    36. * 每次评价获取的成长值
    37. */
    38. private Integer commentGrowthPoint;
    39. /**
    40. * 是否有免邮特权
    41. */
    42. private Integer priviledgeFreeFreight;
    43. /**
    44. * 是否有会员价格特权
    45. */
    46. private Integer priviledgeMemberPrice;
    47. /**
    48. * 是否有生日特权
    49. */
    50. private Integer priviledgeBirthday;
    51. /**
    52. * 备注
    53. */
    54. private String note;
    55. }
    56. <!-- 查询出默认等级-->
    57. <select id="getDefaultLevel" resultType="com.saodai.saodaimall.member.entity.MemberLevelEntity">
    58. SELECT * FROM ums_member_level WHERE default_status = 1
    59. </select>
    60. 2>检查用户名和手机号是否唯一,通过异常机制来感知异常(异常机制就是问题就抛出具体异常,没问题就继续执行下面的语句)
    61. package com.saodai.saodaimall.member.exception;
    62. public class UsernameException extends RuntimeException {
    63. public UsernameException() {
    64. super("存在相同的用户名");
    65. }
    66. }
    67. package com.saodai.saodaimall.member.exception;
    68. public class PhoneException extends RuntimeException {
    69. public PhoneException() {
    70. super("存在相同的手机号");
    71. }
    72. }

    3>密码进行MD5盐值加密

    4>保存用户信息到数据库中

    1. package com.saodai.saodaimall.member.vo;
    2. import lombok.Data;
    3. /**
    4. * 会员注册类
    5. **/
    6. @Data
    7. public class MemberUserRegisterVo {
    8. private String userName;
    9. private String password;
    10. private String phone;
    11. }
    12. package com.saodai.saodaimall.member.entity;
    13. import com.baomidou.mybatisplus.annotation.TableId;
    14. import com.baomidou.mybatisplus.annotation.TableName;
    15. import lombok.Data;
    16. import java.io.Serializable;
    17. import java.util.Date;
    18. /**
    19. * 会员
    20. */
    21. @Data
    22. @TableName("ums_member")
    23. public class MemberEntity implements Serializable {
    24. private static final long serialVersionUID = 1L;
    25. /**
    26. * id
    27. */
    28. @TableId
    29. private Long id;
    30. /**
    31. * 会员等级id
    32. */
    33. private Long levelId;
    34. /**
    35. * 用户名
    36. */
    37. private String username;
    38. /**
    39. * 密码
    40. */
    41. private String password;
    42. /**
    43. * 昵称
    44. */
    45. private String nickname;
    46. /**
    47. * 手机号码
    48. */
    49. private String mobile;
    50. /**
    51. * 邮箱
    52. */
    53. private String email;
    54. /**
    55. * 头像
    56. */
    57. private String header;
    58. /**
    59. * 性别
    60. */
    61. private Integer gender;
    62. /**
    63. * 生日
    64. */
    65. private Date birth;
    66. /**
    67. * 所在城市
    68. */
    69. private String city;
    70. /**
    71. * 职业
    72. */
    73. private String job;
    74. /**
    75. * 个性签名
    76. */
    77. private String sign;
    78. /**
    79. * 用户来源
    80. */
    81. private Integer sourceType;
    82. /**
    83. * 积分
    84. */
    85. private Integer integration;
    86. /**
    87. * 成长值
    88. */
    89. private Integer growth;
    90. /**
    91. * 启用状态
    92. */
    93. private Integer status;
    94. /**
    95. * 注册时间
    96. */
    97. private Date createTime;
    98. /**
    99. * 社交登录用户的ID
    100. */
    101. private String socialId;
    102. /**
    103. * 社交登录用户的名称
    104. */
    105. private String socialName;
    106. /**
    107. * 社交登录用户的自我介绍
    108. */
    109. private String socialBio;
    110. }

    二、用户登录功能

    (1)前端以表单的形式发送请求/login给后端

    1. <form action="/login" method="post">
    2. <div style="color: red;height: 10px;text-align: center;" th:text="${errors != null ? (#maps.containsKey(errors, 'msg') ? errors.msg : '') : ''}"></div>
    3. <ul>
    4. <li class="top_1">
    5. <img src="/static/login/JD_img/user_03.png" class="err_img1"/>
    6. <input type="text" name="loginacct" placeholder=" 邮箱/用户名/已验证手机" class="user"/>
    7. </li>
    8. <li>
    9. <img src="/static/login/JD_img/user_06.png" class="err_img2"/>
    10. <input type="password" name="password" placeholder=" 密码" class="password"/>
    11. </li>
    12. <li class="bri">
    13. <a href="/static/login/" >忘记密码</a>
    14. </li>
    15. <li class="ent">
    16. <button class="btn2" type="submit">&nbsp; &nbsp;录</a></button>
    17. </li>
    18. </ul>
    19. </form>

    (2)在认证服务的LoginController来处理请求/login

    1. /**
    2. * 普通手机账号登录
    3. * @param vo
    4. * @param attributes
    5. * @param session
    6. * @return
    7. */
    8. @PostMapping(value = "/login")
    9. public String login(UserLoginVo vo, RedirectAttributes attributes, HttpSession session) {
    10. //远程登录
    11. R login = memberFeignService.login(vo);
    12. //login.getCode() == 0表示远程调用成功
    13. if (login.getCode() == 0) {
    14. MemberResponseVo data = login.getData("data", new TypeReference<MemberResponseVo>() {});
    15. session.setAttribute(LOGIN_USER,data);
    16. return "redirect:http://saodaimall.com";
    17. } else {
    18. Map<String,String> errors = new HashMap<>();
    19. errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
    20. attributes.addFlashAttribute("errors",errors);
    21. return "redirect:http://auth.saodaimall.com/login.html";
    22. }
    23. }
    1. package com.saodai.saodaimall.auth.vo;
    2. import lombok.Data;
    3. /**
    4. * 用户登录信息封装类
    5. **/
    6. @Data
    7. public class UserLoginVo {
    8. //账户
    9. private String loginacct;
    10. //密码
    11. private String password;
    12. }
    1. package com.saodai.common.vo;
    2. import lombok.Data;
    3. import lombok.ToString;
    4. import java.io.Serializable;
    5. import java.util.Date;
    6. /**
    7. *会员信息
    8. **/
    9. @ToString
    10. @Data
    11. public class MemberResponseVo implements Serializable {
    12. private static final long serialVersionUID = 5573669251256409786L;
    13. private Long id;
    14. /**
    15. * 会员等级id
    16. */
    17. private Long levelId;
    18. /**
    19. * 用户名
    20. */
    21. private String username;
    22. /**
    23. * 密码
    24. */
    25. private String password;
    26. /**
    27. * 昵称
    28. */
    29. private String nickname;
    30. /**
    31. * 手机号码
    32. */
    33. private String mobile;
    34. /**
    35. * 邮箱
    36. */
    37. private String email;
    38. /**
    39. * 头像
    40. */
    41. private String header;
    42. /**
    43. * 性别
    44. */
    45. private Integer gender;
    46. /**
    47. * 生日
    48. */
    49. private Date birth;
    50. /**
    51. * 所在城市
    52. */
    53. private String city;
    54. /**
    55. * 职业
    56. */
    57. private String job;
    58. /**
    59. * 个性签名
    60. */
    61. private String sign;
    62. /**
    63. * 用户来源
    64. */
    65. private Integer sourceType;
    66. /**
    67. * 积分
    68. */
    69. private Integer integration;
    70. /**
    71. * 成长值
    72. */
    73. private Integer growth;
    74. /**
    75. * 启用状态
    76. */
    77. private Integer status;
    78. /**
    79. * 注册时间
    80. */
    81. private Date createTime;
    82. /**
    83. * 社交登录用户的ID
    84. */
    85. private String socialId;
    86. /**
    87. * 社交登录用户的名称
    88. */
    89. private String socialName;
    90. /**
    91. * 社交登录用户的自我介绍
    92. */
    93. private String socialBio;
    94. }

    (3)远程调用会员服务来实现真正的登录

    1. /**
    2. * 会员登录功能
    3. * @param vo
    4. * @return
    5. */
    6. @PostMapping(value = "/login")
    7. public R login(@RequestBody MemberUserLoginVo vo) {
    8. //MemberUserLoginVo就是上面的UserLoginVo只是类名不一样
    9. MemberEntity memberEntity = memberService.login(vo);
    10. if (memberEntity != null) {
    11. return R.ok().setData(memberEntity);
    12. } else {
    13. return R.error(BizCodeEnum.LOGINACCT_PASSWORD_EXCEPTION.getCode(),BizCodeEnum.LOGINACCT_PASSWORD_EXCEPTION.getMessage());
    14. }
    15. }
    16. /**
    17. * 会员登录功能
    18. * @param vo
    19. * @return
    20. */
    21. @Override
    22. public MemberEntity login(MemberUserLoginVo vo) {
    23. //获取用户登录账号
    24. String loginacct = vo.getLoginacct();
    25. String password = vo.getPassword();
    26. //1、去数据库查询 SELECT * FROM ums_member WHERE username = ? OR mobile = ?
    27. //通过用户名或手机号登录都是可以的
    28. MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>()
    29. .eq("username", loginacct).or().eq("mobile", loginacct));
    30. if (memberEntity == null) {
    31. //登录失败
    32. return null;
    33. } else {
    34. //获取到数据库里的password
    35. String password1 = memberEntity.getPassword();
    36. BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    37. //进行密码匹配
    38. boolean matches = passwordEncoder.matches(password, password1);
    39. if (matches) {
    40. //登录成功
    41. return memberEntity;
    42. }
    43. }
    44. return null;
    45. }
    1. package com.saodai.saodaimall.member.vo;
    2. import lombok.Data;
    3. /**
    4. * 会员登录
    5. **/
    6. @Data
    7. public class MemberUserLoginVo {
    8. private String loginacct;
    9. private String password;
    10. }

    社交登录(OAuth2.0)

    这里由于微博开发者权限申请太慢了就使用gitee来实现社交登录

    (1)前端调用第三方应用作为社交登录

    这个跟以往的模式不一样,以往是前段直接给后端发送请求,然后后端处理请求,这个是先调用第三方应用作为社交登录(也就是先跳转到gitee的登录授权页面),然后用户登录自己的gitee账号密码进行授权,授权成功后会跳转到指定的应用回调地址,然后在后端来处理这个应用回调地址的请求

    gitee开发者后台管理链接:https://gitee.com/oauth/applications/16285

    调用gitee第三方登录的url地址:

    1. <li>
    2. <a href="https://gitee.com/oauth/authorize?client_id=32459f971ce6d89cfb9f70899525455d0653cb804f16b38a304e3447dc97d673&redirect_uri=http://auth.saodaimall.com/callback&response_type=code&state=1">
    3. <img style="width: 50px;height: 18px;margin-top: 35px;" src="/static/login/JD_img/gitee.png"/>
    4. </a>
    5. </li>

    (2)社交服务OAuth2Controller来处理应用回调地址/callback请求

    分流程:(其实就只有三行代码是要自己配置的(OAuth2Controller的gitee的42-44行),其他的基本上是固定的)

    1>封装AccessTokenDTO对象然后发给码云服务器,如果AccessTokenDTO对象正确的话就返回一个通行令牌(其实准确来说是用户授权后会返回一个code,然后通过code来去找码云服务器获取到一个通行令牌,最后通过这个通行令牌去找码云服务器要这个用户在gitee上公开的资料信息)

    2>获取到了access_token通行令牌,转为通用gitee社交登录GiteeUser对象

    3>远程调用会员服务来进行社交登录

    1. package com.saodai.saodaimall.auth.controller;
    2. import com.alibaba.fastjson.TypeReference;
    3. import com.saodai.common.utils.R;
    4. import com.saodai.common.vo.MemberResponseVo;
    5. import com.saodai.saodaimall.auth.component.GitheeProvider;
    6. import com.saodai.saodaimall.auth.feign.MemberFeignService;
    7. import com.saodai.saodaimall.auth.vo.AccessTokenDTO;
    8. import com.saodai.saodaimall.auth.vo.GiteeUser;
    9. import lombok.extern.slf4j.Slf4j;
    10. import org.springframework.beans.factory.annotation.Autowired;
    11. import org.springframework.stereotype.Controller;
    12. import org.springframework.util.StringUtils;
    13. import org.springframework.web.bind.annotation.GetMapping;
    14. import org.springframework.web.bind.annotation.RequestParam;
    15. import javax.servlet.http.HttpSession;
    16. import static com.saodai.common.constant.AuthServerConstant.LOGIN_USER;
    17. /**
    18. * 社交第三方授权登录
    19. **/
    20. @Slf4j
    21. @Controller
    22. public class OAuth2Controller {
    23. @Autowired
    24. private MemberFeignService memberFeignService;
    25. @Autowired
    26. private AccessTokenDTO accessTokenDTO;
    27. @Autowired
    28. private GitheeProvider githeeProvider;
    29. @GetMapping(value = "/callback")
    30. // /callback?code=e867a1f4575d4a6161e3249423a0403898253bc593e4b031a8771739ee6769f5&state=1
    31. public String gitee(@RequestParam(name = "code") String code,@RequestParam(name = "state") String state, HttpSession session) throws Exception {
    32. System.out.println(code);
    33. //下面三行代码都是自己应用的值,可以在gitee的第三方应用中看到对应的值
    34. accessTokenDTO.setClient_id("32459f971ce6d89cfb9f70899525455d0653cb804f16b38a304e3447dc97d673");
    35. accessTokenDTO.setClient_secret("f3046c911c03cadcded986062708150d4232af3ca6aef0259e5a0198d2c15ba5");
    36. accessTokenDTO.setRedirect_uri("http://auth.saodaimall.com/callback");
    37. accessTokenDTO.setCode(code);
    38. accessTokenDTO.setState(state);
    39. String accessToken = githeeProvider.getAccessToken(accessTokenDTO);
    40. //2、处理
    41. if (!StringUtils.isEmpty(accessToken)) {
    42. //获取到了access_token,转为通用gitee社交登录对象
    43. GiteeUser giteeUser = githeeProvider.getGiteeUser(accessToken);
    44. //知道了哪个社交用户
    45. //1)、当前用户如果是第一次进网站,自动注册进来(为当前社交用户生成一个会员信息,以后这个社交账号就对应指定的会员)
    46. //登录或者注册这个社交用户
    47. //调用远程服务
    48. R oauthLogin = memberFeignService.oauthLogin(giteeUser);
    49. if (oauthLogin.getCode() == 0) {
    50. MemberResponseVo memberResponseVo = oauthLogin.getData("data", new TypeReference<MemberResponseVo>() {});
    51. log.info("登录成功:用户信息:{}",memberResponseVo.toString());
    52. //1、第一次使用session,命令浏览器保存卡号,JSESSIONID这个cookie
    53. //以后浏览器访问哪个网站就会带上这个网站的cookie
    54. //TODO 1、默认发的令牌。当前域(解决子域session共享问题)
    55. //TODO 2、使用JSON的序列化方式来序列化对象到Redis中
    56. session.setAttribute(LOGIN_USER,memberResponseVo);
    57. //2、登录成功跳回首页
    58. return "redirect:http://saodaimall.com";
    59. } else {
    60. return "redirect:http://auth.saodaimall.com/login.html";
    61. }
    62. } else {
    63. return "redirect:http://auth.saodaimall.com/login.html";
    64. }
    65. }
    66. }
    1. package com.saodai.saodaimall.auth.vo;
    2. /**
    3. * AccessTokenDTO对象封装(gitee社交登录令牌)
    4. */
    5. import org.springframework.stereotype.Component;
    6. @Component
    7. public class AccessTokenDTO {
    8. private String client_id;
    9. private String client_secret;
    10. private String code;
    11. private String redirect_uri;
    12. private String state;
    13. public String getClient_id() {
    14. return client_id;
    15. }
    16. public void setClient_id(String client_id) {
    17. this.client_id = client_id;
    18. }
    19. public String getClient_secret() {
    20. return client_secret;
    21. }
    22. public void setClient_secret(String client_secret) {
    23. this.client_secret = client_secret;
    24. }
    25. public String getCode() {
    26. return code;
    27. }
    28. public void setCode(String code) {
    29. this.code = code;
    30. }
    31. public String getRedirect_uri() {
    32. return redirect_uri;
    33. }
    34. public void setRedirect_uri(String redirect_uri) {
    35. this.redirect_uri = redirect_uri;
    36. }
    37. public String getState() {
    38. return state;
    39. }
    40. public void setState(String state) {
    41. this.state = state;
    42. }
    43. }
    1. package com.saodai.saodaimall.auth.component;
    2. import com.alibaba.fastjson.JSON;
    3. import com.saodai.saodaimall.auth.vo.AccessTokenDTO;
    4. import com.saodai.saodaimall.auth.vo.GiteeUser;
    5. import okhttp3.*;
    6. import org.springframework.stereotype.Component;
    7. import java.io.IOException;
    8. /**
    9. * 请求码云服务器
    10. */
    11. @Component
    12. public class GitheeProvider {
    13. //发起post请求获取AccessToken
    14. public String getAccessToken(AccessTokenDTO accessTokenDTO){
    15. MediaType mediaType= MediaType.get("application/json; charset=utf-8");
    16. OkHttpClient client = new OkHttpClient();
    17. RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(accessTokenDTO));
    18. Request request = new Request.Builder()
    19. .url("https://gitee.com/oauth/token?grant_type=authorization_code&code="+accessTokenDTO.getCode()+
    20. "&client_id="+accessTokenDTO.getClient_id()+"&redirect_uri="+accessTokenDTO.getRedirect_uri()+
    21. "&client_secret="+accessTokenDTO.getClient_secret())
    22. .post(body)
    23. .build();
    24. try (Response response = client.newCall(request).execute()) {
    25. String string = response.body().string();
    26. System.out.println(string);
    27. String str1 = string.split(":")[1];
    28. String str2 = str1.split("\"")[1];
    29. return str2;
    30. } catch (IOException e) {
    31. e.printStackTrace();
    32. }
    33. return null;
    34. }
    35. //发起get请求返回GitUser对象,
    36. public GiteeUser getGiteeUser(String token){
    37. OkHttpClient client = new OkHttpClient();
    38. Request request = new Request.Builder()
    39. .url("https://gitee.com/api/v5/user?access_token="+token)
    40. .build();
    41. try (Response response = client.newCall(request).execute()) {
    42. String string=response.body().string();
    43. GiteeUser giteeUser = JSON.parseObject(string, GiteeUser.class);
    44. return giteeUser;
    45. } catch (IOException e) {
    46. e.printStackTrace();
    47. }
    48. return null;
    49. }
    50. }
    1. package com.saodai.saodaimall.auth.vo;
    2. import lombok.Data;
    3. /**
    4. * GiteeUser对象封装(社交登录的gitee对象)
    5. */
    6. @Data
    7. public class GiteeUser {
    8. //gitee用户名称
    9. private String name;
    10. //gitee用户id
    11. private String id;
    12. //gitee用户自我介绍
    13. private String bio;
    14. }

    (3)远程调用会员服务来进行社交登录

    1. /**
    2. * 社交登录
    3. * @param giteeUser
    4. * @return
    5. * @throws Exception
    6. */
    7. @PostMapping(value = "/oauth2/login")
    8. public R oauthLogin(@RequestBody GiteeUser giteeUser) throws Exception {
    9. MemberEntity memberEntity = memberService.login(giteeUser);
    10. if (memberEntity != null) {
    11. return R.ok().setData(memberEntity);
    12. } else {
    13. return R.error(BizCodeEnum.LOGINACCT_PASSWORD_EXCEPTION.getCode(),BizCodeEnum.LOGINACCT_PASSWORD_EXCEPTION.getMessage());
    14. }
    15. }
    16. /**
    17. * 社交登录
    18. * @param giteeUser
    19. * @return
    20. * @throws Exception
    21. */
    22. @Override
    23. public MemberEntity login(GiteeUser giteeUser) throws Exception {
    24. //获取gitee用户唯一id
    25. String giteeUserId = giteeUser.getId();
    26. //1、判断当前社交用户是否已经登录过系统
    27. MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_id", giteeUserId));
    28. //这个用户已经注册过
    29. if (memberEntity != null) {
    30. return memberEntity;
    31. } else {
    32. //2、没有查到当前社交用户对应的记录我们就需要注册一个
    33. MemberEntity register = new MemberEntity();
    34. //社交gitee登录的id作为会员id
    35. register.setId(Long.valueOf(giteeUserId));
    36. register.setSocialName(giteeUser.getName());
    37. register.setUsername(giteeUser.getName());
    38. register.setNickname(giteeUser.getName());
    39. register.setCreateTime(new Date());
    40. register.setSocialBio(giteeUser.getBio());
    41. register.setSocialId(giteeUserId);
    42. //把用户信息插入到数据库中
    43. this.baseMapper.insert(register);
    44. return register;
    45. }
    46. }
    1. package com.saodai.saodaimall.member.entity;
    2. import com.baomidou.mybatisplus.annotation.TableId;
    3. import com.baomidou.mybatisplus.annotation.TableName;
    4. import lombok.Data;
    5. import java.io.Serializable;
    6. import java.util.Date;
    7. /**
    8. * 会员
    9. */
    10. @Data
    11. @TableName("ums_member")
    12. public class MemberEntity implements Serializable {
    13. private static final long serialVersionUID = 1L;
    14. /**
    15. * id
    16. */
    17. @TableId
    18. private Long id;
    19. /**
    20. * 会员等级id
    21. */
    22. private Long levelId;
    23. /**
    24. * 用户名
    25. */
    26. private String username;
    27. /**
    28. * 密码
    29. */
    30. private String password;
    31. /**
    32. * 昵称
    33. */
    34. private String nickname;
    35. /**
    36. * 手机号码
    37. */
    38. private String mobile;
    39. /**
    40. * 邮箱
    41. */
    42. private String email;
    43. /**
    44. * 头像
    45. */
    46. private String header;
    47. /**
    48. * 性别
    49. */
    50. private Integer gender;
    51. /**
    52. * 生日
    53. */
    54. private Date birth;
    55. /**
    56. * 所在城市
    57. */
    58. private String city;
    59. /**
    60. * 职业
    61. */
    62. private String job;
    63. /**
    64. * 个性签名
    65. */
    66. private String sign;
    67. /**
    68. * 用户来源
    69. */
    70. private Integer sourceType;
    71. /**
    72. * 积分
    73. */
    74. private Integer integration;
    75. /**
    76. * 成长值
    77. */
    78. private Integer growth;
    79. /**
    80. * 启用状态
    81. */
    82. private Integer status;
    83. /**
    84. * 注册时间
    85. */
    86. private Date createTime;
    87. /**
    88. * 社交登录用户的ID
    89. */
    90. private String socialId;
    91. /**
    92. * 社交登录用户的名称
    93. */
    94. private String socialName;
    95. /**
    96. * 社交登录用户的自我介绍
    97. */
    98. private String socialBio;
    99. }

  • 相关阅读:
    【分享】7-Zip压缩包的密码可以取消吗?
    Spring Cloud Alibaba实现服务的无损下线功能
    信息化项目风险控制与应用
    SQL Server创建数据库
    【数字信号处理】序列傅里叶变换(FT)的物理意义
    第三十六篇 Vue中使用Swiper
    题目 1059: 二级C语言-等差数列
    励磁工作原理
    Web架构安全分析/http/URL/Cookie攻击
    Unity嵌入Android项目开发
  • 原文地址:https://blog.csdn.net/qq_50954361/article/details/128177367