I am trying to implement Basic Auth + oAuth2 in springboot, means some url should work like traditional way after login to system, and some should work on AOuth2.
Li
If you need different security setups for different parts of your application, you need to create separate Spring Security @Configuration
-s, where each one will configure just one authentication mechanism. Each configuration should specify the URIs it covers and the configurations need to be @Order
-ed. The configuration without the @Order annotation is considered the last - the fallback. It's described in the Spring Security reference manual.
So you will need three configurations:
http.antMatcher("/superAdmin/**")...
with @Order(1)
.http.antMatcher("/api/vi/**")...
with @Order(2)
.@Order
annotation specified.This has been actually explained in Spring security Guide under Multiple HttpSecurity
@Configuration
@Order(1) 2
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/**") 3
.authorizeRequests()
.anyRequest().hasRole("ADMIN")
.and()
.httpBasic();
}
}
@Configuration 4
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin();
}
}
And to secure OAuth2 endpoints using Resource Server, you can configure your resource server as follows
@Configuration
@EnableResourceServer
@Order(1)
protected static class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId("resource-id");
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.requestMatcher(new OAuthRequestedMatcher())
.authorizeRequests().anyRequest().fullyAuthenticated();
}
}
private static class OAuthRequestedMatcher implements RequestMatcher {
public boolean matches(HttpServletRequest request) {
String auth = request.getHeader("Authorization");
boolean haveOauth2Token = (auth != null) && auth.startsWith("Bearer");
boolean haveAccessToken = request.getParameter("access_token")!=null;
return haveOauth2Token || haveAccessToken;
}
}
Great Question In order to use oAuth with spring security, I think it's there is no any way to use this. You need to create two different projects one is for general sec. and one is for oAuth.