【问题标题】:Spring Cloud OAuth2Authentication returns NullPointerExceptionSpring Cloud OAuth2Authentication 返回 NullPointerException
【发布时间】:2017-09-17 01:45:26
【问题描述】:

我正在慢慢理解 Spring Cloud Security。我创建了一个授权服务,它在授权和返回令牌时工作,但在使用该令牌时不返回任何当前用户详细信息,当从OAuth2Authentication 获取这些信息时。这两行返回一个 NPE:

userInfo.put("user", user.getUserAuthentication().getPrincipal());
            userInfo.put("authorities", AuthorityUtils.authorityListToSet(user.getUserAuthentication().getAuthorities()));

OAuth2Authentication user 未实例化并且为空,而我理解它应该默认由 Spring Security 实例化。也许我缺少一些配置bean?提前致谢!

Application.class

@SpringBootApplication
@RestController
@EnableResourceServer
@EnableAuthorizationServer
public class AuthorizationServiceApplication {

    @RequestMapping(value = {"/user"}, produces = "application/json")
    public Map <String, Object> user (OAuth2Authentication user) {
        Map <String, Object> userInfo = new HashMap <>();
        userInfo.put("user", user.getUserAuthentication().getPrincipal());
        userInfo.put("authorities", AuthorityUtils.authorityListToSet(user.getUserAuthentication().getAuthorities()));
        return userInfo;
    }

    public static void main (String[] args) {
        SpringApplication.run(AuthorizationServiceApplication.class, args);
    }
}

OAuth2Config.class

@Configuration
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Value("${token.secret}")
    private String secret;
    private AuthenticationManager authenticationManager;
    private UserDetailsService userDetailsService;

    public OAuth2Config (AuthenticationManager authenticationManager, UserDetailsService userDetailsService) {
        this.authenticationManager = authenticationManager;
        this.userDetailsService = userDetailsService;
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("eagleeye")
                .secret(secret)
                .authorizedGrantTypes("refresh_token", "password", "client_credentials")
                .scopes("webclient", "mobileclient");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService);
    }
}

WebSecurityConfigurer.class

@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean () throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    @Bean
    public UserDetailsService userDetailsServiceBean() throws Exception {
        return super.userDetailsServiceBean();
    }

    // TODO: implemented DB stuff
    @Override
    protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder
                .inMemoryAuthentication()
                .withUser("deniss").password("deniss1").roles("USER")
                .and()
                .withUser("oksana").password("oksana").roles("USER, ADMIN");
    }

    private CsrfTokenRepository csrfTokenRepository() {
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
        repository.setSessionAttributeName("_csrf");
        return repository;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().csrfTokenRepository(csrfTokenRepository());
    }
}

【问题讨论】:

  • 您是否缺少 OAuth2Config 构造函数上的 @Autowired 注释?
  • @p.streef 嗯,但是这样 userService 不会也不能工作......?
  • 我只是在这里猜测,可能是 Spring 自动为组件/配置自动装配构造函数
  • 我想我之前只尝试过 @Autowire 变量而不是构造函数注入,但这也没有帮助
  • @DeepeshChoudhary 这不是关于一般 java 异常的问题,而是关于与无效 spring 云安全配置相关的异常的问题...

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


【解决方案1】:

最后我得到了这样的工作:

Application.class

@SpringBootApplication
@RestController
@EnableResourceServer
public class AuthorizationServiceApplication {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @RequestMapping("/user")
    public Principal user(Principal user) {
        log.info("User information display for User: " + user.getName());
        return user;
    }

    @Bean
    UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("deniss").password("deniss").roles("USER").build());
        return manager;
    }

    public static void main (String[] args) {
        SpringApplication.run(AuthorizationServiceApplication.class, args);
    }
}

OAuth2Config.java

@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    //TODO: refactor to recieve this info from config server
    @Value("${token.secret}")
    private String secret;

    @Autowired
    private AuthenticationManager authenticationManager;

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

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("eagleeye")
                .secret(secret)
                .authorizedGrantTypes("refresh_token", "password", "client_credentials")
                .scopes("webclient", "mobileclient");
    }
}

SecurityConfigurer.class

@Configuration
@EnableGlobalAuthentication
public class SecurityConfigurer extends GlobalAuthenticationConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    // TODO: implemented DB stuff
    @Override
    public void init(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder.userDetailsService(this.userDetailsService);
    }
}

【讨论】:

    【解决方案2】:

    我遇到了同样的问题,似乎是新版本的错误。我把 Spring Boot 1.5.9.RELEASE,Spring Cloud Edgware.RELEASE 改成 Spring Boot 1.4.4.RELEASE,Spring Cloud Camden.SR5,问题就消失了。

    【讨论】:

      【解决方案3】:

      设置security.oauth2.resource.filter-order=3 配置属性以恢复以前版本中使用的顺序。详情请见enter link description here

      【讨论】:

        猜你喜欢
        • 2017-01-12
        • 1970-01-01
        • 2018-12-13
        • 2018-04-26
        • 1970-01-01
        • 1970-01-01
        • 2019-11-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多