这两天学习了Spring Security,学习过程中看别人的帖子,发现他们的帖子都太长太复杂了,对新手不是很友好啊,所以在这里想给大家分享一波简单的入门案例,废话不多说直接上代码了。
第一步是先要在pom中导入Security的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
接下来在你们的静态资源下随便放入一些东西,然后直接运行你的Spring Boot项目,打开浏览器,输入你们资源的URL。
接着你们会发现Security就已经起作用了,你们的资源不能随意访问了,弹出了一个Security自带的登录界面,此时需要输入账号密码。
账号默认是user,而密码会在控制台给你们输出出来。
可是,大家会发现真实开发中,账号密码肯定是要从数据库中获取的,不能用它原生的,所以接下来解决这个问题。
首先呢,创建一个配置类,继承WebSecurityConfigurerAdapter这个类,重写里面的方法
@Configuration
public class SecurityConfigTest extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;//引用UserDetailsService接口的实现类
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(password());
}
@Bean
PasswordEncoder password(){return new BCryptPasswordEncoder();}//密码加密配置
}
接着需要获取到数据库中的数据,本案例中就使用Mybatis-plus实现。
创建数据库的实体类,注意需要和数据库表名一致。
@Data
@NoArgsConstructor
@AllArgsConstructor
public class login {
private Integer id;
private String user;
private String password;
}
创建mapper文件夹,在里面创建一个mapper接口继承BaseMapper。
@Repository
public interface UserMapper extends BaseMapper<login> {
}
导入两个依赖。
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
最后写一个Service类,继承UserDetailsService这个接口,重写里面的方法。
让我们试着利用Mybatis-plus查询一下数据中user叫zhangsan的数据,还有他的password。
代码中AuthorityUtils.commaSeparatedStringToAuthorityList用来定义用户权限,我们将它赋值给一个list集合中。
return一个security中的User类,在其构造器中需要填入三个属性,前两个调用实体类的get方法获取user和password字段的值,最后一个填入该用户的权限。
@Service("userDetailsService")
public class MyUserDetail implements UserDetailsService {
@Autowired
UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
QueryWrapper<login> wrapper = new QueryWrapper();
wrapper.eq("user","zhangsan");
login login = userMapper.selectOne(wrapper);
List<GrantedAuthority> list = AuthorityUtils.commaSeparatedStringToAuthorityList("rool");
return new User(login.getUser(),new BCryptPasswordEncoder().encode(login.getPassword()),list);
}
}
大功告成,重启项目,此时再登录就会发现user变成了zhangsan,密码变成了zhangsan的密码。
完成了这些我们会觉得还不是很人性化,我们会想要一下我们自定义的一些功能,比如自定义我们的登录页面,以及哪些页面不需要登录也能访问。
当然以上这些,security也为我们想到了,我们只需要回到刚才的配置类中再重写一个方法就可以实现DIY了。
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
// 如果有允许匿名的url,填在下面
// .antMatchers().permitAll()
.anyRequest().authenticated()
.and()
// 设置登陆页
.formLogin().loginPage("/login")
// 设置登陆成功页
.defaultSuccessUrl("/").permitAll()
// 自定义登陆用户名和密码参数,默认为username和password
// .usernameParameter("username")
// .passwordParameter("password")
.and()
.logout().permitAll();
// 关闭CSRF跨域
http.csrf().disable();
}
入门案例总结完毕,喜欢的朋友给新人点赞关注一下,欢迎评论区讨论,如有不足,请大佬们多多指点。