下文主要是认证:
1.导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.数据库等各种配置信息。。。。。
3.创建实体类,实现UserDetails接口
实现UserDetails接口的实体类会被认为是User实体类,SpringSecurity会根据重写的方法加载重要的用户信息。
@Data
public class User implements UserDetails {
private Integer userId;
private String userName;
private String password;
private Boolean locked;
/**
*获取用户的所有角色信息
*/
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
/**
*指定哪一个是用户的密码字段
*/
@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;
}
}
4.Dao的创建
@Select("select * from users where u_name = #{userName}")
@Results({
@Result(property = "userId",column = "u_id"),
@Result(property = "userName",column = "u_name"),
@Result(property = "password",column = "u_password")
})
User selectUserByUserName(String userName);
5.Service层的创建
public interface UserService extends UserDetailsService {
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return userMapper.selectUserByUserName(username);
}
}
6.Security配置
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
//授权
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
//任何请求都认证过
.anyRequest().authenticated()
//任何角色都可以访问
.antMatchers("/man1/**").permitAll()
//仅role2角色能访问
.antMatchers("/man2/**").hasRole("role2")
.and()
//没有权限进入内置登录界面
.formLogin();
//关闭csrf校验
http.csrf().disable();
}
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
版权声明:本文为weixin_58238974原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。