Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于springCloud+Oauth2+LCN的feign请求401问题 #11

Open
loqvliuliang opened this issue Oct 10, 2018 · 1 comment
Open

关于springCloud+Oauth2+LCN的feign请求401问题 #11

loqvliuliang opened this issue Oct 10, 2018 · 1 comment

Comments

@loqvliuliang
Copy link

原来系统采用springCloud+OAUTH2,服务之间采用feign方式调用,先添加了lcn相应注解后,调用feign的时候401了,请问一下这个是lcn请求头没携带token的原因吗?该怎么设置一下呢?

@loqvliuliang
Copy link
Author

我已经解决了,重写apply方法,在请求头上面,添加上自己的token所需信息即可。代码如下:


import com.codingapi.tx.aop.bean.TxTransactionLocal;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class TransactionRestTemplateInterceptor implements RequestInterceptor {

    private Logger logger = LoggerFactory.getLogger(TransactionRestTemplateInterceptor.class);

    public TransactionRestTemplateInterceptor() {
    }

    public void apply(RequestTemplate requestTemplate) {
        TxTransactionLocal txTransactionLocal = TxTransactionLocal.current();
        String groupId = txTransactionLocal == null ? null : txTransactionLocal.getGroupId();
        this.logger.info("LCN-SpringCloud TxGroup info -> groupId:" + groupId);
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = requestAttributes == null ? null : ((ServletRequestAttributes) requestAttributes).getRequest();
        Object attribute = request.getAttribute("OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE");
        String token = attribute == null ? null : attribute.toString();
        requestTemplate.header("Authorization", "Bearer " + token);
        if (txTransactionLocal != null) {
            requestTemplate.header("tx-group", new String[]{groupId});
        }

    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant