本文在通过下文,搭建好了框架的基础上做描述:
https://blog.csdn.net/weixin_42426099/article/details/105620579
让SpringSecurity通过读取数据库的用户名和密码来做验证
- 修改SpringSecurity配置文件spring-security.xml的认证管理器
<authentication-manager>
<authentication-provider user-service-ref="userDetailService">
</authentication-provider>
</authentication-manager>
- 创建UserDetailsServiceImpl类,实现UserDetailsService接口,并实现接口方法
/**
* 认证类
* @author Administrator
*
*/
public class UserDetailsServiceImpl implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//0.loadUserByUsername方法传入的username参数就是用户名
//1.创建被允许登录的角色列表
List<GrantedAuthority> grantAuths=new ArrayList();
grantAuths.add(new SimpleGrantedAuthority("ROLE_SELLER"));
//2.通过username到数据库查找对应的用户信息
//3.如果用户名匹配则返回org.springframework.security.core.userdetails.User对象
return new User(username,"[用户对应的密码]",grantAuths);
//4.如果未查找到用户名,或者该用户不允许登录,则返回null
//return null;
}
}
让SpringSecurity对保存的密码加密
常用的加密算法比如MD5,BCrypt。此处用的是BCrypt
- 修改配置文件spring-security.xml的认证管理器,添加做BCrypt加密的bean
<beans:bean id="bcryptEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />
<!-- 认证管理器 -->
<authentication-manager>
<authentication-provider user-service-ref="userDetailService">
<password-encoder ref="bcryptEncoder"></password-encoder>
</authentication-provider>
</authentication-manager>
- 修改处理保存用户密码的代码
//......
//密码加密
//user就是前端传来的,用户录入的用户信息
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String password = passwordEncoder.encode(user.getPassword());
user.setPassword(password);
//......将user做数据持久化
通过SpringSecurity从后台获取登录后的相关信息
- 可通过SpringSecurity的上下文对象获取:org.springframework.security.core.context.SecurityContextHolder
- 比如获取登录的用户名:
String name=SecurityContextHolder.getContext().getAuthentication().getName()
让SpringSecurity支持采用了frame(框架页)的页面
- 在SpringSecurity配置文件中加入如下配置:
<!-- 页面拦截规则 -->
<http use-expressions="false">
......
<headers>
<frame-options policy="SAMEORIGIN"/>
</headers>
......
</http>
实现对SpringSecurity的代码式配置
-
新建一个SecurityConfig类,并继承org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
-
重写方法:
//与处理URL相关的配置
protected void configure(HttpSecurity http)
//…