JAVAEE - Yicun Mall 11:sso login registration function, access to user information through token, Ajax cross-domain request (jsonp)

Keywords: Java JSON Redis Session Database

1. Learning plan

Day 11:

1. Implementation of sso registration function

2. Implementation of sso login function

3. Obtaining user information through token

4. Ajax cross-domain request (jsonp)

2. Construction of Sso System Engineering

 

 

 

You need to create a sso service project, which can be created with reference to e3-manager.

e3-sso (pom polymerization engineering)

   |--e3-sso-interface(jar)

   |--e3-sso-Service(war)

e3-sso-web

3. Service Interface Implementation

3.1. Check data availability

3.1.1. Functional analysis

The url:/user/check/{param}/{type} of the request

Parameters: Take parameter 1 from url, String param (data to be checked) 2, Integer type (data type to be checked)

Response data: json data. e3Result, encapsulated data validation results true: success false: failure.

Business logic:

1. Query data from tb_user table

2. Query conditions are generated dynamically according to parameters.

3. Judge the query result and return false if the query data.

4. If true is not returned.

5. Pack with e3Result and return.

 

3.1.2. Dao layer

Query from the tb_user table. Reverse engineering can be used.

3.1.3. Service

Parameters:

1. Data to be verified: String param

2. Data type: int type (1, 2, 3 represent username, phone, email, respectively)

Return value: e3Result

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private TbUserMapper userMapper;
    
    @Override
    public e3Result checkData(String param, int type) {
        // 1,from tb_user Query data in tables
        TbUserExample example = new TbUserExample();
        Criteria criteria = example.createCriteria();
        // 2,Query conditions are generated dynamically according to parameters.
        //1,2,3 Represent respectively username,phone,email
        if (type == 1) {
            criteria.andUsernameEqualTo(param);
        } else if (type == 2) {
            criteria.andPhoneEqualTo(param);
        } else if (type == 3) {
            criteria.andEmailEqualTo(param);
        } else {
            return e3Result.build(400, "Illegal parameters");
        }
        //Execution query
        List<TbUser> list = userMapper.selectByExample(example);
        // 3,Judge the query result, if the query returns to the data false. 
        if (list == null || list.size() == 0) {
            // 4,If not returned true. 
            return e3Result.ok(true);
        } 
        // 5,Use e3Result Pack and return.
        return e3Result.ok(false);
    }

}

 


Publishing services

 

 

3.1.4. Appearance layer

It needs to be implemented in e3-sso-web.

Citation service

Controller

The url:/user/check/{param}/{type} of the request

Parameters: Take parameter 1 from url, String param (data to be checked) 2, Integer type (data type to be checked)

Response data: json data. e3Result, encapsulated data validation results true: success false: failure.

@Controller
public class UserController {

    @Autowired
    private UserService userService;
    
    @RequestMapping("/user/check/{param}/{type}")
    @ResponseBody
    public e3Result checkData(@PathVariable String param, @PathVariable Integer type) {
        e3Result e3Result = userService.checkData(param, type);
        return e3Result;
    }
}

 


3.2.1. Functional analysis 3.2. User registration

Request url:/user/register

Parameters: Form data: username, password, phone, email

Return value: json data. e3Result

Receive parameters: Receive using TbUser object.

Method of request: post

Business logic:

1. Use TbUser to receive submitted requests.

2. Complete other attributes of TbUser.

3. The password should be encrypted by MD5.

4. Insert user information into database.

5. Return to e3Result.

 

3.2.2. Dao layer

Reverse engineering can be used.

3.2.3. Service Layer

Parameter: TbUser

Return value: e3Result

 

@Override
    public e3Result createUser(TbUser user) {
        // 1,Use TbUser Receive submitted requests.
        
        if (StringUtils.isBlank(user.getUsername())) {
            return e3Result.build(400, "User name cannot be empty");
        }
        if (StringUtils.isBlank(user.getPassword())) {
            return e3Result.build(400, "Password cannot be empty");
        }
        //Check the availability of data
        e3Result result = checkData(user.getUsername(), 1);
        if (!(boolean) result.getData()) {
            return e3Result.build(400, "This username has been used");
        }
        //Check whether the telephone is OK
        if (StringUtils.isNotBlank(user.getPhone())) {
            result = checkData(user.getPhone(), 2);
            if (!(boolean) result.getData()) {
                return e3Result.build(400, "This mobile phone number has been used.");
            }
        }
        //check email Availability
        if (StringUtils.isNotBlank(user.getEmail())) {
            result = checkData(user.getEmail(), 3);
            if (!(boolean) result.getData()) {
                return e3Result.build(400, "This email address has been used");
            }
        }
        // 2,completion TbUser Other attributes.
        user.setCreated(new Date());
        user.setUpdated(new Date());
        // 3,Password to proceed MD5 Encryption.
        String md5Pass = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(md5Pass);
        // 4,Insert user information into the database.
        userMapper.insert(user);
        // 5,Return e3Result. 
        return e3Result.ok();
    }

 


Publishing services

3.2.4. Appearance layer

Reference services.

 

Controller:

Request url:/user/register

Parameters: Form data: username, password, phone, email

Return value: json data. e3Result

Receive parameters: Receive using TbUser object.

Method of request: post

@RequestMapping(value="/user/register", method=RequestMethod.POST)
    @ResponseBody
    public e3Result register(TbUser user) {
        e3Result result = userService.createUser(user);
        return result;
    }

 


3.2.5. Testing

You can use restclient-ui-3.5-jar-with-dependencies.jar to test the interface.

 

 

content-type of form submission: application/x-www-form-urlencoded

3.3. User login

3.3.1. Functional analysis

Request url:/user/login

Method of request: POST

Parameters: username, password, data submitted by the form. The method can be used for parameter reception.

Return value: json data, containing a token using e3Result.

Business logic:

Login business processes:

 

 

 

Login processing flow:

1. Submit username and password on login page.

2. Generate token after successful login. Token is equivalent to the original jsession id, string, and uuid can be used.

3. Save user information to redis. Key is token, value is TbUser object converted into json.

4. Use String type to save Session information. You can use "prefix: token" as key

5. Setting the expiration time of key. Simulate the expiration time of Session. Usually half an hour.

6. Write token into cookie.

7. Cookie s need to be cross-domain. For example, at www.e3.comsso.e3.comorder.e3.com, tool classes can be used.

8. The validity of Cookie. Close browser failure.

9. The login was successful.

 

3.3.2. Dao layer

Query the tb_user table. Single table query. Reverse engineering can be used.

 

3.3.3. Service Layer

Parameters:

1. User name: String username

2. Password: String password

Return value: e3Result, wrapped token.

Business logic:

1. Determine whether the username password is correct.

2. Generate token after successful login. Token is equivalent to the original jsession id, string, and uuid can be used.

3. Save user information to redis. Key is token, value is TbUser object converted into json.

4. Use String type to save Session information. You can use "prefix: token" as key

5. Setting the expiration time of key. Simulate the expiration time of Session. Usually half an hour.

6. Return e3Result wrapped token.

@Override
    public e3Result login(String username, String password) {
        // 1,Determine whether the username password is correct.
        TbUserExample example = new TbUserExample();
        Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);
        //Query User Information
        List<TbUser> list = userMapper.selectByExample(example);
        if (list == null || list.size() == 0) {
            return e3Result.build(400, "ERROR Incorrect username or password");
        }
        TbUser user = list.get(0);
        //Check password
        if (!user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))) {
            return e3Result.build(400, "ERROR Incorrect username or password");
        }
        // 2,Generation after successful login token. Token Equivalent to the original jsessionid,String, you can use uuid. 
        String token = UUID.randomUUID().toString();
        // 3,Save user information to redis. Key Namely token,value Namely TbUser Object transformation json. 
        // 4,Use String Type preservation Session Information. You can use the prefix:token"by key
        user.setPassword(null);
        jedisClient.set(USER_INFO + ":" + token, JsonUtils.objectToJson(user));
        // 5,Set up key The expiration time. simulation Session The expiration time. Usually half an hour.
        jedisClient.expire(USER_INFO + ":" + token, SESSION_EXPIRE);
        // 6,Return e3Result Packing token. 
        return e3Result.ok(token);
    }

 


Publishing services

3.3.4. Appearance layer

Reference services:

 

Controller

Request url:/user/login

Method of request: POST

Parameters: username, password, data submitted by the form. The method can be used for parameter reception.

HttpServletRequest,HttpServletResponse

Return value: json data, containing a token using e3Result.

Business logic:

1. Receive two parameters.

2. Call Service for login.

3. Take token from the returned result and write it to cookie. Cookies are cross-domain.

Cookie secondary domain names need to be set across domains:

1) setDomain, set up the first-level domain name:

.itcatst.cn

.e3.com

.e3.com.cn

2) setPath. Set to "/"

 

Tool classes are placed in the e3-common project.

4. Response data. Json data. e3Result, which contains Token.

 

@RequestMapping(value="/user/login", method=RequestMethod.POST)
    @ResponseBody
    public e3Result login(String username, String password,
            HttpServletRequest request, HttpServletResponse response) {
        // 1,Two parameters are received.
        // 2,call Service Log in.
        e3Result result = userService.login(username, password);
        // 3,From the returned results token,Write in cookie. Cookie Cross domain.
        String token = result.getData().toString();
        CookieUtils.setCookie(request, response, COOKIE_TOKEN_KEY, token);
        // 4,Response data. Json Data. e3Result,Including Token. 
        return result;
        
    }

 


3.4. Query user information through token

3.4.1. Functional analysis

url:/user/token/{token} of the request

Parameter: String token needs to be fetched from the url.

Return value: json data. Wrap Tbuser objects with e3Result.

Business logic:

1. Take parameters from url.

2. Query redis according to token.

3. If the data can not be queried. The return user has expired.

4. If the data is queried, the user has logged in.

5. The expiration time of the key that needs to be reset.

6. Convert json data into TbUser objects, and then wrap it with e3Result and return it.

 

3.4.2. Dao layer

Use the JedisClient object.

 

3.4.3. Service Layer

Parameter: String token

Return value: e3Result

@Override
    public e3Result getUserByToken(String token) {
        // 2,according to token query redis. 
        String json = jedisClient.get(USER_INFO + ":" + token);
        if (StringUtils.isBlank(json)) {
            // 3,If the data can not be queried. The return user has expired.
            return e3Result.build(400, "User login has expired. Please login again.");
        }
        // 4,If the data is queried, the user has logged in.
        // 5,Need reset key The expiration time.
        jedisClient.expire(USER_INFO + ":" + token, SESSION_EXPIRE);
        // 6,hold json Data Conversion TbUser Object, and then use e3Result Pack and return.
        TbUser user = JsonUtils.jsonToPojo(json, TbUser.class);
        return e3Result.ok(user);
    }

 


3.4.4. Expressive layer

url:/user/token/{token} of the request

Parameter: String token needs to be fetched from the url.

Return value: json data. Wrap Tbuser objects with e3Result.

    @RequestMapping("/user/token/{token}")
    @ResponseBody
    public e3Result getUserByToken(@PathVariable String token) {
        e3Result result = userService.getUserByToken(token);
        return result;
    }

 


Operation 3.4.5. Safe exit

The key in redis needs to be deleted according to token.

 

4. Implementation of login registration page

4.1. Registration function

Step 1: Add static pages to the project.

'

Step 2: Show the page.

The requested url:

Login: / page/login

Registration: / page/register

Parameter: None

Return result: logical view String

 

@Controller
public class PageController {

    @RequestMapping("/page/register")
    public String showRegister() {
        return "register";
    }
    
    @RequestMapping("/page/login")
    public String showLogin() {
        return "login";
    }
}

 

 


Step 3: js processing.  

 

 

 

4.2. Login function

Reference to login.jsp

 

5. Login Registration Page Integration Home Page

5.1. Home page jumps to login and registration pages

 

 

 

5.2. Display the user name on the home page

1. When the user logs in successfully, there is token information in the cookie.

2. Take token from cookie and query user information according to token.

3. Display the user name on the home page.

 

Solution 1: Take token data from cookie in Controller and call sso service to query user information.

Solution 2: When the page is loaded, the data of token is fetched by js, and the user information is queried by ajax request.

 

Question: Service interface in sso system. Sso.e3.com(localhost:8088) displays the user name on the home page. The domain name of the home page is www.e3.com(localhost:8082). The ajax request is cross-domain.

 

Js cannot request data across domains.

What is cross-domain:

1. Domain names are different

2. The same domain name has different ports.

 

jsonp can be used to solve cross-domain problems of js.

 

Jsonp is not a new technology, cross-domain solution. Use the features of JS to bypass cross-domain requests. Js can load JS files across domains.

 

 

5.3. Jsonp Principle

 

 

5.4. Json implementation

5.4.1. Client

Use jQuery.

 

5.4.2. Server

1. Receive the callback parameter and get the method name of the callback js.

2. Business logic processing.

3. Respond to the result and stitch a js statement.

Method 1:

 

 

Method two:

 

Posted by Coco on Fri, 11 Jan 2019 21:36:11 -0800