自定义的username 为 admin;password 为 123;
可是就是不起作用。
UserDetailServiceImpl
package service;
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;
/**
* Created with IntelliJ IDEA.
*
* @User: andyf
* @Date: 2021/4/6
* @Time: 19:08
* @Description: 自定义登录逻辑
*/
@Service
public class UserDetailServiceImpl implements UserDetailsService {
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
// 测试 是否 走自定义登录的逻辑了
System.out.println("执行了自定义登录逻辑!");
// 1 根据用户名 去数据库查询,如果不存在抛异常
if (!"admin".equals(s)){
throw new UsernameNotFoundException("用户名不存在!");
}
// 2 比较密码 【注册时已经加密,】如果匹配成功返回UserDetails
// 由于暂时没有注册,所以先直接加密
String password = passwordEncoder.encode("123");
return new User(s,password, AuthorityUtils
.commaSeparatedStringToAuthorityList("admin,normal"));
}
}
配置类SecurityConfig
package config;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* Created with IntelliJ IDEA.
*
* @User: andyf
* @Date: 2021/4/6
* @Time: 19:06
* @Description:
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// 表单提交
http.formLogin()
// 自定义 登录界面
.loginPage("/login.html")
// 必须和表单提交的 接口一样。会去执行自定义登录逻辑
.loginProcessingUrl("/login")
// 登录成功后跳转的页面 ,只接受 post请求,不能使用 /main.html
.successForwardUrl("/toMain");
// 授权,
http.authorizeRequests()
// 但是,登录页面不需要拦截,要不然就无限循环了
.antMatchers("/login.html").permitAll()
// 所有的请求都必须认证才能访问,必须登录
.anyRequest().authenticated();
// 防火墙 关闭 。csrf防护
http.csrf().disable();
}
@Bean
public PasswordEncoder getPw(){
return new BCryptPasswordEncoder();
}
}
运行之后,还是会出现 默认的密码;
按照教程一步一步做的,就是 不起作用。
各位 ,有没有解决方法?