1、引入SpringSecurity依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2、编写配置类
package com.yoohoo.framework.config;
import com.yoohoo.framework.security.filter.JwtAuthenticationTokenFilter;
import com.yoohoo.framework.security.handle.AuthenticationEntryPointImpl;
import com.yoohoo.framework.security.handle.LogoutSuccessHandlerImpl;
import com.yoohoo.framework.security.service.UserDetailsServiceImpl;
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.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.web.filter.CorsFilter;
import javax.annotation.Resource;
/**
* spring security 配置
*/
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//过滤器配置
@Autowired
private CorsFilter corsFilter;
//认证入口
@Autowired
private AuthenticationEntryPointImpl authenticationEntryPoint;
/*退出处理*/
@Autowired
private LogoutSuccessHandlerImpl logoutSuccessHandler;
//token认证处理
@Autowired
private JwtAuthenticationTokenFilter authenticationTokenFilter;
//自定义用户验证
@Autowired
private UserDetailsServiceImpl userDetailsService;
/**
*注入 AuthenticationManage
* @return
* @throws Exception
*/
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception
{
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
/*使用token认证 不使用session 禁用CSRF*/
http.csrf().disable()
/*认证异常处理*/
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).and()
/*不会创建HttpSession*/
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
/*请求白名单*/
.authorizeRequests().antMatchers("/login","/captchaImage").permitAll()
.antMatchers(
HttpMethod.GET,
"/",
"/*.html",
"/**/*.html",
"/**/*.css",
"/**/*.js",
"/profile/**"
).permitAll()
.antMatchers("/swagger-ui/**").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();
/*退出成功处理*/
http.logout().logoutSuccessUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
/* 认证之前检验token */
http.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
http.addFilterBefore(corsFilter,JwtAuthenticationTokenFilter.class);
http.addFilterBefore(corsFilter, LogoutFilter.class);
}
/**
* 强散列哈希加密
* @return
*/
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder()
{
/*自定义密码匹配规则*/
return new CustomPasswordEncoder();
// return new BCryptPasswordEncoder(); //强散列哈希
}
/**
* 自定义用户验证
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
/*自定义验证 两种方式都可*/
// auth.authenticationProvider(myAuthenticationProvider); myAuthenticationProvider 需要实现 AuthenticationProvider
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
class CustomPasswordEncoder extends BCryptPasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence rawPassword) {
//自定义逻辑
return rawPassword.toString();
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
//自定义逻辑
return true;
}
}
}
4、UserDetailsServiceImpl 类
package com.yoohoo.framework.security.service;
import com.yoohoo.common.utils.Constants;
import com.yoohoo.system.base.domain.ServiceException;
import com.yoohoo.system.modules.system.domain.SysUser;
import com.yoohoo.system.modules.system.domain.vo.LoginUser;
import com.yoohoo.system.modules.system.service.impl.SysUserServiceImpl;
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;
/**
* 用户验证处理
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
@Autowired
private SysUserServiceImpl sysUserService;
// @Autowired
// private PermissionService permissionService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
/*authenticate 执行认证时 会进入此方法 携带 username */
SysUser user = sysUserService.selectUserByUserName(username);
//数据库验证user
return createLoginUser(user);
}
private UserDetails createLoginUser(SysUser user) {
return new LoginUser(user.getUserId(), user.getDeptId(), user, null);
}
5、
public String login(String username, String password, String code, String uuid) {
/*密码匹配验证*/
Authentication authenticate = null;
try{
//此步会进入 UserDetailsServiceImpl 重写
authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
}catch (Exception e){
/*处理验证不通过的异常信息 并抛出*/
}
LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
return tokenService.createToken(loginUser);
}