Spring Security 自定义用户认证

一、PasswordEncoder

在@Configuration注解的类下注入bean:

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
    @Bean
    public PasswordEncoder passwordEncoder () {
        return new BCryptPasswordEncoder();
    }

二、自定义登录业务

新建MyUserDetailsService类实现org.springframework.security.core.userdetails.UserDetailsService 接口 :

package com.xh.sercurity;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.Component;

@Component
public class MyUserDetailsService implements UserDetailsService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查找用户信息
        logger.info("login username is : " + username);
        // 权限  
        // 账号过期 -账户是否锁定-密码过期-账户是否可用 
        // passwordEncoder.encode("123456") 这是注册用的,这里写数据库读出的
        logger.info("数据库密码是: " + passwordEncoder.encode("123456"));
        // 用户名  密码(数据库查出来的,security自动与用户传入的对比)  权限
        // 用户名  密码  权限
        return new User(username, passwordEncoder.encode("123456"), 
                true,true,true,true,
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }

}

你可能感兴趣的:(Spring,Security)