spring--springsecurity:使用springsecurity搭建基于mybatis的用戶認證
Spring Security 是spring項目之中的一個安全模塊括尸,可以非常方便與spring項目無縫集成。下面進行在springboot基礎上使用springsecurity以及mybatis的用戶身份驗證系統(tǒng)的搭建.(demo只具有驗證用戶身份的功能,權限管理及后續(xù)模塊會一步步開發(fā),demo地址https://github.com/superblue6/demo-security.git)
數(shù)據(jù)準備:
數(shù)據(jù)庫新建一張簡單的用戶表
搭建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>
創(chuàng)建從數(shù)據(jù)庫獲取用戶所需要的的mapper,bean;
user的實體類需要實現(xiàn)UserDetails
接口,并實現(xiàn)其方法:
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;
}
}
創(chuàng)建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:
創(chuàng)建UserService
類實現(xiàn)UserDetailsService
接口:
@Service
public class UserService implements UserDetailsService {
@Autowired
private UserMapper userMapper;
//該方法用來向springsecurity提供已存儲的用戶信息以用來與前端傳來的數(shù)據(jù)進行對比驗證
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
//根據(jù)用戶名從數(shù)據(jù)庫中查詢出該用戶的信息
UserInfo user = userMapper.loadUserByUsername(userName);
if (user == null){
throw new UsernameNotFoundException("賬戶不存在");
}
return user;
}
}
創(chuàng)建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保護起來,輸入賬號密碼
成功訪問到接口