我想使用 AngularJS 、 Spring-Boot 和 Spring-security 创建登录页面,我遵循此 tutorial一切都很好。
但这是一种静态登录方式,它是通过包含用户凭据的 application.yml 文件完成的,如下所示:
security:
user:
name: taha
password: password
如何通过检查 Mysql 数据库中的用户凭据来动态创建登录页面?我应该做出哪些改变?
最佳答案
第一步,您需要有域模型 User 来存储用户,然后创建 Repositoy 和 Service 层,通过用户名从数据库中查找用户,然后像这样创建 UserDetailService
@Component("userDetailsService")
public class CustomUserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService {
@Autowired
private IUserService userService;
private final Logger log = LoggerFactory.getLogger(CustomUserDetailsService.class);
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User userEntity = userService.findByUsername(username);
if (userEntity != null) {
log.debug("------------==" + userEntity.getUsername());
log.debug("------------==" + userEntity.getPassword());
} else if (userEntity == null)
throw new UsernameNotFoundException("user not found");
return userEntity;
}
}
并在安全配置中设置UserDetailService,如下所示
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Inject
@Qualifier("userDetailsService")
private UserDetailsService userDetailsService;
@Inject
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService);
}
@Override
public void configure(WebSecurity web) throws Exception {
}
}
关于mysql - 使用 AngularJS 和 Spring Security 进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42955182/