初始springboot

说明
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”,不然会出错,即使你登录的是已经注册的名字,也会认定失败。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值