一庸汗、編寫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);
}