Spring security - Disable CSRF and Authentication for specific URL (Java Conf) - spring

I know this question is old but it is not working in my case.
I have a webapp using spring security authentication and CSRF enabled.
Now I want to expose couple of URL to expose to other application without authentication.
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.antMatchers("/rest/book").permitAll()
.antMatchers("/rest/check").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login")
.successHandler(customizeAuthenticationSuccessHandler)
//.defaultSuccessUrl("/")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/login?logout")
.permitAll();
}
I have other urls with "/rest/" which are secure. I tried csrfMatcher and with that I am able to expose "/rest/book" but then other urls are giving unexpected behavior.
Unexpected behavior like, my default login page is /login when no authentication but it stopped.

Related

how to change the default login path from /login to /auth/login?clientId=123&secret=123 in Spring boot Oauth2

Need to customise the default oauth2 authentication server /login page to user defined page along with passing query parameters
I tried by using this link https://www.javainuse.com/spring/boot_form_security_custom_login
protected void configure(HttpSecurity http) throws Exception {
http.requestMatchers()
.antMatchers("/login","/oauth/authorize")
.and()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.formLogin()
.permitAll();
}

How to access swagger endpoints securely?

I have added swagger ui in my application, earlier below two url's i was able to access directly without any authentication.
http://localhost:1510/swagger-ui.html
http://localhost:1510/v2/api-docs
i need secure swagger urls, don't want anybody directly see the api details of my application.
Note :- For authentication purpose i am using JWT with spring security in my application.
SO in order to secure swagger URLS , i have made entry in spring seurity config .. below code
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
.exceptionHandling()
.authenticationEntryPoint(problemSupport)
.accessDeniedHandler(problemSupport)
.and()
.csrf()
.disable()
.headers()
.frameOptions()
.disable()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/register").permitAll()
.antMatchers("/api/activate").permitAll()
.antMatchers("/api/userLogin").permitAll()
.antMatchers("/v2/api-docs").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/swagger-ui.html").hasAuthority(AuthoritiesConstants.ADMIN)
.and()
.apply(securityConfigurerAdapter());
}
and when i am trying to access swagger urls , i am getting below exception on browser and as well as on eclipse console.
org.springframework.security.authentication.InsufficientAuthenticationException: Full authentication is required to access this resource
How can i pass the jwt token to see the swagger page ?

Spring boot security: Requested url creates unwanted redis session

Lets say the login url is "/login".
There are two protected resources:
"/protected"
"/" which is a 302 redirect to "/protected"
When a unauthenticated user tries to access "/protected" he is being redirected to "/login". In background there is a session created, where SPRING_SECURITY_SAVED_REQUEST is stored in order to redirect user to the "/protected" url after successful login.
This is the default behaviour of spring security.
My issue:
Sessions are being created even when users call "/". So all the bots and penetration tests, which call the domain without valid login information do create sessions in the underlying redis layer.
How can I prevent these sessions from being created when there is no redirect request stored or at least limit them to a defined list of valid backend endpoints?
My security configuration:
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/password/forgot/**").permitAll()
.antMatchers("/password/reset/**").permitAll()
.antMatchers("/css/**").permitAll()
.antMatchers("/js/**").permitAll()
.antMatchers("/img/**").permitAll()
.antMatchers( "/favicon.ico").permitAll()
.antMatchers("/login").permitAll()
.anyRequest().fullyAuthenticated();
http
.formLogin()
.loginPage("/login")
.permitAll()
.successHandler(authSuccessHandler)
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login")
.deleteCookies("SESSION")
.clearAuthentication(true)
.invalidateHttpSession(true)
.permitAll();
http.sessionManagement()
.maximumSessions(1)
.and()
.sessionCreationPolicy(SessionCreationPolicy.NEVER);
http.headers().frameOptions().disable();
http.csrf().disable();
}
You could avoid having SPRING_SECURITY_SAVED_REQUEST created by setting NullRequestCache, but I guess that wouldn't work for your use case.
or at least limit them to a defined list of valid backend endpoints?
This could be done by providing a requestCache and setting the RequestMatcher -
final HttpSessionRequestCache requestCache = new HttpSessionRequestCache();
requestCache.setRequestMatcher(new AntPathRequestMatcher("/**"));
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.requestCache().requestCache(requestCache)
.and()...

Restrict access to Swagger UI

I have swagger UI working with spring-boot. I have a stateless authentication setup for my spring rest api which is restricted based on roles for every api path.
However, I am not sure how can i put <server_url>/swagger-ui.html behind Basic authentication.
UPDATE
I have following websecurity configured via WebSecurityConfig
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers("/sysadmin/**").hasRole("SYSADMIN")
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/siteadmin/**").hasRole("SITEADMIN")
.antMatchers("/api/**").hasRole("USER")
.anyRequest().permitAll();
// Custom JWT based security filter
httpSecurity
.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
}
One suggestion without knowing more about your configuration is from this SO question.
https://stackoverflow.com/a/24920752/1499549
With your updated question details here is an example of what you can add:
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers("/sysadmin/**").hasRole("SYSADMIN")
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/siteadmin/**").hasRole("SITEADMIN")
.antMatchers("/api/**").hasRole("USER")
// add the specific swagger page to the security
.antMatchers("/swagger-ui.html").hasRole("USER")
.anyRequest().permitAll();
// Custom JWT based security filter
httpSecurity
.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
}
The problem with this is it only protects the Swagger UI page and not the API specification which is loaded as a .json file from that UI page.
A better approach is to put the swagger files under a path so that you can just add antMatchers("/swagger/**").hasRole("USER")
A bit late to answer. I carried out a small POC to execute the same. I am using Keycloak and Spring Security. Below is my configuration
http
.antMatcher("/**").authorizeRequests()
.antMatchers("/swagger-resources/**","/swagger-ui.html**","/swagger-ui/").hasRole("admin")
.anyRequest().authenticated()
.and()
.exceptionHandling()
.accessDeniedHandler(new AccessDeniedHandlerImpl())
.defaultAuthenticationEntryPointFor(authenticationEntryPoint(), new CustomRequestMatcher(AUTH_LIST))
.and()
.httpBasic()
.authenticationEntryPoint(restAuthenticationEntryPoint)
.and()
.csrf().disable()
.logout()
.logoutUrl("/logout")
.invalidateHttpSession(true)
.clearAuthentication(true)
.addLogoutHandler(keycloakLogoutHandler());
I have a working example here

two authentication mechanism on a spring boot application (Basic & JWT)

I have a spring boot app, I have just finished implementing a stateless authentication/authorization module based on jwt.
This is how I configured my security module:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.csrf()
.disable()
.headers()
.frameOptions()
.disable()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/authenticate").permitAll()
.antMatchers("/api/**").authenticated()
.and()
.apply(securityConfigurerAdapter());
}
So basically if I want to access the url /api/jobs I get a 401 error unless I send the bearer token which I get after a succesfull authentication on /api/authenticate.
What I need to know is if it's possible to access /api/jobs without supplying the bearer token, using a basic http authentication with a login and passowrd
Yes, it's possible, just make sure you have:
http.httpBasic();
in your configuration. That builder also have other methods to configure the details for basic auth.

Resources