Spring Security OAuth2はRESTサービスでアクセスを拒否されます

ピーター:

SpringセキュリティとOAuth2を使用してSpring RESTサービスを保護しようとしています。私はなんとかトークンを手に入れました:

トークン

しかし、安全な休憩サービスを取得しようとすると、アクセスが拒否されます。

拒否された

なぜこれが起こっているのか誰かに教えてもらえますか?

AuthorizationServerConfig:

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private static String REALM="EXAMPLE_REALM";

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private UserApprovalHandler handler;

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

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        clients.inMemory()
            .withClient("myRestClient") // client id
            .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
            .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
            .scopes("read", "write", "trust")
            .secret("{noop}P@ssw0rd")
            .accessTokenValiditySeconds(240).//invalid after 4 minutes.
            refreshTokenValiditySeconds(600);//refresh after 10 minutes.
    }

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

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.realm(REALM+"/client");
    }

}

ResourceServerConfig:

@Configuration
@EnableResourceServer

public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    private static final String RESOURCE_ID = "SPRING_REST_API";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID).stateless(false);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.
        anonymous().disable()
        .requestMatchers().antMatchers("/api/**")
        .and().authorizeRequests()
        .antMatchers("/api/**").access("hasRole('ADMIN')")
        .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }

}

SecurityConfig:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private ClientDetailsService clientService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
    @Override
    protected void configure(final AuthenticationManagerBuilder auth) throws Exception{        
        auth
            .inMemoryAuthentication()
                .withUser("user")
                .password(passwordEncoder().encode("password"))
                .roles("USER")
            .and()
                .withUser("admin")
                .password(passwordEncoder().encode("admin"))
                .roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .csrf().disable()
        .anonymous().disable()
        .authorizeRequests()
        .antMatchers("/oauth/token").permitAll()
        .antMatchers("/about").authenticated();
    }

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


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

    @Bean
    @Autowired
    public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore){
        TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
        handler.setTokenStore(tokenStore);
        handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientService));
        handler.setClientDetailsService(clientService);
        return handler;
    }

    @Bean
    @Autowired
    public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
        TokenApprovalStore store = new TokenApprovalStore();
        store.setTokenStore(tokenStore);
        return store;
    }

}

AboutController(レストサービス):

    @RestController
public class AboutController {
    @RequestMapping(value = "/about", method = RequestMethod.GET)
    public ResponseEntity<?> home() {
        return new ResponseEntity<>("This is a demo application to show how to secure REST API using Spring Security and OAuth2", HttpStatus.OK);
    }
}

application.properties:

server.servlet.context-path=/api
security.oauth2.resource.filter-order = 3

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.springframework</groupId>
    <artifactId>gs-rest-service</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
        <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>
            <version>2.0.0.RELEASE</version>
        </dependency>

    </dependencies>

    <properties>
        <java.version>1.8</java.version>
    </properties>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

前もって感謝します!

ピーター:

これでうまくいきました。私の問題は、application.configファイルに/ apiを追加して、すべてのサービスに対してapiフォルダーが次のように配置されるようにすることでした:http:// localhost:8080 / api / about .. ResourceServerConfigクラスに/ api /を追加しました** requestMatchersとantMatchers ....のように、security構成は、このapiプレフィックスフォルダーの後でservericeを探しています...したがって、残りの部分を公開するには、次のようにします。

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    private static final String RESOURCE_ID = "SPRING_REST_API";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID).stateless(false);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.
        anonymous().disable()
        .requestMatchers().antMatchers("/about/**")
        .and().authorizeRequests()
        .antMatchers("/about/**").access("hasRole('ADMIN')")
        .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }

}

ちなみに、リクエストサービスのスクリーンショットのように、パラメーターを使用してaboutサービスをリクエストできますが、認証トークンまたはベアラートークン認証ヘッダーを指定しても機能します。

よろしく!

ピーター

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Spring Security-アクセスが拒否されました(ユーザーは匿名ではありません)spring-security-core-4.0.3.RELEASE

分類Dev

Spring Security OAuth2:REST Webサービスでユーザー名を取得する

分類Dev

Spring Boot Security 403「アクセス拒否」

分類Dev

Spring SecurityとKeycloakによって「アクセスが拒否されました」というエラーが表示されるのはなぜですか?

分類Dev

Spring Security Oauth2リソース所有者のパスワードフロー:RESTリクエストを送信すると、ユーザー詳細サービスは常にユーザー名ではなくクライアントIDを取得します

分類Dev

Spring Security4.1のアップグレード-エラー403アクセスが拒否されました

分類Dev

Spring Security4.1のアップグレード-エラー403アクセスが拒否されました

分類Dev

Spring Security4.1のアップグレード-エラー403アクセスが拒否されました

分類Dev

Spring Security Oauth2-InsufficientAuthenticationException:アクセストークンを取得するには認証が必要です(匿名は許可されていません)

分類Dev

Spring Security OAuth2のリソースサーバーは必要ですか?

分類Dev

Spring Security OAuth2は配列として返されるとスコープを解析できません

分類Dev

Spring Security OAuth2ピュアリソースサーバー

分類Dev

Spring Security - Oauth implementations

分類Dev

Spring Security oauth2-/ oauth / tokenルートにアクセスできません

分類Dev

Spring OAuth2でセキュリティを構成する:認証要求のアクセスが拒否されました

分類Dev

java.security.AccessControlException:アクセスが拒否されました( "java.lang.RuntimePermission" "accessClassInPackage.sun.reflect.annotation")Spring

分類Dev

java.security.AccessControlException:アクセスが拒否されました( "java.lang.RuntimePermission" "accessClassInPackage.sun.reflect.annotation")Spring

分類Dev

アクセスが拒否され、申し訳ありませんが、プラグインSpring SecurityコアをGrailsで2.0バージョンにアップグレードした後、このページを表示する権限がありません

分類Dev

spring-security-javaconfigでアクセス拒否ハンドラを追加するにはどうすればよいですか

分類Dev

Spring Security 5.1.1Spring-security-oauth2認証サーバーに接続するOAuth2クライアント

分類Dev

Spring SecurityのhasPermissionを使用している場合、ページへのアクセスが拒否されました

分類Dev

Spring Securityを使用するOAuth2プロバイダーは、jsonでアクセストークンを返します。XML形式でトークンを取得する必要があります

分類Dev

Spring Security Oauth2の認証コードからアクセストークンがフェッチされていませんか?アクセストークンの呼び出しが失敗し、ERR_TOO_MANY_REDIRECTSが発生しますか?

分類Dev

Spring Security OAuth2 | InsufficientAuthenticationException

分類Dev

Spring Security OAuth2:InsufficientAuthenticationException

分類Dev

spring security oauth2 javaconfig-ハンドラーのディスパッチに失敗しました。ネストされた例外はjava.lang.StackOverflowErrorです

分類Dev

spring security oauth2 javaconfig-ハンドラーのディスパッチに失敗しました。ネストされた例外はjava.lang.StackOverflowErrorです

分類Dev

spring security oauth2 javaconfig-ハンドラーのディスパッチに失敗しました。ネストされた例外はjava.lang.StackOverflowErrorです

分類Dev

Spring Security OAuth 2:JavaScriptクライアントでアクセストークンを使用する方法

Related 関連記事

  1. 1

    Spring Security-アクセスが拒否されました(ユーザーは匿名ではありません)spring-security-core-4.0.3.RELEASE

  2. 2

    Spring Security OAuth2:REST Webサービスでユーザー名を取得する

  3. 3

    Spring Boot Security 403「アクセス拒否」

  4. 4

    Spring SecurityとKeycloakによって「アクセスが拒否されました」というエラーが表示されるのはなぜですか?

  5. 5

    Spring Security Oauth2リソース所有者のパスワードフロー:RESTリクエストを送信すると、ユーザー詳細サービスは常にユーザー名ではなくクライアントIDを取得します

  6. 6

    Spring Security4.1のアップグレード-エラー403アクセスが拒否されました

  7. 7

    Spring Security4.1のアップグレード-エラー403アクセスが拒否されました

  8. 8

    Spring Security4.1のアップグレード-エラー403アクセスが拒否されました

  9. 9

    Spring Security Oauth2-InsufficientAuthenticationException:アクセストークンを取得するには認証が必要です(匿名は許可されていません)

  10. 10

    Spring Security OAuth2のリソースサーバーは必要ですか?

  11. 11

    Spring Security OAuth2は配列として返されるとスコープを解析できません

  12. 12

    Spring Security OAuth2ピュアリソースサーバー

  13. 13

    Spring Security - Oauth implementations

  14. 14

    Spring Security oauth2-/ oauth / tokenルートにアクセスできません

  15. 15

    Spring OAuth2でセキュリティを構成する:認証要求のアクセスが拒否されました

  16. 16

    java.security.AccessControlException:アクセスが拒否されました( "java.lang.RuntimePermission" "accessClassInPackage.sun.reflect.annotation")Spring

  17. 17

    java.security.AccessControlException:アクセスが拒否されました( "java.lang.RuntimePermission" "accessClassInPackage.sun.reflect.annotation")Spring

  18. 18

    アクセスが拒否され、申し訳ありませんが、プラグインSpring SecurityコアをGrailsで2.0バージョンにアップグレードした後、このページを表示する権限がありません

  19. 19

    spring-security-javaconfigでアクセス拒否ハンドラを追加するにはどうすればよいですか

  20. 20

    Spring Security 5.1.1Spring-security-oauth2認証サーバーに接続するOAuth2クライアント

  21. 21

    Spring SecurityのhasPermissionを使用している場合、ページへのアクセスが拒否されました

  22. 22

    Spring Securityを使用するOAuth2プロバイダーは、jsonでアクセストークンを返します。XML形式でトークンを取得する必要があります

  23. 23

    Spring Security Oauth2の認証コードからアクセストークンがフェッチされていませんか?アクセストークンの呼び出しが失敗し、ERR_TOO_MANY_REDIRECTSが発生しますか?

  24. 24

    Spring Security OAuth2 | InsufficientAuthenticationException

  25. 25

    Spring Security OAuth2:InsufficientAuthenticationException

  26. 26

    spring security oauth2 javaconfig-ハンドラーのディスパッチに失敗しました。ネストされた例外はjava.lang.StackOverflowErrorです

  27. 27

    spring security oauth2 javaconfig-ハンドラーのディスパッチに失敗しました。ネストされた例外はjava.lang.StackOverflowErrorです

  28. 28

    spring security oauth2 javaconfig-ハンドラーのディスパッチに失敗しました。ネストされた例外はjava.lang.StackOverflowErrorです

  29. 29

    Spring Security OAuth 2:JavaScriptクライアントでアクセストークンを使用する方法

ホットタグ

アーカイブ