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();
}
Related
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();
I want to put restriction on this "/realtime/updates" Url but If I request "/anyurl" it redirects me to Login page. I want to be redirected to login page only for "/realtime/updates".
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecConfig1 extends WebSecurityConfigurerAdapter {
#Override
public void configure(WebSecurity web) throws Exception {
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests().antMatchers("/realtime/updates").hasRole("USER").anyRequest().authenticated().and().formLogin();
}
#Autowired
public void ConfigGlobal(AuthenticationManagerBuilder auth) throws Exception{
auth.inMemoryAuthentication().withUser("abc").password("123").roles("USER");
}
}
You need to change one snippet in the protected void configuremethod.
Try this:
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.authorizeRequests()
.antMatchers("/**").permitAll()
.antMatchers("/realtime/updates").hasRole("USER")
.and().formLogin().permitAll();
}
You need to add your restrictions in configure method.Your method like below :
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/realtime/updates/**").authenticated()
.antMatchers("/otherURL/**").hasRole("ADMIN")
.and()
.exceptionHandling().accessDeniedPage("/login")
.and()
.formLogin().loginPage("/index")
.usernameParameter("username")
.passwordParameter("password")
.loginProcessingUrl("/j_spring_security_check")
.failureUrl("/loginControl?error=true")
.defaultSuccessUrl("/loginControl?error=false")
.and()
.logout().logoutUrl("/logout").logoutSuccessUrl("/index")
;
}
I was calling super.configure(http); inside configure method I removed that it worked.
This is was previous code:
#Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests().antMatchers("/realtime/updates")
.hasRole("USER")
.anyRequest()
.authenticated()
.and()
.formLogin();
}
This is current code that worked:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/realtime/updates")
.hasRole("USER")
.anyRequest()
.authenticated()
.and()
.formLogin();
}
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();
}
I've a REST endpoint in my Spring project /public/signUser; I want to authorize this endpoint without credentials in order to allow to create user. But if I try to do a POST request for signUser endpoint I received unauthorized error. I want to disable for this endpoint the authentication.
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Inject
private UserDetailsService userDetailsService;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http .httpBasic().and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/public/signUser").permitAll()
.antMatchers("/public/hello", "/swagger-ui/**", "/api-docs/**").permitAll()
.antMatchers("/protected/**").authenticated()
.and()
.httpBasic()
.realmName("PlcManager")
.and()
.csrf()
.disable();
}
}
For multiple purposes I need to use
SecurityContextHolder.getContext().getAuthentication()
methods in my controllers/services.
I did migrate my app to Spring Boot 1.4.1 from XML configured Spring MVC app (now only Java configs), similar approach worked before.
I have a problem calling SecurityContextHolder.getContext().getAuthentication(), for example in this controller:
#RestController
#Secured("IS_AUTHENTICATED_ANONYMOUSLY")
#RequestMapping("utils")
public class UtilsController {
#RequestMapping(value = "/check_auth", method = RequestMethod.GET)
public Boolean getAuthState() throws SQLException {
if (SecurityContextHolder.getContext().getAuthentication() == null){
logger.info("Auth obj null");
}
if (SecurityContextHolder.getContext().getAuthentication().getName() != null && SecurityContextHolder.getContext().getAuthentication().getName() != "anonymousUser") {
return true;
} else return false;
}
}
it always returns null. Can't figure out why anonymous authentication is not working.
Here is the Spring Security configuration:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).and()
.formLogin()
.successHandler(ajaxSuccessHandler)
.failureHandler(ajaxFailureHandler)
.loginProcessingUrl("/authentication")
.passwordParameter("password")
.usernameParameter("username")
.and()
.logout()
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true)
.logoutUrl("/logout")
.logoutSuccessUrl("/")
.and()
.csrf().disable()
// .anonymous().disable()
.authorizeRequests()
// .anyRequest().anonymous()
.antMatchers("/utils").permitAll()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/admin/*").access("hasRole('ROLE_ADMIN')")
.antMatchers("/user/*").access("hasRole('ROLE_USER')");
}
I did tried with and without #Secured annotation on the controller.
.authorizeRequests()
// .anyRequest().anonymous()
.antMatchers("/utils").permitAll()
different variations with this settings.
You are getting null with:
SecurityContextHolder.getContext().getAuthentication()
because you are not authenticating within you security configuration.
You can add a simple:
.authenticated()
.and()
// ...
.formLogin();
in case you're using form login.
Now after you'll authenticate each request you suppose to get something other than null.
Here's an example from Spring Security docs:
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**", "/signup", "/about").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
.anyRequest().authenticated()
.and()
// ...
.formLogin();
}