spring boot unauthorized on permit all requests - spring

So I have a very common problem but, all answers didn't work so I hope this will help me...
I am using spring boot and want to permit all request without authentication, but I want to keep the csrf token and the jsession.
The problem is when I use this:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/**")
.permitAll()
.and()
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
It just says unauthorized...
#jaop answer works for get, but for post it still says unothorized
Please Help,
Thanks

How about this:
http.httpBasic().disable()
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
Basically i think you should disable basic authentication =)
Let me know if it works

Related

spring boot security allow post request but only with permission

So my problem is a little different from the rest of the spring boot questions. I want to allow post requests in my security config but only with authentication
here is my config file:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic();
http.csrf().disable();
}
thanks for helping ;)
You can use antMachers with the following pattern.
antMatchers(HttpMethod.POST)
if you want to authenticate POST method of only certainpath
antMatchers(HttpMethod.POST, "/path")

Spring Security and i18n

I have problem with accessing when I change language on page.
Without .antMatchers("/login*").permitAll() doesn't work but with /login* is almost ok but when I provide in URL 'http://localhost:8080/login?lang=estest123' or sth not related with i18n after login I receive ??language.change_estest123??.
I tried add .regexMatchers("^login\\?lang=[a-zA-Z]{2}|^login\\?lang=_{1}[a-zA-Z]{2}").permitAll() but same result as /login*.
Is any possible to accessing only for i18n ? in other case providing error? Or maybe another way of configuration for i18n which allows in easy way to provide this?
My web security config:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**", "/registration").permitAll()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
Does the presence of parameters affect the url parsing for Security? Just use /login and it should pass /login and /login?lang=xxx.
But if you want to use direct mapping in your config you can use both of them: .antMatchers("/login", "/login*").permitAll()

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

Spring security - Getting 404 error for REST call

I have an application that I am securing using Spring Security. I enable it using the annotations:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
I then configure it by overriding the configure() method:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.and()
.addFilterAfter(new CsrfCookieGeneratorFilter(), CsrfFilter.class)
.exceptionHandling()
.accessDeniedHandler(new CustomAccessDeniedHandler())
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.formLogin()
.loginProcessingUrl("/api/authentication")
.successHandler(ajaxAuthenticationSuccessHandler)
.failureHandler(ajaxAuthenticationFailureHandler)
.usernameParameter("username")
.passwordParameter("password")
.permitAll()
.and()
.logout()
.logoutUrl("/api/logout")
.logoutSuccessHandler(ajaxLogoutSuccessHandler)
.deleteCookies("JSESSIONID", "CSRF-TOKEN")
.permitAll()
.and()
.headers()
.frameOptions()
.disable()
.and()
.authorizeRequests()
.antMatchers("/api/**").authenticated()
.antMatchers("/admin/**").hasAuthority(AuthoritiesConstants.ADMIN);
}
I'm getting redirected correctly to the login page when I try to get to the home page, but once I enter my credentials and try to login, I get the 404 not found error for /api/authentication REST call.
The loginProcessingUrl() method specifies the call to make. I don't have to implement this myself do I, as Spring should do that for me? Is there anything else I'm missing?
As far as I understood the login-processing-url, you have to handle the login process by yourself if you specify a special url to process the login.
Have you tried to just remove this line?:
.loginProcessingUrl("/api/authentication")
As you use springs default login form, you should just be able to remove the line and the generated login form will also change.
Maybe there's another way to solve your problem but this should also work.
If you're looking for an example on how to use custom login forms, this link might helo you.
I figured it out, it was a couple of things I needed to change:
I didn't have an Initializer class. After I added the following class, I went from a 404 not found error, to a 403 error:
public class SecurityWebApplicationInitializer
extends AbstractSecurityWebApplicationInitializer {
}
Note: you can also add the corresponding filter in your web.xml (read more here: http://websystique.com/spring-security/spring-security-4-hello-world-annotation-xml-example/)
The above change registers security with the Spring container. But I still needed to disable CSRF, as I wasn't sending the proper tokens from the client side. For my application, I don't need CSRF just yet so I have disabled it for now. However, this is not recommended so make sure sure you know what you are doing before making this change:
http.csrf().disable()

Mix HttpBasic and FormLogin in Spring Security with Spring-boot-starter

I use spring-boot-starter 0.5.0.M6 with spring security to build my application which contains:
"/admin/"**: should be accessible to anyone have role ADMIN, form-based login
"/api/"**: should be accessible to anyone have role API, http basic login
My first attempt was:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.and()
.formLogin()
.defaultSuccessUrl("/admin/home")
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET"))
.permitAll();
http
.authorizeRequests()
.antMatchers("/api/**").hasRole("API")
.and()
.httpBasic();
}
With this approach:
all the "/admin/" and "/api/" can authentication use both basic & form-based login. This is not a critical issue.
when any security issue occurred, eg: authentication failed, or authorization failed, the login form is shown. This is a critical issue, I want if /api/** get authentication failed or authorization failed, it show the basic authentication popup with 401/403 status code.
Then I try with the solution from https://github.com/spring-projects/spring-security-javaconfig/blob/master/samples-web.md#sample-multi-http-web-configuration, but I only able to secure either /api/** or /admin/** but not both, depends on which one I annotated with #Order.
Please give me a hand.
Thanks much
For your api part, use the following. Note the first ant matcher that limits the scope of what is filtered by this security configuration. That was the part I did not understand at first from your reference.
#Configuration
#Order(1)
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
// the ant matcher is what limits the scope of this configuration.
http.antMatcher("/api/**").authorizeRequests()
.antMatchers("/api/**").authenticated()
.and().httpBasic().realmName("Sourcing API");
}
}

Resources