簡體   English   中英

在 Oauth2 Spring Boot 中訪問此資源需要完全身份驗證

[英]Getting Unauthorised Full authentication is required to access this resource in Oauth2 Spring Boot

我在 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;
    }
}

因此,每當我嘗試使用useridsecret作為 Postman 中的Basic-Auth以及另一個usernamepasswordgrant_type=password BASE_URL/api/v1/oauth/token此 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;
    }
}

我不知道我錯過了什么。 任何幫助將不勝感激。 謝謝

檢查您是否在 Postman 中設置了 Headers。 鍵:Content-Type 值:application/x-www-form-urlencoded

你可能有,但你沒有提到。 也許它有幫助。

另外,我注意到您沒有允許所有人獲得令牌。 在您的 AuthorizationServerConfigurerAdapter 中試試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM