【问题标题】:How to implement OAuth2.0 with spring security by adding additional parameter如何通过添加附加参数来实现 OAuth2.0 与 Spring Security
【发布时间】:2019-01-25 06:08:47
【问题描述】:

我正在根据下面的链接使用 springboot2 实现带有 spring-security 的 oauth2。

https://www.devglan.com/spring-security/spring-boot-oauth2-jwt-example

我成功地实施了它。

上面的代码在验证用户时有不同的用例。

我需要在邮递员的“x-www-form-urlencoded”选项卡中传递 companyid 以及用户名和密码以及 grant_type(password)。 我必须根据用户名和 companyId 获取用户。

所以请帮我看看我需要在上面的链接代码中做些什么改变,这样我才能达到我的要求。

在这里我只收到电子邮件。我需要电子邮件和 companyId。

@Override
@Transactional
public 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
@Transactional
public 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_description”:“查询未返回唯一结果:2;嵌套异常为 javax.persistence.NonUniqueResultException:查询未返回唯一结果:2” }

我需要根据用户名和密码以及 companyId 获取用户,这会导致单个用户。

【问题讨论】:

    标签: java spring-boot spring-security-oauth2


    【解决方案1】:

    如果您需要访问令牌的其他信息,您可以使用 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());
    }
    

    【讨论】:

      猜你喜欢
      • 2014-09-29
      • 2016-11-08
      • 2016-12-29
      • 2018-01-29
      • 2014-10-07
      • 1970-01-01
      • 1970-01-01
      • 2019-03-24
      • 2014-08-11
      相关资源
      最近更新 更多