spring boot security 自定义登陆验证(jdbc)

首先加入依赖:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>
然后在spring boot 的main 的启动类中加入
@EnableWebSecurity

这就可以了,下面我们来写一个java的配置文件:

接收http的那个是安全策略,auth的那个就是验证了,auth可以自定义的,也可以用默认的,一般的话,我们都是自定义.

来看一下MyAuthenticationProvider:

package com.ttm.Service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Service;

@Service
public class MyAuthenticationProvider implements AuthenticationProvider{

  @Autowired
  JdbcTemplate jdbcTemplate;

  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    System.out.println("%%%%%%%%%-----查数据库"+authentication);
    return new UsernamePasswordAuthenticationToken("","");
  }

  @Override
  public boolean supports(Class<?> aClass) {
    System.out.println("%%%%%%%%%-----+supports");
    return true;
  }
}

authenticate方法里你可以做任何自定义的验证,

这里注意一下Authentication authentication这个参数会传过来用户名和密码,

你的表单用户名和密码的name属性必须如下,否则接收不到

返回UsernamePasswordAuthenticationToken对象就可以了,我们不用指定验证成功后下一步操作,会自己跳转到登陆前拦截的页面。

经验分享 程序员 微信小程序 职场和发展