springboot security对接mysql数据库

首先要添加springboot security依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
            <version>3.2.4</version>
</dependency>

实现UserDetailsServiceImpl、UserDetailsImpl类

这里只实现了student用户的登录验证

UserDetailsImpl.java: (实现UserDetails接口)

注意默认的方法很多都是false,需要去改成true。(比如是否允许登录等权限要改成true,还有相应的getUsername返回username等)

package com.ajg.backend.service.impl.utils;

import com.ajg.backend.pojo.Student;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserDetailsImpl implements UserDetails {
    private Student student;
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return null;
    }

    @Override
    public String getPassword() {
        return student.getPassword();
    }

    @Override
    public String getUsername() {
        return student.getUsername();
    }

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

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

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

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

UserDetailsServiceImpl.java:(实现UserDetailsService接口)

package com.ajg.backend.service.impl;

import com.ajg.backend.mapper.StudentMapper;
import com.ajg.backend.pojo.Student;
import com.ajg.backend.service.impl.utils.UserDetailsImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private StudentMapper studentMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 如果想要对接数据库,需要根据这个username去数据库中查询这个用户,把这个用户找出来
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        Student student = studentMapper.selectOne(queryWrapper);
        if (student == null) {
            throw new RuntimeException("用户不存在");
        }

        // 这里应该去判断前端传过来的登录信息是哪个类型用户的,然后去调用相应的mapper去查相应的数据库表

        return new UserDetailsImpl(student);
    }
}

现在重启服务会发现需要登录了,这时输入student表中的用户名密码就能登录

这时就已经对接了数据库了

扩展-实现密码加密存储

需要配置一个SecurityConfig.java: (写在backend/config下)

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(); // 返回一个BCryptPasswordEncoder对象,这个对象有.encode()、.matches()等方法,可以对密码加密,判断是否匹配
    }
}

下面这个StudentTestController.java就实现了密码加密存储:

@RestController
public class StudentController {
    @Autowired
    StudentMapper studentMapper;

    @RequestMapping("/student/all/")
    public List<Student> getAll() {
        return studentMapper.selectList(null);
    }
    @GetMapping("/student/add/{username}/{name}/{email}/{password}/")
    public String addStudent(
            @PathVariable String username,
            @PathVariable String name,
            @PathVariable String email,
            @PathVariable String password
            ) {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodedPassword = passwordEncoder.encode(password); // 加密
        Student student = new Student(null,username,encodedPassword,name,email,null,null);
        studentMapper.insert(student);
        return "add student successfully!";
    }
}
posted @ 2024-04-04 20:35  r涤生  阅读(41)  评论(0编辑  收藏  举报