29279

Spring Boot Role Based Authentication

Question:

I have a problem concerning Spring Boot role based authentication. Basically, I would like to have users and admins and I want to prevent users from accessing admin resources. So I created a SecurityConfig class:

package test; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity; @Configuration @EnableWebMvcSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user1").password("password1").roles("USER, ADMIN") .and() .withUser("user2").password("password2").roles("USER"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/service/test").access("hasRole('USER') or hasRole('ADMIN')") .antMatchers("/service/admin").access("hasRole('ADMIN')"); } }

This is my little REST service:

package test; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/service") public class RestService { @RequestMapping(value = "/test", method = RequestMethod.GET) public String echo() { return "This is a test"; } @RequestMapping(value = "/admin", method = RequestMethod.GET) public String admin() { return "admin page"; } }

And my Application class:

package test; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @EnableAutoConfiguration public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }

Unfortunately, I always get a 403 "forbidden/access denied" error message when executing "curl user1:password1@localhost:8080/service/admin"... Did I miss anything in the configure method?

Thank you very much in advance!

Answer1:

Can you please check this.<br />

withUser("user1").password("password1").roles("USER", "ADMIN")

write "USER" and "ADMIN" in separate qoutes.

Answer2:

I changed it in the following way, now it seems to be working:

@Configuration @EnableWebMvcSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user1").password("password1").roles("USER", "ADMIN") .and() .withUser("user2").password("password2").roles("USER"); } @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin().permitAll() .and() .authorizeRequests() .antMatchers("/service/test").hasAnyRole("USER", "ADMIN") .antMatchers("/service/admin").hasRole("ADMIN") .anyRequest().authenticated(); } }

Thank you very much for your answers!

Answer3:

following setup works fine for my spring boot app:

http.authorizeRequests() .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()//allow CORS option calls .antMatchers("/home", "/").hasAnyAuthority(Role.ROLE_ADMIN, Role.ROLE_USER) .antMatchers("/admin").hasAuthority(Role.ROLE_ADMIN)enter code here

Recommend

  • How to authenticate user name and password against Active Directory Federation Services (ADFS)?
  • Django: DRY principle and UserPassesTestMixin
  • Telerik Radgrid GridDataItem.DataItem is empty when updating (OnUpdateCommand handler)
  • Call task's updateProgress
  • Drag and Drop in JList is not working
  • How to work with Master Page that is attached to the page via the page's basepage?
  • Symfony2 and MVC - Is extend controller a good practice?
  • Is it mandatory to have a doGet or doPost method?
  • Is it safe to accept URL parameters for populating the `url_for` method?
  • ASP.NET RegularExpressionValidator, validate on a non-match?
  • Replace Fragment with another on back button
  • Adding Parent and Child Nodes in TreeView from Sql Server 2008
  • How to upload specific List image using click on Upload button
  • Django return user model id with L
  • Configure Spring's MappingJacksonHttpMessageConverter
  • Blackberry 6: how to detect a long click on track pad?
  • unable to get jsonEncode in magento2
  • Authentication failed with Azure Active Directory in Windows Phone
  • How to get listview position?
  • How do I retrieve the user information of a user authenticated with Apache's mod_ldap?
  • Autofac with Web API 2 - Parameter-less constructor error
  • Laravel: Getting Session ID oddly truncates when using foreach
  • How do I configure context broker accept post requests from my remote sensor?
  • Bypass multiple inheritance in Java
  • Creating Java object from class name with constructor, which contains parameters [duplicate]
  • How to use RequestBodyAdvice
  • Recording logins for password protected directories
  • how to do an event when i swipe from fragment to the other
  • Array.prototype.includes - not transformed with babel
  • swift auto completion not working in Xcode6-Beta
  • How to redirect a user to a different server and include HTTP basic authentication credentials?
  • Android Studio and gradle
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • unknown Exception android
  • EntityFramework adding new object to nested object collection
  • Checking variable from a different class in C#
  • How to get NHibernate ISession to cache entity not retrieved by primary key
  • How can i traverse a binary tree from right to left in java?
  • failed to connect to specific WiFi in android programmatically
  • How can I use threading to 'tick' a timer to be accessed by other threads?