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、测试

发现没有自动生成密码

发现没有自动生成密码

 

 

posted @ 2022-04-30 23:20  KwFruit  阅读(116)  评论(0编辑  收藏  举报