|
| 1 | +package com.webank.cmdb.authclient.filter; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.util.ArrayList; |
| 5 | + |
| 6 | +import javax.servlet.FilterChain; |
| 7 | +import javax.servlet.ServletException; |
| 8 | +import javax.servlet.http.HttpServletRequest; |
| 9 | +import javax.servlet.http.HttpServletResponse; |
| 10 | + |
| 11 | +import org.apache.commons.lang3.StringUtils; |
| 12 | +import org.slf4j.Logger; |
| 13 | +import org.slf4j.LoggerFactory; |
| 14 | +import org.springframework.security.access.AccessDeniedException; |
| 15 | +import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; |
| 16 | +import org.springframework.security.authentication.AuthenticationManager; |
| 17 | +import org.springframework.security.authentication.BadCredentialsException; |
| 18 | +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; |
| 19 | +import org.springframework.security.core.AuthenticationException; |
| 20 | +import org.springframework.security.core.GrantedAuthority; |
| 21 | +import org.springframework.security.core.authority.SimpleGrantedAuthority; |
| 22 | +import org.springframework.security.core.context.SecurityContextHolder; |
| 23 | +import org.springframework.security.web.AuthenticationEntryPoint; |
| 24 | +import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; |
| 25 | + |
| 26 | + |
| 27 | +import io.jsonwebtoken.Claims; |
| 28 | +import io.jsonwebtoken.ExpiredJwtException; |
| 29 | +import io.jsonwebtoken.Jws; |
| 30 | +import io.jsonwebtoken.JwtException; |
| 31 | + |
| 32 | +public class JwtSsoBasedAuthenticationFilter extends BasicAuthenticationFilter { |
| 33 | + private static final Logger log = LoggerFactory.getLogger(JwtSsoBasedAuthenticationFilter.class); |
| 34 | + |
| 35 | + private static String HEADER_AUTHORIZATION = "Authorization"; |
| 36 | + private static String PREFIX_BEARER_TOKEN = "Bearer "; |
| 37 | + private static String CLAIM_KEY_TYPE = "type"; |
| 38 | + private static String CLAIM_KEY_AUTHORITIES = "authority"; |
| 39 | + private static String TOKEN_TYPE_ACCESS = "accessToken"; |
| 40 | + |
| 41 | + private JwtSsoTokenParser jwtParser = null; |
| 42 | + |
| 43 | + private boolean ignoreFailure = false; |
| 44 | + |
| 45 | + public JwtSsoBasedAuthenticationFilter(AuthenticationManager authenticationManager, JwtClientConfig jwtClientConfig) { |
| 46 | + super(authenticationManager); |
| 47 | + this.ignoreFailure = true; |
| 48 | + this.jwtParser = new DefaultJwtSsoTokenParser(jwtClientConfig.getSigningKey()); |
| 49 | + } |
| 50 | + |
| 51 | + public JwtSsoBasedAuthenticationFilter(AuthenticationManager authenticationManager, |
| 52 | + AuthenticationEntryPoint authenticationEntryPoint, JwtClientConfig jwtClientConfig) { |
| 53 | + super(authenticationManager, authenticationEntryPoint); |
| 54 | + this.jwtParser = new DefaultJwtSsoTokenParser(jwtClientConfig.getSigningKey()); |
| 55 | + } |
| 56 | + |
| 57 | + @Override |
| 58 | + public void afterPropertiesSet() { |
| 59 | + super.afterPropertiesSet(); |
| 60 | + |
| 61 | + if (log.isInfoEnabled()) { |
| 62 | + log.info("Filter:{} applied", this.getClass().getSimpleName()); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + @Override |
| 67 | + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) |
| 68 | + throws IOException, ServletException { |
| 69 | + if (log.isDebugEnabled()) { |
| 70 | + log.debug("=== doFilterInternal ==="); |
| 71 | + } |
| 72 | + SecurityContextHolder.clearContext(); |
| 73 | + |
| 74 | + String header = request.getHeader(HEADER_AUTHORIZATION); |
| 75 | + if (header == null || !header.startsWith(PREFIX_BEARER_TOKEN)) { |
| 76 | + |
| 77 | + log.debug("bearer token does not exist"); |
| 78 | + |
| 79 | + chain.doFilter(request, response); |
| 80 | + |
| 81 | + return; |
| 82 | + } |
| 83 | + |
| 84 | + if (log.isDebugEnabled()) { |
| 85 | + log.debug("start to authenticate with bearer token"); |
| 86 | + } |
| 87 | + |
| 88 | + try { |
| 89 | + UsernamePasswordAuthenticationToken authentication = getAuthentication(request); |
| 90 | + if (authentication != null && authentication.isAuthenticated()) { |
| 91 | + SecurityContextHolder.getContext().setAuthentication(authentication); |
| 92 | + } |
| 93 | + } catch (AuthenticationException failed) { |
| 94 | + log.debug("authentication failed"); |
| 95 | + |
| 96 | + SecurityContextHolder.clearContext(); |
| 97 | + |
| 98 | + onUnsuccessfulAuthentication(request, response, failed); |
| 99 | + |
| 100 | + if (this.ignoreFailure) { |
| 101 | + chain.doFilter(request, response); |
| 102 | + } else { |
| 103 | + this.getAuthenticationEntryPoint().commence(request, response, failed); |
| 104 | + } |
| 105 | + |
| 106 | + return; |
| 107 | + |
| 108 | + } |
| 109 | + executeFilter(request, response, chain); |
| 110 | + } |
| 111 | + |
| 112 | + protected void executeFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) |
| 113 | + throws IOException, ServletException { |
| 114 | + try { |
| 115 | + chain.doFilter(request, response); |
| 116 | + } finally { |
| 117 | + SecurityContextHolder.clearContext(); |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + protected boolean isIgnoreFailure() { |
| 122 | + return this.ignoreFailure; |
| 123 | + } |
| 124 | + |
| 125 | + protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, |
| 126 | + AuthenticationException failed) throws IOException { |
| 127 | + } |
| 128 | + |
| 129 | + protected void validateRequestHeader(HttpServletRequest request) { |
| 130 | + String header = request.getHeader(HEADER_AUTHORIZATION); |
| 131 | + if (header == null || !header.startsWith(PREFIX_BEARER_TOKEN)) { |
| 132 | + throw new BadCredentialsException("Access token is required."); |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + protected UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) { |
| 137 | + validateRequestHeader(request); |
| 138 | + |
| 139 | + String sAccessTokenHeader = request.getHeader(HEADER_AUTHORIZATION); |
| 140 | + |
| 141 | + String sAccessToken = sAccessTokenHeader.substring(PREFIX_BEARER_TOKEN.length()).trim(); |
| 142 | + |
| 143 | + if (StringUtils.isBlank(sAccessToken)) { |
| 144 | + throw new AuthenticationCredentialsNotFoundException("Access token is blank."); |
| 145 | + } |
| 146 | + |
| 147 | + Jws<Claims> jwt = null; |
| 148 | + try { |
| 149 | + jwt = jwtParser.parseJwt(sAccessToken); |
| 150 | + } catch (ExpiredJwtException e) { |
| 151 | + throw new BadCredentialsException("Access token has expired."); |
| 152 | + } catch (JwtException e) { |
| 153 | + throw new BadCredentialsException("Access token is not available."); |
| 154 | + } |
| 155 | + |
| 156 | + Claims claims = jwt.getBody(); |
| 157 | + |
| 158 | + String sAuthorities = claims.get(CLAIM_KEY_AUTHORITIES, String.class); |
| 159 | + |
| 160 | + String username = claims.getSubject(); |
| 161 | + |
| 162 | + log.info("subject:{}", username); |
| 163 | + |
| 164 | + String tokenType = claims.get(CLAIM_KEY_TYPE, String.class); |
| 165 | + |
| 166 | + if (!TOKEN_TYPE_ACCESS.equals(tokenType)) { |
| 167 | + throw new AccessDeniedException("Access token is required."); |
| 168 | + } |
| 169 | + |
| 170 | + if (sAuthorities.length() >= 2) { |
| 171 | + sAuthorities = sAuthorities.substring(1); |
| 172 | + sAuthorities = sAuthorities.substring(0, sAuthorities.length() - 1); |
| 173 | + } |
| 174 | + |
| 175 | + log.info("Authority String:{}", sAuthorities); |
| 176 | + |
| 177 | + ArrayList<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); |
| 178 | + |
| 179 | + if (StringUtils.isNotBlank(sAuthorities)) { |
| 180 | + String[] aAuthParts = sAuthorities.split(","); |
| 181 | + for (String s : aAuthParts) { |
| 182 | + GrantedAuthority ga = new SimpleGrantedAuthority(s.trim()); |
| 183 | + authorities.add(ga); |
| 184 | + } |
| 185 | + } |
| 186 | + |
| 187 | + log.info("Authorities:{}", authorities); |
| 188 | + |
| 189 | + return new UsernamePasswordAuthenticationToken(username, sAccessTokenHeader, authorities); |
| 190 | + |
| 191 | + } |
| 192 | + |
| 193 | +} |
0 commit comments