(一)新建browser包,在这个包下分别建立BrowserSecurityConfig类和MyUserDetailService类(自定义用户名和密码)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* @program: spring_security
* @description:
* @author: 一条懒咸鱼
* @create:2018-30-19:01
**/
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//http.formLogin()
http.httpBasic()
.and()
.authorizeRequests()
.anyRequest()
.authenticated();
}
}
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;
/**
* @program: spring_security
* @description:
* @author: 一条懒咸鱼
* @create:2018-30-19:06
**/
@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("登录用户名:" + username);
String password = passwordEncoder.encode("123456");
logger.info("数据库密码是" + password);
return new User(username, password, true, true, true, true, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
}
}

项目.png
(二)重新启动项目,并测试
在浏览器URL里输入localhost:8080

登录.png
分别输入用户名:admin 和密码 123456进入登录

登陆成功.png
我们再来观察一下控制台信息

控制台信息.png
用户admin登录被打印并且我们的123456密码被spring security进行了加密,生成的代码可以存到数据库中,并且这个加密后的密码是随机生成的,每次登录都会生成新的加密密码。