how to secure only one url with spring security and permit all - java

Im trying to configure Spring security to block only request to swagger, however it is blocking all urls.
Does anyone know how to only lock the swagger's url and leave all the rest not secured?
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests().anyRequest().permitAll()
.and()
.authorizeRequests()
.antMatchers("/swagger*/**").authenticated();
http.httpBasic();
}

Try the following:
http.authorizeRequests()
.antMatchers("/swagger*/**").authenticated()
.anyRequest().permitAll()
.and()
.csrf().disable();
This should only authenticate swagger but permit the rest of the requests.

Is this what you intent ?
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/swagger*/**").authenticated()
.anyRequest().permitAll();
http.httpBasic();
}

Related

Why does Spring Security demand password for permitAll() url?

Here is URL I want to access
http://localhost:8080/swagger-ui/index.html.
Here is my Security config, both h2-console and swagger url and accesible only with password.
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.requestMatchers(req -> req.getRequestURI().contains("admin")).hasAuthority(Role.ADMIN.getAuthority())
.antMatchers("/h2-console/").permitAll()
.antMatchers("/swagger-ui/index.html").permitAll()
.anyRequest().authenticated()
.and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.headers().frameOptions().disable()
.and()
.httpBasic();
}
In my app, i have this configuration which works for me...
private static final String[] AUTH_WHITELIST = {
// -- swagger ui
"/swagger-resources/**",
"/swagger-ui",
"/swagger-ui/",
"/swagger-ui/**",
"/v2/api-docs",
"/webjars/**"
};
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(AUTH_WHITELIST).permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.and()
.logout();
}

Spring boot security to allow all endpoints except one

For a project that has no spring security. All controllers (GET/POST) of the project are not secured and should stay unsecured. But now, I have a new Controller and i want to secure its path (/private), sub-pathes and parameters. Only this one path must be secured with Basic Authentication. Why is my code not working?
#Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**").permitAll()
.antMatchers("/private**").hasAuthority("ADMIN").and().httpBasic();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user")
.password("{noop}pass")
.roles("ADMIN");
}
}
http.csrf()
.disable()
.authorizeRequests()
.antMatchers("/private").hasRole("ADMIN")
.antMatchers("/private/**").hasRole("ADMIN")
.antMatchers("/**").permitAll()
.and()
.httpBasic();
or
http.csrf()
.disable()
.authorizeRequests()
.antMatchers("/private").hasRole("ADMIN")
.antMatchers("/private/**").hasRole("ADMIN")
.anyRequest().permitAll()
.and()
.httpBasic();

Oauth protected rest api is working without bearer token

The Rest endpoint is protected with OAuth but for some reason, I can hit /users/user without the token. Please let me know what is missing.
In my resource class, I have mentioned below configurations to protect the endpoint.
#Override
public void configure(HttpSecurity http) throws Exception {
http.
anonymous().disable()
.authorizeRequests()
.antMatchers("/users/**")
.access("hasRole('ADMIN')")
.and()
.exceptionHandling()
.accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
Maybe need more information, but try this:
#Override public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/users*//**").access("hasRole('ADMIN')")
.and().exceptionHandling()
.accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
or original pattern "/users/**"

Ignore filters executing on requests made to specific endpoints

I have the following config method for my WebSecurityConfig that extends WebSecurityConfigurerAdapter:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/login").permitAll()
.and()
.authorizeRequests()
.antMatchers("/signup").permitAll()
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.addFilterBefore(
new JWTAuthenticationFilter(userDetailsServiceBean()),
UsernamePasswordAuthenticationFilter.class);
}
JWTAuthenticationFilter actually filters requests received on all endpoints, and checks if they have the correct JWT authentication token in their headers.
I don't expect this filter to execute on requests made to the /login endpoint ! Is there a way to ignore the filter for special endpoints ? (here /login and /signup).
Is there any good reason to keep this filter executing on requests made to all endpoints including login and signup ?
You can try adding the following
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/login**", "/signup**");
}

Java based configuration to enable spring security anonymous access

I want to enable the use of "ROLE_ANONYMOUS" to allow anonymous access to some urls in my app. And I used the below configuration.
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.requestCache()
.requestCache(new NullRequestCache()).and()
.anonymous().authorities("ROLE_ANONYMOUS").and()
.exceptionHandling().and()
.servletApi().and()
.headers().cacheControl().and()
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/profile/image").permitAll()
.antMatchers("/favicon.ico").permitAll()
.antMatchers("/resources/**").permitAll()
//.antMatchers(HttpMethod.GET, "/login/**").permitAll()
//.antMatchers(HttpMethod.GET, "/location/**").permitAll()
.anyRequest().authenticated()/*.and()
.apply(new SpringSocialConfigurer())*/;
// custom Token based authentication based on the header previously given to the client
//.addFilterBefore(new StatelessAuthenticationFilter(tokenAuthenticationService), UsernamePasswordAuthenticationFilter.class);
}
My controller looks like:
#RestController
#RequestMapping(value="/login", produces="application/json")
public class LoginController {
#Secured( value={"ROLE_ANONYMOUS"})
#RequestMapping(method=RequestMethod.GET)
public String get(){
return "hello";
}
}
But when I try to hit "/login" I get 403 access denied error.
Please help me how I can enable annotation based anonymous access.
This should solve your issue.
#Override
protected void configure(HttpSecurity http) throws Exception {
http
...
.formLogin().loginPage("/login").permitAll()
...
But if you prefer not to use permitAll but to stick to anonymous roled user (it would be the same effect on both situation but yet if that's wht you prefer) then try this in the controller.
#Secured("ROLE_ANONYMOUS")
#RequestMapping(method=RequestMethod.GET)
public String get(){
...
As Faraj Farook wrote, you have to permit access to your login page URL. You commented the relevant line out:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.anonymous()
.authorities("ROLE_ANONYMOUS")
.and()
.headers()
.cacheControl()
.and()
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/profile/image").permitAll()
.antMatchers("/favicon.ico").permitAll()
.antMatchers("/resources/**").permitAll()
.antMatchers(HttpMethod.GET, "/login/**").permitAll()
.anyRequest().authenticated()
}
But if you prefer not to use permitAll() you could use hasAuthority("ROLE_ANONYMOUS"). In this case you don't need to annotate your method with
#Secured( value={"ROLE_ANONYMOUS"}).

Categories