通过MultiHttpSecurityConfig实现“oauth2Login()”和“httpBasic()”同一页面

问题描述 投票:0回答:4

如果用户点击/api/*,则会加载“formLogin()”页面;否则加载“httpBasic()”。这个设置工作正常。下面是它的代码。

    @Configuration
        public class SecurityConfig {
    
        @Configuration
        @Order(1)
        public static class SpecialSecurityConfig extends WebSecurityConfigurerAdapter {
    
            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http
                    .antMatcher("/api/**")
                    .authorizeRequests()
                        .anyRequest().authenticated()
                        .and()
                    .formLogin()
                        .loginPage("/api/login");         
            }
            
            @Override
            public void configure(WebSecurity web) throws Exception {
              web.ignoring().antMatchers("/", "/css/**");
            }
        }
    
        @Configuration
        public static class RegularSecurityConfig extends WebSecurityConfigurerAdapter {
    
            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http
                    .authorizeRequests()
                        .anyRequest().authenticated()
                        .and()
                    .httpBasic();
            }
            
            @Override
            public void configure(WebSecurity web) throws Exception {
              web.ignoring().antMatchers("/", "/css/**");
            }
        }
    
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                    .withUser("user")
                    .password("{noop}pass")
                    .roles("USER");
        }
    }

现在我想删除“formLogin()”并将其替换为“oauth2Login()”。之后,当我单击谷歌链接时,它会加载“httpBasic()”登录页面。如果用户点击google,应该会转到google登录页面。请帮我解决这个问题。下面是它的代码。

        http
        .antMatcher("/api/**")
        .authorizeRequests()
        .anyRequest().authenticated()
        .and()
        .oauth2Login()
        .loginPage("/api/oauth_login")
        .permitAll();

oauth_login.html

    <body>
    <div class="container">
    <h1>Social Login</h1>
    <p><a href="/oauth2/authorization/google">Google</a></p>
    </div>
    </body>
spring-boot spring-security oauth-2.0 google-oauth spring-security-oauth2
4个回答
1
投票

您指定匹配

"/api/**"
的请求应使用 OAuth 2 登录通过
SpecialSecurityConfig
进行保护,所有其他请求应使用 HTTP basic 通过
RegularSecurityConfig
进行保护。

由于

"/oauth2/authorization/google"
"/api/**"
不匹配,因此使用 HTTP basic 进行保护。

一种选择是将用于授权请求的基本 URI 更改为以

"/api/"
开头(默认为
"/oauth2/authorization/{registrationId}"
)。

您可能还想自定义

loginProcessingUrl
authorizationRequestResolver

public void configure(HttpSecurity http) throws Exception {
    http
        .antMatcher("/api/**")
        .authorizeRequests(authorize -> authorize
            .anyRequest().authenticated()
        )
        .oauth2Login(oauth2 -> oauth2
            .loginProcessingUrl("/api/login/oauth2/code/*")
            .loginPage("/api/oauth_login")
            .authorizationEndpoint(ae -> ae
                .baseUri("/api/oauth2/authorization/{registrationId}")
                .authorizationRequestResolver(getAuthorizationRequestResolver())
            )
        );
}

private OAuth2AuthorizationRequestResolver getAuthorizationRequestResolver() {
    return new DefaultOAuth2AuthorizationRequestResolver(
        this.clientRegistrationRepository,
        "/api/oauth2/authorization");
}

然后您还可以更新您的登录表单

<p><a href="/api/oauth2/authorization/google">Google</a></p>

1
投票

现在我可以加载谷歌登录页面了。添加凭据后,页面重定向到 Whitelabel 错误页面。

Oauth2 代码

http
            .antMatcher("/api/**")
            .authorizeRequests(authorize -> authorize.anyRequest().authenticated())
            .oauth2Login(oauth2 -> oauth2.loginProcessingUrl("/api/login/oauth2/code/*")
                    .loginPage("/api/oauth_login").permitAll()
                    .authorizationEndpoint(a -> a.baseUri("/api/oauth2/authorization")
                            .authorizationRequestResolver(                                    
                                    getAuthorizationRequestResolver())
                            )
            );

错误->

2021-03-11 15:02:53.319 调试 11762 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : GET "/login/oauth2/code/google?state=Ds-x92t6fpHo8BINK_xYba3fpidheKQSHBaTdctOPRE%3D&code =4%2F0AY0e-g6i-tfqlpBREW45ufRPQEOu-aM7VjIf7VzKOBVMSXrvLkaxB5U2A72dAOxxEUnN1Q&scope=email+profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fau第%2个Fuserinfo .email&authuser=0&hd=wearenoetic.com&prompt=consent",参数={masked}

2021-03-11 15:02:53.321 DEBUG 11762 --- [nio-8080-exec-2] o.s.w.s.handler.SimpleUrlHandlerMapping :映射到 ResourceHttpRequestHandler [类路径资源 [META-INF/resources/],类路径资源 [ resources/]、类路径资源[static/]、类路径资源[public/]、ServletContext资源[/]]

2021-03-11 15:02:53.346 DEBUG 11762 --- [nio-8080-exec-2] o.s.w.s.r.ResourceHttpRequestHandler:找不到资源

2021-03-11 15:02:53.346 调试 11762 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet:已完成 404 NOT_FOUND

2021-03-11 15:02:53.348 DEBUG 11762 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet:“错误”调度 GET“/error?state=Ds-x92t6fpHo8BINK_xYba3fpidheKQSHBaTdctOPRE%3D&code= 4%2F0AY0e-g6i-tfqlpBREW45ufRPQEOu-aM7VjIf7VzKOBVMSXrvLkaxB5U2A72dAOxxEUnN1Q&scope=电子邮件+个人资料+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fau第%2Fuserinfo。 email&authuser=0&hd=wearenoetic.com&prompt=consent",参数={masked}

2021-03-11 15:02:53.349 DEBUG 11762 --- [nio-8080-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping :映射到 org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)

2021-03-11 15:02:53.373 调试 11762 --- [nio-8080-exec-2] o.s.w.s.v.ContentNegotiatingViewResolver :选择“text/html”给定 [text/html, text/html;q=0.8]

2021-03-11 15:02:53.374 DEBUG 11762 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet:退出“错误”调度,状态 404


0
投票

我参考以下网址并修改我的代码

Oauth2Login 仅适用于特定网址

http 
        .authorizeRequests()
        .antMatchers("/api/**").authenticated()        
        .anyRequest().authenticated()
        .and()
        .oauth2Login()
        .loginPage("/api/oauth_login")
        .defaultSuccessUrl("/api/home")
        .permitAll();

普通 URL(/api/* 除外)也会加载 google 登录页面。


0
投票

禁用基本登录和表单登录。示例安全配置如下所示;

 .formLogin()
                .disable()
            .httpBasic()
                .disable()
            .exceptionHandling()
                .authenticationEntryPoint(new RestAuthenticationEntryPoint())
                .and()
            .authorizeRequests()
                .antMatchers("/auth/**", "/oauth2/**")
                    .permitAll()
                .anyRequest()
                    .authenticated()
                .and()
            .oauth2Login()
                .authorizationEndpoint()
                    .baseUri("/oauth2/authorize")
                    .and()
                .redirectionEndpoint()
                .baseUri("/oauth2/callback/*")

从前端调用此端点(Google/Facebook 按钮应链接到以下链接)
http://localhost:8080/oauth2/authorize/{provider}?redirect_uri=

遵循此指南。这正是您正在寻找的。

© www.soinside.com 2019 - 2024. All rights reserved.