Spring Security简单增加短信验证码登录

查网上资料增加短信验证码登录都要增加一大推,要重头写Spring Security的实现,我呢,只想在原来的密码登录基础上简单实现一下短信验证码登录。
1、首先得先一个认证类,来认证验证码是否正确,这个类要实现Spring Security提供的AuthenticationProvider接口
2、其次需要一个认证令牌的类,作为你的认证信息,这个类要继承Spring Security提供的AbstractAuthenticationToken抽象类
3、然后要把你的认证类加到spring security配置中,就是继承WebSecurityConfigurerAdapter的类
4、最后就是登陆时调用Spring Security的认证了
上代码:
1、认证类

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

@Component
public class SmsAuthenticationProvider implements AuthenticationProvider {

	//用户验证处理 实现Spring Security提供的UserDetailsService的类 下面会给这个类
	private UserDetailsServiceImpl userDetailsServiceImpl;
	//redis缓存 用你的缓存就行 这个就不给了 用来存放验证码的
    private RedisCache redisCache;

    public SmsAuthenticationProvider(@Qualifier("userDetailsServiceImpl") UserDetailsServiceImpl smsUserDetailsServiceImpl, RedisCache redisCache) {
        this.userDetailsServiceImpl = smsUserDetailsServiceImpl;
        this.redisCache = redisCache;
    }


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    	SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication;
        Object principal = authentication.getPrincipal();// 获取凭证也就是用户的手机号
        String phone = "";
        if (principal instanceof String) {
            phone = (String) principal;
        }
        
        String inputCode = (String) authentication.getCredentials(); // 获取输入的验证码
        
        Integer cacheObject = redisCache.getCacheObject("login"+phone);
    	
        // 1. 检验Redis手机号的验证码
        if (cacheObject == null) {
            throw new BadCredentialsException("验证码已经过期或尚未发送,请重新发送验证码");
        }
        if (!inputCode.equals(cacheObject+"")) {
            throw new BadCredentialsException("输入的验证码不正确,请重新输入");
        }
        // 2. 根据手机号查询用户信息
        UserDetails userDetails = userDetailsServiceImpl.loadUserByUsername(phone);
        if (userDetails == null) {
            throw new InternalAuthenticationServiceException("phone用户不存在,请注册");
        }
         // 3. 重新创建已认证对象,
        SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(userDetails, inputCode, userDetails.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(aClass);
    }
}

UserDetailsServiceImpl类 这里面的东西就不固定了 想咋写就咋写 主要是loadUserByUsername方法 这个必须有 返回的UserDetails(Spring Security提供的用来存放用户信息的类,你可以随便写个类实现这个类,然后你就可以存放你自己要用的信息了)loadUserByUsername这个方法会在调用Spring Security的认证时用 我会在代码中表明在哪块会调用到这个类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        SysUser user = userService.selectUserByUserNameOrPhone(username);
        if (StringUtils.isNull(user))
        {
            log.info("登录用户:{} 不存在.", username);
            throw new ServiceException("登录用户:" + username + " 不存在");
        }
        else if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            log.info("登录用户:{} 已被删除.", username);
            throw new ServiceException("对不起,您的账号:" + username + " 已被删除");
        }
        else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            log.info("登录用户:{} 已被停用.", username);
            throw new ServiceException("对不起,您的账号:" + username + " 已停用");
        }

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user)
    {
        return new LoginUser(user.getUserId(), user.getDeptId(), user.getClinicId(), user, permissionService.getMenuPermission(user));
    }
}

2、存放认证令牌


import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;

import java.util.Collection;

public class SmsCodeAuthenticationToken extends AbstractAuthenticationToken {
    private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
    
    private final Object principal; //存放认证信息,认证之前存放手机号,认证之后存放登录的用户
    private Object credentials;

    public SmsCodeAuthenticationToken(String mobile, Object credentials) {
        super(null);
        this.principal = mobile;
        this.credentials = credentials;
        this.setAuthenticated(false);
    }

    public SmsCodeAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        this.credentials = credentials;
        super.setAuthenticated(true);
    }

    public Object getCredentials() {
    	return this.credentials;
    }

    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();
        this.credentials = null;
    }
}

3、spring security配置
在这里插入图片描述
在这里插入图片描述
4、登录调用认证

/**
     * 验证码登录
     * 
     * @param username 用户名
     * @param code 验证码
     * @return 结果
     */
    public String loginSms(String phone, String smsCode)
    {
        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername(这块调用了UserDetailsServiceImpl的loadUserByUsername)
            authentication = authenticationManager
                    .authenticate(new SmsCodeAuthenticationToken(phone, smsCode));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, null,Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, null,Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, loginUser.getClinicId(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        //上面已经结束了 剩下交给你自己了
        recordLoginInfo(loginUser.getUserId());
        // 生成token 这块你们根据你们的业务自己写了 tokenService.createToken使我们的业务方法
        return tokenService.createToken(loginUser);
    }
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现自定义短信验证码登录,可以按照以下步骤进行: 1. 添加依赖 在项目中添加 Spring SecuritySpring Security SMS 模块的依赖。 ``` <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>5.2.2.RELEASE</version> </dependency> <dependency> <groupId>com.github.lanceshohara</groupId> <artifactId>spring-security-sms</artifactId> <version>1.0.2</version> </dependency> ``` 2. 配置 Spring SecuritySpring Security 配置文件中添加配置,包括短信验证码登录相关的配置。 ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Autowired private SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig; @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/login/sms").permitAll() .anyRequest().authenticated() .and() .apply(smsCodeAuthenticationSecurityConfig) .and() .formLogin() .loginPage("/login") .loginProcessingUrl("/login/form") .usernameParameter("username") .passwordParameter("password") .defaultSuccessUrl("/") .permitAll() .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/") .permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ``` 其中,`SmsCodeAuthenticationSecurityConfig` 是短信验证码登录的相关配置类,需要单独实现。 3. 实现短信验证码登录相关配置 实现 `SmsCodeAuthenticationSecurityConfig` 配置类,其中包括一个短信验证码过滤器和一个短信验证码认证提供者。 ``` @Configuration public class SmsCodeAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> { @Autowired private UserDetailsService userDetailsService; @Autowired private SmsCodeAuthenticationSuccessHandler smsCodeAuthenticationSuccessHandler; @Autowired private SmsCodeAuthenticationFailureHandler smsCodeAuthenticationFailureHandler; @Override public void configure(HttpSecurity http) throws Exception { SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter(); smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class)); smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(smsCodeAuthenticationSuccessHandler); smsCodeAuthenticationFilter.setAuthenticationFailureHandler(smsCodeAuthenticationFailureHandler); SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider(); smsCodeAuthenticationProvider.setUserDetailsService(userDetailsService); http.authenticationProvider(smsCodeAuthenticationProvider) .addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); } } ``` 其中,`SmsCodeAuthenticationFilter` 是短信验证码过滤器,需要单独实现。`SmsCodeAuthenticationSuccessHandler` 和 `SmsCodeAuthenticationFailureHandler` 分别是短信验证码认证成功和失败的处理器,也需要单独实现。 4. 实现短信验证码过滤器 实现 `SmsCodeAuthenticationFilter` 过滤器,重写 `attemptAuthentication` 方法,来处理短信验证码认证请求。 ``` public class SmsCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter { public static final String SPRING_SECURITY_FORM_MOBILE_KEY = "mobile"; public static final String SPRING_SECURITY_FORM_CODE_KEY = "code"; private String mobileParameter = SPRING_SECURITY_FORM_MOBILE_KEY; private String codeParameter = SPRING_SECURITY_FORM_CODE_KEY; private boolean postOnly = true; public SmsCodeAuthenticationFilter() { super(new AntPathRequestMatcher("/login/sms", "POST")); } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { if (postOnly && !request.getMethod().equals("POST")) { throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); } String mobile = obtainMobile(request); String code = obtainCode(request); if (mobile == null) { mobile = ""; } if (code == null) { code = ""; } mobile = mobile.trim(); SmsCodeAuthenticationToken authRequest = new SmsCodeAuthenticationToken(mobile, code); setDetails(request, authRequest); return this.getAuthenticationManager().authenticate(authRequest); } protected String obtainMobile(HttpServletRequest request) { return request.getParameter(mobileParameter); } protected String obtainCode(HttpServletRequest request) { return request.getParameter(codeParameter); } protected void setDetails(HttpServletRequest request, SmsCodeAuthenticationToken authRequest) { authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); } public void setMobileParameter(String mobileParameter) { this.mobileParameter = mobileParameter; } public void setCodeParameter(String codeParameter) { this.codeParameter = codeParameter; } public void setPostOnly(boolean postOnly) { this.postOnly = postOnly; } public final String getMobileParameter() { return mobileParameter; } public final String getCodeParameter() { return codeParameter; } } ``` 其中,`SmsCodeAuthenticationToken` 是短信验证码认证的 token 类型,需要单独实现。 5. 实现短信验证码认证提供者 实现 `SmsCodeAuthenticationProvider` 提供者,重写 `authenticate` 方法,来进行短信验证码认证。 ``` public class SmsCodeAuthenticationProvider implements AuthenticationProvider { private UserDetailsService userDetailsService; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication; UserDetails userDetails = userDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal()); SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities()); authenticationResult.setDetails(authenticationToken.getDetails()); return authenticationResult; } @Override public boolean supports(Class<?> authentication) { return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication); } public UserDetailsService getUserDetailsService() { return userDetailsService; } public void setUserDetailsService(UserDetailsService userDetailsService) { this.userDetailsService = userDetailsService; } } ``` 6. 实现短信验证码认证成功和失败的处理器 实现 `SmsCodeAuthenticationSuccessHandler` 和 `SmsCodeAuthenticationFailureHandler` 处理器,来处理短信验证码认证成功和失败的情况。 ``` public class SmsCodeAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { super.onAuthenticationSuccess(request, response, authentication); } } ``` ``` public class SmsCodeAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { super.onAuthenticationFailure(request, response, exception); } } ``` 7. 编写控制器 编写控制器,处理短信验证码登录的请求。 ``` @Controller public class LoginController { private final static String SMS_LOGIN_PAGE = "sms-login"; @RequestMapping("/login/sms") public String smsLogin() { return SMS_LOGIN_PAGE; } @RequestMapping(value = "/login/sms", method = RequestMethod.POST) public void smsLogin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String mobile = request.getParameter("mobile"); String code = request.getParameter("code"); SmsCodeAuthenticationToken token = new SmsCodeAuthenticationToken(mobile, code); AuthenticationManager authenticationManager = new ProviderManager(Collections.singletonList(new SmsCodeAuthenticationProvider())); Authentication authentication = authenticationManager.authenticate(token); SecurityContextHolder.getContext().setAuthentication(authentication); request.getRequestDispatcher("/").forward(request, response); } } ``` 其中,`SmsCodeAuthenticationToken` 是短信验证码认证的 token 类型,需要单独实现。 以上就是实现自定义短信验证码登录的步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值