Springboot版本2.3.3
org.springframework.boot
spring-boot-starter-security
io.jsonwebtoken
jjwt
0.9.1
javax.xml.bind
jaxb-api
2.3.1
/**
* Security配置类,启用URL过滤,设置PasswordEncoder密码加密类
* EnableWebSecurity 开启Security
* EnableGlobalMethodSecurity 保证post之前的注解可以使用
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class Config_Security extends WebSecurityConfigurerAdapter {
@Resource
private IUmsMemberService memberService;
@Resource
private SecurityAccessDeniedHandler restfulAccessDeniedHandler;
@Resource
private SecurityAuthenticationEntryPoint restAuthenticationEntryPoint;
/**
* anyRequest | 匹配所有请求路径
* access | SpringEl表达式结果为true时可以访问
* anonymous | 匿名可以访问
* denyAll | 用户不能访问
* fullyAuthenticated | 用户完全认证可以访问(非remember-me下自动登录)
* hasAnyAuthority | 如果有参数,参数表示权限,则其中任何一个权限可以访问
* hasAnyRole | 如果有参数,参数表示角色,则其中任何一个角色可以访问
* hasAuthority | 如果有参数,参数表示权限,则其权限可以访问
* hasIpAddress | 如果有参数,参数表示IP地址,如果用户IP和参数匹配,则可以访问
* hasRole | 如果有参数,参数表示角色,则其角色可以访问
* permitAll | 用户可以任意访问
* rememberMe | 允许通过remember-me登录的用户访问
* authenticated | 用户登录后可访问
*/
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf() //由于使用的是JWT,我们这里不需要csrf
.disable()
.sessionManagement() //基于token,所以不需要session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, //允许对于网站静态资源的无授权访问
"/",
"/*.html",
"/favicon.ico",
"/**/*.html",
"/**/*.css",
"/**/*.js",
"/swagger.**",
"/v3.**",
"**_notify_url"
).permitAll()
.antMatchers("/LoginSecurity", "/Register").permitAll() //对登录注册要允许匿名访问
.antMatchers(HttpMethod.OPTIONS).permitAll() //跨域请求会先进行一次options请求
// .antMatchers("/**").permitAll() //测试时全部运行访问
.anyRequest() //除上面外的所有请求全部需要鉴权认证
.authenticated();
//禁用缓存
httpSecurity.headers().cacheControl();
//添加JWTFilter
httpSecurity.addFilterBefore(jwtFilter(), UsernamePasswordAuthenticationFilter.class);
//添加自定义未授权和未登录结果返回
httpSecurity.exceptionHandling()
.accessDeniedHandler(restfulAccessDeniedHandler)
.authenticationEntryPoint(restAuthenticationEntryPoint);
}
/**
* 重写身份认证接口configure
* 其中userDetailsService为自定义用户认证逻辑接口
* 其中bCryptPasswordEncoder()为加密接口
* 使用authenticationManager.authenticate用户验证的时候,该方法会调用我们接口逻辑接口的实现类UserDetailsServiceImpl.loadUserByUsername
* 就是下面的userDetailsService方法
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
}
/**
* 认证过程中SpringSecurity会调用这个方法访问数据库进行对用户的搜索,逻辑什么都可以自定义,无论是从数据库中还是从缓存中
* 我们需要将我们查询出来的用户信息和权限信息组装成一个UserDetails返回。
* UserDetails也是一个定义了数据形式的接口,用于保存我们从数据库中查出来的数据,其功能主要是验证账号状态和获取权限
*/
@Bean
public UserDetailsService userDetailsService() {
return username -> {
//获取登录用户信息
UmsMember u = memberService.GetByNameMember(username);
if (u == null) {
throw new UsernameNotFoundException("用户名或密码错误");
}
return new SecurityUserDetails(username,u.getPassword(),null);
};
}
/**
* 自定义加密器Bean
* 强散列哈希加密实现,在Controller新增用户的时候用此bean生成密码,与及修改密码的时候用到此bean比较新旧密码是否匹配
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* JWT过滤器
*/
@Bean
public SecurityJwtFilter jwtFilter() {
return new SecurityJwtFilter();
}
/**
* 定义AuthenticationManager
* 声明它的作用是用它帮我们进行认证操作,调用这个Bean的authenticate方法会由Spring Security自动帮我们做认证
*/
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
/**
* 权限不足处理器
*/
@Component
public class SecurityAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
ResponseCon> responseCon = new ResponseCon<>(401, "没有权限", e.getMessage());
response.getWriter().println(GsonUtil.getGson().toJson(responseCon));
response.getWriter().flush();
}
}
/**
* 认证失败处理器
*/
@Component
public class SecurityAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
ResponseCon> responseCon = new ResponseCon<>(401,"身份认证失败", authException.getMessage());
response.getWriter().println(GsonUtil.getGson().toJson(responseCon));
response.getWriter().flush();
}
}
/**
* JwtFilter过滤器
*/
@Slf4j
public class SecurityJwtFilter extends OncePerRequestFilter {
@Resource
private UserDetailsService userDetailsService;
@Resource
private SecurityJwtUtil securityJwtUtil;
private final String Authorization = "Authorization";
private final String tokenHead = "Bearer";
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
//拿到Authorization请求头内的Header信息
String authHeader = request.getHeader(Authorization);
//判断一下内容是否为空且是否为(Bearer)开头
if (authHeader != null && authHeader.startsWith(tokenHead)) {
//去掉token前缀(Bearer),拿到真实token
String authToken = authHeader.substring(tokenHead.length());
//拿到token里面的username
String username = securityJwtUtil.getUsername(authToken);
//然后看看上下文中是否有我们以这个username为标识的主体,没有去new一个
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
//缓存里查询用户,不存在需要重新登陆
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
//拿到用户信息后验证用户信息与token
if (securityJwtUtil.validateToken(authToken, userDetails)) {
//组装authentication对象,构造参数是Principal Credentials与Authorities
//后面的拦截器里面会用到grantedAuthorities 方法
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
//将authentication信息放入到上下文对象中, 这样后面的过滤器看到我们上下文对象中有authentication对象,就相当于我们认证过了
SecurityContextHolder.getContext().setAuthentication(authentication);
log.info("校验token-登录成功, user: {}", username);
}
}
}
chain.doFilter(request, response);
}
}
/**
* jwtToken工具类
*/
@Slf4j
@Component
public class SecurityJwtUtil {
//一天过期
private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;
//解密jwt-token的密钥
private static final String secret = "mySecret";
/**
* 生成token
*/
public static String sign(String username, String loginType) {
return Jwts.builder()
.claim("username", username)
.claim("loginType", loginType)
.setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME))
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
/**
* 根据token解密出用户名
*/
public String getUsername(String token) {
try {
Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
return (String) claims.get("username");
} catch (Exception e) {
log.info("JWT格式验证失败:{}", token);
}
return null;
}
/**
* 根据token解密出登录类型
*/
public String getLoginType(String token) {
try {
Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
return (String) claims.get("loginType");
} catch (Exception e) {
log.info("JWT格式验证失败:{}", token);
}
return null;
}
/**
* 根据token解密出过期时间
*/
public Date getExpiredDate(String token) {
try {
Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
return claims.getExpiration();
} catch (Exception e) {
log.info("JWT格式验证失败:{}", token);
}
return null;
}
/**
* 判断token是否已经过期
*/
public boolean isTokenExpired(String token) {
Date expiredDate = getExpiredDate(token);
return expiredDate.before(new Date());
}
/**
* 判断token是否可以被刷新
*/
public boolean canRefresh(String token) {
return !isTokenExpired(token);
}
/**
* 验证token与数据库中token是否一致
*/
public boolean validateToken(String token, UserDetails userDetails) {
String username = getUsername(token);
assert username != null;
return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
}
/**
* SpringSecurity包装的用户信息
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SecurityUserDetails extends UmsMember implements UserDetails {
private Collection extends GrantedAuthority> authorities;
//返回当前用户的权限
@Override
public Collection extends GrantedAuthority> getAuthorities() {
return authorities;
}
public SecurityUserDetails(String userName, String password, Collection extends GrantedAuthority> authorities){
this.authorities = authorities;
this.setUsername(userName);
this.setPassword(new BCryptPasswordEncoder().encode(password));
this.setAuthorities(authorities);
}
/**
* 账户是否过期
*/
@Override
public boolean isAccountNonExpired() {
return false;
}
/**
* 是否禁用
*/
@Override
public boolean isAccountNonLocked() {
return false;
}
/**
* 密码是否过期
*/
@Override
public boolean isCredentialsNonExpired() {
return false;
}
/**
* 是否启用
*/
@Override
public boolean isEnabled() {
return true;
}
}
一共6个类
@Resource
private BCryptPasswordEncoder passwordEncoder;
//登录:http://localhost:8080/LoginSecurity
@RequestMapping(value = "/LoginSecurity", method = RequestMethod.POST)
public ResponseCon> LoginSecurity(String username, String password) {
UmsMember member = memberService.GetByNameMember(username);
log.info("进入controller-member信息: {}", member);
if (member != null) {
if(passwordEncoder.matches(password,member.getPassword())){
log.info("用户名正确, 密码正确");
member.setToken(SecurityJwtUtil.sign(username, "user"));
...
return new ResponseCon<>(200, "success", member);
} else {
log.info("用户名正确, 密码错误");
}
}
return new ResponseCon<>(401, "error", "用户名或密码错误");
}
//注册:http://localhost:8080/Register
@RequestMapping(value = "/Register", method = RequestMethod.POST)
public boolean Register_OK(String username, String password, String phone) {
password = passwordEncoder.encode(password);
UmsMember mb = new UmsMember();
mb.setPhone(phone);
mb.setUsername(username);
mb.setPassword(password);
...
return true;
}
//测试:http://localhost:8080/TestTokenSecurity
@RequestMapping(value = "/TestTokenSecurity", method = RequestMethod.POST)
public ResponseCon> TestTokenSecurity() {
return new ResponseCon<>(200, "success", "测试成功!");
}
第一次登录直接进controller验证用户名和密码,返回token
下次请求头都带上token,就会被security拦截去校验…
(不明白为啥非要加Bearer)
这篇写的很详细想深究去看看
https://blog.csdn.net/he_erduo/article/details/107178856