主要有2个坑:
1.通过网关访问/oauth/authorize的时候,无法跳转到redirect_uri返回授权码
2.访问/oauth/token 刷新token的时候,新的token解析后用户信息丢失,用户信息变成了用户名
问题一
通过网关访问/oauth/authorize的时候,会把信息缓存到session中,跳转到登录页登录后,正常来说会从session中取出信息,然后跳转到redirect_uri,但是通过网关访问时,跳到的login登录页是授权服务的,点击登录也是直接访问的授权服务,并没有通过网关,所以需要跳转到login登录页的时候,把ip和端口都替换成网关的,具体代码如下
@TsfGatewayFilter
public class ResponseGlobalFilter extends AbstractTsfGlobalFilter {
// @Value("${cors.crossOriginPath}")
private String crossOriginPath = "网关地址";
@Override
public int getOrder() {
//WRITE_RESPONSE_FILTER 之前执行
return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 1;
}
@Override
public boolean shouldFilter(ServerWebExchange exchange, GatewayFilterChain chain) {
return true;
}
@Override
public Mono<Void> doFilter(ServerWebExchange exchange, GatewayFilterChain chain) {
String path = exchange.getRequest().getPath().value();
if (path.contains("/oauth/authorize") || path.contains("login")) {
//构建响应包装类
HttpResponseDecorator responseDecorator = new HttpResponseDecorator(exchange.getRequest(), exchange.getResponse(), crossOriginPath);
return chain
.filter(exchange.mutate().response(responseDecorator).build());
}
return chain.filter(exchange);
}
}
public class HttpResponseDecorator extends ServerHttpResponseDecorator {
private String proxyUrl;
private ServerHttpRequest request;
/**
* 构造函数
*
* @param delegate
*/
public HttpResponseDecorator(ServerHttpRequest request, ServerHttpResponse delegate, String proxyUrl) {
super(delegate);
this.request = request;
this.proxyUrl = proxyUrl;
}
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
HttpStatus status = this.getStatusCode();
if (status.equals(HttpStatus.FOUND)) {
String domain = "";
if (StringUtils.isBlank(proxyUrl)) {
domain = request.getURI().getScheme() + "://" + request.getURI().getAuthority() + "/oauth"; //这是授权服务的服务名
} else {
domain = proxyUrl + "/oauth";
}
String location = getHeaders().getFirst("Location");
// for (int i = 0; i < 3; i++) {
// location = location.substring(location.indexOf("/") + 1);
// }
String replaceLocation = location.replaceAll("^((ht|f)tps?):\\/\\/(\\d{1,3}.){3}\\d{1,3}(:\\d+)?", domain);
if (location.contains("code=")) {
// getHeaders().set("Location",location );
} else {
getHeaders().set("Location", replaceLocation);
}
}
this.getStatusCode();
return super.writeWith(body);
}
}
我这是用的腾讯的tsf服务,AbstractTsfGlobalFilter 是腾讯包里的,普通微服务需要写gateway的拦截器,或者zuul的拦截器,gateway就是implements GlobalFilter, Ordered,这样每次访问/oauth/authorize的时候会先走这个过滤器,然后把重定向地址,也就是Location,替换成网关的ip+端口+授权服务名称,这样跳到login页面的时候,就会通过网关跳转,而不是授权服务,就可以获取授权码了。
问题二
就是这个原因,所以我们需要重写extractAuthentication方法
/**
* 用户认证转化器
* /根据 oauth/check_token 的结果转化用户信息
*
* @author zhuowen
* @since 2019/06/21
*/
@Component
public class ZWUserAuthenticationConverter extends DefaultUserAuthenticationConverter {
private static final String USER_ID = "user_id";
private static final String DEPT_ID = "dept_id";
private static final String ROLE_ID = "role_id";
private static final String NAME = "name";
private static final String TENANT_ID = "tenant_id";
private static final String N_A = "N/A";
/**
* Extract information about the user to be used in an access token (i.e. for resource servers).
*
* @param authentication an authentication representing a user
* @return a map of key values representing the unique information about the user
*/
@Override
public Map<String, ?> convertUserAuthentication(Authentication authentication) {
Map<String, Object> response = new LinkedHashMap<>();
response.put(USERNAME, authentication.getName());
if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
}
return response;
}
/**
* Inverse of {@link #convertUserAuthentication(Authentication)}. Extracts an Authentication from a map.
*
* @param map a map of user information
* @return an Authentication representing the user or null if there is none
*/
@Override
public Authentication extractAuthentication(Map<String, ?> map) {
if (map.containsKey(USERNAME)) {
Collection<? extends GrantedAuthority> authorities = getAuthorities(map);
String username = (String) map.get(USERNAME);
String name = (String) map.get(NAME);
Integer userId = (Integer) map.get("userId");
ZWUser zwUser = new ZWUser(userId.longValue(),username,name,"N/A",true,true,true,true,authorities);
// String userStr = (String)map.get("userInfo");
// System.out.println("userObj=========="+userStr);
// ObjectMapper objectMapper = new ObjectMapper();
// ZWUser user = objectMapper.convertValue(userObj, ZWUser.class);
// System.out.println("user=========="+user.toString());
// System.out.println(jsonObject.toJSONString());
// SysUser user = JSON.parseObject(jsonObject.toJSONString(), SysUser.class);
return new UsernamePasswordAuthenticationToken(zwUser, N_A, authorities);
}
return null;
}
private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
Object authorities = map.get(AUTHORITIES);
if (authorities instanceof String) {
return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
}
if (authorities instanceof Collection) {
return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils
.collectionToCommaDelimitedString((Collection<?>) authorities));
}
throw new IllegalArgumentException("Authorities must be either a String or a Collection");
}
}
重写完后,我们需要在token增强里配置一下
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter() {
/**
* 重写增强token的方法
* 自定义返回相应的信息
*
*/
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
// 与登录时候放进去的UserDetail实现类一直查看link{SecurityConfiguration}
ZWUser userInfo = (ZWUser) authentication.getUserAuthentication().getPrincipal();
/* 自定义一些token属性 ***/
final Map<String, Object> additionalInformation = new HashMap<>(18);
String name = userInfo.getName();
Long userId = userInfo.getUser_id();
additionalInformation.put("name", name);
additionalInformation.put("userId", userId);
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInformation);
return super.enhance(accessToken, authentication);
}
};
accessTokenConverter.setSigningKey(SIGNING_KEY);
((DefaultAccessTokenConverter) accessTokenConverter.getAccessTokenConverter()).setUserTokenConverter(zwUserAuthenticationConverter);
return accessTokenConverter;
}
最后一行代码accessTokenConverter.getAccessTokenConverter()).setUserTokenConverter(zwUserAuthenticationConverter);把ZWUserAuthenticationConverter 注入到token增强的类里,刷新token后,用户信息就不会丢失了