Получение «Несанкционированной полной аутентификации требуется для доступа к этому ресурсу» в Oauth2 Spring Boot при использовании аутентификации JDB C - PullRequest
0 голосов
/ 02 мая 2020

Я использую Oauth2 в Spring Boot и использую хранилище токенов JDB C для хранения токенов JWT. Это мой AuthorizationServerConfig

    @Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    static final String CLIENT_ID = "my-client";
    static final String CLIENT_SECRET = "my-client-secret";
    static final String GRANT_TYPE_PASSWORD = "password";
    static final String AUTHORIZATION_CODE = "authorization_code";
    static final String REFRESH_TOKEN = "refresh_token";
    static final String IMPLICIT = "implicit";
    static final String SCOPE_READ = "read";
    static final String SCOPE_WRITE = "write";
    static final String TRUST = "trust";
    private static final String RESOURCE_ID = "resource_id";
    static final int ACCESS_TOKEN_VALIDITY_SECONDS = 864000; 
    static final int FREFRESH_TOKEN_VALIDITY_SECONDS = 2592000;

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private DataSource dataSource;
    @Resource(name = "UserService")
    UserDetailsService userDetailsService;
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() throws Exception {
        System.out.println("accessTokenConverter " + dataSource.getConnection().getSchema());
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey("as466gf");


        return converter;
    }

    @Bean
    public JdbcTokenStore tokenStore() throws Exception {
        System.out.println("tokenstore");
        return new JdbcTokenStore(dataSource);
    }

    @Bean
    public ApprovalStore approvalStore() throws Exception {
        TokenApprovalStore tokenApprovalStore = new TokenApprovalStore();
        tokenApprovalStore.setTokenStore(tokenStore());

        return tokenApprovalStore;
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {
        System.out.println("configure");

        JdbcClientDetailsService jdbcClientDetailsService = new JdbcClientDetailsService(dataSource);

        if (!jdbcClientDetailsService.listClientDetails().isEmpty()) {
            jdbcClientDetailsService.removeClientDetails(CLIENT_ID);
        }

        configurer
                .jdbc(dataSource)
                .withClient(CLIENT_ID)
                .secret(bCryptPasswordEncoder.encode(CLIENT_SECRET))
                .authorizedGrantTypes(GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT)
                .scopes(SCOPE_READ, SCOPE_WRITE, TRUST)
                .accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS).
                refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS)
                .and()
                .build()
        ;
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        System.out.println("configure below");
        endpoints
                .userDetailsService(userDetailsService)
                .pathMapping("/oauth/token", "/api/v1/oauth/token")
                .tokenStore(tokenStore())
                .authenticationManager(this.authenticationManager)
        ;
    }

    @Bean
    @Primary
    public DefaultTokenServices tokenServices() throws Exception {
        System.out.println("defaulttokenservices");
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setSupportRefreshToken(true);

        return defaultTokenServices;
    }
}

oauth_client сохраняется в базе данных с именем таблицы oauth_client_details с client_id = my-client и любой другой информацией.

Поэтому, когда я пытаюсь нажать на этот URL BASE_URL/api/v1/oauth/token с userid и secret как Basic-Auth в Почтальоне вместе с другими username, password и grant_type=password Я получаю эту ошибку

{
    "error": "unauthorized",
    "error_description": "Full authentication is required to access this resource"
}

Это мой ResourceServerConfig

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    private static final String RESOURCE_ID = "resource_id";
@Autowired
TokenStore tokenStore;
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception{
        System.out.println("resource server configurer "+resources);
        resources.resourceId(RESOURCE_ID).tokenStore(tokenStore);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {

        System.out.println("resource server config");
        http
                .authorizeRequests()
                .antMatchers("api/v1/oauth/token").permitAll()
                .antMatchers("/","/css/**","/js/**","/lib/**","/img/**","/scss/**","/templates/**","/device-mockups/**","/vendor/**").permitAll()
                .anyRequest().authenticated()
                .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());


    }

}

А это мой WebSecurityConfigurerAdapter

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

    @Resource(name = "UserService")
    private UserDetailsService userDetailsService;

    @Autowired
    DataSource dataSource;

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

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        System.out.println("globalUserDetails");
        auth

                .userDetailsService(userDetailsService)
                .passwordEncoder(bCryptPasswordEncoder());
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() throws Exception {
        System.out.println("bcryptEncoder");
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        System.out.println("configure ");


        http.cors().and()
                .authorizeRequests()
                .antMatchers("/","/api/v1/oauth/token","/**").permitAll()
                .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                ;
    }


    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }
}

Я не знаю, что я делаю неправильно. Любая помощь будет высоко ценится. Спасибо

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...