上週寫了一個 適合初學者入門 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);
}
}複製代碼
若是你們想要實時關注我更新的文章以及分享的乾貨的話,能夠關注個人公衆號。