Spring Security-从入门到精通-自定义登录逻辑
1、将BCryptPasswordEncoder 注入到ioc容器里面
package com.mangoubiubiu.security.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; /** * SecurityConfig 配置类 */ @Configuration public class SecurityConfig { @Bean public PasswordEncoder pw(){ return new BCryptPasswordEncoder(); } }
2、Service 实现类 要实现 UserDetailsService 里的loadUserByUsername 方法
package com.mangoubiubiu.security.service; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; public interface UserService { UserDetails loadUserByUsername(String username) throws UsernameNotFoundException; }
package com.mangoubiubiu.security.service.impl; import com.mangoubiubiu.security.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements UserService , UserDetailsService { @Autowired private PasswordEncoder pw; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { //1. 根据username 去查数据库 if(!"admin".equals(username)){ throw new UsernameNotFoundException("用户名或密码错误!"); } //2。 根据查询的对象比较密码 String password=pw.encode("123456"); //3、 返回用户对象 return new User("admin",password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal")); } }
3、测试
发现没有自动生成密码
发现没有自动生成密码
本文作者:KwFruit
本文链接:https://www.cnblogs.com/mangoubiubiu/p/16211811.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步