SpringSecurity实现密码验证等常用功能

本文在通过下文,搭建好了框架的基础上做描述:
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)
    //…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值