亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何通過添加附加參數來實現 OAuth2.0 與 Spring Security

如何通過添加附加參數來實現 OAuth2.0 與 Spring Security

一只名叫tom的貓 2022-05-20 18:34:17
我正在使用基于以下鏈接的 springboot2 使用 spring-security 實現 oauth2。https://www.devglan.com/spring-security/spring-boot-oauth2-jwt-example我成功地實施了它。在這里,我在驗證用戶時對上述代碼有不同的用例。我需要在郵遞員的“x-www-form-urlencoded”選項卡中傳遞公司ID以及用戶名和密碼以及grant_type(密碼)。我必須根據用戶名和 companyId 獲取用戶。所以請幫我看看我需要在上面的鏈接代碼中做些什么改變,這樣我才能達到我的要求。在這里我只收到電子郵件。我需要電子郵件和 companyId。@Override@Transactionalpublic UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {    User user = userRepository.findByEmail(email).orElseThrow(            () -> new UsernameNotFoundException("User Not Found with -> username or email : " + email));    return UserPrinciple.build(user);}Expected:@Override@Transactionalpublic UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {    User user = userRepository.findByEmailAndCompanyId(email,companyId).orElseThrow(            () -> new UsernameNotFoundException("User Not Found with -> username or email : " + email));    return UserPrinciple.build(user);}目前使用用戶名和密碼它工作正常。但是在我的系統中,我將同一用戶映射到不同的公司。如果發現同一用戶映射到多個公司,我會收到如下錯誤。{ "error": "unauthorized", "error_description": "查詢沒有返回唯一結果:2;嵌套異常是 javax.persistence.NonUniqueResultException:查詢沒有返回唯一結果:2" }我需要根據用戶名和密碼以及導致單個用戶的 companyId 獲取用戶。
查看完整描述

1 回答

?
絕地無雙

TA貢獻1946條經驗 獲得超4個贊

如果您想要訪問令牌的其他信息,您可以使用 TokenEnhancer 類來做到這一點。


CustomTokenEnhancer.java


public class CustomTokenEnhancer implements TokenEnhancer {


    @Override

    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {

        User user = (User) authentication.getPrincipal();

        final Map<String, Object> additionalInfo = new HashMap<>();


        additionalInfo.put("id", user.getCompanyId());

        additionalInfo.put("authorities", user.getAuthorities());


        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);


        return accessToken;

    }


}

然后使用此類的實例來 void configure(AuthorizationServerEndpointsConfigurer endpoints) 像這樣的方法


AuthorizationServerConfig.java


@Override

public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

    endpoints.authenticationManager(authenticationManager)

            .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)

            .tokenEnhancer(new CustomTokenEnhancer());

}


查看完整回答
反對 回復 2022-05-20
  • 1 回答
  • 0 關注
  • 191 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號