How to reload the Configure method of WebSecurityConfigurerAdapter when the application is up and running - spring

I am using spring boot and in spring security we are using "WebSecurityConfigurerAdapter" and using the method
#Override
protected void configure(HttpSecurity http) throws Exception {
AuthenticationFilter authenticationFilter = new AuthenticationFilter(authenticationManager(), tokenService(), externalServiceAuthenticator());
http.addFilterBefore(authenticationFilter, BasicAuthenticationFilter.class)
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().authorizeRequests().antMatchers(externalServiceCaller.getPrivateEndPoints())
.hasAnyAuthority(externalServiceCaller.getAllAuthorities()).anyRequest().authenticated()
.and().authorizeRequests().anyRequest().anonymous()
.and().exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint())
.and().exceptionHandling().authenticationEntryPoint(forbiddenEntryPoint());
}
This is working fine for existing role and user but when we are adding more users and role at run time (After the application start) then spring security is not able to recognize new role and new user . Is there any way to call the above method again when the application is up and running.

Reload configure(HttpSecurity http) is impossible in runtime, because it's some kind of builder and it's creates some part of the spring security chain when the application is starting - if you'd like to reload the method you have to replace the spring security chain during runtime - it's not so easy and recommended way.
If you need add some user during runtime - implement custom AuthentificationProvider

Related

Keep session id in case of presence of special parameter in request. Spring Security

Does anybody know if there any way to configure Spring Security in the way that it doesn't change session id if there is some parameter in the request.
For example:
somesite.com/home.jsp?password=encrypted- change session id after
authentication
somesite.com/home.jsp?password=encrypted& keepsessionid - don't
change session id after authentication
I was thinking about filter chain, maybe removing conditionally SessionManagementFilter, but not sure if this is a proper way, and even if this will be working
For someone with the same question. I found the answer. Different session management strategy can be achieved by using multiple http security configuration (inner classes of main security classes). The special case http security configurer should be adjusted to some special request
#Configuration
#Order(1)
public class SpecialCaseSessionHandlingConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatcher(request -> Check1(request))
.authorizeRequests()
.anyRequest().authenticated();
}
}

how to use .antMatchers("/").not() method in spring security, and i am using spring MVC

I wanted to permit 100 url's if the user do not have the given permission and also want to restrict him only to a single page, how can i do it using spring security, or can someone help me with antMatchers() to proceed with my requirement, thank you in advance.
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests() .antMatchers("/p1/**").permitAll()
.antMatchers("/p2","/p3","/p4").wantRestrictIfItHasRole.access("hasRole('ROLEA')")
.anyRequest().authenticated();
}

How can I allow public access to parts of Spring Security app using permitAll?

I'm trying to get a Spring application to allow some requests to public (without login) and some requests to private (with login).
At this point I'd like to just get the public part to work properly.
I have tried most of the example configurations listed on the Spring Security documentation, including all sorts of combinations of anonymous(), and permitAll(). All end up redirecting to the login page.
protected void configure(HttpSecurity http) throws Exception{
http.authorizeRequests()
.antMatchers("/resources/**", "/signup", "/about","/api/home").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
.anyRequest().authenticated()
.and()
// ...
.formLogin();
}
Expected result: items under permitAll() are accessible without logging in
Actual result:
redirect to login page. This shows up in the log: 2019-06-06
17:29:43.593 INFO 56330 --- [ main]
o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: any
request, [org.sprin...
This leads me to believe that it isn't even reading this configuration. Is there any way to fix this?
Thanks!
UPDATE: I tried adding the websecurity ignores, and it doesn't appear to be working still. It appears to still print the "defaultsecuritychain" error so I feel like this may have something to do with it.
UPDATE 2: Added application.properties file under src/main/resources with this line logging.level.org.springframework.security=DEBUG to make it log debug messages.
pastebin.com/2u9k7eHD
Have a look at http://blog.florian-hopf.de/2017/08/spring-security.html, it may explain your use-case in more detail.
My recommendation is to try and use WebSecurity for static and public resources
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**", "/signup", "/about","/api/home");
}
You can achieve your requirements with below configurations. It's a good way to use the URLs which does't require Authentication/Authorization to be placed in WebSecurity using ignoring instead of HttpSecurity as WebScurity will bypass the Spring Security Filter Chain and reduce the execution time
#Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/resources/**", "/signup", "/about","/api/home");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
.anyRequest().authenticated()
.yourConfigurations
}
When you use HttpSecurity and try to permitAll() requests. Your requests will be allowed to be accessed from the Spring Security Filter Chain. This is costly as there will be requests other requests which would also come into this filter chain which needs to be allowed or disallowed based on Authentication/Authorization
But when you use WebSecurity, any requests to "/resources/**", "/signup", "/about","/api/home" will completely by pass the Spring Security Filter Chain all together. It is safe because you don't need any Authentication/Authorization to be in place to see an image or read a javascript file.
Turns out that I was missing the #SpringBootApplication annotation all along in one of my source files. Make sure that's in there and perhaps it will work.
Thank you to all who replied!

Setting session timeout in spring boot application using google App Engine

I have a spring boot application which is being deployed in google app engine.
I have a requirement of setting session time out on condition basis.
I tried attaching a successHandler in spring security configuration as
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
.and()
.successHandler(successHandler())
}
And here is the success handler
private AuthenticationSuccessHandler successHandler() {
return (httpServletRequest, httpServletResponse, authentication) -> {
httpServletRequest.getSession().setMaxInactiveInterval(10);
};
}
I figured out that google app engine uses jetty server (jetty 9 actually) and
it frequently keeps storing the created sessions in memcache and datastore.
some how app engine does not honor the session time out set by calling
httpServletRequest.getSession().setMaxInactiveInterval(10);

Authentication of background tasks using Spring Boot and Spring Security

I have a background task (running with Project Reactor, but I don't think it is relevant) that I need to run in with an authenticated user to get through some #PreAuthorize annotated methods.
I'm doing something like this:
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(login, password));
SecurityContextHolder.getContext().setAuthentication(authentication);
But when I trace into the authenticationManager call, I find that it is using Spring-Boot's default InMemoryUserDetailsService, rather than my custom authentication configuration. This happens regardless of whether I run the authentication in a web request thread, or in the background thread.
I don't know if it is relevant, but I am running this code in an integration test, with these annotations (among others):
#SpringApplicationConfiguration(classes=MyAppConfiguration.class)
#WebAppConfiguration
#IntegrationTest({"server.port:0"})
In addition to this problem, my test makes an authenticated web request to my server, and that authenticates just fine. So I know at least the web portion of my system is using the correct authenication configuration.
Here is my authentication configuration:
#EnableWebMvcSecurity
#EnableGlobalMethodSecurity(jsr250Enabled=true, prePostEnabled=true)
public abstract class BaseSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public LocalUserDetailsService localUserDetailsService;
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(localUserDetailsService);
}
#Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable().httpBasic()
.and()
.authorizeRequests()
.antMatchers( "/admin/**" ).hasRole( "ADMIN" )
}
It is hard to tell without your test implementatiton but it matters that you are running it in integration test
Maybe you are forgetting to add `FilterChainProxy to your mockMvc
like this mvc = MockMvcBuilders.webAppContextSetup(context)
.addFilter(springSecurityFilterChain).build();
instance of filterChainPrioxy can be #Autowired into your test class, of course this answer may not make sense, depends of your implementation of test class
---after your comment
this line :
SecurityContextHolder.getContext().setAuthentication(authentication);
assigns security constrains to current thread and does not impact threads running in background, unless your strategy is global and it is not default

Resources