6.springsecurity+mybatis realizes login verification

springsecurity+mybatis implements login verification

1. Design the database table

This chapter no longer design a table separately, continue to use the jpa table:

Insert picture description here

2. Create a project

Insert picture description here

3. Create a directory structure

Insert picture description here

4. Configure mybatis

#配置数据库
spring.datasource.url=jdbc:mysql://localhost:3306/withjpa?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456

mybatis.mapper-locations=classpath:mapper/*.xml

5. Write entity classes

user

package com.example.mybatisandsecurity.model;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author: 王泽
 */


public class User implements UserDetails {
    private Long id;
    private String username;
    private String password;
    private List<Role> roles;
    private boolean accountNonExpired;
    private boolean accountNonLocked;
    private boolean credentialsNonExpired;
    private boolean enabled;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }

    public void setAccountNonExpired(boolean accountNonExpired) {
        this.accountNonExpired = accountNonExpired;
    }

    public void setAccountNonLocked(boolean accountNonLocked) {
        this.accountNonLocked = accountNonLocked;
    }

    public void setCredentialsNonExpired(boolean credentialsNonExpired) {
        this.credentialsNonExpired = credentialsNonExpired;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
      List<SimpleGrantedAuthority> authorities=new ArrayList<>(roles.size());
        for (Role role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return accountNonExpired;
    }

    @Override
    public boolean isAccountNonLocked() {
        return accountNonLocked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return credentialsNonExpired;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }
}

Role

package com.example.mybatisandsecurity.model;

import java.io.Serializable;

/**
 * @author: 王泽
 */

public class Role implements Serializable {

    private Long id;
    private String name;
    private String nameZh;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNameZh() {
        return nameZh;
    }

    public void setNameZh(String nameZh) {
        this.nameZh = nameZh;
    }
}

6. Write the dao layer

UserMapper

package com.example.mybatisandsecurity.mapper;

import com.example.mybatisandsecurity.model.Role;
import com.example.mybatisandsecurity.model.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * @author: 王泽
 */

@Mapper
public interface UserMapper {


    User loadUserByUsername(String username);

    List<Role> getRolesByUserid(Long id);
}

UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mybatisandsecurity.mapper.UserMapper">
<select id="loadUserByUsername" resultType="com.example.mybatisandsecurity.model.User">
    select * from t_user where username=#{username};
</select>
    <select id="getRolesByUserid" resultType="com.example.mybatisandsecurity.model.Role">
        select * from t_role r,t_user_roles tur where tur.`roles_id`=r.`id` AND tur.`t_user_id`=#{id};
    </select>

</mapper>

7. Write service

package com.example.mybatisandsecurity.service;

import com.example.mybatisandsecurity.mapper.UserMapper;
import com.example.mybatisandsecurity.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author: 王泽
 */

@Service
public class UserService implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
       User user = userMapper.loadUserByUsername(username);
       if(user==null){
           throw new UsernameNotFoundException("用户不存在");
       }
       user.setRoles(userMapper.getRolesByUserid(user.getId()));
       return user;
    }

}

8. Configure security

package com.example.mybatisandsecurity.config;
import com.example.mybatisandsecurity.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author: 王泽
 */

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    UserService userService;

    @Bean  //密码加密
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()//所有用户必须登录才能访问
        .and().formLogin()
                .permitAll()
        .and().csrf().disable();
    }
}

9. Write controller test


@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello(){
        return "hello, security + mybatis!!";
    }



}