ssh + springboot + springsecurity + mysql整合
1.build.gradle配置文件
plugins {
id 'org.springframework.boot' version '2.2.0.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'java'
}
group = 'com.ying'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.social:spring-social-security:1.1.6.RELEASE'
runtimeOnly 'mysql:mysql-connector-java'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
testImplementation 'org.springframework.security:spring-security-test'
}
test {
useJUnitPlatform()
}
2.application.properties配置文件
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/ssh_springboot_ying?serverTimezone=UTC&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
#JPA配置
#显示sql语句
spring.jpa.show-sql=true
#更新数据库表
spring.jpa.hibernate.ddl-auto=update
#扩大Sesison作用范围
spring.jpa.open-in-view=true
#热部署静态文件
spring.thymeleaf.cache=false
#使用HTML5标准
spring.thymeleaf.mode=HTML5
**3.Springsecurity 拦截的自定义配置
1.继承WebSecurityConfigurerAdapter
2.重写configure(HttpSecurity http)方法**
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@EnableWebSecurity
public class MyWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
// 配置个加密的实现类用来给密码加密
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// 请求授权
http.formLogin().and().authorizeRequests()
// 访问 "/" 和 "/login" 路径的请求都允许
// .antMatchers("/","/login").permitAll()
// 所有请求
.anyRequest()
// 都需要我们身份认证
.authenticated()
// 修改Spring Security默认的登陆界面
// .and().formLogin().loginPage("/login").permitAll()
// 配置SpringSecurity允许使用ifrme嵌入页面
.and().headers().frameOptions().disable()
// 跨站请求伪造的防护
.and().csrf().disable();
}
}
4.自定义Springsecurity密码设置
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.social.security.SocialUser;
import org.springframework.stereotype.Component;
@Component
public class MyUserDetailsService implements UserDetailsService {
@Autowired
// 用来加密
private PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return new SocialUser(username, passwordEncoder.encode("123"),
AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
}
}
5.使用JpaRepository
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;
import com.ying.ssh_springboot_ying.domain.User;
public interface LoginRepository extends JpaRepository<User, Integer> {
@Query(value = "select * from user where username = ?1", nativeQuery = true)
User findUserName(String username);
//更新删除操作需要 @Transactional,@Modifying 注解
@Transactional
@Modifying
@Query(value = "update user set username = ?1", nativeQuery = true)
void updateUserName(String username);
}
6.Test
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.ying.ssh_springboot_ying.Repository.login.LoginRepository;
import com.ying.ssh_springboot_ying.domain.User;
@SpringBootTest
class SshSpringbootYingApplicationTests {
@Autowired
private LoginRepository loginRepository;
@Test
void contextLoads() throws FileNotFoundException, UnsupportedEncodingException {
//查询所有
List<User> findAll = loginRepository.findAll();
//更具姓名查询用户
User findUserName = loginRepository.findUserName("小明");
//设置所有用户名为小刚
loginRepository.updateUserName("小刚");
}
}
7.实体类
import java.util.Arrays;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name = "user")
public class User {
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
private Integer id;
@Column(length = 225, nullable = false)
private String username;
@Column(length = 225, nullable = false)
private String password;
@Temporal(TemporalType.DATE)
private Date registertime;
@Lob
@Basic(fetch = FetchType.LAZY)
@Column(columnDefinition = "BLOB",nullable=true)
private byte[] blobXml;
public Integer getId() {
return id;
}
public byte[] getBlobXml() {
return blobXml;
}
public void setBlobXml(byte[] blobXml) {
this.blobXml = blobXml;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getRegistertime() {
return registertime;
}
public void setRegistertime(Date registertime) {
this.registertime = registertime;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + ", registertime=" + registertime
+ ", blobXml=" + Arrays.toString(blobXml) + "]";
}
}