0
votes

Hi I guys I am developing application using spring boot and spring security in my application for authentication I using custom tokens and I am able to successfully authenticate users. Now I want to add custom authorization to my application I want authorization in following way:

Users of application are stored in database,roles and corresponding permissions assosiated with roles will be stored in database.I went through lot of articles on net but in all articles roles for user are generally hardcoded in preAuthorize method like preAuthorize(hasRole(Role_admin)) or preAuthorize(hasRole(Role_User)) could you please help me with any solutions so that that value of role will be compared with those that are saved in relational database, with customized UserDetails service I am able to fetch User object from databse but not this authorization thing could you please let me know if you have any links on this ?

My current security configuration is as follows:

@EnableWebMvcSecurity
@EnableWebSecurity(debug = false)
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private DashBoardUserService dashBoadUserService;

    @Autowired 
    private TokenUtils tokenUtils;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.authorizeRequests().antMatchers(IConstants.CAMEL_URL_MAPPING).hasRole(DashBoardUserService.ROLE_USER);
        http.headers().frameOptions().disable();
        SecurityConfigurer<DefaultSecurityFilterChain, HttpSecurity> securityConfigurerAdapter = new XAuthTokenConfigurer(
                userDetailsServiceBean(),tokenUtils);
        http.apply(securityConfigurerAdapter);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder authManagerBuilder) throws Exception {
        authManagerBuilder.userDetailsService(dashBoadUserService);
    }


    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

My custom userDetails Service is as follows:

@Service
public class DashBoardUserService implements UserDetailsService {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    public static final String ROLE_ADMIN = "ADMIN";
    public static final String ROLE_USER = "USER";

    private final IUserService userService; 

    @Autowired
    public DashBoardUserService(IUserService userService) {
        this.userService=userService;
    }
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        log.info("Loading user with userName : {} from database ", userName);
        DashBoardUser dashBoardUser = null;
        try {
            BusinessUser user = userService.getUserByUserName(userName);
            dashBoardUser = new DashBoardUser();
            BeanUtils.copyProperties(user, dashBoardUser);
        } catch (Exception e) {
            log.error("Exception occured while finding user", e);
        }
        if (dashBoardUser.getUsername() == null) {
            log.error("Username : {} not found in dashboard database.", userName);
            throw new UsernameNotFoundException(
                    String.format("userName : %s not found in dashboard database", userName));
        }
        return dashBoardUser;
    }

}
1

1 Answers

0
votes

you can use WebSecurityConfigurerAdapter where you can use datasource to get authentication by sql.

full example

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    DataSource dataSource;

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery("select username,password,enabled from s_admin where username=?")
                .authoritiesByUsernameQuery("select username,role from s_admin_roles where username=?");
    }
}