相关资料以及注意事项:
- SpringSecurity参考手册官方文档
- 本文工程GitHub
- SpringSecurity内存方式管理版本
- 本文环境:SpringBoot 2.x + SpringSecurity 5.0.6 + SpringJPA + Druid + mySQL + Thymeleaf + Lomok
- 注意:由于引入Lomok,所以需要安装Lomok插件,否则程序无法运行。
一.Maven配置
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--thymeleaf调用spring security工具-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
<!--druid数据连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<!--在idea中需要安装lombok插件-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
二.文件结构
└─com
└─example
└─securityjpa
│ SecurityJpaApplication.java
│
├─config
│ DruidConfig.java Druid配置文件
│ SecurityConfig.java SpringSecurity配置文件
│
├─controller
│ CommonController.java 页面映射
│
├─entity
│ RoleEntity.java 角色类型
│ UserEntity.java 用户类型
│
├─handler
│ CustomAccessDeniedHandler.java 自定义授权失败
│ myPassWordEncoder.java 自定义密码加密规则
│
├─jpa
│ UserEntityJpa.java JPA连接类
│
└─service
UserService.java 自定义用户用户认证规则
说实话,大概踩了一个礼拜的坑,今天终于把坑全部填平了,SpringSecurity5.0的改动内容实在是多,接下来把有关于SpringSecurity的配置慢慢讲来。此处省略了一些非核心代码。
a.UserService+UserEntity认证规则以及用户对象类
/**
* 自定义身份认证
* 需要实现UserDetailsService接口
* @author BaoZhou
* @date 2018/7/4
*/
public class UserService implements UserDetailsService {
@Autowired
UserEntityJpa userEntityJpa;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserEntity userEntity = userEntityJpa.findByUsername(username);
if (userEntity == null) {
throw new UsernameNotFoundException("未找到用户名");
}
return userEntity;
}
}
/**
* 用户类
* 在SpringSecurity中,用户表对象类需要实现UserDetails接口
*
* @author BaoZhou
* @date 2018/7/4
*/
@Entity
@Table(name = "users")
@Getter
@Setter
public class UserEntity implements Serializable, UserDetails {
@Id
@Column(name = "u_id")
private Long id;
@Column(name = "u_username")
private String username;
@Column(name = "u_password")
private String password;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "user_roles",
joinColumns = {
@JoinColumn(name = "ur_user_id")
},
inverseJoinColumns = {
@JoinColumn(name = "ur_role_id")
}
)
private List<RoleEntity> roles;
//设置用户身份权限
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> authorities = new ArrayList<>();
List<RoleEntity> roles = getRoles();
for (RoleEntity 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 true;
}
//设置账户没有被锁
@Override
public boolean isAccountNonLocked() {
return true;
}
//设置认证没有过期
@Override
public boolean isCredentialsNonExpired() {
return true;
}
//设置用户可以用
@Override
public boolean isEnabled() {
return true;
}
b.SecurityConfig配置类
/**
* @author: BaoZhou
* @date : 2018/7/4 17:15
*/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
UserDetailsService getServiceDetail() {
return new UserService();
}
//SpringSecurity会默认在身份前加上前缀,这里设置去除
@Override
public void configure(WebSecurity web) throws Exception {
web.expressionHandler(new DefaultWebSecurityExpressionHandler() {
@Override
protected SecurityExpressionOperations createSecurityExpressionRoot(Authentication authentication, FilterInvocation fi) {
WebSecurityExpressionRoot root = (WebSecurityExpressionRoot) super.createSecurityExpressionRoot(authentication, fi);
//remove the prefix ROLE_
root.setDefaultRolePrefix("");
return root;
}
});
}
//SpringSecurity5.0.6必须使用加密算法,此处注入加密方法
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* 注入自定义认证类
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(getServiceDetail());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
/*匹配所有路径的*/
http
/*关闭跨站支持,不关闭的话,无法登陆Druid监控页面*/
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/").permitAll()
...
...
...
}
}
c.JPA配置类
/**
- 用户信息JPA,JPA中只要按照命名规则,JPA会自动配置查找方法,无需实现
- @author BaoZhou
- @date 2018/7/4
*/
public interface UserEntityJpa extends JpaRepository<UserEntity,Long> {
public UserEntity findByUsername (String username);
}
三.配置文件
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://192.168.15.128:3306/jdbc
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
filters: {stat,wall,log4j}
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
jpa:
show-sql: true
hibernate:
ddl-auto: update
server:
port: 8005
配置文件中主要是Druid与JPA的配置
收工!