博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring Security自定义用户认证逻辑
阅读量:4186 次
发布时间:2019-05-26

本文共 1718 字,大约阅读时间需要 5 分钟。

在Spring Security中,用户的校验逻辑是不需要自己是实现的。但是我们需要通过页面用户输入的信息和数据库的用户信息进行比较。

Spring Security中提供了一个 接口UserDetailsService, 在他的loadUserByUsername方法中,对从数据库获取的用户信息进行封装。

自定义实现UserDetailsService

@Componentpublic class MyUserDetailService implements UserDetailsService {        private static final Logger logger = LoggerFactory.getLogger(MyUserDetailService.class);   // 需要使用Spring Security提供的密码加密类,不然会报错。   // 可以实现该接口,自定义密码加密类。    @Autowired    private PasswordEncoder passwordEncoder;    @Override    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {        logger.info("用户给名:{}", username);        //  从数据库获取用户信息        String password = passwordEncoder.encode("123456");        return new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));    }}在这里插入代码片

在这里需要使用 Spring Security的加密类,PasswordEncoder。

PasswordEncoder有两个方法,

encode方法供 加密时使用。

matches方法,供spring Security进行密码校验时使用。

public interface PasswordEncoder {    String encode(CharSequence var1);    boolean matches(CharSequence var1, String var2);    default boolean upgradeEncoding(String encodedPassword) {        return false;    }}

在返回UserDetails时,可以设置对用户的账号使用情况进行校验。

boolean isAccountNonExpired();  账号是否过期boolean isAccountNonLocked(); 账号是否冻结boolean isCredentialsNonExpired();  凭证是否过期boolean isEnabled(); 账号是否可用
@Override    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {        logger.info("用户给名:{}", username);        //  从数据库获取用户信息        String password = passwordEncoder.encode("123456");        // 根据数据信息进行判断账号使用情况        return new User(username, password, true, true, true, true,AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));    }```

转载地址:http://wdfoi.baihongyu.com/

你可能感兴趣的文章
MyEclipse中WEB项目加载mysql驱动方法
查看>>
常见编写JAVA报错总结
查看>>
org.gjt.mm.mysql.Driver和com.mysql.jdbc.Driver的区别
查看>>
UTF-8和GBK有什么区别
查看>>
增加MyEclipse分配内存的方法
查看>>
头痛与早餐
查看>>
[转]在ASP.NET 2.0中操作数据::创建一个数据访问层
查看>>
Linux命令之chmod详解
查看>>
【java小程序实战】小程序注销功能实现
查看>>
leetcode Unique Paths II
查看>>
几个大数据的问题
查看>>
CareerCup Pots of gold game:看谁拿的钱多
查看>>
CarreerCup Sort Height
查看>>
CareerCup Sort an array in a special way
查看>>
CareerCup Find lexicographic minimum in a circular array 循环数组字典序
查看>>
CareerCup Cost of cutting wood
查看>>
Find the number of subsets such that the sum of numbers in the subset is a prime number
查看>>
CareerCup Binary Tree the Maximum of 人
查看>>
CareerCup Divide n cakes to k different people
查看>>
CareerCup Randomly return a node in a binary tree
查看>>