4

I am developing a web service which uses Spring Security toolbox for authorizing the request by the 'Authority'. Naturally, the web service has a configuration class which extends to WebSecurityConfigurerAdapter class and overrides the configure(HttpSecurity http) method.

Within the method I have written the profiles (roles or Authorities) with the follow code:

           http
              .authorizeRequests() 
                         .antMatchers("/**").hasAnyAuthority("PERFIL")      
                         .anyRequest().authenticated()
                         .and() 
             .logout().clearAuthentication(true)
                      .invalidateHttpSession(true)
                      .and()

             .csrf().disable(); 

It works very well, however I would want to charge dynamic profiles (roles or Authorities) from a database because I want to change them without changing the web service.

Does someone know how could do it?

Regards.

J. Abel
  • 890
  • 3
  • 17
  • 38

3 Answers3

0

There are many configurations which you will have to change in order to pass those details from database.

Use jdbc-user-service to define a query to perform database authentication.

<authentication-manager>
      <authentication-provider>
        <jdbc-user-service data-source-ref="dataSource"
          users-by-username-query=
            "select username,password, enabled from users where username=?"
          authorities-by-username-query=
            "select username, role from user_roles where username =?  " />
      </authentication-provider>
    </authentication-manager>

Follow this tutorial to learn how Spring Security works.

Rohan Kadu
  • 1,311
  • 2
  • 12
  • 22
  • Hi Rohan. I have already changed Authority for each user in the authentication, but I am trying to use dynamic Role in the configure(HttpSecurity http) method i.e. I want to change the code `.antMatchers("/**").hasAnyAuthority("PERFIL")` by something like this (this code does not exist, obviously): `.antMatchers("/**").hasAnyAuthority("?")`, such that `?` has to change when the service starts and based on a query to a database. It is the idea, but I do know if it is the form correct. – J. Abel Dec 20 '17 at 16:01
  • Hi Abel, Have you gone through following link. https://stackoverflow.com/questions/8321696/creating-new-roles-and-permissions-dynamically-in-spring-security-3 – Rohan Kadu Dec 20 '17 at 16:07
0

You can find a full working example here.

Although the logic is reversed in my project, you can extract information that will help with your case (as in how to "inject" these authorities to spring security)

In Authorities class i have defined 2 static authorities. This is the point where you can fetch your Authorities from the db. You could have an empty List<Authority> which will get populated from the db automatically when your application starts (see @PostConstruct).

Your Authority class should implement spring's GrantedAuthority as in here.

alextsil
  • 504
  • 3
  • 11
  • 26
0

the simplest way is when your roles are not change.for example you have 7 part in your system, admin panel(just for see the panel and do nothing), users etc. like below:

 http.csrf().disable()
 .authorizeRequests().antMatchers("/","/css/**","/js/**","/img/**","/loginUser/**","/users/**","/webfonts/**",
 "/productsList/**","/collectionList/**","/artists/**"
 ,"/loginCllients"
 ).permitAll()
 .antMatchers("/admin").hasAuthority("1")
 .antMatchers("/admin/users/**").hasAuthority("2")
 .antMatchers("/admin/products/**").hasAuthority("3")
 .antMatchers("/admin/collections/**").hasAuthority("4")
 .antMatchers("/admin/categoryies/**").hasAuthority("5")
 .antMatchers("/admin/authorities/**").hasAuthority("6")

also have this below code:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    
    auth.jdbcAuthentication().dataSource(dataSource)
    .passwordEncoder(NoOpPasswordEncoder.getInstance())
             .passwordEncoder(new BCryptPasswordEncoder())
            .usersByUsernameQuery("select username,password, enabled from users where username = ?")
            .authoritiesByUsernameQuery("select username,authorities from authorities where username = ?");
}

now you should create an table for this permissions like below:

private int id;
private String username;
private String authorities;

public Authorities() {
    super();
}

public Authorities(int id, String username, String authorities) {
    super();
    this.id = id;
    this.username = username;
    this.authorities = authorities;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getAuthorities() {
    return authorities;
}

public void setAuthorities(String authorities) {
    this.authorities = authorities;
}

}

and put some code for insert role for every username. for example admin username have 5 role. roles 1,2,3,4,5 notice : if you want to dynamic roles the approach were be different. I hope it is helpfull.