Spring Security not working on Weblogic 12.2.1.2 - java

I have a web application that uses Spring Security. It works on Tomcat, but didn't on Weblogic 12.2.1.2.
On Weblogic, user isn't redirected to the login page when tries to reach a restricted URL (for example localhost:7001/website/restricted/welcome). On Tomcat the user is correclty redirected to the login page.
I read that this is a bug of Weblogic 12.1 and it seems to be fixed in Weblogic 12.2. But I'm using Weblogic 12.2.1.2 and I enconter the same problem.
I read some solutions, but I have difficult to understand them, since I have a different Spring configuration.
These are my classes about Spring Security.
This is the class that extends WebSecurityConfigurerAdapter.
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication()
.passwordEncoder(passwordEncoder())
.withUser("username1")
.password(passwordEncoder()
.encode("password1"))
.roles("ADMIN");
}
#Bean
public PasswordEncoder passwordEncoder() {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder;
}
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.formLogin()
.loginPage("/login")
.usernameParameter("userId")
.passwordParameter("password");
httpSecurity.formLogin()
.defaultSuccessUrl("/")
.failureHandler(new CustomAuthenticationFailureHandler())
.and()
.sessionManagement()
.maximumSessions(1)
.expiredUrl("/login?expired")
.maxSessionsPreventsLogin(true);
httpSecurity.logout()
.logoutSuccessUrl("/login?logout");
httpSecurity.rememberMe()
.rememberMeParameter("rememberMe")
.key("rememberMeKey")
.tokenValiditySeconds(1800);
httpSecurity.exceptionHandling()
.accessDeniedPage("/login?accessDenied");
httpSecurity.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/**/add").access("hasRole('ADMIN')")
.antMatchers("/**/market/**").access("hasRole('USER')");
httpSecurity.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
}
This is the class that extends AbstractSecurityWebApplicationInitializer.
public class SecurityWebApplicationInitializer
extends AbstractSecurityWebApplicationInitializer
implements WebApplicationInitializer {
#Override
protected boolean enableHttpSessionEventPublisher() {
return true;
}
}
The problem seems to be bound to Spring Boot.
When, with Spring Tool Suite, I use the Spring Starter Project wizard (Spring boot) I encounter the problem.
If I don't use Spring Boot, Spring Security work properly!
How should I fix this problem?
Thank you

Related

Spring security Multiple Http Configurations - Ony order(1) works [duplicate]

I am trying to set up multiple WebsecurityConfigurerAdapter for my project where the spring boot actuator APIs are secured using basic auth and all other endpoints are authenticated using JWtAuthentication. I am just not able to make it work together, only the config with the lower order works. I am using Spring Boot 2.1.5.RELEASE
Security Config One with JWT Authenticator
#Order(1)
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final String[] AUTH_WHITELIST = {
"/docs/**",
"/csrf/**",
"/webjars/**",
"/**swagger**/**",
"/swagger-resources",
"/swagger-resources/**",
"/v2/api-docs"
};
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(AUTH_WHITELIST).permitAll()
.antMatchers("/abc/**", "/abc/pdf/**").hasAuthority("ABC")
.antMatchers("/ddd/**").hasAuthority("DDD")
.and()
.csrf().disable()
.oauth2ResourceServer().jwt().jwtAuthenticationConverter(new GrantedAuthoritiesExtractor());
}
}
The basic Auth config with username/password
#Order(2)
#Configuration
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {
/* #Bean
public UserDetailsService userDetailsService(final PasswordEncoder encoder) {
final InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(
User
.withUsername("user1")
.password(encoder.encode("password"))
.roles("ADMIN")
.build()
);
return manager;
}
#Bean PasswordEncoder encoder(){
return new BCryptPasswordEncoder();
}*/
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/actuator/**").hasRole("ADMIN")
.and()
.httpBasic();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user1").password("password").authorities("ADMIN");
}
}
I have been trying to make it work for many days but cannot make both of them work together. If i swap the order, only basic auth works and not the JWT Auth Manager.
I have gone through a lot of SOF Questions, like
[https://stackoverflow.com/questions/40743780/spring-boot-security-multiple-websecurityconfigureradapter][1]
[https://stackoverflow.com/questions/52606720/issue-with-having-multiple-websecurityconfigureradapter-in-spring-boot][1]
[https://github.com/spring-projects/spring-security/issues/5593][1]
[https://www.baeldung.com/spring-security-multiple-entry-points][1]
Nothing seems to be working, is this a known issue in Spring?
To use multiple WebsecurityConfigurerAdapter, you need restrict them to specific URL patterns using RequestMatcher.
In your case you can set a higher priority for ActuatorSecurityConfig and limit it only to actuator endpoints:
#Order(-1)
#Configuration
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.requestMatchers().antMatchers("/actuator/**")
.and()
.authorizeRequests().anyRequest().hasRole("ADMIN")
.and()
.httpBasic();
}
}

Multiple WebSecurityConfigurerAdapter in spring boot for multiple patterns

I am trying to set up multiple WebsecurityConfigurerAdapter for my project where the spring boot actuator APIs are secured using basic auth and all other endpoints are authenticated using JWtAuthentication. I am just not able to make it work together, only the config with the lower order works. I am using Spring Boot 2.1.5.RELEASE
Security Config One with JWT Authenticator
#Order(1)
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final String[] AUTH_WHITELIST = {
"/docs/**",
"/csrf/**",
"/webjars/**",
"/**swagger**/**",
"/swagger-resources",
"/swagger-resources/**",
"/v2/api-docs"
};
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(AUTH_WHITELIST).permitAll()
.antMatchers("/abc/**", "/abc/pdf/**").hasAuthority("ABC")
.antMatchers("/ddd/**").hasAuthority("DDD")
.and()
.csrf().disable()
.oauth2ResourceServer().jwt().jwtAuthenticationConverter(new GrantedAuthoritiesExtractor());
}
}
The basic Auth config with username/password
#Order(2)
#Configuration
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {
/* #Bean
public UserDetailsService userDetailsService(final PasswordEncoder encoder) {
final InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(
User
.withUsername("user1")
.password(encoder.encode("password"))
.roles("ADMIN")
.build()
);
return manager;
}
#Bean PasswordEncoder encoder(){
return new BCryptPasswordEncoder();
}*/
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/actuator/**").hasRole("ADMIN")
.and()
.httpBasic();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user1").password("password").authorities("ADMIN");
}
}
I have been trying to make it work for many days but cannot make both of them work together. If i swap the order, only basic auth works and not the JWT Auth Manager.
I have gone through a lot of SOF Questions, like
[https://stackoverflow.com/questions/40743780/spring-boot-security-multiple-websecurityconfigureradapter][1]
[https://stackoverflow.com/questions/52606720/issue-with-having-multiple-websecurityconfigureradapter-in-spring-boot][1]
[https://github.com/spring-projects/spring-security/issues/5593][1]
[https://www.baeldung.com/spring-security-multiple-entry-points][1]
Nothing seems to be working, is this a known issue in Spring?
To use multiple WebsecurityConfigurerAdapter, you need restrict them to specific URL patterns using RequestMatcher.
In your case you can set a higher priority for ActuatorSecurityConfig and limit it only to actuator endpoints:
#Order(-1)
#Configuration
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.requestMatchers().antMatchers("/actuator/**")
.and()
.authorizeRequests().anyRequest().hasRole("ADMIN")
.and()
.httpBasic();
}
}

java Spring #EnableResourceServer and #EnableWebSecurity

I have RESTful spring resource server with #EnableResourceServer and extending ResourceServerConfigurerAdapter
In documentations says:
...In order to use this filter you must #EnableWebSecurity somewhere in your application, either in the same place as you use this annotation, or somewhere else.
But when I get to the public #interface EnableResourceServer I see ResourceServerConfiguration extends WebSecurityConfigurerAdapter.
Question:
So what do I need for pure RESTful API?
#EnableWebSecurity on any #Config
Extend the WebSecurityConfigurerAdapter?
1 + 2
Neither
My config
#Configuration
#EnableResourceServer
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class HGResourceServerConfigurerAdapter extends ResourceServerConfigurerAdapter {
#Override
public void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.cors().disable()
.csrf().disable()
.formLogin().disable()
.httpBasic().disable()
.jee().disable()
.logout().disable()
.rememberMe().disable()
.servletApi().disable()
.x509().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.and().authorizeRequests().antMatchers(Url.API_ERROR_LOGS_FRONTEND).permitAll()
.and().authorizeRequests().antMatchers(Url.API_REGISTER_PATH).permitAll()
.and().authorizeRequests().antMatchers(Url.API_VERIFY_EMAIL_PATH).permitAll()
.and().authorizeRequests().antMatchers(Url.API_RESET_PASSWORD_PATH).permitAll()
.and().authorizeRequests().antMatchers(Url.API_CONFIRM_RESET_PASSWORD_PATH).permitAll()
.and().authorizeRequests().anyRequest().authenticated();
}
#Primary
#Bean
public RemoteTokenServices tokenService() {
RemoteTokenServices tokenService = new RemoteTokenServices();
tokenService.setCheckTokenEndpointUrl("http://localhost:8081/oauth/check_token");
tokenService.setClientId("client");
tokenService.setClientSecret("secret");
return tokenService;
}
//disable default user creation
#Bean
public UserDetailsService userDetailsService() throws Exception {
return new InMemoryUserDetailsManager();
}
//password encoder
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
No, the enable EnableWebSecurity is implicit.
I do not recommend to use WebSecurityConfigurerAdapter, you will come across some troubles :
Correctly configure spring security oauth2
Spring Boot makes #EnableWebSecurtiy implicit, but otherwise is it required.
You can prove this to yourself by taking a look at this OAuth2 resource server example. If you remove the #EnableWebSecurity annotation there, you will find that the Spring Security Filter Chain is not wired.
You can still extend WebSecurityConfigurerAdapter to separate general web application security concerns from those specific to resource server configuration. This isn't technically necessary, but can make for a cleaner separation of concerns.

How to provide custom security configuration for oauth2 with spring-boot 1.3.0.RC1

With spring-cloud Angel.SR3 release I followed example in https://github.com/spring-cloud-samples/sso and things work fine with spring-boot 1.2.6.RELEASE.
However with spring-boot 1.3.0.RC1, the oauth2 stuff has moved into spring-boot itself, and the code below fails to compile because class OAuth2SsoConfigurerAdapter no longer exists.
What is the spring-boot only way to create equivalent configuration?
public static void main(String[] args) {
SpringApplication.run(MainAppApplication.class, args);
}
...
#Component
public static class LoginConfigurer extends OAuth2SsoConfigurerAdapter {
#Override
public void match(RequestMatchers matchers) {
matchers.antMatchers("/dashboard/**");
}
#Override
public void configure(HttpSecurity http) throws Exception {
http.antMatcher("/dashboard/**").authorizeRequests().anyRequest()
.authenticated().and().csrf()
.csrfTokenRepository(csrfTokenRepository()).and()
.addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
}
private Filter csrfHeaderFilter() {
return new OncePerRequestFilter() {
...
};
}
...
}
You just have to use org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter and carefully use this annotation org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso
I've written carefully because its behaviour depends on where you add it. As stated in the javadoc:
Enable OAuth2 Single Sign On (SSO). If there is an existing WebSecurityConfigurerAdapter provided by the user and annotated with #EnableOAuth2Sso, it is enhanced by adding an authentication filter and an authentication entry point. If the user only has #EnableOAuth2Sso but not on a WebSecurityConfigurerAdapter then one is added with all paths secured and with an order that puts it ahead of the default HTTP Basic security chain in Spring Boot.
Hope that helps!
Turns out not special adapter needed, just the regular WebSecurityConfigurerAdapter does the trick. You cannot tell the code from below if oauth2 SSO is involved, more transparent, sort to speak.
#Configuration
#Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
protected static class ApplicationSecurity extends WebSecurityConfigurerAdapter {
#Autowired
private SecurityProperties security;
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http
.authorizeRequests()
.antMatchers("/", "/ssologout").permitAll()
.anyRequest().fullyAuthenticated()
.and()
.formLogin()
.loginPage("/login").failureUrl("/login?error")
.permitAll()
.and()
.logout().permitAll();
// #formatter:on
}
}

Spring rest webservice with BasicAuth without xml configuration

I was wondering if it is possible to create Spring Webservice with BasicAuth without creating web.xml or any xml based configuration stuff.
I saw ton of tutorials to do it with xml, but I'd like to do this in class configuration way.
Hm I'm sorry this may not be exact because I don't use this implementation anymore, I replaced with EE-based model BUT.... work with me here. :)
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.passwordEncoder(passwordEncoder())
.withUser("fooserviceuser").password("$2a$10$9DvfxB.Sj2B/QznFRw85FenDvhUGglWWgOR7mmal/jNImhdHQRJgi").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/**").hasRole("USER")
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
#Bean
public BCryptPasswordEncoder passwordEncoder(){
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
}
You also need an initializer to hook into the container like --
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}
This uses bcrypt for password hashing. Sorry this isn't working code but I think there is enough here to put you on the right track! Google around for similar code snippets, they're there.

Categories

Resources