若依系統(tǒng)(Security)增加手機(jī)驗證碼登錄

一庸汗、編寫token類

package com.zensun.framework.security.sms;

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

import java.util.Collection;

/**
 * 短信登錄 AuthenticationToken凳寺,模仿 UsernamePasswordAuthenticationToken 實現(xiàn)
 *
 * @author gmk
 */
public class SmsCodeAuthenticationToken extends AbstractAuthenticationToken {

    private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;

    /**
     * 在 UsernamePasswordAuthenticationToken 中該字段代表登錄的用戶名,
     * 在這里就代表登錄的手機(jī)號碼
     */
    private final Object principal;

    /**
     * 構(gòu)建一個沒有鑒權(quán)的 SmsCodeAuthenticationToken
     */
    public SmsCodeAuthenticationToken(Object principal) {
        super(null);
        this.principal = principal;
        setAuthenticated(false);
    }

    /**
     * 構(gòu)建擁有鑒權(quán)的 SmsCodeAuthenticationToken
     */
    public SmsCodeAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        // must use super, as we override
        super.setAuthenticated(true);
    }

    @Override
    public Object getCredentials() {
        return null;
    }

    @Override
    public Object getPrincipal() {
        return this.principal;
    }

    @Override
    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");
        }

        super.setAuthenticated(false);
    }

    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
    }

}

二套啤、編寫短信登陸鑒權(quán) Provider

package com.zensun.framework.security.sms;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * 短信登陸鑒權(quán) Provider宽气,要求實現(xiàn) AuthenticationProvider 接口
 *
 * @author gmk
 */
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication;

        String telephone = (String) authenticationToken.getPrincipal();

        UserDetails userDetails = userDetailsService.loadUserByUsername(telephone);

        // 此時鑒權(quán)成功后,應(yīng)當(dāng)重新 new 一個擁有鑒權(quán)的 authenticationResult 返回
        SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(userDetails, userDetails.getAuthorities());

        authenticationResult.setDetails(authenticationToken.getDetails());

        return authenticationResult;
    }


    @Override
    public boolean supports(Class<?> authentication) {
        // 判斷 authentication 是不是 SmsCodeAuthenticationToken 的子類或子接口
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}

三纲岭、編寫UserDetailsService實現(xiàn)類

package com.zensun.framework.web.service;

import com.zensun.common.core.domain.entity.SysUser;
import com.zensun.common.core.domain.model.LoginUser;
import com.zensun.common.enums.UserStatus;
import com.zensun.common.exception.BaseException;
import com.zensun.common.utils.StringUtils;
import com.zensun.system.service.ISysUserService;
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 gmk
 */
@Service("userDetailsByTelephoneServiceImpl")
public class UserDetailsByTelephoneServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsByTelephoneServiceImpl.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        SysUser user = userService.selectUserByPhonenumber(phone);
        if (StringUtils.isNull(user)) {
            log.info("登錄用戶:{} 不存在.", phone);
            throw new UsernameNotFoundException("登錄用戶:" + phone + " 不存在");
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登錄用戶:{} 已被刪除.", phone);
            throw new BaseException("對不起抹竹,您的賬號:" + phone + " 已被刪除");
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登錄用戶:{} 已被停用.", phone);
            throw new BaseException("對不起,您的賬號:" + phone + " 已停用");
        }

        return createLoginUser(user);
    }

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

四止潮、編寫SecurityConfig配置類

package com.zensun.framework.config;

import com.zensun.framework.security.filter.JwtAuthenticationTokenFilter;
import com.zensun.framework.security.handle.AuthenticationEntryPointImpl;
import com.zensun.framework.security.handle.LogoutSuccessHandlerImpl;
import com.zensun.framework.security.sms.SmsCodeAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.web.filter.CorsFilter;

/**
 * spring security配置
 *
 * @author gmk
 */
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 自定義用戶(賬號密碼)認(rèn)證邏輯
     */
    @Autowired
    @Qualifier("userDetailsServiceImpl")
    private UserDetailsService userDetailsService;

    /**
     * 自定義用戶(手機(jī)號驗證碼)認(rèn)證邏輯
     */
    @Autowired
    @Qualifier("userDetailsByTelephoneServiceImpl")
    private UserDetailsService userDetailsServiceByTelephone;

    /**
     * 認(rèn)證失敗處理類
     */
    @Autowired
    private AuthenticationEntryPointImpl unauthorizedHandler;

    /**
     * 退出處理類
     */
    @Autowired
    private LogoutSuccessHandlerImpl logoutSuccessHandler;

    /**
     * token認(rèn)證過濾器
     */
    @Autowired
    private JwtAuthenticationTokenFilter authenticationTokenFilter;

    /**
     * 跨域過濾器
     */
    @Autowired
    private CorsFilter corsFilter;


    /**
     * 解決 無法直接注入 AuthenticationManager
     *
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * anyRequest          |   匹配所有請求路徑
     * access              |   SpringEl表達(dá)式結(jié)果為true時可以訪問
     * anonymous           |   匿名可以訪問
     * denyAll             |   用戶不能訪問
     * fullyAuthenticated  |   用戶完全認(rèn)證可以訪問(非remember-me下自動登錄)
     * hasAnyAuthority     |   如果有參數(shù)窃判,參數(shù)表示權(quán)限,則其中任何一個權(quán)限可以訪問
     * hasAnyRole          |   如果有參數(shù)喇闸,參數(shù)表示角色袄琳,則其中任何一個角色可以訪問
     * hasAuthority        |   如果有參數(shù)询件,參數(shù)表示權(quán)限,則其權(quán)限可以訪問
     * hasIpAddress        |   如果有參數(shù)唆樊,參數(shù)表示IP地址宛琅,如果用戶IP和參數(shù)匹配,則可以訪問
     * hasRole             |   如果有參數(shù)逗旁,參數(shù)表示角色嘿辟,則其角色可以訪問
     * permitAll           |   用戶可以任意訪問
     * rememberMe          |   允許通過remember-me登錄的用戶訪問
     * authenticated       |   用戶登錄后可訪問
     */
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {


        SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();
        smsCodeAuthenticationProvider.setUserDetailsService(userDetailsServiceByTelephone);

        httpSecurity
                // CSRF禁用,因為不使用session
                .csrf().disable()
                // 認(rèn)證失敗處理類
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                // 基于token片效,所以不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                // 過濾請求
                .authorizeRequests()
                // 對于登錄login 驗證碼captchaImage 允許匿名訪問
                .antMatchers("/login", "/captchaImage", "/loginByTelephone", "/captchaTelephone").anonymous()
                .antMatchers(
                        HttpMethod.GET,
                        "/*.html",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js"
                ).permitAll()
                .antMatchers("/profile/**").anonymous()
                .antMatchers("/common/download**").anonymous()
                .antMatchers("/common/download/resource**").anonymous()
                .antMatchers("/swagger-ui.html").anonymous()
                .antMatchers("/swagger-resources/**").anonymous()
                .antMatchers("/webjars/**").anonymous()
                .antMatchers("/*/api-docs").anonymous()
                .antMatchers("/druid/**").anonymous()
                // 除上面外的所有請求全部需要鑒權(quán)認(rèn)證
                .anyRequest().authenticated()
                .and()
                .headers().frameOptions().disable();
        httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
        // 添加JWT filter
        httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        // 添加CORS filter
        httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class);
        httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class)
                //手機(jī)驗證碼的provider
                .authenticationProvider(smsCodeAuthenticationProvider);
    }


    /**
     * 強(qiáng)散列哈希加密實現(xiàn)
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }


    /**
     * 身份認(rèn)證接口
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }
}

五红伦、編寫手機(jī)號驗證碼登錄接口

1.控制層

 /**
     * 登錄方法
     *
     * @param loginBody 登錄信息
     * @return 結(jié)果
     */
    @PostMapping("/loginByTelephone")
    public AjaxResult loginByTelephone(@RequestBody LoginByTelephoneBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.loginByTelephone(loginBody.getTelephone(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

2.邏輯層

/**
     * 手機(jī)驗證碼登錄驗證
     *
     * @param telephone 手機(jī)號
     * @param code      驗證碼
     * @param uuid      唯一標(biāo)識
     * @return 結(jié)果
     */
    public String loginByTelephone(String telephone, String code, String uuid) {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);

      /*  if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(user.getUserName(), Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(user.getUserName(), Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }*/
        // 用戶驗證
        Authentication authentication = null;
        try {
            // 該方法會去調(diào)用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new SmsCodeAuthenticationToken(telephone));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(telephone, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(telephone, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(telephone, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市淀衣,隨后出現(xiàn)的幾起案子昙读,更是在濱河造成了極大的恐慌,老刑警劉巖膨桥,帶你破解...
    沈念sama閱讀 221,430評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蛮浑,死亡現(xiàn)場離奇詭異,居然都是意外死亡只嚣,警方通過查閱死者的電腦和手機(jī)沮稚,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,406評論 3 398
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來介牙,“玉大人壮虫,你說我怎么就攤上這事』反。” “怎么了囚似?”我有些...
    開封第一講書人閱讀 167,834評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長线得。 經(jīng)常有香客問我饶唤,道長,這世上最難降的妖魔是什么贯钩? 我笑而不...
    開封第一講書人閱讀 59,543評論 1 296
  • 正文 為了忘掉前任募狂,我火速辦了婚禮,結(jié)果婚禮上角雷,老公的妹妹穿的比我還像新娘祸穷。我一直安慰自己,他們只是感情好勺三,可當(dāng)我...
    茶點故事閱讀 68,547評論 6 397
  • 文/花漫 我一把揭開白布雷滚。 她就那樣靜靜地躺著,像睡著了一般吗坚。 火紅的嫁衣襯著肌膚如雪祈远。 梳的紋絲不亂的頭發(fā)上呆万,一...
    開封第一講書人閱讀 52,196評論 1 308
  • 那天,我揣著相機(jī)與錄音车份,去河邊找鬼谋减。 笑死,一個胖子當(dāng)著我的面吹牛扫沼,可吹牛的內(nèi)容都是我干的出爹。 我是一名探鬼主播,決...
    沈念sama閱讀 40,776評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼缎除,長吁一口氣:“原來是場噩夢啊……” “哼以政!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起伴找,我...
    開封第一講書人閱讀 39,671評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎废菱,沒想到半個月后技矮,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,221評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡殊轴,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,303評論 3 340
  • 正文 我和宋清朗相戀三年衰倦,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片旁理。...
    茶點故事閱讀 40,444評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡樊零,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出孽文,到底是詐尸還是另有隱情驻襟,我是刑警寧澤,帶...
    沈念sama閱讀 36,134評論 5 350
  • 正文 年R本政府宣布芋哭,位于F島的核電站沉衣,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏减牺。R本人自食惡果不足惜豌习,卻給世界環(huán)境...
    茶點故事閱讀 41,810評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望拔疚。 院中可真熱鬧肥隆,春花似錦、人聲如沸稚失。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,285評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽墩虹。三九已至嘱巾,卻和暖如春憨琳,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背旬昭。 一陣腳步聲響...
    開封第一講書人閱讀 33,399評論 1 272
  • 我被黑心中介騙來泰國打工篙螟, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人问拘。 一個月前我還...
    沈念sama閱讀 48,837評論 3 376
  • 正文 我出身青樓遍略,卻偏偏與公主長得像,于是被迫代替她去往敵國和親骤坐。 傳聞我的和親對象是個殘疾皇子绪杏,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,455評論 2 359

推薦閱讀更多精彩內(nèi)容