使用springcloud+oauth2攜帶token去請求其他服務(wù)
springcloud+oauth2攜帶token去請求其他服務(wù)
當(dāng)從oauth2服務(wù)中獲取到了token后
攜帶該token去請求其他服務(wù)時,報出
{ "error": "invalid_token", "error_description": "Invalid access token: e5224346-ea39-49ff-bd0e-1b9aef3db1da" }
需要在當(dāng)前服務(wù)的配置文件配置
#內(nèi)置有user對象的地址,才能獲取到同一個token security.oauth2.resource.user-info-uri=http://localhost:8003/api/user security.oauth2.resource.prefer-token-info=false
springcloud 微服務(wù)之間傳遞token
在springcloud 微服務(wù)中大部分是通過token來驗證用戶的,那么有個問題,假設(shè)現(xiàn)在有A服務(wù),B服務(wù),外部使用RESTApi請求調(diào)用A服務(wù),在請求頭上有token字段,A服務(wù)使用完后,B服務(wù)也要使用,如何才能把token也轉(zhuǎn)發(fā)到B服務(wù)呢,最差的解決辦法就是吧token放到請求參數(shù)中,但是這樣第一個是明文傳輸,第二個是比較麻煩,前端每次都要加個參數(shù)。
這里可以使用Feign的RequestInterceptor,把request里的請求參數(shù)包括請求頭全部復(fù)制到feign的request里,但是直接使用一般情況下HttpServletRequest上下文對象是為空的,其實加個配置就可以解決。
1、服務(wù)A中 application.yml 加入如下配置
hystrix: command: default: execution: isolation: strategy: SEMAPHORE #加上這個就可以獲取到HttpServletRequest thread: timeoutInMilliseconds: 10000
2、服務(wù)A中加入 FeginInterceptor
@Configuration public class FeginInterceptor implements RequestInterceptor { @Override public void apply(RequestTemplate requestTemplate) { try { Map<String,String> headers = getHeaders(); for(String headerName : headers.keySet()){ requestTemplate.header(headerName, headers.get(headerName)); } }catch (Exception e){ e.printStackTrace(); } } private Map<String, String> getHeaders(){ HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); Map<String, String> map = new LinkedHashMap<>(); Enumeration<String> enumeration = request.getHeaderNames(); while (enumeration.hasMoreElements()) { String key = enumeration.nextElement(); String value = request.getHeader(key); map.put(key, value); } return map; } }
若服務(wù)B或C也想傳遞token,加上上述A配置即可~
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot使用prometheus監(jiān)控的示例代碼
這篇文章主要介紹了SpringBoot使用prometheus監(jiān)控的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03SpringBoot整合EasyExcel實現(xiàn)批量導(dǎo)入導(dǎo)出
這篇文章主要為大家詳細(xì)介紹了SpringBoot整合EasyExcel實現(xiàn)批量導(dǎo)入導(dǎo)出功能的相關(guān)知識,文中的示例代碼講解詳細(xì),需要的小伙伴可以參考下2024-03-03Java給JFrame窗口設(shè)置熱鍵的方法實現(xiàn)
這篇文章主要介紹了Java給JFrame窗口設(shè)置熱鍵的方法實現(xiàn),文中通過示例代碼以及圖文介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07crawler4j抓取頁面使用jsoup解析html時的解決方法
crawler4j對response沒有指定編碼的頁面,解析成亂碼,很讓人煩惱,下面給出解決方法,需要的朋友可以參考下2014-04-04