spring security 学习(二)用户认证自定义

 spring security 学习(一)spring boot 中开启spring security 中介绍了spring boot开启security的简单实例 ,security会生成用户名和密码,项目开发中用户名和密码都是必须的,spring security 提供了自定义用户认证。

自定义认证需要重新实现userDetailService 接口,接口中有个方法 loadUserByUserName。

package org.springframework.security.core.userdetails;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public interface UserDetailsService {
    UserDetails loadUserByUsername(String var1) throws UsernameNotFoundException;
}

UserDetails返回用户信息,也是一个接口。

package org.springframework.security.core.userdetails;

import java.io.Serializable;
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;

public interface UserDetails extends Serializable {
//获取用户包含的权限,返回权限集合,权限是一个继承了GrantedAuthority的对象; Collection
<? extends GrantedAuthority> getAuthorities(); //密码 String getPassword();    //用户名 String getUsername(); //是否已过期,已过期返回false;未过期返回true boolean isAccountNonExpired(); //是否未锁定,未锁定返回true,锁定返回false boolean isAccountNonLocked();   //判断密码是否过期 boolean isCredentialsNonExpired();    //判断用户是否可用  boolean isEnabled(); }

创建UserVoDetailsService 实现UserDetailsService;

@Configuration
public class UserVoDetailsService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;
    //@Autowired
    //private UserDao userDao;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 模拟一个用户,替代数据库获取逻辑
        UserVo user = new UserVo(); user.setUserName(username); user.setPassword(this.passwordEncoder.encode("123456")); // 输出加密后的密码  System.out.println(user.getPassword()); return new User(username, user.getPassword(), user.isEnabled(), user.isAccountNonExpired(), user.isCredentialsNonExpired(), user.isAccountNonLocked(), AuthorityUtils.commaSeparatedStringToAuthorityList("admin")); } }

 

转载于:https://www.cnblogs.com/yuiqng/p/10547470.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值