博客
关于我
Spring Security集成Spring Data Jpa
阅读量:779 次
发布时间:2019-03-24

本文共 8643 字,大约阅读时间需要 28 分钟。

如何将用户数据存入数据库并使用Spring Data Jpa进行操作

1. 启动MySQL并创建数据库

首先,启动MySQL客户端并执行以下命令创建数据库:

mysql -u root -p

输入密码后,执行以下命令创建数据库:

CREATE DATABASE test;

2. 创建Spring Boot项目并添加必要依赖

创建一个新Spring Boot项目,添加以下依赖到项目的 pom.xml 中:

org.springframework.boot
spring-boot-starter-security
org.springframework.boot
spring-boot-starter-data-jpa
mysql
mysql-connector-java
runtime

3. 配置数据库连接信息

在应用.properties 文件中添加以下配置:

spring.datasource.username=rootspring.datasource.password=rootsspring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=falsespring.datasource.driver-class-name=com.mysql.cj.jdbc.Driverjpa.hibernate.ddl-auto=updatejpa.show-sql=truejpa.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

4. 创建实体类

User 实体类

import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import org.springframework.security.core.userdetails.UserDetails;@Entity(name = "t_user")public class User implements UserDetails {    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    private Long id;    private String username;    private String password;    private boolean accountNonExpired = true;    private boolean accountNonLocked = true;    private boolean credentialsNonExpired = true;    private boolean enabled = true;    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)    private List
roles; @Override public String getUsername() { return username; } @Override public String getPassword() { return password; } @Override public boolean isAccountNonExpired() { return accountNonExpired; } @Override public boolean isAccountNonLocked() { return accountNonLocked; } @Override public boolean isCredentialsNonExpired() { return credentialsNonExpired; } @Override public boolean isEnabled() { return enabled; } @Override public Collection
getAuthorities() { List
authorities = new ArrayList<>(); for (Role role : roles) { authorities.add(new SimpleGrantedAuthority(role.getName())); } return authorities; }}

Role 实体类

import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;@Entity(name = "t_role")public class Role {    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    private Long id;    private String name;    private String nameZh;    // Getters and Setters omitted for brevity}

5. 创建DAO和Service接口

UserDao 接口

import com.example.domain.User;import org.springframework.data.jpa.repository.JpaRepository;public interface UserDao extends JpaRepository
{ User findUserByUsername(String username);}

UserService implementing UserDetailsService

import com.example.dao.UserDao;import com.example.domain.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;@Servicepublic class UserService implements UserDetailsService {    @Autowired    private UserDao userDao;    @Override    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {        User user = userDao.findUserByUsername(username);        if (user == null) {            throw new UsernameNotFoundException("Username not found");        }        return user;    }}

6. 安全配置

SecurityConfig

import com.example.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.builders.WebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.crypto.password.NoOpPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;import java.io.PrintWriter;@Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter {    @Autowired    private UserService userService;    @Bean    public PasswordEncoder passwordEncoder() {        return NoOpPasswordEncoder.getInstance();    }    @Override    protected void configure(AuthenticationManagerBuilder auth) throws Exception {        auth.userDetailsService(userService);    }    @Override    public void configure(WebSecurity web) {        web.ignoring().antMatchers("/js/**", "/css/**", "/images/**");    }    @Override    protected void configure(HttpSecurity http) throws Exception {        http.authorizeRequests()                .antMatchers("/admin/**").hasRole("admin")                .antMatchers("/user/**").hasRole("user")                .anyRequest().authenticated()                .and()                .formLogin()                .loginPage("/login.html")                .loginProcessingUrl("/doLogin")                .successHandler((req, resp, authentication) -> {                    Object principal = authentication.getPrincipal();                    resp.setContentType("application/json;charset=utf-8");                    PrintWriter out = resp.getWriter();                    out.write(new ObjectMapper().writeValueAsString(principal));                    out.flush();                    out.close();                })                .failureHandler((req, resp, e) -> {                    resp.setContentType("application/json;charset=utf-8");                    PrintWriter out = resp.getWriter();                    out.write(e.getMessage());                    out.flush();                    out.close();                })                .permitAll()                .and()                .logout()                .logoutUrl("/logout")                .logoutSuccessHandler((req, resp, authentication) -> {                    resp.setContentType("application/json;charset=utf-8");                    PrintWriter out = resp.getWriter();                    out.write("Logout successful");                    out.flush();                    out.close();                })                .permitAll()                .and()                .csrf().disable()                .exceptionHandling()                .authenticationEntryPoint((req, resp, authException) -> {                    resp.setContentType("application/json;charset=utf-8");                    PrintWriter out = resp.getWriter();                    out.write("Please login first");                    out.flush();                    out.close();                });    }}

7. 测试类

UserDaoTest

import com.example.domain.Role;import com.example.domain.User;import org.junit.Test;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;import static org.junit.Assert.*;@RunWith(SpringRunner.class)@SpringBootTestpublic class UserDaoTest {    @Autowired    private UserDao userDao;    @Test    public void insertUser() {        User user = new User();        user.setUsername("testuser");        user.setPassword("testpass");        user.setEnabled(true);                List
roles = new ArrayList<>(); Role role = new Role(); role.setName("ROLE_regular"); role.setNameZh("普通用户"); roles.add(role); user.setRoles(roles); userDao.save(user); assertEquals("testuser", userDao.findUserByUsername("testuser").getUsername()); }}

8. 测试接口

HelloController

import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class HelloController {    @GetMapping("/hello")    public String sayHello() {        return "Welcome to our application";    }    @GetMapping("/admin/hello")    public String sayHelloForAdmin() {        return "Hello, Admin!";    }    @GetMapping("/user/hello")    public String sayHelloForUser() {        return "Hello, User!";    }}

总结

通过以上步骤,我们成功将用户数据存入MySQL数据库,并使用Spring Data Jpa进行数据库操作。用户和角色之间建立了多对多关系,实现了用户的 CRUD 操作和权限管理。接下来可以根据项目需求添加更多功能,比如用户注册、角色管理等。

转载地址:http://gdvkk.baihongyu.com/

你可能感兴趣的文章
Mstsc 远程桌面链接 And 网络映射
查看>>
Myeclipse常用快捷键
查看>>
MyEclipse更改项目名web发布名字不改问题
查看>>
MyEclipse用(JDBC)连接SQL出现的问题~
查看>>
mt-datetime-picker type="date" 时间格式 bug
查看>>
myeclipse的新建severlet不见解决方法
查看>>
MyEclipse设置当前行背景颜色、选中单词前景色、背景色
查看>>
Mtab书签导航程序 LinkStore/getIcon SQL注入漏洞复现
查看>>
myeclipse配置springmvc教程
查看>>
MyEclipse配置SVN
查看>>
MTCNN 人脸检测
查看>>
MyEcplise中SpringBoot怎样定制启动banner?
查看>>
MyPython
查看>>
MTD技术介绍
查看>>
MySQL
查看>>
MySQL
查看>>
mysql
查看>>
MTK Android 如何获取系统权限
查看>>
MySQL - 4种基本索引、聚簇索引和非聚索引、索引失效情况、SQL 优化
查看>>
MySQL - ERROR 1406
查看>>