说明
1、springboot框架,jpa,spring-data持久化
2、想要实现:在用户看到hello页面前先进行登录

步骤:
1、spring-security配置类,继承WebSecurityConfigurerAdapter,重写一些方法来设置一些WEB安全的细节。
2、重写configure(HttpSecurity http)对需要进行保护的url进行定义。

 @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http
                .authorizeRequests()
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                   .loginPage("/login").defaultSuccessUrl("/hello",true)
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }

3、重写configure(AuthenticationManagerBuilder auth)方法,将用户验证功能交给一个实现了UserDetailsService接口的服务类。

 WebSecurityConfig.java

  @Bean
    UserDetailsService customUserServer(){
        return new UserServer();
    }
  @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.userDetailsService(customUserServer());
    }

 WebSecurityConfig.java

@Autowired
    private UserService userService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth)throws Exception {
        auth.userDetailsService(this.userService);
    }

而且,实现UserDetailsService的服务类需要重写loadUserByUsername方法,从数据库提取用户信息。

UserServer.java
    @Autowired
    UserRepo userRepo;
    @Override
    public UserDetails loadUserByUsername(String name){


        User user = userRepo.findByName(name);

        if( user == null ){
            throw new  UsernameNotFoundException(String.format("User with username=%s was not found"));
        }

        return user;
    }

注意!在前端登录界面,表单中name的一定要分别为“username”和“password”,不然会出错,即使你登录的是已经注册的名字,也会认定失败。