springsecurity实现UserDetailsService改变用户信息来源

springsecurity用户验证,默认我们为了简单,直接使用在配置文件中写死用户名和密码的方式:

在真实的系统中,我们希望用户的信息来自数据库,而不是写死的,我们就需要实现UserDetailsService接口,实现相应的方法,然后配置authentication-provider,指定我们自定义的UserDetailService。

这里定义一个类SecurityUserDetailsService,实现UserDetailsService接口:

package com.xxx.ssh.web.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.xxx.ssh.web.domain.User;
import com.xxx.ssh.web.service.UserService;
public class SecurityUserDetailsService implements UserDetailsService {
	@Autowired
	private UserService userService;
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user = userService.findByUsername(username);
		if(user==null) {
			throw new UsernameNotFoundException("用户名或密码错误");
		}
		return new org.springframework.security.core.userdetails.User(username, 
				user.getPassword(), 
				user.isStatus(), 
				true, 
				true, 
				true, 
				getGrantedAuthority(user));
	}
	public List<GrantedAuthority> getGrantedAuthority(User user){
		List<GrantedAuthority> list = new ArrayList<>();
		list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
		return list;
	}
}

另外,就需要配置一下authentication-provider即可,在配置之前,我们需要将SecurityUserDetailsService这个实体bean配置好。修改后的spring-security配置。

<bean id="securityUserDetailsService" class="com.xxx.ssh.web.service.impl.SecurityUserDetailsService">
</bean>
<sec:authentication-manager id="authentication-manager">
	<sec:authentication-provider user-service-ref="securityUserDetailsService">
	   <sec:password-encoder hash="md5"/>
	</sec:authentication-provider>
</sec:authentication-manager>

数据库中的密码使用了md5加密,所以这里配置authentication-provider属性的时候,我们需要配置password-encoder,指定hash="md5",这样在登录验证的时候,我们前端传过来的密码会经过md5加密,然后和数据库中的密码做比对,如果用户名密码都正确,登录成功,否则,登录失败。 

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luffy5459

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值