The dependencies of some of the beans in the application context form a cycle: - spring-boot

2022-12-31T00:48:58.789+05:30 ERROR 10168 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
The dependencies of some of the beans in the application context form a cycle:
┌──->──┐
| authenticationManager defined in class path resource [com/ecommerce/admin/config/AdminConfiguration.class]
└──<-──┘
Action:
Despite circular references being allowed, the dependency cycle between beans could not be broken. Update your application to remove the dependency cycle.
Process finished with exit code 0
package com.ecommerce.admin.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
#EnableWebSecurity
#Configuration
public class AdminConfiguration {
#Bean
public UserDetailsService userDetailsService() {
return new AdminServiceConfig();
}
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public AuthenticationManager authenticationManager(AuthenticationManager authenticationManager) throws Exception {
return authenticationManager;
}
#Bean
public DaoAuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(userDetailsService());
provider.setPasswordEncoder(passwordEncoder());
return provider;
}
#Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeHttpRequests()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/do-login")
.defaultSuccessUrl("/admin/index")
.permitAll()
.and()
.logout()
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login/logout")
.permitAll();
DefaultSecurityFilterChain build = http.build();
return build;
}
}
package com.ecommerce.admin.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
#EnableWebSecurity
#Configuration
public class AdminConfiguration {
#Bean
public UserDetailsService userDetailsService() {
return new AdminServiceConfig();
}
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public AuthenticationManager authenticationManager(AuthenticationManager authenticationManager) throws Exception {
return authenticationManager;
}
#Bean
public DaoAuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(userDetailsService());
provider.setPasswordEncoder(passwordEncoder());
return provider;
}
#Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeHttpRequests()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/do-login")
.defaultSuccessUrl("/admin/index")
.permitAll()
.and()
.logout()
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login/logout")
.permitAll();
DefaultSecurityFilterChain build = http.build();
return build;
}
}

Circular dependency issue is coming because of this Bean present inside AdminConfiguration class. Here in method argument you are passing an instance of AuthenticationManager and also creating another instance of AuthenticationManager using #Bean annotation. This is incorrect, please remove this and try again.
#Bean
public AuthenticationManager authenticationManager(AuthenticationManager authenticationManager) throws Exception {
return authenticationManager;
}

Related

The method antMatchers(String) is undefined for the type

package com.codewitheshan.blog.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.codewitheshan.blog.security.CustomUserDetailService;
import com.codewitheshan.blog.security.JwtAuthenticationEntryPoint;
import com.codewitheshan.blog.security.JwtAuthenticationFilter;
#Configuration
#EnableWebSecurity
public class SecurityConfig {
#Autowired
private CustomUserDetailService customUserDetailService;
#Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
#Autowired
private JwtAuthenticationFilter jwtAuthenticationFilter;
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeHttpRequests()
.antMatchers("/api/v1/auth/login").permitAll()
.anyRequest()
.authenticated()
.and()
.exceptionHandling()
.authenticationEntryPoint(this.jwtAuthenticationEntryPoint)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(this.jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
auth.userDetailsService(this.customUserDetailService).passwordEncoder(passwordEncoder());
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public AuthenticationManager authenticationManagerBean(AuthenticationConfiguration configuration) throws Exception {
return configuration.getAuthenticationManager();
}
}
There is error showing in antMatchers
**I'm getting an error for "antMatchers". It is not recognised. I have tied searching but did not get any thing related to this.
Error is:
The method antMatchers(String) is undefined for the type AuthorizeHttpRequestsConfigurer.AuthorizationManagerRequestMatcherRegistry
How to fix it? **
This method has changed to :
.requestMatchers({your-matcher})
So, in your case :
http
.csrf()
.disable()
.authorizeHttpRequests()
.requestMatchers("/api/v1/auth/login").permitAll()
.anyRequest()
.authenticated()
// ...
More information : https://docs.spring.io/spring-security/reference/servlet/authorization/authorize-http-requests.html
I hope this has helped you

UnsatisfiedDependencyException

need your help to optimize and solve my issue trying to implement oauth2.
I try to implement it on my backend, i received some code from to add in my project but i got an issue that i can't resolve even by looking over google.
First issue when compiling
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'authorizationServerConfiguration':
Unsatisfied dependency expressed through field
'authenticationManager'; nested exception is
org.springframework.beans.factory.BeanCurrentlyInCreationException:
Error creating bean with name 'securityConfiguration': Requested bean
is currently in creation: Is there an unresolvable circular reference?
Second issue when compiling
Caused by:
org.springframework.beans.factory.BeanCurrentlyInCreationException:
Error creating bean with name 'securityConfiguration': Requested bean
is currently in creation: Is there an unresolvable circular reference?
AuthorizationServerConfiguration.java
package com.kfm.management.security.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private TokenStore tokenStore;
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("angular")
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT", "USER")
.scopes("read", "write")
.autoApprove(true)
.secret(passwordEncoder.encode("angular-secret"));
}
#Autowired
private UserDetailsService userDetailsService;
#Autowired
public PasswordEncoder passwordEncoder;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager)
.tokenStore(tokenStore);
endpoints.userDetailsService(userDetailsService);
}
#Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
//
}
SecurityConfiguration
package com.kfm.management.security.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.ArrayList;
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Autowired
public UserDetailsService customUserDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and().csrf().disable()
.authorizeRequests().and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout() // Metodo get pues he desabilitado CSRF
.permitAll();
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// configure AuthenticationManager so that it knows from where to load
// user for matching credentials
// Use BCryptPasswordEncoder
auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
}
#Bean
CorsConfigurationSource corsConfigurationSource() {
ArrayList<String> allowed = new ArrayList<String>();
allowed.add("*");
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(allowed);
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");
configuration.setAllowCredentials(false);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
I have to admit that i'm a bit lost with all that configuration steps!
Thks for your help!

Spring security configure issue

Here is my configuration in security and the problem is all the requests such as /v3/api-docs will be redirected to /login or /register.I don't know why and Please help.
package reg.example.confgure;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import reg.example.model.User;
import reg.example.service.UserRepositoryUserDetailService;
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private UserRepositoryUserDetailService userDetailsService;
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v3/api-docs",
"/swagger-resources/configuration/ui",
"/swagger-resources",
"/swagger-resources/configuration/security",
"/swagger-ui.html");
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(this.userDetailsService)
.passwordEncoder(User.PASSWORD_ENCODER);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
// 关闭csrf防护
.csrf().disable()
.headers().frameOptions().disable()
.and()
.authorizeRequests()
.antMatchers("/user/**").permitAll()
.antMatchers("/v3/api-docs", "/swagger-resources/configuration/ui",
"/swagger-resources", "/swagger-resources/configuration/security",
"/swagger-ui.html", "/webjars/**").permitAll()
.antMatchers("/", "/login","/register").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
}
package reg.example.confgure;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
#Configuration
public class MvcConfig implements WebMvcConfigurer {
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
registry.addViewController("/register").setViewName("register");
}
}

I want to see the login page first even any user want access any other page need to redirect to login page in spring security

Here is the sample controller. My problem is basically when i am entering the base url it is redirecting to inner page not in the log in page. What i want. What should i do to achieve this.
Here is the sample controller. My problem is basically when i am entering the base url it is redirecting to inner page not in the log in page. What i want. What should i do to achieve this.
package com.sushovan.security.controller;
import javax.validation.groups.ConvertGroup;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class HomeController {
#RequestMapping("/")
public String home() {
return "home.jsp";
}
#RequestMapping("/login")
public String loginPage() {
return "login.jsp";
}
#RequestMapping("/logout-success")
public String logoutPage() {
return "logout.jsp";
}
}
Here is the sample Security Configuration class.Mostly all configuration have been done here.
package com.sushovan.security.config;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.AntPathMatcher;
#Configuration
#EnableWebSecurity
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
/**This is for authentication from database**/
#Bean
public AuthenticationProvider authProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(userDetailsService);
//provider.setPasswordEncoder(NoOpPasswordEncoder.getInstance());//This is for not use any encryption
provider.setPasswordEncoder(new BCryptPasswordEncoder());//This is for BCryptPasswordEncoder
return provider;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().antMatchers("/login")
.permitAll()
.and()
.formLogin()
.loginPage("/login")
.usernameParameter("userName").passwordParameter("password")
.permitAll()
.and()
.logout().invalidateHttpSession(true)
.clearAuthentication(true)
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/logout-success").permitAll();
}
}
Spring security filters algorithm works like this ;
is web resource protected ?
is user authenticated ?
is user authorized ?
So if its not authenticated it redirect request to login page, which is what you want.
So you should update your configure method
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.usernameParameter("userName").passwordParameter("password")
.permitAll()
.and()
.logout().invalidateHttpSession(true)
.clearAuthentication(true)
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/logout-success").permitAll();
}
can you please try this and let me know if it works ?

org.springframework.security.access.AccessDeniedException: Access is denied

I'm trying to implement OAuth in my spring boot rest server. Here's my configurations
configuration\AuthorizationServerConfig.java
package com.vcomm.server.configuration;
import com.vcomm.server.service.util.CustomAuthenticationKeyGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.event.EventListener;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import javax.annotation.Resource;
import javax.sql.DataSource;
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Resource(name = "roomUserDetailsService")
UserDetailsService userDetailsService;
#Autowired
private DataSource dataSource;
#Bean
public TokenStore tokenStore() {
JdbcTokenStore tokenStore = new JdbcTokenStore(dataSource);
tokenStore.setAuthenticationKeyGenerator(new CustomAuthenticationKeyGenerator());
return tokenStore;
}
#Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("123");
return converter;
}
#Bean
#Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore());
defaultTokenServices.setSupportRefreshToken(true);
defaultTokenServices.setAuthenticationManager(authenticationManager);
return defaultTokenServices;
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource);
}
#Autowired
private AuthenticationManager authenticationManager;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints
.pathMapping("/oauth/authorize", Constant.AUTH_V1 + "/oauth/authorize")
.pathMapping("/oauth/check_token", Constant.AUTH_V1 + "/oauth/check_token")
.pathMapping("/oauth/confirm_access", Constant.AUTH_V1 + "/auth/v1/oauth/confirm_access")
.pathMapping("/oauth/error", Constant.AUTH_V1 + "/oauth/error")
.pathMapping("/oauth/token", Constant.AUTH_V1 + "/oauth/token")
.pathMapping("/oauth/token_key", Constant.AUTH_V1 + "/oauth/token_key")
.tokenStore(tokenStore())
.userDetailsService(userDetailsService)
.authenticationManager(authenticationManager);
}
#EventListener
public void authSuccessEventListener(AuthenticationSuccessEvent authorizedEvent){
// write custom code here for login success audit
System.out.println("User Oauth2 login success");
System.out.println("This is success event : "+authorizedEvent.getSource());
}
#Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
oauthServer.allowFormAuthenticationForClients();
}
}
configuration\ResourceServerConfig.java
package com.vcomm.server.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
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;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
#Configuration
#EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/**")
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.exceptionHandling()
.accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
#Autowired
TokenStore tokenStore;
#Override
public void configure(ResourceServerSecurityConfigurer config) {
config.tokenServices(tokenServicesResourceServer());
}
#Autowired
private AuthenticationManager authenticationManager;
#Bean
public DefaultTokenServices tokenServicesResourceServer() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore);
defaultTokenServices.setAuthenticationManager(authenticationManager);
return defaultTokenServices;
}
}
configuration\SpringWebSecurityConfig.java
package com.vcomm.server.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringWebSecurityConfig extends WebSecurityConfigurerAdapter {
#Configuration
#Order(1001)
public static class superAdminWebSecurityConfig extends WebSecurityConfigurerAdapter {
#Resource(name = "emUserDetailsService")
UserDetailsService emUserDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement()
.maximumSessions(2)
.maxSessionsPreventsLogin(true);
http
.csrf().disable();
http
.httpBasic()
.disable();
http
.authorizeRequests()
.antMatchers("/superadmin/api/v1/login")
.permitAll();
http
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/superadmin/api/v1/logout", "POST"))
.deleteCookies("JSESSIONID")
.logoutSuccessHandler((httpServletRequest, httpServletResponse, authentication) -> httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT))
.invalidateHttpSession(true);
http
.antMatcher("/superadmin/**")
.authorizeRequests()
.antMatchers("/superadmin/**").hasAuthority("ADMIN_PRIVILEGE");
}
#Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
#Override
#Bean
#Primary
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean(name = "emAuthenticationProvider")
public AuthenticationProvider emAuthenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(passwordEncoder());
provider.setUserDetailsService(emUserDetailsService);
return provider;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(emUserDetailsService);
auth.authenticationProvider(emAuthenticationProvider());
}
}
#Configuration
#Order(1002)
public static class adminWebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement()
.maximumSessions(2)
.maxSessionsPreventsLogin(true);
http
.csrf().disable();
http
.httpBasic()
.disable();
http
.authorizeRequests()
.antMatchers("/admin/api/v1/login")
.permitAll();
http
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/admin/api/v1/logout", "POST"))
.deleteCookies("JSESSIONID")
.logoutSuccessHandler((httpServletRequest, httpServletResponse, authentication) -> httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT))
.invalidateHttpSession(true);
http
.antMatcher("/admin/**")
.authorizeRequests()
.antMatchers("/admin/**").hasAuthority("ORGANISATION_PRIVILEGE");
}
}
#Configuration
#Order(1003)
public static class appWebSecurityConfig extends WebSecurityConfigurerAdapter{
#Resource(name = "roomUserDetailsService")
UserDetailsService roomUserDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement()
.maximumSessions(2)
.maxSessionsPreventsLogin(true);
http
.csrf().disable();
http
.httpBasic()
.disable();
http
.authorizeRequests()
.antMatchers("/api/v1/*/login")
.permitAll();
http
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/api/v1/logout", "POST"))
.deleteCookies("JSESSIONID")
.logoutSuccessHandler((httpServletRequest, httpServletResponse, authentication) -> httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT))
.invalidateHttpSession(true);
http
.antMatcher("/api/**")
.authorizeRequests()
.antMatchers("/api/**").hasAuthority("ROOM_PRIVILEGE");
}
#Bean(name = "roomPasswordEncoder")
public PasswordEncoder roomPasswordEncoder(){
return new BCryptPasswordEncoder();
}
#Override
#Bean(name = "roomAuthenticationManager")
public AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManagerBean();
}
#Bean(name = "roomAuthenticationProvider")
public AuthenticationProvider roomAuthenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(roomPasswordEncoder());
provider.setUserDetailsService(roomUserDetailsService);
return provider;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(roomUserDetailsService);
auth.authenticationProvider(roomAuthenticationProvider());
}
}
}
While calling http://localhost:5524/auth/v1/oauth/authorize?client_id=clientapp&response_type=code&scope=read
I got this response
{
"timestamp": 1582545217836,
"status": 401,
"error": "Unauthorized",
"message": "Unauthorized",
"path": "/auth/v1/oauth/authorize"
}
I'm using jdbc to manage state of oauth here's my oauth table data
+-----------+--------------+---------------+-------+-------------------------------------------+-------------------------+-------------+-----------------------+------------------------+
| client_id | resource_ids | client_secret | scope | authorized_grant_types | web_server_redirect_uri | authorities | access_token_validity | refresh_token_validity |
+-----------+--------------+---------------+-------+-------------------------------------------+-------------------------+-------------+-----------------------+------------------------+
| clientapp | NULL | secret | read | password,authorization_code,refresh_token | http://localhost:8081/ | room | 36000 | 36000 |
+-----------+--------------+---------------+-------+-------------------------------------------+-------------------------+-------------+-----------------------+------------------------+
I think this error log is enough to answer this question because I'm new to spring boot.
If need additional information please ask through commants
It was my misunderstanding OAuth workflow. While calling this URL it's trying to authenticate me before grant. But postman showed just 401 instead of giving a redirect response. Calling it via a browser will redirect me to the login page for authentication.
Posting this answer to help guys new to OAuth and spring boot :)

Resources