I have Spring Boot application with basic auth enabled. UserServiceDetails consumed from DB. For the unit-testing purpose, I want to mock it, so the data will be consumed from elsewhere.
How can I do it?
My question is not how to mock UserServiceDetails itself but how to mock the way that I can use it to test Controllers with basic auth.
The below is my SpringSecurity config:
#Configuration
#EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final String[] AUTH_WHITELIST = {
// -- swagger ui
"/",
"/csrf",
"/swagger-resources",
"/swagger-resources/**",
"/configuration/ui",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**"
};
#Autowired
#Qualifier("customUserDetailsService")
private UserDetailsService userDetailsService;
private final static Integer bCryptEncryptionLevel = 8;
#Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder(bCryptEncryptionLevel);
}
public SecurityConfig() {
super();
}
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder authManagerBuilder) throws Exception {
authManagerBuilder.authenticationProvider(authenticationProvider());
authManagerBuilder.userDetailsService(userDetailsService)
.passwordEncoder(bCryptPasswordEncoder());
}
#Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(bCryptPasswordEncoder());
return authenticationProvider;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers(AUTH_WHITELIST).permitAll()
// allow default swagger docket
.regexMatchers("\\A/v2/api-docs\\Z").permitAll()
// require auth for any other swagger docket
.regexMatchers("\\A/v2/api-docs?.*\\Z").authenticated()
.antMatchers("/**").authenticated()
.and()
.httpBasic()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
To summarize, how can I mock UserServiceDetails into SpringSecurity config, so I can unit-test controllers into my Spring Boot app?
I think you should use #Profile, UserDetailesService is an interface creates two implementation of UserDetailesService, one for test and another for the rest of the case
#Component
#Profile("test")
public class UserDetailesServiceTestImpl implements UserDetailesService{
}
#Component
#Profile("!test")
public class UserDetailesServiceImpl implements UserDetailesService{
}
Related
I am currently refactoring the security configuration removing WebSecurityConfigurerAdapter and am currently stuck on a config using two Basic Auth configurations with different user stores on different paths.
Current configuration looks like this and works fine:
#EnableWebSecurity
public class SecurityConfig {
#Order(1)
#Configuration
public static class BasicSpecialAuth extends WebSecurityConfigurerAdapter {
// some code
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// some code
auth.inMemoryAuthentication().withUser(specialUser.getId()).password(passwordEncoder().encode(specialUser.getPassword())).roles("SPECIALROLE");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic()
.and()
.antMatcher("/very-special-path/**")
//. more code
.authorizeRequests(r -> r
.anyRequest().authenticated());
}
}
#Order(2)
#Configuration
public static class BasicAppAuth extends WebSecurityConfigurerAdapter {
// some code
#Bean
public CustomUserDetailsService customUserDetailsService() {
return new CustomUserDetailsService(userRepository);
}
#Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailsService())
.passwordEncoder(encoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic()
.and()
//. more code
.authorizeRequests(auth -> auth
.anyRequest().authenticated());
}
}
}
As can be seen, /very-special-path uses InMemoryAuthentication set up at start by configuration.
All other paths should be authenticated using users from local database. Due to possible duplicates on usernames I am not able to use the database for /very-special-path users too. Requirement is to have these separated.
Following documentation it was quite simple to change this on our apps providing Basic Auth and JWT Auth on different path. But with both using Basic Auth and different user stores, I have no idea how to set up configuration properly.
Any help would be appreciated.
Edit, the current config:
#Configuration
public class SecurityConfig {
// some code
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public UserDetailsService customUserDetailsService() {
return new CustomUserDetailsService(userRepository);
}
#Bean
public InMemoryUserDetailsManager inMemoryUserDetailsService() {
// more code
UserDetails healthUser = User.withUsername(specialUser.getId())
.password(passwordEncoder().encode(specialUser.getPassword()))
.roles("SPECIALROLE")
.build();
return new InMemoryUserDetailsManager(healthUser);
}
#Bean
#Order(1)
public SecurityFilterChain specialFilterChain(HttpSecurity http) throws Exception {
http.httpBasic()
.and()
.antMatcher("/very-special-path/**")
.authorizeRequests(auth -> auth
.anyRequest().authenticated());
return http.build();
}
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.httpBasic()
.and()
.authorizeRequests(auth -> auth
.anyRequest().authenticated());
return http.build();
}
}
The app starts without any Warning or Error.
Both chains are mentioned in the log:
o.s.s.web.DefaultSecurityFilterChain : Will secure any request with ..
o.s.s.web.DefaultSecurityFilterChain : Will secure Ant [pattern='/very-special-path/**'] with ..
But authentication does not work. Checked for different endpoints and with different users. Every request gets an 401.
This config misses the assignment of the UserDetails to the specific filter chain. Is there a way to do so?
Based on the extra information you provided, there are only a couple of tweaks needed to get your configuration working. Take a look at this blog post that details common patterns for replacing WebSecurityConfigurerAdapter with the component-based approach, specifically the local AuthenticationManager.
For the special/health user, you can manually construct a local authentication manager so as not to collide with the global one declared as an #Bean. Here's a full example:
#EnableWebSecurity
public class SecurityConfig {
// ...
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public UserDetailsService customUserDetailsService() {
return new CustomUserDetailsService(userRepository);
}
#Bean
#Order(1)
public SecurityFilterChain specialFilterChain(HttpSecurity http, PasswordEncoder passwordEncoder) throws Exception {
http
.mvcMatcher("/very-special-path/**")
.authorizeRequests((authorize) -> authorize
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults())
.authenticationManager(specialAuthenticationManager(passwordEncoder));
return http.build();
}
private AuthenticationManager specialAuthenticationManager(PasswordEncoder passwordEncoder) {
UserDetailsService userDetailsService = specialUserDetailsService(passwordEncoder);
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setPasswordEncoder(passwordEncoder);
authenticationProvider.setUserDetailsService(userDetailsService);
return new ProviderManager(authenticationProvider);
}
private UserDetailsService specialUserDetailsService(PasswordEncoder passwordEncoder) {
UserDetails specialUser = User.withUsername("specialuser")
.password(passwordEncoder.encode("specialpassword"))
.roles("SPECIALROLE")
.build();
return new InMemoryUserDetailsManager(specialUser);
}
#Bean
#Order(2)
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests((authorize) -> authorize
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults());
return http.build();
}
}
This is my admin controllers which i am not able to access
import mis.entity.User;
import mis.services.AdminService;
#Controller
#RequestMapping("/admin/")
public class AdminController {
#Autowired
private AdminService adminService;
#RequestMapping("adduser")
public String adduser() {
return "admin/adduser";
}
#RequestMapping(value = "do_register", method = RequestMethod.POST)
public String registerUser(#ModelAttribute("user") User user) {
System.out.println(user);
adminService.addUser(user);
return "redirect:/admin/adduser";
}}
This is happening after i configured spring security before activating spring security iwas able to access all routes.
#Configuration
#EnableAutoConfiguration
#EnableWebSecurity
public class MyConfig extends WebSecurityConfigurerAdapter {
#Bean
public UserDetailsService userDetailsService() {
return new UserDetailsServiceImpl();
}
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/new").hasAnyAuthority("ADMIN", "CREATOR")
.antMatchers("/admin/**").hasAnyAuthority("ADMIN", "EDITOR")
.antMatchers("/delete/**").hasAuthority("ADMIN")
.antMatchers("/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().permitAll()
.and()
.logout().permitAll()
.and()
.exceptionHandling().accessDeniedPage("/403")
;
}}
There is one more controller which i can access.
But i cant access this admincontroller i think that /admin/ is causing problem.
Edited code in MyConfig
http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN").antMatchers("/user/**").hasRole("USER")
.antMatchers("/**").permitAll().and().formLogin()
.loginPage("/signin")
.defaultSuccessUrl("/home")
.and().csrf().disable();
I have spring boot app with thymeleaf. I am using spring security formLogin method for security and now I need to add JWT for only some APIs.
#EnableWebSecurity
public class SecurityConfigurations {
#Autowired
UserDetailsServiceImpl userDetails;
#Bean
DaoAuthenticationProvider provider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(encoder());
provider.setUserDetailsService(userDetails);
return provider;
}
#Bean
PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
#Configuration
#Order(1)
public class JWTSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
#Autowired
private JwtRequestFilter jwtRequestFilter;
#Autowired
DaoAuthenticationProvider provider;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(provider);
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable()
.authorizeRequests().antMatchers("/api/user/authenticate").permitAll()
.antMatchers("/api/user/**").hasRole("USER")
.and().
exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// Add a filter to validate the tokens with every request
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
}
#Configuration
public static class FormLoginConfigurationAdapter extends WebSecurityConfigurerAdapter {
#Autowired
DaoAuthenticationProvider provider;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(provider);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/admin/admins**").hasAnyRole("SADMIN").antMatchers("/admin/**")
.hasAnyRole("ADMIN", "SADMIN", "WADMIN").antMatchers("/rest/**")
.hasAnyRole("ADMIN", "SADMIN", "WADMIN", "USER").antMatchers("/user/**").hasAnyRole("USER")
.anyRequest().permitAll().and().formLogin().loginPage("/sign-in-up")
.loginProcessingUrl("/signInProcess").usernameParameter("phone").and().logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/")
.invalidateHttpSession(false).and().csrf().disable().cors();
}
}
}
by doing this JWT is working fine as just I need but the formlogin has stopped and calling "/signInProcess" now give 404:
NOTE: if I change the order and make formLogin #order(1) it works again but of course will not work.
Also I tried to combine them both like this now it is both works fine but the problem with exception handling if the JWT authentication error will return formlogin thymeleaf error page :
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/admin/admins**").hasAnyRole("SADMIN").antMatchers("/admin/**")
.hasAnyRole("ADMIN", "SADMIN", "WADMIN").antMatchers("/rest/**")
.hasAnyRole("ADMIN", "SADMIN", "WADMIN", "USER").antMatchers("/user/**").hasAnyRole("USER")
.antMatchers("/api/user/authenticate").permitAll()
.antMatchers("/api/user/**").hasRole("USER")
.anyRequest().permitAll().and().formLogin().loginPage("/sign-in-up")
.loginProcessingUrl("/signInProcess").usernameParameter("phone").and().logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/")
.invalidateHttpSession(false).and().csrf().disable().cors();
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
any suggestions to make this work. thank you.
Your WebSecurityConfigurerAdapters will process the incoming requests in order.
Since JWTSecurityConfig is annotated with #Order(1) it will process the requests first.
You have not specified a antMatcher for this Adapter, so it will match all requests.
This means that a request will never reach FormLoginConfigurationAdapter, since JWTSecurityConfig matches them all.
If you want JWTSecurityConfig to only apply to certain requests, you can specify an antMatcher in your security configuration.
Below is an example:
#EnableWebSecurity
public class SecurityConfigurations {
#Configuration
#Order(1)
public class JWTSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.requestMatchers(matchers -> matchers
.antMatchers("/api/**") // apply JWTSecurityConfig to requests matching "/api/**"
)
.authorizeRequests(authz -> authz
.anyRequest().authenticated()
)
.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
}
#Configuration
public class FormLoginConfigurationAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests(authz -> authz
.anyRequest().authenticated()
)
.formLogin();
}
}
}
For more details on multiple WebSecurityConfigurerAdapter, you can see the multiple HttpSecurity section in the Spring Security reference docs.
For more details on the difference between authorizeRequests() and requestMatchers(), you can see this Stack Overflow question.
I struggle to understand how to test the Spring Boot application with the Spring Security layer.
I have asked similar questions How to enforce Spring Security with MockitoJUnit runner? and How to mock customer user service details in Spring Security layer?
I have a custom implementation for UserDetailsService which take data from the database, so naturally, I want to take it from somewhere else during unit-testing phase
I want to test my web-layer to see if Spring Security works and if all other use-cases work as well.
How can I achieve both tasks above?
SecurityConfig class:
#Configuration
#EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final String[] AUTH_WHITELIST = {
// -- swagger ui
"/",
"/csrf",
"/swagger-resources",
"/swagger-resources/**",
"/configuration/ui",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**"
};
#Autowired
#Qualifier("customUserDetailsService")
private UserDetailsService userDetailsService;
private final static Integer bCryptEncryptionLevel = 8;
#Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder(bCryptEncryptionLevel);
}
public SecurityConfig() {
super();
}
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder authManagerBuilder) throws Exception {
authManagerBuilder.authenticationProvider(authenticationProvider());
authManagerBuilder.userDetailsService(userDetailsService)
.passwordEncoder(bCryptPasswordEncoder());
}
#Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(bCryptPasswordEncoder());
return authenticationProvider;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers(AUTH_WHITELIST).permitAll()
// allow default swagger docket
.regexMatchers("\\A/v2/api-docs\\Z").permitAll()
// require auth for any other swagger docket
.regexMatchers("\\A/v2/api-docs?.*\\Z").authenticated()
.antMatchers("/**").authenticated()
.and()
.httpBasic()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
CustomUserDetailsService class:
#Service("customUserDetailsService")
#Profile("!test")
public class CustomUserDetailsService implements UserDetailsService {
private final static Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);
private StringRedisTemplate redisTemplate;
private RedisProperties redisProperties;
#Autowired
public CustomUserDetailsService(RedisProperties redisProperties, StringRedisTemplate redisTemplate) {
this.redisProperties = redisProperties;
this.redisTemplate = redisTemplate;
}
#Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
// Do queries to DB and return user if such user exists
}
}
I also added CustomUserDetailsServiceTest class for the unit-testing purpose only into the same package but under src/test/java:
#Service("customUserDetailsService")
#Profile("test")
public class CustomUserDetailsServiceTest implements UserDetailsService {
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
#SuppressWarnings("serial")
Map<Object, Object> entries = new HashMap<Object, Object>(){{
put("username", username);
put("password_hash", "$2a$08$YjMcOsLmbbUB4DYPxqSAxOa3STLjEDovwd2..Uidwp.asyhSi8Y5u");
put("role", "ADMIN");
}};
UserEntity user = new UserEntity(entries);
return new HiccasoftApiUser(user);
}
}
How can I use custom implementation for customUserDetailsService in unit-tests while testing web-layer?
I am trying to configure Spring Security and OAuth2 on java config. I am using Spring Security version 4.0.4.RELEASE and OAuth2 version 2.0.11.RELEASE.
Spring Security config works well. Also I can get an access token with OAuth2 AuthorizationServer, but my ResourceServer does not work correctly. When I set the annotation #EnableResourceServer I can only check my access token and other URLs I cannot open (Security configuration and AuthorizationServer configuration do not work). I see the following error:
<oauth>
<error_description>
An Authentication object was not found in the SecurityContext
</error_description>
<error>unauthorized</error>
</oauth>
If I remove an annotation #EnableResourceServer, my ResourceServer does not check an access token. It just redirects to the authentication page.
This is my code:
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
public class GlobalSecurityConfig extends GlobalMethodSecurityConfiguration {
#Bean(name = "passwordEncoder")
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Autowired
#Qualifier("authUserDetailsService")
private UserDetailsService userDetailsService;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
#Autowired
#Qualifier("permissionEvaluator")
private PermissionEvaluator permissionEvaluator;
#Bean
public DefaultMethodSecurityExpressionHandler expressionHandler() {
DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
handler.setDefaultRolePrefix("");
handler.setPermissionEvaluator(permissionEvaluator);
return handler;
}
#Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
return expressionHandler();
}
}
SecurityConfig:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Bean(name = "clientAuthenticationEntryPoint")
public OAuth2AuthenticationEntryPoint oauthAuthenticationEntryPoint() {
OAuth2AuthenticationEntryPoint entry = new OAuth2AuthenticationEntryPoint();
entry.setRealmName("myapp/client");
entry.setTypeName("Basic");
return entry;
}
#Autowired
#Qualifier("webExpressionHandler")
private DefaultWebSecurityExpressionHandler expressionHandler;
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public SessionRegistry sessionRegistry() {
return new SessionRegistryImpl();
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/html/**", "/webapi/**");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.requestMatchers().antMatchers("/admin/**", "/**")
.and()
.authorizeRequests()
.expressionHandler(expressionHandler)
.antMatchers("/admin/**").access("hasRole('ADMINISTRATOR')")
.antMatchers("/1/admin/**").access("hasRole('ADMINISTRATOR')")
.antMatchers("/profile**").authenticated()
.antMatchers("/oauth/authorize").authenticated()
.and()
.formLogin().loginPage("/login")
.failureUrl("/login?error=1")
.loginProcessingUrl("/login-attempt")
.defaultSuccessUrl("/", false)
.and()
.sessionManagement()
.sessionFixation().migrateSession()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/")
.and()
.exceptionHandling()
.accessDeniedPage("/access-denied")
.and()
.csrf();
}
}
Oauth config:
#Configuration
public class Oauth {
#Configuration
#EnableResourceServer
public static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
private static final String RESOURCE_ID = "my_oauth_server";
#Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId(RESOURCE_ID);
}
#Override
public void configure(HttpSecurity http) throws Exception {
http
.anonymous().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.regexMatchers("/api/v0/.*").authenticated()
.antMatchers("/**").denyAll()
;
}
}
#Configuration
#EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private AuthorizationCodeServices verificationCodeService;
#Autowired
#Qualifier("clientDetails")
private ClientDetailsService clientDetailsService;
#Autowired
#Qualifier("tokenStore")
private TokenStore tokenStore;
#Bean(name = "tokenServices")
public DefaultTokenServices tokenServices() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setTokenStore(tokenStore);
tokenServices.setSupportRefreshToken(true);
tokenServices.setClientDetailsService(clientDetailsService);
return tokenServices;
}
#Bean
public ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter() throws Exception {
ClientCredentialsTokenEndpointFilter filter = new ClientCredentialsTokenEndpointFilter();
filter.setAuthenticationManager(authenticationManager);
return filter;
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(clientDetailsService);
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
endpoints.authorizationCodeServices(verificationCodeService);
endpoints.tokenServices(tokenServices());
endpoints.reuseRefreshTokens(true);
}
#Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("permitAll()");
oauthServer.checkTokenAccess("permitAll()");
oauthServer.realm("myapp/client");
oauthServer.addTokenEndpointAuthenticationFilter(clientCredentialsTokenEndpointFilter());
oauthServer.allowFormAuthenticationForClients();
}
}
}
So, ResourceServer config overlap other configuration. How can I fix it? I would be thankful for any help.
I see that you want to protect some endpoints with an access token, and other endpoints with normal form login.
Can you try restricting the applicability of your ResourceServerConfiguration to apply only to certain endpoints by something like: http.requestMatcher(new AntPathRequestMatcher("/api/v0/**")).... Do the same for SecurityConfig but for the endpoints you want it to take care of.