Spring OAuth with JWT custom UserDetails - Set Principal inside JwtAccessTokenConverter

前端 未结 1 1387
梦毁少年i
梦毁少年i 2021-01-14 19:27

Some additional info is sent from OAuth Authorization Server that is needed inside a custom UserDetails class on Resource Server, and preferably inside SpringSe

相关标签:
1条回答
  • 2021-01-14 20:11

    I can not say if this is the preferred solution, but after trying to solve the same thing myself, I ended up extending the DefaultUserAuthenticationConverter.

    So you can do something like this

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
      DefaultAccessTokenConverter defaultConverter = new DefaultAccessTokenConverter();
      defaultConverter.setUserTokenConverter(new CustomUserAuthenticationConverter());
    
      JwtAccessTokenConverter jwtConverter = new JwtAccessTokenConverter();
      converter.setAccessTokenConverter(defaultConverter);
      return converter;
    }
    

    Then the DefaultUserAuthenticationConverter is not very extendable since most methods and properties are private. But here is an example

    public class CustomUserAuthenticationConverter extends DefaultUserAuthenticationConverter {
    
      private static final String CUST_PROP = "custProp";
    
      @Override
      public Authentication extractAuthentication(Map<String, ?> map) {
        if (map.containsKey(USERNAME) && map.containsKey(CUST_PROP)) {
          String username = (String) map.get(USERNAME);
          String custProp = (String) map.get(CUST_PROP);
    
          CustomPrincipal principal = new CustomPrincipal();
          pricipal.setUsername(username);
          pricipal.setCustomProp(custProp);
    
          Collection<? extends GrantedAuthority> authorities = getAuthorities(map);
          return new UsernamePasswordAuthenticationToken(user, "N/A", authorities);
        }
        return null;
      }
    
      private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
        //Copy this method from DefaultUserAuthenticationConverter or create your own.
      }
    
    }
    
    0 讨论(0)
提交回复
热议问题