JWT全称JSON Web Token,实现过程简单的说就是用户登录成功之后,将用户的信息进行加密,然后生成一个token返回给客户端,与传统的session交互没太大区别。
区别就是token存放了用户的基本信息,更直观一点就是将原本放入redis中的用户数据,放入到token中去了。
1、导入依赖2、生成tokenio.jsonwebtoken jjwt0.9.0
public static String getBearerToken(String userId, Integer expireSecond) {
Date date = new Date(System.currentTimeMillis() + expireSecond * 1000);
//json web token构建
return Jwts.builder()
//此处的subject可以用一个用户名,也可以是多个信息的组合,根据需要来定
.setSubject(userId)
//设置token过期时间,24小時
.setExpiration(date)
//设置token签名、密钥
.signWith(SignatureAlgorithm.HS512, jwtKey)
.compact();
}
3、解析token
public static String parseBearerToken(String token) {
token = token.replace("Bearer ", "");
return Jwts.parser()
//签名、密钥
.setSigningKey(jwtKey)
.parseClaimsJws(token)
.getBody()
.getSubject();
}
4、监听网络请求
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService myCustomUserService;
@Autowired
private MyPasswordEncoder myPasswordEncoder;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
//关闭跨站请求防护
.cors().and().csrf().disable()
//允许不登陆就可以访问的方法,多个用逗号分隔
.authorizeRequests().antMatchers("/api/user/login","/api/test/test").permitAll()
//其他的需要授权后访问
.anyRequest().authenticated()
.and()
//增加登录拦截
.addFilter(new JWTLoginFilter(authenticationManager()))
//增加是否登陸过滤
.addFilter(new JWTAuthenticationFilter(authenticationManager()))
// 前后端分离是无状态的,所以暫時不用session,將登陆信息保存在token中。
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
//覆盖UserDetailsService类
auth.userDetailsService(myCustomUserService)
//覆盖默认的密码验证类
.passwordEncoder(myPasswordEncoder);
}
}
5、验证是否登录
@Slf4j
public class JWTAuthenticationFilter extends BasicAuthenticationFilter {
public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
super(authenticationManager);
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) {
try {
log.info("doFilterInternal"+request.getRequestURI());
//请求体的头中是否包含Authorization
String header = request.getHeader("Authorization");
//Authorization中是否包含Bearer,有一个不包含时直接返回
if (header == null || !header.startsWith("Bearer ")) {
chain.doFilter(request, response);
responseJson(response);
return;
}
//获取权限失败,会抛出异常
UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
//获取后,将Authentication写入SecurityContextHolder中供后序使用
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(request, response);
} catch (Exception e) {
log.info("doFilterInternal"+e.toString());
responseJson(response);
e.printStackTrace();
}
}
private void responseJson(HttpServletResponse response){
try {
//未登录时,使用json進行提示
response.setContentType("application/json;charset=utf-8");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
PrintWriter out = response.getWriter();
Map map = new HashMap();
map.put("code", HttpServletResponse.SC_FORBIDDEN);
map.put("message","请登录!");
out.write(new ObjectMapper().writeValueAsString(map));
out.flush();
out.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
String token = request.getHeader("Authorization");
if (token != null) {
//通过token解析出用户信息
String user = JwtUtil.parseBearerToken(token);
//不为null,返回
if (user != null) {
return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
}
return null;
}
return null;
}
}
6、登录拦截
@Slf4j
public class JWTLoginFilter extends UsernamePasswordAuthenticationFilter {
private AuthenticationManager authenticationManager;
public JWTLoginFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res){
try {
User user = new ObjectMapper().readValue(req.getInputStream(), User.class);
return authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
user.getUserName(),
user.getPassword(),
new ArrayList<>())
);
} catch (Exception e) {
try {
//未登录提示账号密码错误
res.setContentType("application/json;charset=utf-8");
res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
PrintWriter out = res.getWriter();
Map map = new HashMap();
map.put("code",HttpServletResponse.SC_UNAUTHORIZED);
map.put("message","账号或密码错误!");
out.write(new ObjectMapper().writeValueAsString(map));
out.flush();
out.close();
} catch (Exception e1) {
e1.printStackTrace();
}
throw new RuntimeException(e);
}
}
@Override
protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain, Authentication auth){
String userName = ((UserDetails) auth.getPrincipal()).getUsername();
String token = JwtUtil.getBearerToken(userName, 60*60*3600);
//返回token
res.addHeader("Authorization", "Bearer " + token);
try {
//登录成功時,返回json格式进行提示
res.setContentType("application/json;charset=utf-8");
res.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = res.getWriter();
Map map = new HashMap();
map.put("code",HttpServletResponse.SC_OK);
map.put("message","登陆成功!");
map.put("token","Bearer " + token);
out.write(new ObjectMapper().writeValueAsString(map));
out.flush();
out.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
7、自定义用户验证
@Component
@Slf4j
public class MyCustomUserService implements UserDetailsService {
@Autowired
private UserService userService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userService.getUserByName(username);
if (user == null) {
log.error("user not found {}", username);
}
return new org.springframework.security.core.userdetails.User(user.getUserName(), user.getPassword(), emptyList());
}
}
public interface UserDetailsService {
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
}
8、自定义密码验证
@Component
public class MyPasswordEncoder implements PasswordEncoder {
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
@Override
public boolean matches(CharSequence charSequence, String s) {
return bCryptPasswordEncoder.matches(encode(charSequence), s);
}
}



