上周写了一个 适合初学者入门 Spring Security With JWT 的 Demo,这篇文章主要是对代码中涉及到的比较重要的知识点的说明。前端
适合初学者入门 Spring Security With JWT 的 Demo 这篇文章中说到了要在十一假期期间对代码进行讲解说明,可是,大家懂得,到了十一就一拖再拖,眼看着今天就是十一的尾声了,抽了一下午完成了这部份内容。git
明天就要上班了,擦擦眼泪,仍是一条好汉!扶我起来,学不动了。github
若是 对 JWT 不了解的话,能够看前几天发的这篇原创文章:《一问带你区分清楚Authentication,Authorization以及Cookie、Session、Token》。spring
Demo 地址:https://github.com/Snailclimb/spring-security-jwt-guide 。数据库
这个是 UserControler
主要用来验证权限配置是否生效。api
getAllUser()
方法被注解@PreAuthorize("hasAnyRole('ROLE_DEV','ROLE_PM')")
修饰表明这个方法能够被 DEV,PM 这两个角色访问,而deleteUserById()
被注解@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
修饰表明只能被 ADMIN 访问。跨域
/**
* @author shuang.kou
*/
@RestController
@RequestMapping("/api")
public class UserController {
private final UserService userService;
private final CurrentUser currentUser;
public UserController(UserService userService, CurrentUser currentUser) {
this.userService = userService;
this.currentUser = currentUser;
}
@GetMapping("/users")
@PreAuthorize("hasAnyRole('ROLE_DEV','ROLE_PM')")
public ResponseEntity<Page<User>> getAllUser(@RequestParam(value = "pageNum", defaultValue = "0") int pageNum, @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
System.out.println("当前访问该接口的用户为:" + currentUser.getCurrentUser().toString());
Page<User> allUser = userService.getAllUser(pageNum, pageSize);
return ResponseEntity.ok().body(allUser);
}
@DeleteMapping("/user")
@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
public ResponseEntity<User> deleteUserById(@RequestParam("username") String username) {
userService.deleteUserByUserName(username);
return ResponseEntity.ok().build();
}
}复制代码
里面主要有一些经常使用的方法好比 生成 token 以及解析 token 获取相关信息等等方法。安全
/**
* @author shuang.kou
*/
public class JwtTokenUtils {
/**
* 生成足够的安全随机密钥,以适合符合规范的签名
*/
private static byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SecurityConstants.JWT_SECRET_KEY);
private static SecretKey secretKey = Keys.hmacShaKeyFor(apiKeySecretBytes);
public static String createToken(String username, List<String> roles, boolean isRememberMe) {
long expiration = isRememberMe ? SecurityConstants.EXPIRATION_REMEMBER : SecurityConstants.EXPIRATION;
String tokenPrefix = Jwts.builder()
.setHeaderParam("typ", SecurityConstants.TOKEN_TYPE)
.signWith(secretKey, SignatureAlgorithm.HS256)
.claim(SecurityConstants.ROLE_CLAIMS, String.join(",", roles))
.setIssuer("SnailClimb")
.setIssuedAt(new Date())
.setSubject(username)
.setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
.compact();
return SecurityConstants.TOKEN_PREFIX + tokenPrefix;
}
private boolean isTokenExpired(String token) {
Date expiredDate = getTokenBody(token).getExpiration();
return expiredDate.before(new Date());
}
public static String getUsernameByToken(String token) {
return getTokenBody(token).getSubject();
}
/**
* 获取用户全部角色
*/
public static List<SimpleGrantedAuthority> getUserRolesByToken(String token) {
String role = (String) getTokenBody(token)
.get(SecurityConstants.ROLE_CLAIMS);
return Arrays.stream(role.split(","))
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
}
private static Claims getTokenBody(String token) {
return Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(token)
.getBody();
}
}复制代码
先来看一下比较重要的两个过滤器。服务器
第一个过滤器主要用于根据用户的用户名和密码进行登陆验证(用户请求中必须有用户名和密码这两个参数),它继承了 UsernamePasswordAuthenticationFilter
而且重写了下面三个方法:session
attemptAuthentication()
: 验证用户身份。 successfulAuthentication()
: 用户身份验证成功后调用的方法。 unsuccessfulAuthentication()
: 用户身份验证失败后调用的方法。 /**
* @author shuang.kou
* 若是用户名和密码正确,那么过滤器将建立一个JWT Token 并在HTTP Response 的header中返回它,格式:token: "Bearer +具体token值"
*/
public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private ThreadLocal<Boolean> rememberMe = new ThreadLocal<>();
private AuthenticationManager authenticationManager;
public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
// 设置登陆请求的 URL
super.setFilterProcessesUrl(SecurityConstants.AUTH_LOGIN_URL);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
ObjectMapper objectMapper = new ObjectMapper();
try {
// 从输入流中获取到登陆的信息
LoginUser loginUser = objectMapper.readValue(request.getInputStream(), LoginUser.class);
rememberMe.set(loginUser.getRememberMe());
// 这部分和attemptAuthentication方法中的源码是同样的,
// 只不过因为这个方法源码的是把用户名和密码这些参数的名字是死的,因此咱们重写了一下
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
loginUser.getUsername(), loginUser.getPassword());
return authenticationManager.authenticate(authRequest);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 若是验证成功,就生成token并返回
*/
@Override
protected void successfulAuthentication(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain,
Authentication authentication) {
JwtUser jwtUser = (JwtUser) authentication.getPrincipal();
List<String> roles = jwtUser.getAuthorities()
.stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.toList());
// 建立 Token
String token = JwtTokenUtils.createToken(jwtUser.getUsername(), roles, rememberMe.get());
// Http Response Header 中返回 Token
response.setHeader(SecurityConstants.TOKEN_HEADER, token);
}
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage());
}
}复制代码
这个过滤器继承了 BasicAuthenticationFilter
,主要用于处理身份认证后才能访问的资源,它会检查 HTTP 请求是否存在带有正确令牌的 Authorization 标头并验证 token 的有效性。
/**
* 过滤器处理全部HTTP请求,并检查是否存在带有正确令牌的Authorization标头。例如,若是令牌未过时或签名密钥正确。
*
* @author shuang.kou
*/
public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
private static final Logger logger = Logger.getLogger(JWTAuthorizationFilter.class.getName());
public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
super(authenticationManager);
}
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain) throws IOException, ServletException {
String authorization = request.getHeader(SecurityConstants.TOKEN_HEADER);
// 若是请求头中没有Authorization信息则直接放行了
if (authorization == null || !authorization.startsWith(SecurityConstants.TOKEN_PREFIX)) {
chain.doFilter(request, response);
return;
}
// 若是请求头中有token,则进行解析,而且设置受权信息
SecurityContextHolder.getContext().setAuthentication(getAuthentication(authorization));
super.doFilterInternal(request, response, chain);
}
/**
* 这里从token中获取用户信息并新建一个token
*/
private UsernamePasswordAuthenticationToken getAuthentication(String authorization) {
String token = authorization.replace(SecurityConstants.TOKEN_PREFIX, "");
try {
String username = JwtTokenUtils.getUsernameByToken(token);
// 经过 token 获取用户具备的角色
List<SimpleGrantedAuthority> userRolesByToken = JwtTokenUtils.getUserRolesByToken(token);
if (!StringUtils.isEmpty(username)) {
return new UsernamePasswordAuthenticationToken(username, null, userRolesByToken);
}
} catch (SignatureException | ExpiredJwtException exception) {
logger.warning("Request to parse JWT with invalid signature . Detail : " + exception.getMessage());
}
return null;
}
}复制代码
当用户使用 token 对须要权限才能访问的资源进行访问的时候,这个类是主要用到的,下面按照步骤来讲一说每一步到底都作了什么。
doFilterInternal()
方法,这个方法会从请求的 Header 中取出 token 信息,而后判断 token 信息是否为空以及 token 信息格式是否正确。 SecurityContextHolder.getContext().setAuthentication(getAuthentication(authorization));
咱们在讲过滤器的时候说过,当认证成功的用户访问系统的时候,它的认证信息会被设置在 Spring Security 全局中。那么,既然这样,咱们在其余地方获取到当前登陆用户的受权信息也就很简单了,经过SecurityContextHolder.getContext().getAuthentication();
方法便可。为此,咱们实现了一个专门用来获取当前用户的类:
/**
* @author shuang.kou
* 获取当前请求的用户
*/
@Component
public class CurrentUser {
private final UserDetailsServiceImpl userDetailsService;
public CurrentUser(UserDetailsServiceImpl userDetailsService) {
this.userDetailsService = userDetailsService;
}
public JwtUser getCurrentUser() {
return (JwtUser) userDetailsService.loadUserByUsername(getCurrentUserName());
}
/**
* TODO:因为在JWTAuthorizationFilter这个类注入UserDetailsServiceImpl一致失败,
* 致使没法正确查找到用户,因此存入Authentication的Principal为从 token 中取出的当前用户的姓名
*/
private static String getCurrentUserName() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() != null) {
return (String) authentication.getPrincipal();
}
return null;
}
}复制代码
JWTAccessDeniedHandler
实现了AccessDeniedHandler
主要用来解决认证过的用户访问须要权限才能访问的资源时的异常。
/**
* @author shuang.kou
* AccessDeineHandler 用来解决认证过的用户访问须要权限才能访问的资源时的异常
*/
public class JWTAccessDeniedHandler implements AccessDeniedHandler {
/**
* 当用户尝试访问须要权限才能的REST资源而权限不足的时候,
* 将调用此方法发送401响应以及错误信息
*/
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
accessDeniedException = new AccessDeniedException("Sorry you don not enough permissions to access it!");
response.sendError(HttpServletResponse.SC_FORBIDDEN, accessDeniedException.getMessage());
}
}
复制代码
JWTAuthenticationEntryPoint
实现了 AuthenticationEntryPoint
用来解决匿名用户访问须要权限才能访问的资源时的异常
/**
* @author shuang.kou
* AuthenticationEntryPoint 用来解决匿名用户访问须要权限才能访问的资源时的异常
*/
public class JWTAuthenticationEntryPoint implements AuthenticationEntryPoint {
/**
* 当用户尝试访问须要权限才能的REST资源而不提供Token或者Token过时时,
* 将调用此方法发送401响应以及错误信息
*/
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());
}
}复制代码
在 SecurityConfig 配置类中咱们主要配置了:
BCryptPasswordEncoder
(存入数据库的密码须要被加密)。 AuthenticationManager
设置自定义的 UserDetailsService
以及密码编码器; @EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsServiceImpl userDetailsServiceImpl;
/**
* 密码编码器
*/
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public UserDetailsService createUserDetailsService() {
return userDetailsServiceImpl;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 设置自定义的userDetailsService以及密码编码器
auth.userDetailsService(userDetailsServiceImpl).passwordEncoder(bCryptPasswordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()
// 禁用 CSRF
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/auth/login").permitAll()
// 指定路径下的资源须要验证了的用户才能访问
.antMatchers("/api/**").authenticated()
.antMatchers(HttpMethod.DELETE, "/api/**").hasRole("ADMIN")
// 其余都放行了
.anyRequest().permitAll()
.and()
//添加自定义Filter
.addFilter(new JWTAuthenticationFilter(authenticationManager()))
.addFilter(new JWTAuthorizationFilter(authenticationManager()))
// 不须要session(不建立会话)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
// 受权异常处理
.exceptionHandling().authenticationEntryPoint(new JWTAuthenticationEntryPoint())
.accessDeniedHandler(new JWTAccessDeniedHandler());
}
}
复制代码
跨域:
在这里踩的一个坑是:若是你没有设置exposedHeaders("Authorization")
暴露 header 中的"Authorization"属性给客户端应用程序的话,前端是获取不到 token 信息的。
@Configuration
public class CorsConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
//暴露header中的其余属性给客户端应用程序
//若是不设置这个属性前端没法经过response header获取到Authorization也就是token
.exposedHeaders("Authorization")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT")
.maxAge(3600);
}
}复制代码
若是你们想要实时关注我更新的文章以及分享的干货的话,能够关注个人公众号。