当前位置:网站首页>27: Chapter 3: develop Passport Service: 10: [registration / login] interface: after the registration / login is OK, save the user session information (uid, utoken) to redis and cookies; (one main poi
27: Chapter 3: develop Passport Service: 10: [registration / login] interface: after the registration / login is OK, save the user session information (uid, utoken) to redis and cookies; (one main poi
2022-07-02 18:47:00 【Small withered forest】
explain :
(1) The content of this blog : Continue to develop 【 register / Sign in 】 Interface ;
● Current position ,【 register / Sign in 】 The content of interface development is : First verify whether the verification code OK; Verification code verification OK after , First check whether the user already exists according to the mobile phone number , If the user does not exist, create the user ;
● This blog , We will continue to improve 【 register / Sign in 】 Interface : register / Sign in OK after , Send the user session information (uid,utoken) Save to redis and cookie in ;
(2) There are special points to pay attention to in this blog :
● Set up cookie Of SOP;
● Set up cookie When ,cookie Of key Make an agreement between the front and back ;
(3) A possible missing point in this blog : Front end browsing cookie, We set it up uid and utoken;; however , At the back end, we only redis I've saved utoken, But it didn't exist uid;
(4)PS: For a better understanding of cookie、token The content such as , Deeply aware of the necessity of full stack at the front and back end ~~~
Catalog
One : Rationality of this blog ;
(1) Perfect the content , sketch ;
(3) Use 【UUID】 Generate a random and unique character , Then take this character as token Value ;
(7) Last , according to “ The agreement between front and back ”, Return to user status ;
One : Rationality of this blog ;
After logging in , We need to save user session information ( In order to facilitate the interaction between the front and back ends , Can verify login information ):
(1) before , On the back end, we will store user information session in ; At the front browser , User session information will exist Cookies in ;
● of cookie,session Basic content , You can refer to 【Servlet And JSP Advanced five : browser Cookie】、【Servlet And JSP Advanced five : The user's session Session object 】、【Servlet And JSP Advanced six :ServletContext Global object ;Java Web Summary of three scope objects ;】;
(2) however , In distributed services , You need to use distributed sessions to do ;
● On the back end : In a distributed session , Whether distributed 、 Or clustering 、 Micro services ;;; On the back end , As long as the user session information exists redis in , Session information can be obtained at any node ( As long as it can be connected redis service );
● At the front browser : Let's put the user session information , Save in cookie in ;
● thus , User session information , We save it on the back end redis in , It is also saved in the front-end browser ;;;; In this way , When the user logs in and checks, etc , It will be easy to process through user session information ;
Two : We will continue to improve 【 register / Sign in 】 Interface : register / Sign in OK after , Send the user session information (uid,utoken) Save to redis and cookie in ;
1.【user】 In the user microservice ,PassportController Medium 【 register / Sign in 】 Interface : We will continue to improve ;
/** * 【 One click registration / Sign in , Interface 】 * @param registLoginBo * @param result * @return */ @Override public GraceJSONResult doLogin(@Valid RegistLoginBo registLoginBo, BindingResult result, HttpServletRequest request, HttpServletResponse response) { //0. Judge BindingResult Whether the error message of validation failure is saved in , If there is , It indicates that there is a problem with the input of the front end ( Mobile phone number or verification code , At least one has not been entered ); // that , We get this error message , And build a GraceJSONResult Unified return object , return ; if (result.hasErrors()) { Map<String, String> map = getErrorsFromBindingResult(result); return GraceJSONResult.errorMap(map); } // 1. Check whether the verification code matches ; //1.1 Get the mobile phone number and verification code entered by the user in the front end ; String mobile = registLoginBo.getMobile(); String smsCode = registLoginBo.getSmsCode(); //1.2 According to the mobile phone number entered by the user in the front end , Try to go redis Get the corresponding verification code in ; String redisSMSCode = redisOperator.get(MOBILE_SMSCODE + ":" + mobile); //1.3 If the verification code entered by the front end , stay redis Does not exist in the ( explain : We are not targeting 【 The mobile phone number entered by the user 】 Sent verification code ; // Or after the user receives the verification code text message , After that 30min Before use ,redis The verification code stored in the has expired ), // Or the front-end input verification code and redis The difference between ( explain : The user's verification code is entered incorrectly ); // that , Go back to the corresponding , With error messages GraceJSONResult Unified return object ; // among , Here we use 【org.apache.commons.lang3】 Medium StringUtils The utility class isBlank() Method to judge the null ; if (StringUtils.isBlank(redisSMSCode) || !redisSMSCode.equals(smsCode)) { return GraceJSONResult.errorCustom(ResponseStatusEnum.SMS_CODE_ERROR); } // 2. Use your mobile number , Query database , Whether the user is registered ; AppUser user = userService.queryMobileIsExist(mobile); //2.1 If the user exists but is frozen ; Return the corresponding ( Contains error messages ) Of GraceJSONResult Unified return object if ((user != null) && (user.getActiveStatus() == UserStatus.FROZEN.type)) { return GraceJSONResult.errorCustom(ResponseStatusEnum.USER_FROZEN); } else if (user == null) {//2.2 If the user is empty , Let's register this user user = userService.createUser(mobile); } // 3. Save the related operations of the user's distributed session ;( If we can get to this point , It means that the user is either logged in , Or register ) int userActiveStatus = user.getActiveStatus();// Get user status //3.1 If the user status is not frozen , Just save if (userActiveStatus != UserStatus.FROZEN.type) { // The user's session , You can use one token; then ,token You can use a random uuid To do it ; String uToken = UUID.randomUUID().toString(); // Put the user's token Information , Save in redis in ; Its key yes 【redis_user_token:200628AFYM7AGWPH】 such ; redisOperator.set(REDIS_USER_TOKEN + ":" + user.getId(), uToken); // Save the user id and token To cookie in ; setCookie(request, response, "utoken", uToken, COOKIE_MONTH); setCookie(request, response, "uid", user.getId(), COOKIE_MONTH); } //4. The user login / After successful registration ,【 We are in front of the user login / Registration time , Save in redis Verification code in 】 To delete ;( because , The verification code can only be used once ) redisOperator.del(MOBILE_SMSCODE + ":" + mobile); // Last , Return the user's status ;;;( This is mainly ,【 The agreement between the back end and the front end 】 That's it ) return GraceJSONResult.ok(user.getActiveStatus()); }explain :
(1) Perfect the content , sketch ;
……………………………………………………
(2) The user is registering / After successful login , If the user is not frozen , Save the user's session information ;
……………………………………………………
(3) Use 【UUID】 Generate a random and unique character , Then take this character as token Value ;
● of UUID The content of , You can refer to 【 additional :UUID, Universal unique identification code (Universally Unique Identifier)(Java Of UUID.randomUUID() Tool class , Random and unique uniform identification code can be generated );】;
● of token The content of , You can refer to 【 To be written ……】
……………………………………………………
(4) Put the token, Deposit in ( Back end )redis in ; The storage method is :【“redis_user_token: user id”:“token value ”】, such as 【“redis_user_token:200628AFYM7AGWPH”:“f2eb40e3-7715-4e20-a20d-939df8e60413”】
● explain ;
● A small gain : Because when inserting data , Its primary key id We set it based on the characters generated by the snowflake Algorithm , So there is no need to consider the matter of primary key backfill at this time ;
● After that , stay redis in , Save a specific for the user token Information (【“redis_user_token: user id”:“token value ”】);;; then , Actually saved to redis in , It is equivalent to that we save the user's token Information ;
……………………………………………………
(5.1) Put the token, Save to ( Front end browser's )cookie in ; meanwhile , Users should also id, Save to ( Front end browser's )cookie in ;
● Because our project is a front-end and back-end separation , Above we put the user's token The information is saved to the back end ;
● Then we should also put the user's token Save the information to the front-end browser ; namely , Also put the relevant conversation information , Saved to the front-end browser cookie in ;;; Register at / After successful login , Front end browsers will retain some of the most basic information of users ;;
● The front end is saved userId and token Words , When the front and back end interact ;;; They can easily verify the user login ;
● Here is our cookie What is kept is 【 user id】 and 【token】; Its cookie Of key We set it as 【uid】 and 【utoken】, these two items. key It's not random , It needs to be agreed with the front end ;;;; such as , We are registering / The login page OK after , It will jump to accountInfo.html page ;
● cookie Life time of , We set it to 30 God ; This value , We defined it in BaseController in ;
(5.2) Because of the settings cookie When , need request and response, So we injected HttpServletResponse and HttpServletRequest;
(5.3) So , We are 【api】 Interface Engineering BaseController in , Created a setting cookie Methods setCookie() Method ;
/** * Tool method : Set up Cookie * @param request * @param response * @param cookieName * @param cookieValue * @param maxAge */ public void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, Integer maxAge) { try { cookieValue = URLEncoder.encode(cookieValue, "UTF-8"); setCookieValue(request, response, cookieName, cookieValue, maxAge); // Cookie cookie = new Cookie(cookieName, cookieValue); // cookie.setMaxAge(maxAge); // // Set up , Under which domain names , Can get cookie Information ; // // After this setting , As long as the domain name is 【imoocnews.com】, Front end browsers are available cookie Information ; // cookie.setDomain("imoocnews.com"); // cookie.setPath("/");// In what url Next , Can contain cookie; That is to say 【imoocnews.com】 } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } public void setCookieValue(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, Integer maxAge) { Cookie cookie = new Cookie(cookieName, cookieValue); cookie.setMaxAge(maxAge); // Set up , Under which domain names , Can get cookie Information ; // After this setting , As long as the domain name is 【imoocnews.com】, Front end browsers are available cookie Information ; cookie.setDomain("imoocnews.com"); cookie.setPath("/");// In what url Next , Can contain cookie; That is to say 【imoocnews.com】 // hold cookie Set it in the response ; response.addCookie(cookie); }● We set this method to BaseController in , thus , When other places in the back need it , You can call ;
● Pass it on cookieValue be based on UTF-8, Code it ;
● Use cookieName and cookieValue Instantiate a cookie object ; then , Set up cookie Life time of ;
● Set up cookie The domain of (domain);( I think :cookie The domain of , The main functions are 【 stay “ domain name ” On this coarser granularity , To control the cookie Accessible range of 】)
● Set up cookie Of path;( I think :cookie Of path, The main functions are 【 stay “ domain name ” After the coarser granularity is determined , stay “ Catalog ” This finer granularity can be controlled cookie Accessible range of 】)
● hold cookie Set to response In response ;
● Besides ,cookie There are other contents ;
(5.4) thus , The current page requests us to register / When logging into the interface , This interface will put the user related uid、utoken Save to cookie in ;
For some 【 It needs to be a page that can be operated only when the user logs in 】, The corresponding front-end file of these pages will try to get uid、utoken these cookie The code of information ;;; If , The front page can successfully obtain these cookie Information , everything OK;;; If , Can't get , The front page naturally writes the corresponding logic , To remind and block users ;
……………………………………………………
(6) User registration / After successful login , We need to delete our previous save in redis Verification code in ;
● Once the user registers / Login successful , It means that the verification code has been used , Then you need to delete ;
……………………………………………………
(7) Last , according to “ The agreement between front and back ”, Return to user status ;
● When the system designer is designing this project , It makes strict settings for each interface ;;; As front-end developers and back-end developers , Strictly follow the contents of interface documents and system design , Just develop ;
3、 ... and : test ;
1. First, the whole situation install Look at the whole project ;
2. then , function 【user】 Main startup class of user microservice ;
● If in the process , It is found that the port is occupied , about Windows System , The following solutions can be adopted ;
3. then , Visit registration / The login page ;
additional , For example, log in by yourself CSDN after , Save it in the browser CSDN Set in cookie Some information in ;
● So , Feeling 【 towards cookie Set the value of 】 It's a very good tool ;;; Through this means , The front and back end can check and control user session information very well ;
● At the beginning , We put 【uid】 and 【utoken】 It's all stored in 【 Front end browser 】 and 【 Back end redis】 in ;;; that , Later, the front-end interface will access the back-end interface , The request will be accompanied by 【uid】 and 【utoken】 Information ;;; When the backend interface gets the request , Will be based on 【uid】 and 【utoken】 The specific value of the information , Come and exist redis Compare the values in , To confirm whether the login of the user is OK Of ;
边栏推荐
- 如何优雅的写 Controller 层代码?
- MySQL about only_ full_ group_ By limit
- The text editor hopes to mark the wrong sentences in red, and the text editor uses markdown
- 夜神模拟器+Fiddler抓包测试App
- 在支付宝账户上买基金安全吗
- How to write controller layer code gracefully?
- Leetcode interview question 16.17 Continuous sequence
- Stretchdibits function
- How to set vscode to delete the whole line shortcut key?
- Steamos 3.3 beta release, steam deck Chinese keyboard finally came
猜你喜欢

Troubleshooting ideas that can solve 80% of faults

In early summer, Kaiyuan magic changed an electric mosquito racket with killing sound effect!

27:第三章:开发通行证服务:10:【注册/登录】接口:注册/登录OK后,把用户会话信息(uid,utoken)保存到redis和cookie中;(一个主要的点:设置cookie)
![Unity学习shader笔记[八十二]增强单通道颜色渲染的黑白处理](/img/db/d745a434e76511742d1264706b5d9a.png)
Unity学习shader笔记[八十二]增强单通道颜色渲染的黑白处理

Comprendre complètement le tutoriel de traitement de Point Cloud basé sur open3d!
![[Yugong series] July 2022 go teaching course 001 introduction to go language premise](/img/f2/3b95f53d67cd1d1979163910dbeeb8.png)
[Yugong series] July 2022 go teaching course 001 introduction to go language premise

昨天阿里学长写了一个责任链模式,竟然出现了无数个bug

NM01-独立于总线协议的NM模块功能概述与API定义

Simulateur nightGod + application de test de capture de paquets Fiddler

Qt官方示例:Qt Quick Controls - Gallery
随机推荐
Leetcode 面试题 16.11. 跳水板
The official docker image running container in version 1.5.1 can be set to use MySQL 8 driver?
阿里三面被面试官狂问Redis,简历上再也不敢写'精通'了
Qt Official examples: Qt Quick Controls - Gallery
Unity学习shader笔记[八十一]简单的颜色调整后处理(亮度,饱和度,对比度)
Comprendre complètement le tutoriel de traitement de Point Cloud basé sur open3d!
呆错图床系统源码图片CDN加速与破J防盗链功能
Matlab中弧度转角度、角度转弧度
Leetcode(154)——寻找旋转排序数组中的最小值 II
如何清理废弃pv和其对应的文件夹
Wechat nucleic acid detection appointment applet system graduation design completion (5) task statement
Leetcode interview question 16.17 Continuous sequence
QT official example: QT quick controls - Gallery
Redis(6)----对象与数据结构
Wechat applet video sharing platform system graduation design completion (5) assignment
【Oracle 期末复习】表空间、表、约束、索引、视图的增删改
719. Find the distance of the number pair with the smallest K
CDN acceleration and breaking J anti-theft chain function
任职 22 年,PowerShell 之父将从微软离职:曾因开发 PowerShell 被微软降级过
饭卡 HDU2546

































