Spring boot 2 - OAuth 2 my access_token does not persist
I'm working on a spring boot project that uses OAuth 2 authentication (spring boot 1.5). In my solution, I store access token in my postgresql database, on table oauth_access_token.
I migrated my project from spring boot 1.5 to spring boot 2. I did not change anything in my configuration, and I can authenticate myself, but the persistence of the token does not work, my table "oauth_access_token" remain empty.
Here is my OAuth configuration class:
@Configuration
public class OAuth2ServerConfiguration
private final DataSource dataSource;
public OAuth2ServerConfiguration(DataSource dataSource)
this.dataSource = dataSource;
@Bean
public JdbcTokenStore tokenStore()
return new JdbcTokenStore(dataSource);
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter
private final TokenStore tokenStore;
private final Http401UnauthorizedEntryPoint http401UnauthorizedEntryPoint;
private final AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler;
private final CorsFilter corsFilter;
public ResourceServerConfiguration(TokenStore tokenStore, Http401UnauthorizedEntryPoint http401UnauthorizedEntryPoint,
AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler, CorsFilter corsFilter)
this.tokenStore = tokenStore;
this.http401UnauthorizedEntryPoint = http401UnauthorizedEntryPoint;
this.ajaxLogoutSuccessHandler = ajaxLogoutSuccessHandler;
this.corsFilter = corsFilter;
@Override
public void configure(HttpSecurity http) throws Exception
http
.exceptionHandling()
.authenticationEntryPoint(http401UnauthorizedEntryPoint)
.and()
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(ajaxLogoutSuccessHandler)
.and()
.csrf()
.disable()
.addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
.headers()
.frameOptions().disable()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers("/api/authenticate").permitAll()
.antMatchers("/api/register").permitAll()
.antMatchers("/api/profile-info").permitAll()
.antMatchers("/api/**").authenticated()
.antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/v2/api-docs/**").permitAll()
.antMatchers("/swagger-resources/configuration/ui").permitAll()
.antMatchers("/swagger-ui/index.html").hasAuthority(AuthoritiesConstants.ADMIN);
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception
resources.resourceId("res_appli").tokenStore(tokenStore);
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter
private final AuthenticationManager authenticationManager;
private final TokenStore tokenStore;
private final DataSource dataSource;
public AuthorizationServerConfiguration(@Qualifier("authenticationManagerBean") AuthenticationManager authenticationManager,
TokenStore tokenStore, DataSource dataSource)
this.authenticationManager = authenticationManager;
this.tokenStore = tokenStore;
this.dataSource = dataSource;
@Bean
protected AuthorizationCodeServices authorizationCodeServices()
return new JdbcAuthorizationCodeServices(dataSource);
@Bean
public ApprovalStore approvalStore()
return new JdbcApprovalStore(dataSource);
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception
endpoints
.authorizationCodeServices(authorizationCodeServices())
.approvalStore(approvalStore())
.tokenStore(tokenStore)
.authenticationManager(authenticationManager);
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception
oauthServer.allowFormAuthenticationForClients();
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception
clients.jdbc(dataSource);
And my security configuration class:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter
private final AuthenticationManagerBuilder authenticationManagerBuilder;
private final UserDetailsService userDetailsService;
public SecurityConfiguration(AuthenticationManagerBuilder authenticationManagerBuilder, UserDetailsService userDetailsService)
this.authenticationManagerBuilder = authenticationManagerBuilder;
this.userDetailsService = userDetailsService;
@PostConstruct
public void init()
try
authenticationManagerBuilder
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
catch (Exception e)
throw new BeanInitializationException("Security configuration failed", e);
@Bean
public AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler()
return new AjaxLogoutSuccessHandler();
@Bean
public Http401UnauthorizedEntryPoint http401UnauthorizedEntryPoint()
return new Http401UnauthorizedEntryPoint();
@Bean
public PasswordEncoder passwordEncoder()
return new BCryptPasswordEncoder();
@Override
public void configure(WebSecurity web) throws Exception
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**")
.antMatchers("/app/**/*.js,html")
.antMatchers("/i18n/**")
.antMatchers("/content/**")
.antMatchers("/swagger-ui/index.html")
.antMatchers("/api/register")
.antMatchers("/api/activate")
.antMatchers("/api/account/reset-password/init")
.antMatchers("/api/account/reset-password/finish")
.antMatchers("/test/**");
@Override
public void configure(HttpSecurity http) throws Exception
http
.httpBasic().realmName("yvidya")
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.requestMatchers().antMatchers("/oauth/authorize")
.and()
.authorizeRequests()
.antMatchers("/oauth/authorize").authenticated();
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception
return super.authenticationManagerBean();
@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension()
return new SecurityEvaluationContextExtension();
And my UserDetailService
@Component("userDetailsService")
public class DomainUserDetailsService implements UserDetailsService
private final Logger log = LoggerFactory.getLogger(DomainUserDetailsService.class);
private final UserRepository userRepository;
public DomainUserDetailsService(UserRepository userRepository)
this.userRepository = userRepository;
@Override
@Transactional
public UserDetails loadUserByUsername(final String login)
log.debug("Authenticating ", login);
String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
Optional<User> userFromDatabase = userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin);
return userFromDatabase.map(user ->
if (!user.getActivated())
throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream()
.map(authority -> new SimpleGrantedAuthority(authority.getName()))
.collect(Collectors.toList());
return new CustomUser(user, lowercaseLogin, user.getPassword(), grantedAuthorities);
).orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the " +
"database"));
And my file properties contains:
security:
basic:
enabled: false
oauth2:
resource:
filter-order: 3
I change nothing in my code, I can get an access token, but it isn't persist un database, I don't know why
Do you have an idea?
Thank you
java spring-boot spring-security oauth-2.0 spring-security-oauth2
add a comment |
I'm working on a spring boot project that uses OAuth 2 authentication (spring boot 1.5). In my solution, I store access token in my postgresql database, on table oauth_access_token.
I migrated my project from spring boot 1.5 to spring boot 2. I did not change anything in my configuration, and I can authenticate myself, but the persistence of the token does not work, my table "oauth_access_token" remain empty.
Here is my OAuth configuration class:
@Configuration
public class OAuth2ServerConfiguration
private final DataSource dataSource;
public OAuth2ServerConfiguration(DataSource dataSource)
this.dataSource = dataSource;
@Bean
public JdbcTokenStore tokenStore()
return new JdbcTokenStore(dataSource);
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter
private final TokenStore tokenStore;
private final Http401UnauthorizedEntryPoint http401UnauthorizedEntryPoint;
private final AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler;
private final CorsFilter corsFilter;
public ResourceServerConfiguration(TokenStore tokenStore, Http401UnauthorizedEntryPoint http401UnauthorizedEntryPoint,
AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler, CorsFilter corsFilter)
this.tokenStore = tokenStore;
this.http401UnauthorizedEntryPoint = http401UnauthorizedEntryPoint;
this.ajaxLogoutSuccessHandler = ajaxLogoutSuccessHandler;
this.corsFilter = corsFilter;
@Override
public void configure(HttpSecurity http) throws Exception
http
.exceptionHandling()
.authenticationEntryPoint(http401UnauthorizedEntryPoint)
.and()
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(ajaxLogoutSuccessHandler)
.and()
.csrf()
.disable()
.addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
.headers()
.frameOptions().disable()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers("/api/authenticate").permitAll()
.antMatchers("/api/register").permitAll()
.antMatchers("/api/profile-info").permitAll()
.antMatchers("/api/**").authenticated()
.antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/v2/api-docs/**").permitAll()
.antMatchers("/swagger-resources/configuration/ui").permitAll()
.antMatchers("/swagger-ui/index.html").hasAuthority(AuthoritiesConstants.ADMIN);
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception
resources.resourceId("res_appli").tokenStore(tokenStore);
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter
private final AuthenticationManager authenticationManager;
private final TokenStore tokenStore;
private final DataSource dataSource;
public AuthorizationServerConfiguration(@Qualifier("authenticationManagerBean") AuthenticationManager authenticationManager,
TokenStore tokenStore, DataSource dataSource)
this.authenticationManager = authenticationManager;
this.tokenStore = tokenStore;
this.dataSource = dataSource;
@Bean
protected AuthorizationCodeServices authorizationCodeServices()
return new JdbcAuthorizationCodeServices(dataSource);
@Bean
public ApprovalStore approvalStore()
return new JdbcApprovalStore(dataSource);
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception
endpoints
.authorizationCodeServices(authorizationCodeServices())
.approvalStore(approvalStore())
.tokenStore(tokenStore)
.authenticationManager(authenticationManager);
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception
oauthServer.allowFormAuthenticationForClients();
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception
clients.jdbc(dataSource);
And my security configuration class:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter
private final AuthenticationManagerBuilder authenticationManagerBuilder;
private final UserDetailsService userDetailsService;
public SecurityConfiguration(AuthenticationManagerBuilder authenticationManagerBuilder, UserDetailsService userDetailsService)
this.authenticationManagerBuilder = authenticationManagerBuilder;
this.userDetailsService = userDetailsService;
@PostConstruct
public void init()
try
authenticationManagerBuilder
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
catch (Exception e)
throw new BeanInitializationException("Security configuration failed", e);
@Bean
public AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler()
return new AjaxLogoutSuccessHandler();
@Bean
public Http401UnauthorizedEntryPoint http401UnauthorizedEntryPoint()
return new Http401UnauthorizedEntryPoint();
@Bean
public PasswordEncoder passwordEncoder()
return new BCryptPasswordEncoder();
@Override
public void configure(WebSecurity web) throws Exception
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**")
.antMatchers("/app/**/*.js,html")
.antMatchers("/i18n/**")
.antMatchers("/content/**")
.antMatchers("/swagger-ui/index.html")
.antMatchers("/api/register")
.antMatchers("/api/activate")
.antMatchers("/api/account/reset-password/init")
.antMatchers("/api/account/reset-password/finish")
.antMatchers("/test/**");
@Override
public void configure(HttpSecurity http) throws Exception
http
.httpBasic().realmName("yvidya")
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.requestMatchers().antMatchers("/oauth/authorize")
.and()
.authorizeRequests()
.antMatchers("/oauth/authorize").authenticated();
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception
return super.authenticationManagerBean();
@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension()
return new SecurityEvaluationContextExtension();
And my UserDetailService
@Component("userDetailsService")
public class DomainUserDetailsService implements UserDetailsService
private final Logger log = LoggerFactory.getLogger(DomainUserDetailsService.class);
private final UserRepository userRepository;
public DomainUserDetailsService(UserRepository userRepository)
this.userRepository = userRepository;
@Override
@Transactional
public UserDetails loadUserByUsername(final String login)
log.debug("Authenticating ", login);
String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
Optional<User> userFromDatabase = userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin);
return userFromDatabase.map(user ->
if (!user.getActivated())
throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream()
.map(authority -> new SimpleGrantedAuthority(authority.getName()))
.collect(Collectors.toList());
return new CustomUser(user, lowercaseLogin, user.getPassword(), grantedAuthorities);
).orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the " +
"database"));
And my file properties contains:
security:
basic:
enabled: false
oauth2:
resource:
filter-order: 3
I change nothing in my code, I can get an access token, but it isn't persist un database, I don't know why
Do you have an idea?
Thank you
java spring-boot spring-security oauth-2.0 spring-security-oauth2
add a comment |
I'm working on a spring boot project that uses OAuth 2 authentication (spring boot 1.5). In my solution, I store access token in my postgresql database, on table oauth_access_token.
I migrated my project from spring boot 1.5 to spring boot 2. I did not change anything in my configuration, and I can authenticate myself, but the persistence of the token does not work, my table "oauth_access_token" remain empty.
Here is my OAuth configuration class:
@Configuration
public class OAuth2ServerConfiguration
private final DataSource dataSource;
public OAuth2ServerConfiguration(DataSource dataSource)
this.dataSource = dataSource;
@Bean
public JdbcTokenStore tokenStore()
return new JdbcTokenStore(dataSource);
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter
private final TokenStore tokenStore;
private final Http401UnauthorizedEntryPoint http401UnauthorizedEntryPoint;
private final AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler;
private final CorsFilter corsFilter;
public ResourceServerConfiguration(TokenStore tokenStore, Http401UnauthorizedEntryPoint http401UnauthorizedEntryPoint,
AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler, CorsFilter corsFilter)
this.tokenStore = tokenStore;
this.http401UnauthorizedEntryPoint = http401UnauthorizedEntryPoint;
this.ajaxLogoutSuccessHandler = ajaxLogoutSuccessHandler;
this.corsFilter = corsFilter;
@Override
public void configure(HttpSecurity http) throws Exception
http
.exceptionHandling()
.authenticationEntryPoint(http401UnauthorizedEntryPoint)
.and()
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(ajaxLogoutSuccessHandler)
.and()
.csrf()
.disable()
.addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
.headers()
.frameOptions().disable()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers("/api/authenticate").permitAll()
.antMatchers("/api/register").permitAll()
.antMatchers("/api/profile-info").permitAll()
.antMatchers("/api/**").authenticated()
.antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/v2/api-docs/**").permitAll()
.antMatchers("/swagger-resources/configuration/ui").permitAll()
.antMatchers("/swagger-ui/index.html").hasAuthority(AuthoritiesConstants.ADMIN);
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception
resources.resourceId("res_appli").tokenStore(tokenStore);
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter
private final AuthenticationManager authenticationManager;
private final TokenStore tokenStore;
private final DataSource dataSource;
public AuthorizationServerConfiguration(@Qualifier("authenticationManagerBean") AuthenticationManager authenticationManager,
TokenStore tokenStore, DataSource dataSource)
this.authenticationManager = authenticationManager;
this.tokenStore = tokenStore;
this.dataSource = dataSource;
@Bean
protected AuthorizationCodeServices authorizationCodeServices()
return new JdbcAuthorizationCodeServices(dataSource);
@Bean
public ApprovalStore approvalStore()
return new JdbcApprovalStore(dataSource);
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception
endpoints
.authorizationCodeServices(authorizationCodeServices())
.approvalStore(approvalStore())
.tokenStore(tokenStore)
.authenticationManager(authenticationManager);
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception
oauthServer.allowFormAuthenticationForClients();
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception
clients.jdbc(dataSource);
And my security configuration class:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter
private final AuthenticationManagerBuilder authenticationManagerBuilder;
private final UserDetailsService userDetailsService;
public SecurityConfiguration(AuthenticationManagerBuilder authenticationManagerBuilder, UserDetailsService userDetailsService)
this.authenticationManagerBuilder = authenticationManagerBuilder;
this.userDetailsService = userDetailsService;
@PostConstruct
public void init()
try
authenticationManagerBuilder
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
catch (Exception e)
throw new BeanInitializationException("Security configuration failed", e);
@Bean
public AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler()
return new AjaxLogoutSuccessHandler();
@Bean
public Http401UnauthorizedEntryPoint http401UnauthorizedEntryPoint()
return new Http401UnauthorizedEntryPoint();
@Bean
public PasswordEncoder passwordEncoder()
return new BCryptPasswordEncoder();
@Override
public void configure(WebSecurity web) throws Exception
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**")
.antMatchers("/app/**/*.js,html")
.antMatchers("/i18n/**")
.antMatchers("/content/**")
.antMatchers("/swagger-ui/index.html")
.antMatchers("/api/register")
.antMatchers("/api/activate")
.antMatchers("/api/account/reset-password/init")
.antMatchers("/api/account/reset-password/finish")
.antMatchers("/test/**");
@Override
public void configure(HttpSecurity http) throws Exception
http
.httpBasic().realmName("yvidya")
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.requestMatchers().antMatchers("/oauth/authorize")
.and()
.authorizeRequests()
.antMatchers("/oauth/authorize").authenticated();
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception
return super.authenticationManagerBean();
@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension()
return new SecurityEvaluationContextExtension();
And my UserDetailService
@Component("userDetailsService")
public class DomainUserDetailsService implements UserDetailsService
private final Logger log = LoggerFactory.getLogger(DomainUserDetailsService.class);
private final UserRepository userRepository;
public DomainUserDetailsService(UserRepository userRepository)
this.userRepository = userRepository;
@Override
@Transactional
public UserDetails loadUserByUsername(final String login)
log.debug("Authenticating ", login);
String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
Optional<User> userFromDatabase = userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin);
return userFromDatabase.map(user ->
if (!user.getActivated())
throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream()
.map(authority -> new SimpleGrantedAuthority(authority.getName()))
.collect(Collectors.toList());
return new CustomUser(user, lowercaseLogin, user.getPassword(), grantedAuthorities);
).orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the " +
"database"));
And my file properties contains:
security:
basic:
enabled: false
oauth2:
resource:
filter-order: 3
I change nothing in my code, I can get an access token, but it isn't persist un database, I don't know why
Do you have an idea?
Thank you
java spring-boot spring-security oauth-2.0 spring-security-oauth2
I'm working on a spring boot project that uses OAuth 2 authentication (spring boot 1.5). In my solution, I store access token in my postgresql database, on table oauth_access_token.
I migrated my project from spring boot 1.5 to spring boot 2. I did not change anything in my configuration, and I can authenticate myself, but the persistence of the token does not work, my table "oauth_access_token" remain empty.
Here is my OAuth configuration class:
@Configuration
public class OAuth2ServerConfiguration
private final DataSource dataSource;
public OAuth2ServerConfiguration(DataSource dataSource)
this.dataSource = dataSource;
@Bean
public JdbcTokenStore tokenStore()
return new JdbcTokenStore(dataSource);
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter
private final TokenStore tokenStore;
private final Http401UnauthorizedEntryPoint http401UnauthorizedEntryPoint;
private final AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler;
private final CorsFilter corsFilter;
public ResourceServerConfiguration(TokenStore tokenStore, Http401UnauthorizedEntryPoint http401UnauthorizedEntryPoint,
AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler, CorsFilter corsFilter)
this.tokenStore = tokenStore;
this.http401UnauthorizedEntryPoint = http401UnauthorizedEntryPoint;
this.ajaxLogoutSuccessHandler = ajaxLogoutSuccessHandler;
this.corsFilter = corsFilter;
@Override
public void configure(HttpSecurity http) throws Exception
http
.exceptionHandling()
.authenticationEntryPoint(http401UnauthorizedEntryPoint)
.and()
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(ajaxLogoutSuccessHandler)
.and()
.csrf()
.disable()
.addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
.headers()
.frameOptions().disable()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers("/api/authenticate").permitAll()
.antMatchers("/api/register").permitAll()
.antMatchers("/api/profile-info").permitAll()
.antMatchers("/api/**").authenticated()
.antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/v2/api-docs/**").permitAll()
.antMatchers("/swagger-resources/configuration/ui").permitAll()
.antMatchers("/swagger-ui/index.html").hasAuthority(AuthoritiesConstants.ADMIN);
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception
resources.resourceId("res_appli").tokenStore(tokenStore);
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter
private final AuthenticationManager authenticationManager;
private final TokenStore tokenStore;
private final DataSource dataSource;
public AuthorizationServerConfiguration(@Qualifier("authenticationManagerBean") AuthenticationManager authenticationManager,
TokenStore tokenStore, DataSource dataSource)
this.authenticationManager = authenticationManager;
this.tokenStore = tokenStore;
this.dataSource = dataSource;
@Bean
protected AuthorizationCodeServices authorizationCodeServices()
return new JdbcAuthorizationCodeServices(dataSource);
@Bean
public ApprovalStore approvalStore()
return new JdbcApprovalStore(dataSource);
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception
endpoints
.authorizationCodeServices(authorizationCodeServices())
.approvalStore(approvalStore())
.tokenStore(tokenStore)
.authenticationManager(authenticationManager);
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception
oauthServer.allowFormAuthenticationForClients();
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception
clients.jdbc(dataSource);
And my security configuration class:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter
private final AuthenticationManagerBuilder authenticationManagerBuilder;
private final UserDetailsService userDetailsService;
public SecurityConfiguration(AuthenticationManagerBuilder authenticationManagerBuilder, UserDetailsService userDetailsService)
this.authenticationManagerBuilder = authenticationManagerBuilder;
this.userDetailsService = userDetailsService;
@PostConstruct
public void init()
try
authenticationManagerBuilder
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
catch (Exception e)
throw new BeanInitializationException("Security configuration failed", e);
@Bean
public AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler()
return new AjaxLogoutSuccessHandler();
@Bean
public Http401UnauthorizedEntryPoint http401UnauthorizedEntryPoint()
return new Http401UnauthorizedEntryPoint();
@Bean
public PasswordEncoder passwordEncoder()
return new BCryptPasswordEncoder();
@Override
public void configure(WebSecurity web) throws Exception
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**")
.antMatchers("/app/**/*.js,html")
.antMatchers("/i18n/**")
.antMatchers("/content/**")
.antMatchers("/swagger-ui/index.html")
.antMatchers("/api/register")
.antMatchers("/api/activate")
.antMatchers("/api/account/reset-password/init")
.antMatchers("/api/account/reset-password/finish")
.antMatchers("/test/**");
@Override
public void configure(HttpSecurity http) throws Exception
http
.httpBasic().realmName("yvidya")
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.requestMatchers().antMatchers("/oauth/authorize")
.and()
.authorizeRequests()
.antMatchers("/oauth/authorize").authenticated();
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception
return super.authenticationManagerBean();
@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension()
return new SecurityEvaluationContextExtension();
And my UserDetailService
@Component("userDetailsService")
public class DomainUserDetailsService implements UserDetailsService
private final Logger log = LoggerFactory.getLogger(DomainUserDetailsService.class);
private final UserRepository userRepository;
public DomainUserDetailsService(UserRepository userRepository)
this.userRepository = userRepository;
@Override
@Transactional
public UserDetails loadUserByUsername(final String login)
log.debug("Authenticating ", login);
String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
Optional<User> userFromDatabase = userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin);
return userFromDatabase.map(user ->
if (!user.getActivated())
throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream()
.map(authority -> new SimpleGrantedAuthority(authority.getName()))
.collect(Collectors.toList());
return new CustomUser(user, lowercaseLogin, user.getPassword(), grantedAuthorities);
).orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the " +
"database"));
And my file properties contains:
security:
basic:
enabled: false
oauth2:
resource:
filter-order: 3
I change nothing in my code, I can get an access token, but it isn't persist un database, I don't know why
Do you have an idea?
Thank you
java spring-boot spring-security oauth-2.0 spring-security-oauth2
java spring-boot spring-security oauth-2.0 spring-security-oauth2
asked Nov 15 '18 at 15:21
user1450740user1450740
99112
99112
add a comment |
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53322609%2fspring-boot-2-oauth-2-my-access-token-does-not-persist%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53322609%2fspring-boot-2-oauth-2-my-access-token-does-not-persist%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown