I have an app and I have implemented Spring Security. Now I want to force logout a user 24 hrs after his login regardless of his activity. How can I achieve this?
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler
{
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException
{
Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
request.getSession(false).setMaxInactiveInterval(60);
response.sendRedirect("/successfullLogin");
}
}
The setMaxInactiveInterval is only for timing out session in case of inactivity.
http
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.antMatchers("/loginPage**").permitAll()
.antMatchers("/admin/*").hasRole("ADMIN")
.antMatchers("/guest/*").hasRole("GUEST")
.antMatchers("/**").authenticated()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.and()
.formLogin()
.loginPage("/loginPage")
.usernameParameter("username")
.passwordParameter("password")
.successHandler(new MyAuthenticationSuccessHandler())
.failureUrl("/loginPage?error=true")
.and()
.exceptionHandling().accessDeniedPage("/forbiddenPage")
.and().csrf().disable();
This is my spring security configure method.
Related
I am currently setting up a service allowing user login on a web portal, for comfort I have added the "Remember Me" function using Spring Security by using a persistent approach that stores tokens in DB for a defined time.
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/h2-console/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll()
.and()
.rememberMe()
.rememberMeCookieName("ugeddit-cookie")
.tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(172800);
http.csrf().disable();
http.headers().frameOptions().disable();
}
How is it possible to write a test covering this case, without adding too many dependencies to the project?
I can see at the moment how to add a User and simulate a connection to the formLogin but I can't see what method can allow me to simulate the activation of the "Remember Me" checkbox
#Test
void whenRememberedUser_TokenIsAddedInDB() throws Exception {
User user = new User(1L, "test", "$2a$10$/fAVkMGa6gHeM6Q0VHJyFOTznAo3qrXbj5CF0ZvMhxVldxYbxnk/6", "ROLE_USER");
userRepo.save(user);
mvc.perform(formLogin("/login").user("test").password("spring")).andExpect(authenticated());
}
Here is my configure code snippet
#Override
public void configure(HttpSecurity http) throws Exception {
http.
authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/api/user/**").hasAnyAuthority("ROLE_ADMIN")
.antMatchers("/api/status/**").hasAuthority("ROLE_ADMIN").anyRequest()
.authenticated()
.and()
.exceptionHandling()
.accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
In this I need to make ROLE_ADMIN to access only POST and PUT httpmethods. He should not be able to access GET or DELETE httpmethod. I need this to be done in a single .antMatchers() method.
How can I do this?
Have a look at this Spring example project. You can define matchers per path and HTTP verb.
http
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/employees").hasRole("ADMIN")
.antMatchers(HttpMethod.PUT, "/employees/**").hasRole("ADMIN")
.antMatchers(HttpMethod.PATCH, "/employees/**").hasRole("ADMIN")
when I config spring security like this
#EnableWebSecurity
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{
#Bean
public UserDetailsService userDetailsService(){
return new MyUserDetailsService();
}
#Bean
public MyAuthenticationProvider myAuthenticationProvider(){
MyAuthenticationProvider provider = new MyAuthenticationProvider();
provider.setUserDetailsService(userDetailsService());
return provider;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// TODO Auto-generated method stub
http
.csrf()
.disable()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll();
}
}
and then I config my controller like this
#GetMapping("/login")
public String showLoginPage(){
System.out.println("GetMapping");
return "login";
}
#PostMapping("/login")
public void authUser(#RequestParam String username,#RequestParam String password){
// just for testing
System.out.println("PostMapping");
}
and then I visit my login page and enter my username and password, but the console doesn't print "PostMapping", which means the program doesn't go into my method "authUser" with #PostMapping.
Though my program runs successfully, but it makes me quite confuse.I suppose spring security doing some work automatically, but now I have no idea where to add my Authentications to the SecurityContextHolder.
I hope somebody can help and thanks very much
It has done by UsernamePasswordAuthenticationFilter, and the default processing path is Post /login, and the Authentication already exist in SecurityContextHolder, you can get it in controller.
If you want to disable form login, change to this.
http
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated().and()
.formLogin().disable();
Normally, POST mappings are filtered by CSRFfilters. Although it is not recommended in the production environment, you can disable CSRF filter simply using for learning cases:
http.authorizeRequests().anyRequest().authenticated().and().httpBasic()
.and().logout()
.and().csrf().disable();
When do we use antMatcher() vs antMatchers()?
For example:
http
.antMatcher("/high_level_url_A/**")
.authorizeRequests()
.antMatchers("/high_level_url_A/sub_level_1").hasRole('USER')
.antMatchers("/high_level_url_A/sub_level_2").hasRole('USER2')
.somethingElse()
.anyRequest().authenticated()
.and()
.antMatcher("/high_level_url_B/**")
.authorizeRequests()
.antMatchers("/high_level_url_B/sub_level_1").permitAll()
.antMatchers("/high_level_url_B/sub_level_2").hasRole('USER3')
.somethingElse()
.anyRequest().authenticated()
.and()
...
What I expect here is,
Any request matches to /high_level_url_A/** should be authenticated + /high_level_url_A/sub_level_1 only for USER and /high_level_url_A/sub_level_2 only for USER2
Any request matches to /high_level_url_B/** should be authenticated + /high_level_url_B/sub_level_1 for public access and /high_level_url_A/sub_level_2 only for USER3.
Any other pattern I don't care - But should be public ?
I have seen latest examples do not include antMatcher() these days. Why is that? Is antMatcher() no longer required?
You need antMatcher for multiple HttpSecurity, see Spring Security Reference:
5.7 Multiple HttpSecurity
We can configure multiple HttpSecurity instances just as we can have multiple <http> blocks. The key is to extend the WebSecurityConfigurationAdapter multiple times. For example, the following is an example of having a different configuration for URL’s that start with /api/.
#EnableWebSecurity
public class MultiHttpSecurityConfig {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) { 1
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER", "ADMIN");
}
#Configuration
#Order(1) 2
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/**") 3
.authorizeRequests()
.anyRequest().hasRole("ADMIN")
.and()
.httpBasic();
}
}
#Configuration 4
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin();
}
}
}
1 Configure Authentication as normal
2 Create an instance of WebSecurityConfigurerAdapter that contains #Order to specify which WebSecurityConfigurerAdapter should be considered first.
3 The http.antMatcher states that this HttpSecurity will only be applicable to URLs that start with /api/
4 Create another instance of WebSecurityConfigurerAdapter. If the URL does not start with /api/ this configuration will be used. This configuration is considered after ApiWebSecurityConfigurationAdapter since it has an #Order value after 1 (no #Order defaults to last).
In your case you need no antMatcher, because you have only one configuration. Your modified code:
http
.authorizeRequests()
.antMatchers("/high_level_url_A/sub_level_1").hasRole('USER')
.antMatchers("/high_level_url_A/sub_level_2").hasRole('USER2')
.somethingElse() // for /high_level_url_A/**
.antMatchers("/high_level_url_A/**").authenticated()
.antMatchers("/high_level_url_B/sub_level_1").permitAll()
.antMatchers("/high_level_url_B/sub_level_2").hasRole('USER3')
.somethingElse() // for /high_level_url_B/**
.antMatchers("/high_level_url_B/**").authenticated()
.anyRequest().permitAll()
I'm updating my answer...
antMatcher() is a method of HttpSecurity, it doesn't have anything to do with authorizeRequests(). Basically, http.antMatcher() tells Spring to only configure HttpSecurity if the path matches this pattern.
The authorizeRequests().antMatchers() is then used to apply authorization to one or more paths you specify in antMatchers(). Such as permitAll() or hasRole('USER3'). These only get applied if the first http.antMatcher() is matched.
I just upgraded from Spring Security 3.2.0.RC1 to 3.2.0.RC2. Everything worked fine under RC1. Under RC2, my custom login page no longer works. The login page is just redislayed after clicking the Login button. If invalid credentials (or no credentials) are submitted, it also redisplays without any error message. Before it would correctly display an error message if the credentials were incorrect.
What is interesting is if I change from:
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
// #formatter:off
httpSecurity
.authorizeRequests()
.antMatchers("/restricted/**").hasRole("admin"))
// all requests must be authenticated
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/myLoginUrl.request")
.failureUrl("/myLoginUrl.request?error")
.permitAll()
.and()
.logout()
.permitAll()
.logoutSuccessUrl("/myLoginUrl.request")
;
// #formatter:on
}
to:
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
// #formatter:off
httpSecurity
.authorizeRequests()
.antMatchers("/restricted/**").hasRole("admin"))
// all requests must be authenticated
.anyRequest().authenticated()
.and()
.formLogin()
.permitAll()
.and()
.logout()
.permitAll()
.logoutSuccessUrl("/myLoginUrl.request")
;
// #formatter:on
}
The default Spring Security login page is displayed and works. I've looked at the source of the default page and compared it to my custom page and it seems to call the same action with fields with the same names.
If I step through the debugger, I find that in AntPathMatcher.java, public boolean matches(HttpServletRequest request):
String url = getRequestPath(request)
The url returned is "/error" when using my custom login page. getRequestPath() just returns request.getServletPath() appended to request.getPathInfo(). I'm not sure why upgrading to RC2 would cause this to return "/error".
There were three things that I changed that made this work.
1) Added a CSRF hidden field to the form:
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
2) Capitalized POST for the form method:
<form action="login" method="POST">
3) Explicitly added loginProcessingUrl to the configuration:
.formLogin()
.loginPage("/myLoginUrl.request")
.loginProcessingUrl("/login")
.failureUrl("/myLoginUrl.request?error")
.permitAll()