Why is #EnableOAuth2Sso deprecated in Spring Security?
That's the only reason why OAuth2 will work for me.
If I remove #EnableOAuth2Sso, then this will not work
#Configuration
#EnableOAuth2Client
#EnableOAuth2Sso <- Need to have this!
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/Intranet/Bokning").authenticated()
.antMatchers("/**", "/Intranet**").permitAll()
.anyRequest().authenticated()
.and().logout().logoutSuccessUrl("/").permitAll();
}
}
Is there another solution?
This is a solution to latest Spring Security with Facebook OAuth2.0.
Security:
#Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/Intranet/Bokning").authenticated() // Block this
.antMatchers("/**", "/Intranet**").permitAll() // Allow this for all
.anyRequest().authenticated()
.and().logout().logoutSuccessUrl("/").permitAll()
.and()
.oauth2Login();
}
}
And appllication.yml
spring:
security:
oauth2:
client:
registration:
facebook:
clientId: myID
clientSecret: mySecret
accessTokenUri: https://graph.facebook.com/oauth/access_token
userAuthorizationUri: https://www.facebook.com/dialog/oauth
tokenName: oauth_token
authenticationScheme: query
clientAuthenticationScheme: form
resource:
userInfoUri: https://graph.facebook.com/me
server:
port: 8080
And pom.xml file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-client</artifactId>
</dependency>
In Spring Security 5.2.x those annotations are deprecated and we need to use DSL method.
public class SecurityConf extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.oauth2Client(); //equivalent to #EnableOAuth2Client
http.oauth2Login(); //equivalent to #EnableOAuth2Sso
}
Spring OAuth2 migration guide
https://github.com/spring-projects/spring-security/wiki/OAuth-2.0-Migration-Guide
Related
Could you help me with setup Hilla + Spring Security (LDAP)?
I have created demo project from https://hilla.dev/docs/getting-started
npx #vaadin/cli init --hilla --auth hilla-with-auth
This project has simple auth, but i would like LDAP auth.
Like in my another application without Hilla:
#Configuration
#EnableAutoConfiguration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
class WebSecurityConfig extends VaadinWebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/logout/**", "/logout-success", "/login/**", "/static/**", "/**.png").permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/grocery", true)
.failureUrl("/login?error=true")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login?logout=true")
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID")
.permitAll()
.and()
.exceptionHandling().accessDeniedPage("/403")
.and()
.httpBasic();
http.addFilterAfter(new CsrfLoggerFilter(), CsrfFilter.class);
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder authBuilder) throws Exception {
authBuilder
.ldapAuthentication()
.userSearchFilter(new ParseConfigFile().getConf("AuthenticationManagerBuilder.userSearchFilter"))
.userSearchBase(new ParseConfigFile().getConf("AuthenticationManagerBuilder.userSearchBase"))
.groupSearchBase(new ParseConfigFile().getConf("AuthenticationManagerBuilder.groupSearchBase"))
.groupSearchFilter(new ParseConfigFile().getConf("AuthenticationManagerBuilder.groupSearchFilter"))
.contextSource()
.url(new ParseConfigFile().getConf("AuthenticationManagerBuilder.url"))
.managerDn(new ParseConfigFile().getConf("AuthenticationManagerBuilder.managerDn"))
.managerPassword(new ParseConfigFile().getConf("AuthenticationManagerBuilder.managerPassword"));
}
}
What I must change in config file for get LDAP auth?
LDAP uses a different protocol for communication. So you must have an LDAP server running first and foremost, and then use Spring Security to authenticate using what Spring Security offers.
The spring boot doc have an config file similar to what you may be looking for :Ldap Auth example
I am able to configure session timeout in web.xml, but after session timeout getting errors from react side.
using spring security and jwt token.
WebSecurity.java
#Configuration
#EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {
#Autowired
UserDetailServiceImpl userDetails;
#Autowired
JWTAuthenticationFilter jwtRequestFilter;
#Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetails).passwordEncoder(getPasswordEncoder());
}
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable().authorizeRequests()
.antMatchers(HttpMethod.GET, "/index*", "/static/**", "/*.js", "/*.json", "/*.ico", "/*.png")
.permitAll().antMatchers("/resources/**", "/login", "/", "/actuator").permitAll()
.antMatchers("/authenticate/**", "/identity/**").permitAll().anyRequest().authenticated().and().cors().and()
.exceptionHandling().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
web.xml
<session-config>
<session-timeout>1</session-timeout>
</session-config>
I tried sessionManagement().InvalidSessionURL("url") but on login it always redirect to invalid url only.
There is no api for login, we are loading from React directly.
Please let me know how to redirect to login page on session timeout ? and how to handle errors from react side ?
I am working on a legacy Spring MVC application and I need to pass the _csrf token to a javascript but, after introducing spring-security (in particular auth0 user authentication), these two rows are always null:
<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>
This is how I override the configure(HttpSecurity http):
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
#PropertySources(#PropertySource("classpath:auth0.properties"))
#Order(-2 /* SecurityProperties.ACCESS_OVERRIDE_ORDER */)
public class AppConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/download/**", "/resources/**", "/plugins/**", "/js/**", "/css/**", "/colors/**", "/callback", "/login", "/loggedout").permitAll()
.antMatchers("/**").authenticated()
.and()
.logout().permitAll();
}
}
I have removed the DelegationgFilterProxy from the web.xml because it should be created extending the WebSecurityConfigurerAdapter and in according with this SO question ${_csrf.parameterName} and ${_csrf.token} return null I should re-add but, if I do, I get a startup error (missing springSecurityFilterChain).
So, the question is, why my token are null if I have implemented WebSecurityConfigurerAdapter and I do not disable the csrf?
I have a fundamental problem with spring boot application. The start webpage is http://127.0.0.1:8080/login and after log in user is redirect to http://127.0.0.1:8080/MainMenu. Unfortunatelly it is also possible to write in url bar http://127.0.0.1:8080/MainMenu and going there without authentication.
What is the main idea to block that action?
#edit
This is my configuration:
package local.vlex.security;
import org.springframework.context.annotation.Configuration;
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;
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "src/main/resources/static/assets/css/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
}
and Controller:
#GetMapping("/MainMenu")
public ModelAndView correctCredentials(){
ModelAndView mav = new ModelAndView();
mav.setViewName("MainMenu");
return mav;
}
Sum up:
I would like to block going to other sites without authentication - if someone is not logged in then it should go 404 on everything other than /login
if someone is not logged in then it should go 404 on everything other
than /login
This is a bit pecular requirement. What is usually done is that people get redirected to login page on all other urls than login, or get 401 Unauthorized or 403 Forbidden. However, it's not hard to do this one either.
You mentioned you need your static resources (css, js, images) in the assets directory as well, so given that, this should work:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
#Configuration
#EnableWebSecurity
public class YourSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login", "/assets/**").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling()
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.NOT_FOUND))
;
}
}
Using
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
and
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
in Maven pom.xml
Note that there is also accessDeniedHandler() in exceptionHandling(), but that seems to only fire when user is already authenticated but denied access, so you'd need authenticationentrypoint for your use case.
Addition:
Sometimes having a custom authentication entrypoint messes the existing entry point handler. That is the case at least if you use default spring-generated form login. One way to go around that is to specify your entrypoint to only match urls that are not matching your authentication handler url, like this:
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.NegatedRequestMatcher;
// snip...
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login", "/assets/**").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling()
.defaultAuthenticationEntryPointFor(new HttpStatusEntryPoint(HttpStatus.NOT_FOUND),
new NegatedRequestMatcher(new AntPathRequestMatcher("/login")) )
.and()
.formLogin()
;
}
Add the following code, It will block all the request except "/" & "/login"
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
#Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers(
"/css/**",
"/js/**",
"/lib/**",
"/video/**",
"/images/**"
);
}
}
And add WebConfig
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter{
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/**")
.addResourceLocations("classpath:/static/")
.setCachePeriod(31556926)
.resourceChain(true);
}
}
Don't forget to add the security dependency in your pom.xml file.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Provided that you have spring-security dependencies on classpath, this is a working example from my code.
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/login**")
.permitAll()
.anyRequest()
.authenticated();
This blocks me from any other requests than '/' or 'login' or 'loginPage' etc. with Authorization.
Follow that with ignoring the static ones, css, js etc.,
If this still doesn't work, for now try working on blocking the page alone:
http.authorizeRequests()
.antMatchers("/MainMenu")
.authenticated();
The above would give idea what's happening. Dependency issue or something like that.
I have the following Spring security configuration class for two separate security realms, the admin area and the frontend area:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private CustomUserDetailsServiceImpl userDetailsService;
#Configuration
#Order(1)
public static class AdminAreaConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private AuthSuccessAdmin authSuccessAdmin;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.requestMatcher(new AntPathRequestMatcher("/admin/**"))
.csrf().disable()
.authorizeRequests()
.antMatchers("/admin/login/login.html").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/admin/login.html")
.permitAll()
.successHandler(authSuccessAdmin)
.and()
.logout()
.permitAll();
}
}
#Configuration
#Order(2)
public static class UserAreaConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private AuthSuccessFrontend authSuccessFrontend;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.requestMatcher(new AntPathRequestMatcher("/**"))
.csrf().disable()
.authorizeRequests()
.antMatchers("/about", "/register").permitAll()
.antMatchers("/**").hasRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.successHandler(authSuccessFrontend)
.and()
.logout()
.permitAll();
}
}
}
When the app is started, the authentication success handler of the admin area is overwritten by the authentication handler of the frontend area, which is loaded after the first. This results in a wrong redirect when logging into the admin area (redirects to url defined in the frontend auth success handler). How can I assign disctinct handlers to the separate configurations?
The issue seems to be in RequestMatcher pattern.
Your USER app has the RequestMatcher pattern '/**'(means anything after / which will include path /admin as well) which will override your ADMIN RequestMatcher pattern /admin/**
Change the user RequestMatcher to /user/**