I have updated recently to spring-security-3.2.0.RC2 from RC1, and according to the blog post the QUIESCENT_POST_PROCESSOR have been removed. Before I used to create an AuthenticationManager bean like this below:
#Bean(name = {"defaultAuthenticationManager", "authenticationManager"})
public AuthenticationManager defaultAuthenticationManager() throws Exception {
return new AuthenticationManagerBuilder(null).userDetailsService(context.getBean(MyUserDetailsService.class)).passwordEncoder(new Md5PasswordEncoder()).and().build();
}
so I've changed it to:
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws BeansException, Exception {
auth.userDetailsService(context.getBean(MyUserDetailsService.class)).passwordEncoder(new Md5PasswordEncoder());
}
but unfortunately I can't get hold of the AuthenticationManager any more. I'm also creating RememberMeAuthenticationFilter like this:
#Bean(name = { "defaultRememberMeAuthenticationFilter", "rememberMeAuthenticationFilter" })
protected RememberMeAuthenticationFilter defaultRememberMeAuthenticationFilter() throws Exception {
return new RememberMeAuthenticationFilter(defaultAuthenticationManager(), context.getBean(DefaultRememberMeServices.class));
}
so as you can see I need to get hold of AuthenticationManager, but I don't know how???
You really shouldn't need to get a hold of the AuthenticationManager. From the javadoc of HttpSecurity the following should work just fine:
#Configuration
#EnableWebSecurity
public class RememberMeSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**").hasRole("USER")
.and()
.formLogin()
.permitAll()
.and()
// Example Remember Me Configuration
.rememberMe();
}
}
Of course if you are using global AuthenticationManager, this will work too:
#Configuration
#EnableWebSecurity
public class RememberMeSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**").hasRole("USER")
.and()
.formLogin()
.permitAll()
.and()
// Example Remember Me Configuration
.rememberMe();
}
}
The only difference is the first example isolates the AuthenticationManger to the HttpSecurity where as the second example will allow the AuthenticationManager to be used by global method security or another HttpSecurity (WebSecurityConfigurerAdapter).
The reason this works is the .rememberMe() will automatically find the AuthenticationManager, UserDetailsService and use that when creating the RememberMeAuthenticationFilter. It also creates the appropriate RememberMeServices so there is no need to do that. Of course there are additional options on .rememberMe() if you want to customize it, so refer to the RememberMeConfigurer javadoc for additional options.
If you REALLY need a reference to the AuthenticationManager instance you can do the following:
#Configuration
#EnableWebSecurity
public class RememberMeSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private AuthenticationManagerBuilder auth;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
#Bean
public AuthenticationManager authenticationManager() {
return auth.build();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**").hasRole("USER")
.and()
.formLogin()
.permitAll()
.and()
// Example Remember Me Configuration
.rememberMe();
}
}
If you want to have multiple AuthenticationManager instances, you can do the following:
#Autowired
private ObjectPostProcessor<Object> opp;
public AuthenticationManager authenticationManager()
throws Exception {
return new AuthenticationManagerBuilder(opp)
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER").and()
.and()
.build();
}
public AuthenticationManager authenticationManager2()
throws Exception {
return new AuthenticationManagerBuilder(opp)
.inMemoryAuthentication()
.withUser("admin").password("password").roles("ADMIN").and()
.and()
.build();
}
NOTE This is almost the same as you had things before hand except instead of using the QUIESENT_POST_PROCESSOR you are using a real ObjectPostProcessor using the #Autowired annotation
PS: Thanks for giving RC2 a try!
The way to expose and get access to the AuthenticationManager bean is as follows:
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception
{
return super.authenticationManagerBean();
}
Related
filterOne is only for path /1 and filterTwo is only for /2.
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.antMatcher("/1")
.addFilterAfter(filterOneBean(), BasicAuthenticationFilter.class)
.authorizeRequests()
.and()
.antMatcher("/2")
.addFilterAfter(filterTwoBean(), BasicAuthenticationFilter.class)
.authorizeRequests()
.and();
/1 does not invoke filterOne or filterTwo, while /2 only filterOne is invoked. Why and how to fix it?
EDIT: The following configuration would still enter filterOne for /2
#SuppressWarnings("SpringJavaAutowiringInspection")
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class MultiHttpSecurityConfig {
#Bean
public FilterTwo setFilterTwo() {
return new FilterTwo();
}
#Bean
public FilterOne setFilterOne() {
return new FilterOne();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
}
#Configuration
#Order(1)
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
#Autowired
private FilterTwo filterTwo;
protected void configure(HttpSecurity http) throws Exception {
http.addFilterAfter(filterTwo, BasicAuthenticationFilter.class)
.antMatcher("/2")
.authorizeRequests()
.anyRequest()
.authenticated();
}
}
#Configuration
#Order(2)
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
#Autowired
private FilterOne filterOne;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterAfter(filterOne, BasicAuthenticationFilter.class)
.antMatcher("/1")
.authorizeRequests()
.anyRequest()
.authenticated();
}
}
}
I may restate what I am trying to achieve: /1 and /2 have different authentication rules, and they are implemented in an customized authentication filter, therefore they each have different filter chain.
EDIT 2: I found that filterTwo and One have different filterChain object id, and this is because setAuthentication method.
public class FilterTwo extends OncePerRequestFilter {
#Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain)
throws ServletException, IOException {
...
SecurityContextHolder.getContext().setAuthentication(authentication); // This causes filterTwo invoked.
chain.doFilter(request,response);
}
}
I'm developing a Spring Boot application where I'm trying to use the #PreAuthorize annotation to filter access to the User resource so that an User only can access to his own resource. Here is my UserRepository:
#Repository
#RepositoryRestResource
public interface MyUserRepository extends PagingAndSortingRepository<MyUser, UUID> {
#Override
#PreAuthorize("principal.getId().equals(#uuid)")
MyUser findOne(UUID uuid);
MyUser findByUsername(#Param("username") String username);
MyUser findByEmail(#Param("email") String email);
}
You can see the stack trace here.
Somewhere in the stacktrace references the class WebSecurityConfig line 42. This is the method configureAuthentication of the following class:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private RestAuthenticationEntryPoint unauthorizedHandler;
#Autowired
private BasicUserDetailsService userDetailsService;
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Autowired
public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder
.userDetailsService(this.userDetailsService)
.passwordEncoder(passwordEncoder());
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public JwtAuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
JwtAuthenticationTokenFilter authenticationTokenFilter = new JwtAuthenticationTokenFilter();
authenticationTokenFilter.setAuthenticationManager(authenticationManagerBean());
return authenticationTokenFilter;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
// we don't need CSRF because our token is invulnerable
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
// don't create session
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/login").permitAll()
.antMatchers(HttpMethod.POST, "/myUsers").permitAll()
.antMatchers(HttpMethod.PUT).authenticated()
.antMatchers(HttpMethod.POST).authenticated()
.antMatchers(HttpMethod.DELETE).authenticated()
.antMatchers(HttpMethod.PATCH).authenticated()
.anyRequest().permitAll();
// Custom JWT based security filter
http.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
http.addFilterBefore(new CORSFilter(), ChannelProcessingFilter.class);
}
}
Thank you!
Updating to Spring boot 1.4 has solved the problem.
We would like to apply Oauth2 based security for the Rest Controllers while the rest of the application will have Spring Security. Will that be possible? Can you provide any examples please?
It seems like WebSecurityConfigurerAdapter and ResourceServerConfigurerAdapter conflicting when both configured.
Thank you in advance.
Yes it's possible. Here the example template configuration code is given. Please change the required configs to your need. The key is to define Sub static classes of configuration with different order. Here i have considered any requests which is orginating from \api as a REST API call.
I have not checked the code by compiling it.
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true, proxyTargetClass = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
#Order(1)
#Configuration
public static class ApiWebSecurityConfig extends OAuth2ServerConfigurerAdapter{
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//Write the AuthenticationManagerBuilder codes for the OAuth
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.antMatcher("/api/**")
.authorizeRequests()
.anyRequest().authenticated()
.and()
.apply(new OAuth2ServerConfigurer())
.tokenStore(new InMemoryTokenStore())
.resourceId(applicationName);
}
}
}
#Order(2)
#Configuration
public static class FormWebSecurityConfig extends WebSecurityConfigurerAdapter{
#Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
//Write the AuthenticationManagerBuilder codes for the Normal authentication
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable() //HTTP with Disable CSRF
.authorizeRequests() //Authorize Request Configuration
.anyRequest().authenticated()
.and() //Login Form configuration for all others
.formLogin()
.loginPage("/login").permitAll()
.and() //Logout Form configuration
.logout().permitAll();
}
}
}
I'm trying to do an example using spring-boot with spring security. My idea is to create a web app and also provide an API, I would like to both have security; so I need to create a multi http web security configuration however it is not working.
I followed this link http://docs.spring.io/spring-security/site/docs/3.2.x/reference/htmlsingle/#multiple-httpsecurity but no success. And, I'm getting this error
Error creating bean with name 'webSecurityConfiguration': Injection of autowired dependencies failed; nested exception is java.lang.IllegalStateException: Cannot apply org.springframework.security.config.annotation.authentication.configurers.provisioning.InMemoryUserDetailsManagerConfigurer to already built object
The configuration that I'm using is the following:
#Configuration
#Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
#EnableGlobalAuthentication
#EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfiguration {
#Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("12345").roles("USER").and()
.withUser("admin").password("12345").roles("USER", "ADMIN");
}
#Configuration
#Order(1)
public static class ApiConfigurationAdapter extends
WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/**")
.authorizeRequests()
.anyRequest().hasRole("ADMIN")
.and()
.httpBasic();
}
}
#Configuration
#Order(2)
public static class WebConfigurationAdapter extends
WebSecurityConfigurerAdapter {
#Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/resources/**");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.and()
.logout().permitAll();
}
}
}
Thanks in advance
after a lot of reading I found something that works for me:
#Configuration
#Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
#EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfiguration extends GlobalAuthenticationConfigurerAdapter {
#Resource(name = "customUserDetailsService")
protected CustomUserDetailsService customUserDetailsService;
#Resource
private DataSource dataSource;
#Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailsService);
}
#Configuration
#Order(1)
public static class ApiConfigurationAdapter extends WebSecurityConfigurerAdapter {
#Resource(name = "restUnauthorizedEntryPoint")
private RestUnauthorizedEntryPoint restUnauthorizedEntryPoint;
#Resource(name = "restAccessDeniedHandler")
private RestAccessDeniedHandler restAccessDeniedHandler;
#Override
protected void configure(HttpSecurity http) throws Exception {
SecurityConfigurer<DefaultSecurityFilterChain, HttpSecurity> securityXAuthConfigurerAdapter = new XAuthTokenConfigurer(
userDetailsServiceBean());
// #formatter:off
http
.antMatcher("/api/**").csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.exceptionHandling()
.authenticationEntryPoint(restUnauthorizedEntryPoint)
.accessDeniedHandler(restAccessDeniedHandler)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/api/authenticate").permitAll()
.anyRequest().hasRole("ADMIN")
.and()
.apply(securityXAuthConfigurerAdapter);
// #formatter:on
}
}
#Configuration
#Order(2)
public static class WebConfigurationAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.and()
.logout().permitAll()
;
// #formatter:on
}
}
}
I'm also faced the same issue. But I got it solved when I extend the WebSecurityConfiguration master class from WebSecurityConfigurerAdapter.
Kindly refer the following stackoverflow post in which you can find the full configuration.
Spring Security HTTP Basic for RESTFul and FormLogin for web - Annotations
I found I could solve this problem by annotating my class with
#EnableWebSecurity after reading this hint: https://github.com/spring-projects/spring-data-examples/issues/189#issuecomment-229552207
I have a Spring-boot app that is using Spring-security, configured with Java-config. Ideally, I will have a customer UserDetailsService so I can add/modify users. Until then I am failing to configure this correctly.
I am using the following dependencies:
compile("org.springframework.boot:spring-boot-starter-web:1.1.1.RELEASE")
compile("org.springframework.boot:spring-boot:1.0.1.RELEASE")
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile("org.springframework.boot:spring-boot-starter-data-jpa:1.1.1.RELEASE")
compile("org.springframework.security:spring-security-web:4.0.0.M1")
compile("org.springframework.security:spring-security-config:4.0.0.M1")
I have the following Configurations
#Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
#Configuration
#EnableWebMvcSecurity
public class ApplicationSecurity extends WebSecurityConfigurerAdapter {
#Autowired
private DataSource datasource;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/resources/**").permitAll()
.antMatchers("/css/**").permitAll();
http
.formLogin().failureUrl("/login?error")
.defaultSuccessUrl("/")
.loginPage("/login")
.permitAll()
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/")
.permitAll();
http
.authorizeRequests().anyRequest().authenticated();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
JdbcUserDetailsManager userDetailsService = jdbcUserService();
// userDetailsService.setDataSource(datasource);
// PasswordEncoder encoder = new BCryptPasswordEncoder();
auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
auth.jdbcAuthentication().dataSource(datasource);
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public org.springframework.security.provisioning.JdbcUserDetailsManager jdbcUserService() throws Exception {
JdbcUserDetailsManager jdbcUserDetailsManager = new JdbcUserDetailsManager();
jdbcUserDetailsManager.setDataSource(datasource);
jdbcUserDetailsManager.setAuthenticationManager(authenticationManagerBean());
return jdbcUserDetailsManager;
}
}
#Order(Ordered.HIGHEST_PRECEDENCE)
#Configuration
public class AuthenticationSecurity extends GlobalAuthenticationConfigurerAdapter {
#Autowired
private DataSource dataSource;
#Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth
.jdbcAuthentication()
.dataSource( dataSource );
}
}
So, I realize that my configurations are wrong but not really sure how to best fix them. The symptoms are that when I log into my Thymeleaf UI, the session never exires.
I have used various online resources for my spring-security learning & implementation. Unfortunately, I am still not grasping why this is not correct.
You appear to be configuring 3 filter chains (3 WebSecurityConfigurerAdapters) but only one of them configures the HttpSecurity. That's probably not what you intended to do. Maybe consolidate down to WebSecurityConfigurerAdapter and one GlobalAuthenticationConfigurerAdapter and see where it gets you.