使用Spring Boot 2.0.0和OAuth2进行身份验证:在localhost上可以正常工作,但是在Heroku或AWS上部署时会自动返回401

时间:2019-06-09 12:22:26

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

我用Spring Boot 2.0和OAuth2创建了一个应用程序。当我在本地主机上运行应用程序时,通过端点/ oauth / token进行的OAuth2身份验证可以正常工作。但是,当我将其打包并部署到Heroku或AWS上时,此特定端点无法正常工作。 我创建的所有其他端点在这两种配置中均能正常工作。

这两个配置(在application.yml文件中)实际上是相同的,除了主机和端口。我不只是为了清楚而将其发布在这里。

我的AuthorizationServer看起来像这样:

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

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

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private DataSource dataSource;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                .tokenKeyAccess("permitAll")
                .checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource).passwordEncoder(passwordEncoder);
    }

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

    }

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

    @Bean
    public TokenEnhancer tokenEnhancer() {
        return new CustomTokenEnhancer();
    }
}

我的安全配置如下:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
        prePostEnabled = true
)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private UnauthorizedHandler unauthorizedHandler;


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

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .anonymous().disable()
                .cors().disable()
                .authorizeRequests()
                .antMatchers("/oauth/token").permitAll()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }


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

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

}

这是pom.xml中我对安全性的依赖:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security.oauth.boot</groupId>
            <artifactId>spring-security-oauth2-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
        </dependency>

我在两种情况下都使用Postman来测试API。当它位于本地主机上时,使用类似http://localhost:8080/oauth/token的URL,我成功获得了令牌:

{
    "access_token": "917d04c6-a6a8-4702-9686-3a8f21f2a552",
    "token_type": "bearer",
    "refresh_token": "0ccc4593-13d4-465b-a804-594672390e4a",
    "expires_in": 3599,
    "scope": "read write",
    "authorities": [
        {
            "authority": "ROLE_USER"
        }
    ],
    "username": "XXXXXX"
}

但是当我在远程服务器上使用诸如http://appname.herokuapp.com/oauth/token之类的URL进行调用时,总是会收到以下错误响应:

{
    "timestamp": "2019-06-09T11:33:49.345+0000",
    "status": 401,
    "error": "Unauthorized",
    "message": "Unauthorized",
    "path": "/oauth/token"
}

以下是与上述响应对应的服务器日志:

2019-06-09T11:33:49.244116+00:00 app[web.1]: 2019-06-09 11:33:49.243  INFO 4 --- [io-14394-exec-3] o.s.b.f.xml.XmlBeanDefinitionReader      : Loading XML bean definitions from class path resource [org/springframework/jdbc/support/sql-error-codes.xml]
2019-06-09T11:33:49.307111+00:00 app[web.1]: 2019-06-09 11:33:49.306  INFO 4 --- [io-14394-exec-3] o.s.jdbc.support.SQLErrorCodesFactory    : SQLErrorCodes loaded: [DB2, Derby, H2, HSQL, Informix, MS-SQL, MySQL, Oracle, PostgreSQL, Sybase, Hana]
2019-06-09T11:33:49.425217+00:00 heroku[router]: at=info method=POST path="/oauth/token" host=appname.herokuapp.com request_id=a805d042-910c-4791-a9ef-4d45cc0bb976 fwd="92.151.100.165" dyno=web.1 connect=1ms service=2403ms status=401 bytes=775 protocol=http

让我知道是否需要更多信息。任何帮助将不胜感激。

0 个答案:

没有答案