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 中国大陆许可协议进行许可。

posted @   KwFruit  阅读(121)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起