【问题标题】:Getting Unauthorised Full authentication is required to access this resource in Oauth2 Spring Boot在 Oauth2 Spring Boot 中访问此资源需要获取未经授权的完整身份验证
【发布时间】:2020-06-18 09:50:14
【问题描述】:

我在 Spring Boot 中使用 Oauth2,并且我使用 JDBC 令牌存储来存储 JWT 令牌。这是我的AuthorizationServerConfig

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(AuthorizationServerConfig.class);
    static final String MERCHANT_ID = "merchant-id";
    static final String MERCHANT_SECRET = "merchant-secret-bcrypted-value";
    static final String CUSTOMER_ID = "customer-id";
    static final String CUSTOMER_SECRET = "customer-secret-bcrypted-value";
    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";
    static final int ACCESS_TOKEN_VALIDITY_SECONDS = 1 * 60 ;
    static final int FREFRESH_TOKEN_VALIDITY_SECONDS = 5 * 60 ;

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private DataSource dataSource;
    @Resource(name = "UserService")
    private UserDetailsService userDetailsService;
    @Bean
    public JwtAccessTokenConverter accessTokenConverter() throws Exception {
        logger.debug("accessTokenConverter");
        System.out.println("accessTokenConverter");
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey("asagasdg");


        return converter;
    }

    @Bean
    public TokenStore tokenStore() throws Exception {
        logger.debug("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");
        configurer
                .jdbc(dataSource)
//                .inMemory()
                .withClient(MERCHANT_ID)
                .secret(MERCHANT_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()
                .withClient(CUSTOMER_ID)
                .secret(CUSTOMER_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
                .pathMapping("/oauth/token","/api/v1/oauth/token")
                .tokenStore(tokenStore())
                .authenticationManager(authenticationManager)
                .accessTokenConverter(accessTokenConverter());
    }



    @Bean
    @Primary
    public DefaultTokenServices tokenServices() throws Exception {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setSupportRefreshToken(true);
        return defaultTokenServices;
    }
}

因此,每当我尝试使用 Postman 中的 useridBasic-Auth 以及另一个 usernamepasswordgrant_type=password 来访问此 URL BASE_URL/api/v1/oauth/token 时,我都会收到此错误

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

内存中的身份验证工作正常,但是当我创建数据库 oauth_access_tokenoauth_refresh_tokenoauth_client_details 以保存和检索数据库中的 JWT 时,我收到了该错误。

这是我的ResourceServerConfig

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    private static final String RESOURCE_ID = "resource_id";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception{
        System.out.println("resource server configurer "+resources);
        resources.resourceId(RESOURCE_ID).stateless(false);
    }

    @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;
    }
}

我不知道我错过了什么。任何帮助将不胜感激。谢谢

【问题讨论】:

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


    【解决方案1】:

    检查您是否在 Postman 中设置了标头。 键:Content-Type 值:application/x-www-form-urlencoded

    你可能有,但你没有提到。也许有帮助。

    另外,我注意到您没有允许所有人获得令牌。在您的 AuthorizationServerConfigurerAdapter 中试试这个:

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

    【讨论】:

    • 邮递员正在添加这个Key: Content-Type Value: application/x-www-form-urlencoded 标头我也尝试了另一种解决方案,但问题仍然存在。
    • 对不起,帮不上忙了。
    猜你喜欢
    • 2018-09-11
    • 2020-11-21
    • 2020-10-25
    • 2020-09-02
    • 2016-10-03
    • 2022-07-22
    • 2015-01-08
    • 2018-06-29
    • 2019-01-01
    相关资源
    最近更新 更多