自定义登录扩展类
- 继承DaoAuthenticationProvider类型,重写additionalAuthenticationChecks方法
- CustomLoginAuthenticationProvider.java
package com.qcn.framework.config;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
public class CustomLoginAuthenticationProvider extends DaoAuthenticationProvider {
public CustomLoginAuthenticationProvider(UserDetailsService userDetailsService) {
super();
setUserDetailsService(userDetailsService);
}
protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
if (authentication.getCredentials() == null) {
this.logger.debug("Authentication failed: no credentials provided");
throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
} else {
String presentedPassword = authentication.getCredentials().toString();
if("CUSTOM_LOGIN_SMS".equals(presentedPassword)){
}else{
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
this.logger.debug("Authentication failed: password does not match stored value");
throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
}
}
}
}
}
修改spring security配置
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200811183233278.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2dpdGh1Yl8zOTY5ODMwMw==,size_16,color_FFFFFF,t_70)
package com.qcn.framework.config;
import org.springframework.beans.factory.annotation.Autowired;
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;
import com.qcn.framework.security.filter.JwtAuthenticationTokenFilter;
import com.qcn.framework.security.handle.AuthenticationEntryPointImpl;
import com.qcn.framework.security.handle.LogoutSuccessHandlerImpl;
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private AuthenticationEntryPointImpl unauthorizedHandler;
@Autowired
private LogoutSuccessHandlerImpl logoutSuccessHandler;
@Autowired
private JwtAuthenticationTokenFilter authenticationTokenFilter;
@Autowired
private CorsFilter corsFilter;
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception
{
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception
{
httpSecurity
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers("/login", "/captchaImage","/api/anonymous/**").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()
.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);
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder()
{
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(new CustomLoginAuthenticationProvider(userDetailsService));
auth.userDetailsService(userDetailsService)
.passwordEncoder(bCryptPasswordEncoder());
}
}
controller
@ApiOperation("手机号+密码登录")
@Log(title = "手机号+密码登录", businessType = BusinessType.OTHER)
@PostMapping(value="/loginByMobile")
public AjaxResult loginByMobile(@Validated @RequestBody LoginByPwdBody body)
{
CardUser entity=cardUserService.loginByMobileAndPwd(body.getMobile(),body.getPassword());
String token=cardLoginService.login(body.getMobile(),body.getPassword());
AjaxResult result = AjaxResult.success("登录成功!",entity);
result.put(Constants.TOKEN, token);
return result;
}
@ApiOperation("手机号+短信验证码登录")
@Log(title = "手机号+短信验证码登录", businessType = BusinessType.OTHER)
@PostMapping(value="/loginByCode")
public AjaxResult loginByCode(@Validated @RequestBody LoginByCodeBody body)
{
CardUser entity=cardUserService.loginByMobileAndCode(body);
String token=cardLoginService.login(body.getMobile(),"CUSTOM_LOGIN_SMS");
AjaxResult result = AjaxResult.success("登录成功!",entity);
result.put(Constants.TOKEN, token);
smsService.deleteSmsRedis(body.getSource());
return result;
}