spring--springsecurity:使用springsecurity搭建基于mybatis的用户认证
Spring Security 是spring项目之中的一个安全模块,可以非常方便与spring项目无缝集成。下面进行在springboot基础上使用springsecurity以及mybatis的用户身份验证系统的搭建.(demo只具有验证用户身份的功能,权限管理及后续模块会一步步开发,demo地址https://github.com/superblue6/demo-security.git)
数据准备:
数据库新建一张简单的用户表
搭建springboot项目
使用idea快速搭建springboot项目
所需要的的依赖:
<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.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</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>
创建从数据库获取用户所需要的的mapper,bean;
user的实体类需要实现UserDetails
接口,并实现其方法:
public class USer implements UserDetails {
private String userId;
private String userName;
private String password;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setPassword(String password) {
this.password = password;
}
//获取用户权限,暂不用,所以返回null
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
@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;
}
}
创建mapper接口以及xml文件:
@Repository
@Mapper
public interface UserMapper {
USer getUserByName(String userName);
}
<mapper namespace="com.example.demosecurity.dao.UserMapper">
<select id="getUserByName" resultType="com.example.demosecurity.bean.USer">
select * from deal_user where userName=#{userName};
</select>
</mapper>
yml配置:
spring:
datasource:
url: jdbc:mysql://localhost:3306/deal?useUnicode=true&charset=UTF-8&useAffectedRows=true&useSSL=false
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
server:
tomcat:
uri-encoding: utf-8
port: 8082
servlet:
context-path: /security
mybatis:
mapper-locations: classpath:/mapper/*.xml
添加一个controller
@RestController
public class UserController {
@GetMapping("/hello")
public String hello(){
return "hello";
}
}
配置springsecurity:
创建UserService
类实现UserDetailsService
接口:
@Service
public class UserService implements UserDetailsService {
@Autowired
private UserMapper userMapper;
//该方法用来向springsecurity提供已存储的用户信息以用来与前端传来的数据进行对比验证
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
//根据用户名从数据库中查询出该用户的信息
UserInfo user = userMapper.loadUserByUsername(userName);
if (user == null){
throw new UsernameNotFoundException("账户不存在");
}
return user;
}
}
创建WebSecurityConfig
继承WebSecurityConfigurerAdapter
:
//添加security注解
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
//注入自定义的userService类
@Autowired
private UserService userService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//将自定义的用户信息提供类传入该方法
auth.userDetailsService(userService);
}
//设置密码加密策略,这里使用明文密码,即无加密策略
@Bean
PasswordEncoder passwordEncoder(){
return NoOpPasswordEncoder.getInstance();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()//表示任何请求都需要验证
.and()
.formLogin()
.permitAll()//表示开启表单验证,permitall表示与登录相关的接口不需要认证
.and()
.csrf().disable();//取消跨站请求伪造(Cross-site request forgery)保护
}
}
启动项目:
访问http://localhost:8082/security/hello
可以看到该接口已被springsecurity保护起来,输入账号密码
成功访问到接口