簡體   English   中英

如何在自定義 Web 安全配置中使用 Spring OAuth2 客戶端身份驗證過濾器

[英]How to use Spring OAuth2 Client authentication filter with custom web security configuration

我有基本的WebOAuth2 Client Spring 啟動應用程序。 只需將以下內容添加到application.yml Google SignIn 即可。

spring:
    security:
        oauth2:
            client:
                registration:
                    google:
                        clientId: 1135813....
                        clientSecret: esdf...

但是當添加自定義WebSecurityConfigurerAdapter時,OAuth2 身份驗證不再有效。

@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser(User.withUsername("user").password("123").roles("USER"));
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests() //
                .antMatchers("/").permitAll() //
                .antMatchers("/login/social").permitAll() //
                .antMatchers("/login/social/google").permitAll() //
                .anyRequest().authenticated();
    }
}

我想在 OAuth2 身份驗證處理默認重定向 URL ( /login/oauth2/code/google ) 時保留基本身份驗證。 我如何實現這一目標?

下面是關於@EnableResourceServer 的演示


import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;



@Configuration
@EnableResourceServer
public class ResServerConfig extends ResourceServerConfigurerAdapter{


    @Override
    public void configure(HttpSecurity http) throws Exception {
        final String[] urlPattern = {"/api/**"}; //eg.,  url protected by oauth2
        http
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // or SessionCreationPolicy.IF_REQUIRED for your required
            .and()
            .requestMatchers().antMatchers(urlPattern)
            .and()
            .authorizeRequests()
            .antMatchers(urlPattern)
            authenticated()
        ;

    }



}

暫無
暫無

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

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