【苍穹外卖 | 篇⑥】登录流程
在牛某网看见了牛肉哥的帖子之后打算向牛肉大佬学习故开始书写CSDN博客通过博客的方式来巩固自身知识学习。因为之前有粗略的学习了Java Web 的基础课程所以博客内容主要是巩固之前学习当中的模糊点以及一些自己认为重要的内容用于自己进一步的掌握开发技能。1. HttpClientHttpClient作用发送HTTP请求 接收响应数据HttpClient应用场景当我们在使用扫描支付、查看地图、获取验证码、查看天气等功能时应用程序本身并未实现这些功能都是在应用程序里访问提供这些功能的服务访问这些服务需要发送HTTP请求并且接收响应数据可通过HttpClient来实现。HttpClient的核心APIHttpClientHttp客户端对象类型使用该类型对象可发起Http请求。HttpClients可认为是构建器可创建HttpClient对象。CloseableHttpClient实现类实现了HttpClient接口。HttpGetGet方式请求类型。HttpPostPost方式请求类型。HttpClient发送请求步骤创建HttpClient对象创建Http请求对象调用HttpClient的execute方法发送请求GET方式请求创建HttpClient对象创建请求对象发送请求接受响应结果解析结果关闭资源package com.sky.test; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; SpringBootTest public class HttpClientTest { /** * 测试通过httpclient发送GET方式的请求 */ Test public void testGET() throws Exception{ //创建httpclient对象 CloseableHttpClient httpClient HttpClients.createDefault(); //创建请求对象 HttpGet httpGet new HttpGet(http://localhost:8080/user/shop/status); //发送请求接受响应结果 CloseableHttpResponse response httpClient.execute(httpGet); //获取服务端返回的状态码 int statusCode response.getStatusLine().getStatusCode(); System.out.println(服务端返回的状态码为 statusCode); HttpEntity entity response.getEntity(); String body EntityUtils.toString(entity); System.out.println(服务端返回的数据为 body); //关闭资源 response.close(); httpClient.close(); } }2.微信登录流程小程序端调用wx.login()获取code就是授权码。小程序端调用wx.request()发送请求并携带code请求开发者服务器(自己编写的后端服务)。开发者服务端通过HttpClient向微信接口服务发送请求并携带appIdappsecretcode三个参数。开发者服务端接收微信接口服务返回的数据session_keyopendId等。opendId是微信用户的唯一标识。开发者服务端自定义登录态生成令牌(token)和openid等数据返回给小程序端方便后绪请求身份校验。小程序端收到自定义登录态存储storage。小程序端后绪通过wx.request()发起业务请求时携带token。开发者服务端收到请求后通过携带的token解析当前登录用户的id。开发者服务端身份校验通过后继续相关的业务逻辑处理最终返回业务数据。流程简介要登录我们的小程序进入小程序就会发送code发送code是因为他需要openid给开发者服务器服务器接受code后结合多种信息向微信服务器获取openid保存在开发者服务器的数据库里同时进行jwt加密生成token将token返回给小程序端openid很敏感不直接返回小程序后续不再需要发送code重复流程了它有了token后就能获取开发者服务器里数据库里的openid了。Controller层public class UserController { Autowired private UserService userService; Autowired private JwtProperties jwtProperties; /** * 微信登录 * param userLoginDTO * return */ PostMapping(/login) ApiOperation(微信登录) public ResultUserLoginVO login(RequestBody UserLoginDTO userLoginDTO){ log.info(微信用户登录{},userLoginDTO.getCode()); //微信登录 User user userService.wxLogin(userLoginDTO);//后绪步骤实现 //为微信用户生成jwt令牌 MapString, Object claims new HashMap(); claims.put(JwtClaimsConstant.USER_ID,user.getId()); String token JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims); UserLoginVO userLoginVO UserLoginVO.builder() .id(user.getId()) .openid(user.getOpenid()) .token(token) .build(); return Result.success(userLoginVO); } }Service层实现类public class UserServiceImpl implements UserService { //微信服务接口地址 public static final String WX_LOGIN https://api.weixin.qq.com/sns/jscode2session; Autowired private WeChatProperties weChatProperties; Autowired private UserMapper userMapper; /** * 微信登录 * param userLoginDTO * return */ public User wxLogin(UserLoginDTO userLoginDTO) { String openid getOpenid(userLoginDTO.getCode()); //判断openid是否为空如果为空表示登录失败抛出业务异常 if(openid null){ throw new LoginFailedException(MessageConstant.LOGIN_FAILED); } //判断当前用户是否为新用户 User user userMapper.getByOpenid(openid); //如果是新用户自动完成注册 if(user null){ user User.builder() .openid(openid) .createTime(LocalDateTime.now()) .build(); userMapper.insert(user);//后绪步骤实现 } //返回这个用户对象 return user; } /** * 调用微信接口服务获取微信用户的openid * param code * return */ private String getOpenid(String code){ //调用微信接口服务获得当前微信用户的openid MapString, String map new HashMap(); map.put(appid,weChatProperties.getAppid()); map.put(secret,weChatProperties.getSecret()); map.put(js_code,code); map.put(grant_type,authorization_code); String json HttpClientUtil.doGet(WX_LOGIN, map); JSONObject jsonObject JSON.parseObject(json); String openid jsonObject.getString(openid); return openid; } }UserMapper.xmlkeyPropertyid指定将返回的主键值赋值到入参实体类的id属性上。insert idinsert useGeneratedKeystrue keyPropertyid insert into user (openid, name, phone, sex, id_number, avatar, create_time) values (#{openid}, #{name}, #{phone}, #{sex}, #{idNumber}, #{avatar}, #{createTime}) /insertJwtTokenUserInterceptor拦截用户端发送的请求并进行jwt校验public class JwtTokenUserInterceptor implements HandlerInterceptor { Autowired private JwtProperties jwtProperties; /** * 校验jwt * * param request * param response * param handler * return * throws Exception */ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //判断当前拦截到的是Controller的方法还是其他资源 if (!(handler instanceof HandlerMethod)) { //当前拦截到的不是动态方法直接放行 return true; } //1、从请求头中获取令牌 String token request.getHeader(jwtProperties.getUserTokenName()); //2、校验令牌 try { log.info(jwt校验:{}, token); Claims claims JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token); Long userId Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString()); log.info(当前用户的id, userId); BaseContext.setCurrentId(userId); //3、通过放行 return true; } catch (Exception ex) { //4、不通过响应401状态码 response.setStatus(401); return false; } } }WebMvcConfigurationAutowired private JwtTokenUserInterceptor jwtTokenUserInterceptor; /** * 注册自定义拦截器 * param registry */ protected void addInterceptors(InterceptorRegistry registry) { log.info(开始注册自定义拦截器...); //......... registry.addInterceptor(jwtTokenUserInterceptor) .addPathPatterns(/user/**) .excludePathPatterns(/user/user/login) .excludePathPatterns(/user/shop/status); }
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2463591.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!