mysql - 使用 AngularJS 和 Spring Security 进行身份验证

标签 mysql angularjs spring-boot spring-security

我想使用 AngularJSSpring-BootSpring-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/

相关文章:

mysql - select rows mysql order by 自定义值 从表底部到表顶部

java - 服务器错误或 Android 问题?

javascript - Angular 是否会干扰此点击事件绑定(bind)?

java - 升级到 Spring Boot 2.4.2 后,现有的 Flyway 迁移验证失败

spring - Spring Security 从 3.2.7 更新到 4.0.2.RELEASE 如何处理 defaultRolePrefix ="ROLE_"

php - mysql 持久连接的优点

php - 在某些特殊情况下不会插入数据?

javascript - Angular 中的嵌套 ng-repeats

javascript - AngularJS ng-include on ng-click

java - 如何配置 spring-boot 使用基于文件的 H2 数据库