需求
实现步骤
获取短信验证码
在这一步我们需要写一个controller接收用户的获取验证码请求。注意:一定要为“/smscode”访问路径配置为permitAll访问权限,因为spring security默认拦截所有路径,除了默认配置的/login请求,只有经过登录认证过后的请求才会默认可以访问。
@Slf4j
@RestController
public class SmsController {
@Autowired
private UserDetailsService userDetailsService;
@RequestMapping(value="/smscode",method = RequestMethod.GET)
public String sms(@RequestParam String mobile, HttpSession session) throws IOException {
UserDetails userDetails = userDetailsService.loadUserByUsername(mobile);
if(userDetails == null){
return "您输入的手机号不是系统注册用户";
}
String randomNumeric = RandomStringUtils.randomNumeric(4);
SmsCode smsCode = new SmsCode(randomNumeric,60,mobile);
log.info(smsCode.getCode() + "=》" + mobile);
session.setAttribute("sms_key",smsCode);
return "短信息已经发送到您的手机";
}
}
public class SmsCode {
private String code;
private LocalDateTime expireTime;
private String mobile;
public SmsCode(String code,int expireAfterSeconds,String mobile){
this.code = code;
this.expireTime = LocalDateTime.now().plusSeconds(expireAfterSeconds);
this.mobile = mobile;
}
public boolean isExpired(){
return LocalDateTime.now().isAfter(expireTime);
}
public String getCode() {
return code;
}
public String getMobile() {
return mobile;
}
}
前端初始化短信登录界面
<h1>短信登陆</h1>
<form action="/smslogin" method="post">
<span>手机号码:</span><input type="text" name="mobile" id="mobile"> <br>
<span>短信验证码:</span><input type="text" name="smsCode" id="smsCode" >
<input type="button" onclick="getSmsCode()" value="获取"><br>
<input type="button" onclick="smslogin()" value="登陆">
</form>
<script>
function getSmsCode()
{
$.ajax({
type: "GET",
url: "/smscode",
data:{"mobile":$("#mobile").val()},
success: function (res) {
console.log(res)
},
error: function (e) {
console.log(e.responseText);
}
});
}
function smslogin() {
var mobile = $("#mobile").val();
var smsCode = $("#smsCode").val();
if (mobile === "" || smsCode === "") {
alert('手机号和短信验证码均不能为空');
return;
}
$.ajax({
type: "POST",
url: "/smslogin",
data: {
"mobile": mobile,
"smsCode": smsCode
},
success: function (res) {
console.log(res)
},
error: function (e) {
console.log(e.responseText);
}
});
}
</script>
spring security配置类
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private ObjectMapper objectMapper=new ObjectMapper();
@Resource
private CaptchaCodeFilter captchaCodeFilter;
@Bean
PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/js/**", "/css/**","/images/**");
}
@Autowired
DataSource dataSource;
@Bean
JdbcTokenRepositoryImpl jdbcTokenRepository() {
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
return jdbcTokenRepository;
}
@Override
@Bean
protected UserDetailsService userDetailsService() {
JdbcUserDetailsManager manager = new JdbcUserDetailsManager();
manager.setDataSource(dataSource);
if (!manager.userExists("dhy")) {
manager.createUser(User.withUsername("dhy").password("123").roles("admin").build());
}
if (!manager.userExists("大忽悠")) {
manager.createUser(User.withUsername("大忽悠").password("123").roles("user").build());
}
if (!manager.userExists("123456789")) {
manager.createUser(User.withUsername("123456789").password("").roles("user").build());
}
return manager;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.
authorizeRequests()
.antMatchers("/admin/**").hasRole("admin")
.antMatchers("/user/**").hasRole("user")
.antMatchers("/kaptcha","/smscode").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.html").permitAll()
.loginProcessingUrl("/login").permitAll()
.defaultSuccessUrl("/main.html")
.failureHandler(new MyFailHandler())
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/logout.html").permitAll()
.deleteCookies("JSESSIONID")
.and()
.rememberMe()
.key("dhy")
.tokenRepository(jdbcTokenRepository())
.and()
.addFilterBefore(captchaCodeFilter, UsernamePasswordAuthenticationFilter.class)
.csrf().disable();
}
@Bean
RoleHierarchy roleHierarchy() {
RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();
hierarchy.setHierarchy("ROLE_admin > ROLE_user");
return hierarchy;
}
}
短信验证码校验过滤器
短信验证码的校验过滤器,和图片验证码的验证实现原理是一致的。都是通过继承OncePerRequestFilter实现一个Spring环境下的过滤器。其核心校验规则如下:
@Component
public class SmsCodeValidateFilter extends OncePerRequestFilter {
@Resource
UserDetailsService userDetailsService;
@Resource
MyFailHandler myAuthenticationFailureHandler;
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain)
throws ServletException, IOException {
if (request.getRequestURI().equals("/smslogin")
&& request.getMethod().equalsIgnoreCase("post")) {
try {
validate(new ServletWebRequest(request));
}catch (AuthenticationException e){
myAuthenticationFailureHandler.onAuthenticationFailure(
request,response,e);
return;
}
}
filterChain.doFilter(request,response);
}
private void validate(ServletWebRequest request) throws ServletRequestBindingException {
HttpSession session = request.getRequest().getSession();
SmsCode codeInSession = (SmsCode) session.getAttribute("sms_key");
String codeInRequest = request.getParameter("smsCode");
String mobileInRequest = request.getParameter("mobile");
if(StringUtils.isEmpty(mobileInRequest)){
throw new SessionAuthenticationException("手机号码不能为空!");
}
if(StringUtils.isEmpty(codeInRequest)){
throw new SessionAuthenticationException("短信验证码不能为空!");
}
if(Objects.isNull(codeInSession)){
throw new SessionAuthenticationException("短信验证码不存在!");
}
if(codeInSession.isExpired())
{
session.removeAttribute("sms_key");
throw new SessionAuthenticationException("短信验证码已过期!");
}
if(!codeInSession.getCode().equals(codeInRequest)){
throw new SessionAuthenticationException("短信验证码不正确!");
}
if(!codeInSession.getMobile().equals(mobileInRequest)){
throw new SessionAuthenticationException("短信发送目标与该手机号不一致!");
}
UserDetails myUserDetails = userDetailsService.loadUserByUsername(mobileInRequest);
if(Objects.isNull(myUserDetails)){
throw new SessionAuthenticationException("您输入的手机号不是系统的注册用户");
}
session.removeAttribute("sms_key");
}
}
注意:一定要为"/smslogin"访问路径配置为permitAll访问权限
到这里,我们可以讲一下整体的短信验证登录流程,如上面的时序图。
短信验证码登录认证
我们可以仿照用户密码登录的流程,完成相关类的动态替换
由上图可以看出,短信验证码的登录认证逻辑和用户密码的登录认证流程是一样的。所以:
模拟实现:只不过将用户名、密码换成手机号进行认证,短信验证码在此部分已经没有用了,因为我们在SmsCodeValidateFilter已经验证过了。
public class SmsCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public static final String SPRING_SECURITY_FORM_MOBILE_KEY = "mobile";
private String mobileParameter = SPRING_SECURITY_FORM_MOBILE_KEY ;
private boolean postOnly = true;
private static final AntPathRequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER = new AntPathRequestMatcher("/smslogin", "POST");
public SmsCodeAuthenticationFilter() {
super(DEFAULT_ANT_PATH_REQUEST_MATCHER);
}
public Authentication attemptAuthentication(
HttpServletRequest request,
HttpServletResponse response)
throws AuthenticationException {
if (this.postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
} else {
String mobile = this.obtainMobile(request);
if (mobile == null) {
mobile = "";
}
mobile = mobile.trim();
SmsCodeAuthenticationToken authRequest = new SmsCodeAuthenticationToken(mobile);
this.setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
}
protected String obtainMobile(HttpServletRequest request) {
return request.getParameter(this.mobileParameter);
}
protected void setDetails(HttpServletRequest request, SmsCodeAuthenticationToken authRequest) {
authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
}
public void setMobileParameter(String mobileParameter) {
Assert.hasText(mobileParameter, "Username parameter must not be empty or null");
this.mobileParameter = mobileParameter;
}
public void setPostOnly(boolean postOnly) {
this.postOnly = postOnly;
}
public final String getMobileParameter() {
return this.mobileParameter;
}
}
认证令牌也需要替换:
public class SmsCodeAuthenticationToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private final Object principal;
public SmsCodeAuthenticationToken(String mobile) {
super((Collection)null);
this.principal = mobile;
this.setAuthenticated(false);
}
public SmsCodeAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
super.setAuthenticated(true);
}
public Object getCredentials() {
return null;
}
public Object getPrincipal() {
return this.principal;
}
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
if (isAuthenticated) {
throw new IllegalArgumentException("Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
} else {
super.setAuthenticated(false);
}
}
public void eraseCredentials() {
super.eraseCredentials();
}
}
当前还需要提供能够对我们当前自定义令牌对象起到认证作用的provider,仿照DaoAuthenticationProvider
public class SmsCodeAuthenticationProvider implements AuthenticationProvider{
private UserDetailsService userDetailsService;
public UserDetailsService getUserDetailsService() {
return userDetailsService;
}
public void setUserDetailsService(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken)authentication;
UserDetails user = userDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal());
if(user == null){
throw new InternalAuthenticationServiceException("无法获取用户信息");
}
SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(user,user.getAuthorities());
authenticationResult.setDetails(authenticationToken.getDetails());
return authenticationResult;
}
@Override
public boolean supports(Class<?> aClass) {
return SmsCodeAuthenticationToken.class.isAssignableFrom(aClass);
}
}
配置类进行综合组装
最后我们将以上实现进行组装,并将以上接口实现以配置的方式告知Spring Security。因为配置代码比较多,所以我们单独抽取一个关于短信验证码的配置类SmsCodeSecurityConfig,继承自SecurityConfigurerAdapter。
@Component
public class SmsCodeSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
@Resource
private MyFailHandler myAuthenticationFailureHandler;
private UserDetailsService myUserDetailsService;
@Resource
private SmsCodeValidateFilter smsCodeValidateFilter;
@Override
public void configure(HttpSecurity http) throws Exception {
SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter();
smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
smsCodeAuthenticationFilter.setAuthenticationFailureHandler(myAuthenticationFailureHandler);
SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();
smsCodeAuthenticationProvider.setUserDetailsService(myUserDetailsService);
http.addFilterBefore(smsCodeValidateFilter, UsernamePasswordAuthenticationFilter.class);
http.authenticationProvider(smsCodeAuthenticationProvider)
.addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
}
该配置类可以用以下代码,集成到SecurityConfig中。
完整配置
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private ObjectMapper objectMapper=new ObjectMapper();
@Resource
private CaptchaCodeFilter captchaCodeFilter;
@Resource
private SmsCodeSecurityConfig smsCodeSecurityConfig;
@Bean
PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/js/**", "/css/**","/images/**");
}
@Autowired
DataSource dataSource;
@Bean
JdbcTokenRepositoryImpl jdbcTokenRepository() {
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
return jdbcTokenRepository;
}
@Override
@Bean
protected UserDetailsService userDetailsService() {
JdbcUserDetailsManager manager = new JdbcUserDetailsManager();
manager.setDataSource(dataSource);
if (!manager.userExists("dhy")) {
manager.createUser(User.withUsername("dhy").password("123").roles("admin").build());
}
if (!manager.userExists("大忽悠")) {
manager.createUser(User.withUsername("大忽悠").password("123").roles("user").build());
}
if (!manager.userExists("123456789")) {
manager.createUser(User.withUsername("123456789").password("").roles("user").build());
}
return manager;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
smsCodeSecurityConfig.setMyUserDetailsService(userDetailsService());
http.
authorizeRequests()
.antMatchers("/admin/**").hasRole("admin")
.antMatchers("/user/**").hasRole("user")
.antMatchers("/kaptcha","/smscode","/smslogin").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.html").permitAll()
.loginProcessingUrl("/login").permitAll()
.defaultSuccessUrl("/main.html")
.failureHandler(new MyFailHandler())
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/logout.html").permitAll()
.deleteCookies("JSESSIONID")
.and()
.rememberMe()
.key("dhy")
.tokenRepository(jdbcTokenRepository())
.and()
.apply(smsCodeSecurityConfig)
.and()
.addFilterBefore(captchaCodeFilter, UsernamePasswordAuthenticationFilter.class)
.csrf().disable();
}
@Bean
RoleHierarchy roleHierarchy() {
RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();
hierarchy.setHierarchy("ROLE_admin > ROLE_user");
return hierarchy;
}
}
|