Spring Security OAuth2実装で成功したOAuth2認証にCookieを設定する

VRuter:

https://spring.io/guides/tutorials/spring-boot-oauth2/で提供されるガイドに従って、ややシンプルなOAuth2で保護されたWebアプリケーションを実装しています

ログインが成功した後、いくつかの任意のCookieを設定して、フロントエンドブラウザーアプリケーションの処理を簡略化する必要があります。

現在、OAuth2を使用してGoogleアカウントでユーザーを認証する作業設定があります。

HttpSecurity oauth2Login().successHandler()は自分のWebSecurityConfigurerAdapter configure()機能で使用するつもりでしたが、ClientRegistrationRepository提供されておらず、自動配線することができないようです。

そのガイドに示されている実装にログイン成功ロジックを追加する方法について文書化されている標準的なアプローチを見つけることができなかったようです。

これは私のメインアプリケーションクラスです。OAuth2クライアントはapplication.ymlファイルで構成されます。

@SpringBootApplication
@EnableOAuth2Client
public class RestApplication extends WebSecurityConfigurerAdapter {

    @Autowired
    LogoutSuccessHandler logoutHandler;

    @Autowired
    OAuth2ClientContext oauth2ClientContext;

    public static void main(String[] args) {
        SpringApplication.run(RestApplication.class, args);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
        .antMatcher("/**").authorizeRequests()
        .antMatchers("/", "/login**", "/error**", "/webapp/**").permitAll()
        .anyRequest().authenticated()
        .and().addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class)
        .logout().logoutSuccessUrl("/").invalidateHttpSession(true).clearAuthentication(true).deleteCookies("JSESSIONID").logoutSuccessHandler(logoutHandler)
        // @formatter:on
    }

    private Filter ssoFilter() {
        OAuth2ClientAuthenticationProcessingFilter authFilter = new OAuth2ClientAuthenticationProcessingFilter(
                "/login");

        OAuth2RestTemplate oAuthTemplate = new OAuth2RestTemplate(oAuth2ResourceDetails(), oauth2ClientContext);
        UserInfoTokenServices tokenServices = new UserInfoTokenServices(oAuth2Resource().getUserInfoUri(),
                oAuth2ResourceDetails().getClientId());

        authFilter.setRestTemplate(oAuthTemplate);
        tokenServices.setRestTemplate(oAuthTemplate);
        authFilter.setTokenServices(tokenServices);

        return authFilter;
    }

    @Bean
    @ConfigurationProperties("oauth.client")
    public AuthorizationCodeResourceDetails oAuth2ResourceDetails() {
        return new AuthorizationCodeResourceDetails();
    }

    @Bean
    @ConfigurationProperties("oauth.resource")
    public ResourceServerProperties oAuth2Resource() {
        return new ResourceServerProperties();
    }

    @Bean
    public FilterRegistrationBean<OAuth2ClientContextFilter> oauth2ClientFilterRegistration(
            OAuth2ClientContextFilter filter) {
        FilterRegistrationBean<OAuth2ClientContextFilter> registration = new FilterRegistrationBean<OAuth2ClientContextFilter>();
        registration.setFilter(filter);
        registration.setOrder(-100);
        return registration;
    }
}

特に、ユーザープリンシパルオブジェクトにアクセスした後で、認証が成功したときに一度発生するロジックを追加する正しい方法は何でしょうか。

VRuter:

私はOAuth2ClientAuthenticationProcessingFilter実装をさらに掘り下げて、次の可能な解決策を見つけました。

SessionAuthenticationStrategyデフォルトでは実装されていないカスタムをプラグインすることが可能です。インターフェイスのドキュメントには次のように記載されています。

認証が発生したときのHttpSession関連の動作のプラグ可能なサポートを許可します。

ssoFilter()次のように変更しました。

private Filter ssoFilter() {
        OAuth2ClientAuthenticationProcessingFilter authFilter = new OAuth2ClientAuthenticationProcessingFilter(
                "/login");

        authFilter.setSessionAuthenticationStrategy(new SessionAuthenticationStrategy() {
            @Override
            public void onAuthentication(Authentication authentication, HttpServletRequest request,
                    HttpServletResponse response) throws SessionAuthenticationException {
                LinkedHashMap<String, Object> userDets = (LinkedHashMap<String, Object>) ((OAuth2Authentication) authentication)
                        .getUserAuthentication().getDetails();
                response.addCookie(new Cookie("authenticated", userDets.get("email").toString()));
            }
        });

        OAuth2RestTemplate oAuthTemplate = new OAuth2RestTemplate(oAuth2ResourceDetails(), oauth2ClientContext);
        UserInfoTokenServices tokenServices = new UserInfoTokenServices(oAuth2Resource().getUserInfoUri(),
                oAuth2ResourceDetails().getClientId());

        authFilter.setRestTemplate(oAuthTemplate);
        tokenServices.setRestTemplate(oAuthTemplate);
        authFilter.setTokenServices(tokenServices);

        return authFilter;
    }

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

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

編集
0

コメントを追加

0

関連記事

分類Dev

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

分類Dev

Spring Security - oAuth2 実装のための UserDetailsService?

分類Dev

Spring Security OAuth2 | InsufficientAuthenticationException

分類Dev

Spring Security OAuth2:InsufficientAuthenticationException

分類Dev

Spring Security OAuth2でさまざまなユーザータイプを認証する

分類Dev

Spring Security OAuth2のauth_code付与で匿名認証は可能ですか?

分類Dev

JHipster、Spring Security、およびoauth2を使用した認証リダイレクトの制御

分類Dev

Spring SecurityはOAuth2トークンを生成するために何を使用しますか?

分類Dev

Migrating from Spring Boot Oauth2 to Spring Security 5

分類Dev

Spring boot 2.0.3 + Security + Oauth2 autoconfigure

分類Dev

Incremental authorization for Google OAuth2 Sign in with Spring Security

分類Dev

Spring Security Oauth 2.xからのOAuth2 Spring Security 5.2.xアクセス認証済みoauth / token_keyが403を取得

分類Dev

Spring Security OAuth2はJSONを受け入れる

分類Dev

同じリソースへのSpring Security OAuth2とLdap認証

分類Dev

Spring Boot Security OAuth2 Get Access_token from Cookie

分類Dev

OAuth2を使用したSpring Security 5レストクライアント

分類Dev

oAuth2 Spring Security を介して認証 (プリンシパル) オブジェクトを取得しますか?

分類Dev

Spring Security + Spring Sessionで認証をtrueに設定する

分類Dev

Spring Security OAuth2: how to add multiple Security Filter Chain of type ResourceServerConfigurer?

分類Dev

Spring Security - Oauth implementations

分類Dev

Spring Boot Security OAuth2アプリの特定のクラスに対してのみOAuth2を有効にするにはどうすればよいですか?

分類Dev

Spring Boot Security OAuth2:WebSecurityConfigurerAdapter:302 / errorにリダイレクト

分類Dev

GoogleでのSpring Security OAuth2ログイン

分類Dev

Spring-security @ PreAuthorizeアノテーションとOAuth2を使用してRESTAPIを保護する

分類Dev

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

分類Dev

Spring Boot + Angularで外部OAuth2認証を処理する方法

分類Dev

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

分類Dev

Spring Security-Oauthの実装

分類Dev

Spring BootとOAuth 2によるSpring Security

Related 関連記事

  1. 1

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

  2. 2

    Spring Security - oAuth2 実装のための UserDetailsService?

  3. 3

    Spring Security OAuth2 | InsufficientAuthenticationException

  4. 4

    Spring Security OAuth2:InsufficientAuthenticationException

  5. 5

    Spring Security OAuth2でさまざまなユーザータイプを認証する

  6. 6

    Spring Security OAuth2のauth_code付与で匿名認証は可能ですか?

  7. 7

    JHipster、Spring Security、およびoauth2を使用した認証リダイレクトの制御

  8. 8

    Spring SecurityはOAuth2トークンを生成するために何を使用しますか?

  9. 9

    Migrating from Spring Boot Oauth2 to Spring Security 5

  10. 10

    Spring boot 2.0.3 + Security + Oauth2 autoconfigure

  11. 11

    Incremental authorization for Google OAuth2 Sign in with Spring Security

  12. 12

    Spring Security Oauth 2.xからのOAuth2 Spring Security 5.2.xアクセス認証済みoauth / token_keyが403を取得

  13. 13

    Spring Security OAuth2はJSONを受け入れる

  14. 14

    同じリソースへのSpring Security OAuth2とLdap認証

  15. 15

    Spring Boot Security OAuth2 Get Access_token from Cookie

  16. 16

    OAuth2を使用したSpring Security 5レストクライアント

  17. 17

    oAuth2 Spring Security を介して認証 (プリンシパル) オブジェクトを取得しますか?

  18. 18

    Spring Security + Spring Sessionで認証をtrueに設定する

  19. 19

    Spring Security OAuth2: how to add multiple Security Filter Chain of type ResourceServerConfigurer?

  20. 20

    Spring Security - Oauth implementations

  21. 21

    Spring Boot Security OAuth2アプリの特定のクラスに対してのみOAuth2を有効にするにはどうすればよいですか?

  22. 22

    Spring Boot Security OAuth2:WebSecurityConfigurerAdapter:302 / errorにリダイレクト

  23. 23

    GoogleでのSpring Security OAuth2ログイン

  24. 24

    Spring-security @ PreAuthorizeアノテーションとOAuth2を使用してRESTAPIを保護する

  25. 25

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

  26. 26

    Spring Boot + Angularで外部OAuth2認証を処理する方法

  27. 27

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

  28. 28

    Spring Security-Oauthの実装

  29. 29

    Spring BootとOAuth 2によるSpring Security

ホットタグ

アーカイブ