Shiro security framework: Shiro security framework: Shiro security framework: Shiro security framework: Shiro security framework: Shiro security framework (We created the user table in previous articles. You can modify it or delete it and create it again.)

GitHub:github.com/baiyuliang/…

Of course, many of the fields in this user table are irrelevant, and you can choose to ignore it!

User:

package com.byl.springboottest.bean;

import javax.persistence.*;
import java.io.Serializable;

@Entity(name = "user")
public class User implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)// Add the primary key
    private Integer id;
    @Column(unique = true)
    private String username;
    @Column(name = "role_id")
    private Integer roleId;
    @Column
    private String nickname;
    @Column
    private String realname;
    @Column
    private String password;
    @Column
    private String salt;
    @Column
    private Integer gender;
    @Column
    private Integer age;
    @Column
    private Integer status;
    @Column
    private Integer createtime;
    @Column
    privateInteger createby; . setter/getter }Copy the code

Select * from user where id, username, password are not null;

Open UserRepository under DAO and write database login request method:

User findByUsernameAndPassword(String username,String password);
Copy the code

Note that findBy is automatically generated as prompted!

Open the UserService:

 User login(String username,String password);
Copy the code

UserServiceImpl implementation:

    @Override
    public User login(String username, String password) {
        return null;
    }
Copy the code

At this point, we need to think about whether to be a little bit more formal. We know that a real interface returns content in a certain format, as mentioned earlier, such as:

{
	code:1.msg:"Request successful".data: {}}Copy the code

The actual data content is placed in the data, and the code and MSG indicate whether the interface request was successful or not.

ResponseData:

package com.byl.springbootdemo.bean.data;

import com.fasterxml.jackson.annotation.JsonInclude;

import java.io.Serializable;


public class ResponseData implements Serializable {
    private int code;
    private String msg;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private Object data;// If it is empty, no return is made

    public ResponseData(a) {}public ResponseData(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public ResponseData(int code, String msg, Object data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public int getCode(a) {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg(a) {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData(a) {
        return data;
    }

    public void setData(Object data) {
        this.data = data; }}Copy the code

{code:1, MSG :””}} @jsoninclude (jsoninclude.include.non_null) {JsonInclude(jsoninclude.non_null) {JsonInclude(jsoninclude.non_null);

And then, as mentioned earlier, we shouldn’t write any more business logic code in the Controller, so all of the business is going to be done in the Service, so ResponseData, we’re going to wrap it up and return it to the Controller call, Alter UserService and Impl method return values:

 ResponseData login(String username, String password);
Copy the code
 @Override
    public ResponseData login(String username, String password) {
        return null;
    }
Copy the code

To continue with the implementation of login, we have introduced userRepository earlier:

  @Resource
  UserRepository userRepository;
Copy the code

Therefore, it is directly used in the login method to achieve the ultimate login service:

    @Override
    public ResponseData login(String username, String password) {
        ResponseData responseData = new ResponseData();
        User user = userRepository.findByUsernameAndPassword(username, password);
        if (user == null) {
            responseData.setCode(-1);
            responseData.setMsg("Wrong account or password");
        } else {
            responseData.setCode(1);
            responseData.setMsg("Login successful");
            responseData.setData(user);
        }
        return responseData;
    }
Copy the code

Testing:

    @Test
    void testLogin(a) {
        ResponseData responseData = userService.login("admin"."admin");
        System.out.println(JSON.toJSON(responseData));
    }
Copy the code

Results:No problem, OK, now write Controller layer:

UserController:

    @PostMapping("/login")
    public ResponseData login(String username, String password) {
        // determine the null logic to omit...
        return userService.login(username, password);
    }
Copy the code

Write js login method in login. HTML:

   // Log in
   form.on('submit(login)'.function (data) {
       data = data.field;
       if (data.username === ' ') {
           layer.msg('User name cannot be empty');
           return false;
       }
       if (data.password === ' ') {
           layer.msg('Password cannot be empty');
           return false;
       }
       if (data.captcha === ' ') {
           layer.msg('Captcha cannot be null');
           return false;
       }
       $.post("user/login", {
           username: data.username,
           password: data.password
       }, function (data) {
           console.log(data);
          // if (data.code === 1) {
             // window.location.href = "index";
             // } else {
             // layer. MSG (" Wrong account or password, please enter again!" )
             // }
       });
       return false;
   });
Copy the code

Note:

I will first hide the logic after successful login authentication, in order to print the result returned by the interface:

OK, let go of that part of the code and let you do it, did that also work? !

Login verification succeeded, but at this time one of the biggest and most obvious vulnerability is that login does not seem to have any effect, even without login, I can also directly through the URL to access the deep page… How do you block requests from non-logged-in users? Intercept? Create an Interceptor folder and write the LoginHandlerInterceptor interceptor interceptor:

package com.byl.springboottest.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** * interceptor */
public class LoginHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object username = request.getSession().getAttribute("username");/ / remove the session
        if (username == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return false;/ / intercept
        } else {
            return true;/ / release}}}Copy the code

Use Session to store logged-in user information. Don’t panic, we’re not done yet, we need to configure the interceptor in AppConfig:

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginHandlerInterceptor())
                .addPathPatterns("/ * *")// Intercept all
                .excludePathPatterns("/"."/login"."/login.html"."/user/login")/ / out
                .excludePathPatterns("/css/**"."/images/**"."/js/**"."/lib/**");/ / out
    }
Copy the code

Finally, modify the login method in Controller and save it to session:

    @PostMapping("/login")
    public ResponseData login(String username, String password, HttpSession session) {
        // determine the null logic to omit...
        session.setAttribute("username", username);
        return userService.login(username, password);
    }
Copy the code

Restart the program, you can enter other url address in addition to the login screen, such as: http://localhost:8080/byl/index, you will find that the absence of the login, all are redirected to the login screen, after the success of the login, can go to visit other interface!

Of course, you can also define a login interface, to clear the session, log out of the function!