如果用户点击/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>
最佳答案
您指定匹配 "/api/**"
的请求应使用 OAuth 2 登录通过 SpecialSecurityConfig
进行保护,所有其他请求应通过 RegularSecurityConfig
使用 HTTP basic。
由于 “/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>
关于spring-boot - 通过MultiHttpSecurityConfig实现 "oauth2Login()"和 "httpBasic()"同一页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66559839/