antMatchers(HttpMethod.GET, "path").permitAll() is still 401 unauthorized - spring

I was searching a lot to find solution of my problem but nothing helps.
I am tryng to set up my Spring Security as:
#Override
public void configure(HttpSecurity http) throws Exception {
http
.httpBasic()
.and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/shapes").hasAnyAuthority("USER")
.antMatchers(HttpMethod.PUT, "/shapes").hasAnyAuthority("USER")
.antMatchers(HttpMethod.GET, "/shapes").permitAll()
.antMatchers("/users", "/shapes/history").permitAll()
.anyRequest().authenticated()
.and()
.cors()
.and()
.csrf()
.disable();
}
and now:
every request on endpoint /users is open, is not secured
#PostMapping("/shapes") is secured and returns 401 unauthorized
#GetMapping is secured too - it returns 401 error if I not add username and password <- there is problem of that question
/shapes/history is secured too
so the problem has to be here somewhere:
.antMatchers(HttpMethod.POST, "/shapes").hasAnyAuthority("USER")
.antMatchers(HttpMethod.PUT, "/shapes").hasAnyAuthority("USER")
.antMatchers(HttpMethod.GET, "/shapes").permitAll()
I won't to change endpoints, I would like to have #GetMapping and #PostMapping on the /shapes.

Related

Spring security ant matcher's permitall doesn't work

As the title says Spring security's ant matcher's permit all doesn't work at all here's the method for it
#Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers( "/css/*", "/js/*", "index").permitAll()
.antMatchers(HttpMethod.POST, "/api/v1/user/auth/register").permitAll()
.antMatchers("/get", "/delete/*", "/api/v1/user/auth/**").hasRole(ADMIN.name())
.anyRequest()
.authenticated()
.and()
.httpBasic();
}
it should only allow the url ending with /get to be accessed by user that has admin role but I can access it without it (USER role) is there anything I'm doing wrong?
I tried changing the endpoint but didn't succeed at all

403 Bad Request sending a post request from URI with name parameter

I have my post request filtered after JWT Authentication (and even if I disable it as following code). Not sure if I do anything wrong.
URI REQUEST: localhost:8016/api/v1/VILLA+ITALIA/table
PARAMETER: name
enter image description here
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().disable().formLogin().disable()
.csrf().ignoringAntMatchers(API_URL_PREFIX, H2_URL_PREFIX)
.and()
.headers().frameOptions().sameOrigin() // for H2 Console
.and()
.cors()
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, RESTAURANT_URL).permitAll()
.antMatchers(HttpMethod.POST, RESTAURANT_URL).permitAll()
.antMatchers(HttpMethod.POST, TOKEN_URL).permitAll()
.antMatchers(HttpMethod.DELETE, TOKEN_URL).permitAll()
.antMatchers(HttpMethod.POST, SIGNUP_URL).permitAll()
.antMatchers(HttpMethod.POST, REFRESH_URL).permitAll()
.antMatchers(HttpMethod.GET, SERVICES_URL).permitAll()
.antMatchers(HttpMethod.POST, SERVICES_URL).permitAll()
.antMatchers(HttpMethod.GET, BOOKINGS_URL).permitAll()
.antMatchers(HttpMethod.POST, BOOKINGS_URL).permitAll()
.antMatchers(HttpMethod.GET, CUSTOMERS_URL).permitAll()
.antMatchers(HttpMethod.POST, CUSTOMERS_URL).permitAll()
.antMatchers(HttpMethod.POST, TABLES_URL).permitAll()
// .mvcMatchers(HttpMethod.POST, "/api/v1/restaurants**")
// .hasAuthority(RoleEnum.ADMIN.getAuthority())
.anyRequest().authenticated()
.and()
//.addFilterBefore(new JwtAuthenticationFilter(new JwtManager(), (UserService) userService), UsernamePasswordAuthenticationFilter.class)
// .oauth2ResourceServer(oauth2ResourceServer -> oauth2ResourceServer.jwt(
// jwt -> jwt.jwtAuthenticationConverter(getJwtAuthenticationConverter())))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
} ```
There are nothing antMatchers sentence which match with "/api/v1/VILLA+ITALIA/table" url.
Try it using the following sentence:
.antMatchers(HttpMethod.GET, "/api/v1/**/table").permitAll()

Users are able to access all endpoints after setting antMachers in Spring Security

I'm developing a spring-boot application and its spring security configuration is as follows:
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.authorizeRequests()
.antMatchers("/actuator/**", "/login*", "/logout*")
.permitAll();
httpSecurity
.cors().and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/taas/v1/**").hasRole("admin")
.antMatchers("/taas/v1/teams", "/taas/v1/profiles", "/taas/v1/tests/summary").hasRole("tester")
.antMatchers( "/taas/v1/teams", "/taas/v1/tests/summary").hasRole("user")
.anyRequest().authenticated()
.and()
.exceptionHandling().accessDeniedHandler(customAccessDeniedHandler)
.and()
.httpBasic()
.and()
.formLogin()
.successHandler(customAuthenticationSuccessHandler)
.failureHandler(customAuthenticationFailureHandler)
.and()
.logout()
.logoutSuccessHandler(customLogoutSuccessHandler())
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID");
}
}
Even though i have set the url pattern for each roles. All users are able to access all endpoints as mentioned in antMatchers(). A user with role user is not supposed to access /taas/v1/profiles. But when I try to access that endpoint by logging in as user, I'm getting the response but expected response is 403 forbidden.
I request someone to provide a workaround for me.
I got this issue resolved by doing some minor changes in my antMatchers(). Below is the modified code.
The main issue is that antMatcher() pattern must not contain the context path, see Spring security antMatcher does not work
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.cors()
.and()
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/profiles").hasAnyRole("TESTER")
.antMatchers( "/teams", "/tests/summary").hasAnyRole("USER", "TESTER", "ADMIN")
.anyRequest().authenticated()
.and().csrf().disable()
.exceptionHandling()
.accessDeniedHandler(customAccessDeniedHandler)
.and()
.httpBasic()
.and()
.formLogin()
.successHandler(customAuthenticationSuccessHandler)
.failureHandler(customAuthenticationFailureHandler)
.and()
.sessionManagement()
.invalidSessionUrl("/invalidSession.html")
.maximumSessions(1).sessionRegistry(sessionRegistry()).and()
.sessionFixation().none()
.and()
.logout()
.logoutSuccessHandler(customLogoutSuccessHandler())
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID");
}
}
Please verify the code that you're sharing because as you've mentioned. A user with role user is not supposed to access /ptaas/v1/profiles. But when I try to access that endpoint by logging in as user.
Where your mapping says you've not configured access to user role as given.
.antMatchers( "/taas/v1/teams", "/taas/v1/tests/summary").hasRole("user")
As per your comments it should have been .antMatchers( "/taas/v1/teams", "/taas/v1/tests/summary", "/ptaas/v1/profiles").hasRole("user")

Spring Security Ignores all requests when you should just ignore the OPTIONS requests

Before GET/POST request the client make a OPTIONS request, so I keep this calls ignored. But when I make this configuration, the another requests(GET/POST) are ignored too (but should not ignore).
When I add this line:
.antMatchers(HttpMethod.OPTIONS);
All requests are ignored, but the GET/POST should not ignored.
The following is the configuration method:
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(HttpMethod.POST, "/login")
.antMatchers(HttpMethod.OPTIONS);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.anyRequest().authenticated()
.antMatchers(HttpMethod.OPTIONS).permitAll()
.antMatchers(HttpMethod.GET, "/login/authenticate").authenticated()
.antMatchers(HttpMethod.GET, "/credenciadas**").hasRole(PermissaoEnum.CONSULTAR_CREDENCIADA.getNomeInterno())
.antMatchers(HttpMethod.POST, "/credenciadas/validar").hasRole(PermissaoEnum.CONSULTAR_CREDENCIADA.getNomeInterno())
.antMatchers(HttpMethod.POST, "/credenciadas").hasRole(PermissaoEnum.INCLUIR_CREDENCIADA.getNomeInterno())
.antMatchers(HttpMethod.POST, "/credenciadas/alterar").hasRole(PermissaoEnum.ALTERAR_CREDENCIADA.getNomeInterno())
.antMatchers(HttpMethod.DELETE, "/credenciadas/").hasRole(PermissaoEnum.EXCLUIR_CREDENCIADA.getNomeInterno())
.and()
.addFilterBefore(authenticationByTokenFilter(), UsernamePasswordAuthenticationFilter.class)
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint())
.and()
.csrf().disable();
}
Could you verify if you set the prefix string at role name as: "ROLE_"? The role name could be wrong.

Match everything but some specific path with Java configuration - antMatchers

Base on this Answer, I'm trying to secure everything but the login page in my spring app.
So I'm using this Java configuration files for OAuth2
The extends for the ResourceServerConfigurerAdapter:
#Override
public void configure(final HttpSecurity http) throws Exception {
http
.requestMatchers()
.antMatchers("/**")
.and()
.authorizeRequests()
.anyRequest()
.authenticated()
.antMatchers("/login")
.permitAll()
The extends for OAuth2SsoConfigurerAdapter {
#Override
public void match(RequestMatchers matchers) {
matchers.antMatchers("/login");
}
#Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest()
.authenticated()
}
So, what I looking for is to have a http 401 for every request but for /login.
If a login request is perform the #EnableOAuth2Sso annotation would be used to redirect it to the OAuth2 server.
Update 1
After changing the order of the filter ResourceServerConfigurerAdapter, the /login request is not found.
http
.requestMatchers()
.antMatchers("/**")
.and()
.authorizeRequests()
.antMatchers("/login")
.permitAll()
.anyRequest()
.authenticated()
This request would be Unauthorized because any token is provided
~/ http 401 Unauthorized (good)
~/resource http 401 Unauthorized (good)
But the login page is not found:
~/login http 404 Not Found (bad)
The correct functionality should be a http 302 redirection to the OAuth2 server when the ~/login is hit.

Resources