${_csrf.token} on jsp always null with spring-security - java

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?

Related

Can I make Signin modal with Spring security?

#Bean
public SecurityFilterChain securityFilterChain (HttpSecurity http) throws Exception {
http.csrf().disable();
http.formLogin()
.loginProcessingUrl("/")
.defaultSuccessUrl("/")
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/")
.invalidateHttpSession(true);
I made SecurityConfigure Class in my project.
but i want with new page, only Modal
#GetMapping("/signin")
public void signIn() {
}
#PostMapping("/signin")
#ResponseBody
public String signIn() {
}
and I made controller
<a class="w3-bar-item w3-button w3-right btn nav-link" data-bs-toggle="modal"
id="btnSignIn" href="#staticBackdrop" role="button"
style="font-size:medium; margin-top:25px; margin-right:20px;">SignIn</a>
i tried to login my self, but i don't think about token.
i can't find about Modal with it. so i think i must use Security basic(?) login system.
i want to know how to use Security login system on Modal.

session timeout in spring boot + React

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 ?

Why is #EnableOAuth2Sso deprecated?

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

How to assign auth success handler to multiple spring security realms

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/**

Both isAnonymous() and isAuthenticated() are returning false

I have a simple page which is displays simple text depending on whether the user is logged in or not.
<sec:authorize access="isAnonymous()">
No, you failed!
</sec:authorize>
<sec:authorize access="isAuthenticated()">
yes, logged in. Well done!
</sec:authorize>
The above code displays nothing! which means both isAuthenticated() and isAnonymous() have returned false.
It is suggested here (Both isAnonymous() and isAuthenticated() return false on error page) that I must use this configuration for my filter mapping:
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<!-- apply Spring Security authentication to error-pages -->
<dispatcher>ERROR</dispatcher>
</filter-mapping>
I am not using XML, but my configuration is the same:
EnumSet<DispatcherType> dispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD);
characterEncoding.addMappingForUrlPatterns(dispatcherTypes, true, "/*");
FilterRegistration.Dynamic security = servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy());
security.addMappingForUrlPatterns(dispatcherTypes, true, "/*");
Why else would this happen?
Edit:
This is my security context:
#Configuration
#EnableWebSecurity
public class SecurityContext extends WebSecurityConfigurerAdapter {
#Autowired
private UserRepository userRepository;
#Override
public void configure(WebSecurity web) throws Exception {
web
//Spring Security ignores request to static resources such as CSS or JS files.
.ignoring()
.antMatchers("/static/**");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
//Configures form login
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login/authenticate")
.failureUrl("/login?error=bad_credentials")
//Configures the logout function
.and()
.logout()
.deleteCookies("JSESSIONID")
.logoutUrl("/logout")
.logoutSuccessUrl("/login")
//Configures url based authorization
.and()
.authorizeRequests()
//Anyone can access the urls
.antMatchers(
"/auth/**",
"/login",
"/signin/**",
"/signup/**",
"/user/register/**"
).permitAll()
//The rest of the our application is protected.
.antMatchers("/**").hasRole("USER")
//Adds the SocialAuthenticationFilter to Spring Security's filter chain.
.and()
.apply(new SpringSocialConfigurer());
}
/**
* Configures the authentication manager bean which processes authentication
* requests.
*/
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService())
.passwordEncoder(passwordEncoder());
}
/**
* This is used to hash the password of the user.
*/
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(10);
}
/**
* This bean is used to load the user specific data when social sign in
* is used.
*/
#Bean
public SocialUserDetailsService socialUserDetailsService() {
return new SimpleSocialUserDetailsService(userDetailsService());
}
/**
* This bean is load the user specific data when form login is used.
*/
#Bean
public UserDetailsService userDetailsService() {
return new RepositoryUserDetailsService(userRepository);
}
}
This the page controller:
#Controller
public class LoginController {
private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);
protected static final String VIEW_NAME_LOGIN_PAGE = "user/login";
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String showLoginPage() {
LOGGER.debug("Rendering login page.");
return VIEW_NAME_LOGIN_PAGE;
}
}
Make sure you are not bypassing security for that URL like as follows:
<http pattern="/xyz.xx" security="none" />
The ApplicationContext must contain
#ComponentScan(basePackages = {
"com.social.user.detail.service"
})
In this package I have the my user class containing the following:
public interface UserService {
public User registerNewUserAccount(RegistrationForm userAccountData) throws DuplicateEmailException;
}

Categories

Resources