簡體   English   中英

使用Spring Boot OAuth2 Client登錄后訪問用戶數據

[英]Access user data after login with Spring Boot OAuth2 Client

我正在嘗試使用spring boot來構建OAuth2客戶端以訪問自定義API。

到目前為止,這是我的代碼:

@SpringBootApplication
public class MyClient {
    public static void main(String[] args){
        SpringApplication.run(MyClient.class, args);
    }
}
@Configuration
@EnableOAuth2Sso
public class ApplicationSecurity extends WebSecurityConfigurerAdapter{
    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.antMatcher("/**")
        .authorizeRequests().antMatchers("/","/callback","/login**","/error**")
        .permitAll().anyRequest().authenticated();
    }
}
@RestController
public class HomeController {
    @RequestMapping("/user")
    public String login() {
        String userInfoJson = "get data returned from API somehow";
        return userInfoJson;
    }

    @RequestMapping("/callback")
    public void callback(HttpServletResponse response) {
        response.sendRedirect("/user");
    }
}

我創建了一個application.yml文件,其中包含所需的所有屬性,登錄過程完美運行,成功登錄后將流返回到/ callback。

此時我應該收到一個令牌,我可以使用該令牌從服務器獲取用戶的數據。

我該如何訪問此令牌?

此外,spring boot是否有自動執行令牌驗證過程的任何類,或者我是否必須手動創建請求?

謝謝

來自文檔

OAuth2客戶端可用於從提供程序獲取用戶詳細信息(如果此類功能可用),然后將其轉換為Spring Security的身份驗證令牌。

上面的Resource Server通過user-info-uri屬性支持這一點。這是基於OAuth2的單點登錄(SSO)協議的基礎,Spring Boot通過提供注釋@EnableOuth2Sso使其易於參與。

上面的Github客戶端可以保護其所有資源並使用Gi​​thub / user / endpoint進行身份驗證,方法是添加該注釋並聲明在哪里找到端點(除了上面已經列出的security.oauth2.client。*配置):

application.yml。

security:
    oauth2:
...
    resource:
        userInfoUri: https://api.github.com/user
        preferTokenInfo: false

因此,如果您設置了從中獲取用戶信息的位置,則應該自動完成此操作,然后將填充該信息。

填充身份驗證令牌后,您可以通過多種不同方式從安全上下文中獲取此令牌。

@RequestMapping("/callback")
public void callback(Authentication authentication) {
    final String name = authentication.getName();
    response.sendRedirect("/user");
}

如果你想訪問原始的json,你可能需要自己進行休息。 如果要將自定義值添加到身份驗證對象,則必須實現自己的UserDetails類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM