Spring Security OAuth2资源服务器无法获取包含详细信息的主体

时间:2019-10-20 13:35:37

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

我使用OAuth2创建了资源服务器,并且在成功通过身份验证后,当然无法检索Principal对象。我可以看到主体用户名,但没有任何详细信息。 我应该如何配置资源或身份验证服务器以传输所有用户信息?

我准备了两个微服务,一个是授权服务器,第二个是资源服务器。在应用程序之间正确配置了身份验证。他们两个都使用Spring Security Cloud OAuth2,并且问题是转移所有Principal对象,我无法理解。也许我应该用用户信息纠正一些问题,但是我只是在文档之间迷路了。

授权服务器源代码:

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Autowired
    @Qualifier("authenticationManager")
    private AuthenticationManager authenticationManager;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("client")
                .secret(passwordEncoder.encode("password"))
                .authorizedGrantTypes("authorization_code", "refresh_token", "password")
                .accessTokenValiditySeconds(1800)
                .refreshTokenValiditySeconds(30 * 24 * 3600)
                .redirectUris("http://example.test")
                .authorizedGrantTypes("ROLE_USER")
                .autoApprove(true)
                .scopes("all");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints
                .authenticationManager(authenticationManager)
                .tokenStore(tokenStore());
    }

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
        oauthServer
                .checkTokenAccess("permitAll()")
                .allowFormAuthenticationForClients();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    private final UserService userService;

    public WebSecurityConfiguration(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder authentication) throws Exception {
        authentication
                .userDetailsService(userService)
                .passwordEncoder(passwordEncoder);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/oauth/*").permitAll()
                .antMatchers("/*").permitAll();
    }

    @Bean(name = "authenticationManager")
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
@Service
public class UserService implements UserDetailsService {
    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("Invalid username or password"));

        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                Collections.singletonList(new SimpleGrantedAuthority(Role.ROLE_USER.name())));
    }
}
spring:
  jpa:
    hibernate:
      ddl-auto: validate
    database-platform: org.hibernate.dialect.PostgreSQLDialect
    properties:
      hibernate:
        temp:
          use_jdbc_metadata_defaults: false
    show-sql: true
  datasource:
    url: jdbc:postgresql://localhost:5432/mydb
    username: user
    password: password

资源服务器源代码:

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true, jsr250Enabled = true)
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/public").permitAll()
                .anyRequest().authenticated();
    }
}
@RestController
public class WelcomeController {

    @GetMapping("/public")
    public String welcomePublic() {
        return "welcome public/guest user";
    }

    @RolesAllowed({"ROLE_USER"})
    @GetMapping("/user")
    public String welcomeUser() {
        return "welcome user";
    }
}
security:
  oauth2:
    client:
      client-id: client
      client-secret: password
    resource:
      token-info-uri: http://localhost:8080/oauth/check_token
      user-info-uri: http://localhost:8080/oauth/userinfo
server:
  port: 8081

Authentication对象中的主要对象只是String-用户名。详细信息为空。

我希望检索有关当前登录用户的信息,将来我将增强有关电子邮件或其他内容的JDBC用户,并将所有信息保存在Resource Server中。我希望有人也有类似的问题。 :)

0 个答案:

没有答案