spring boot spring security基于自定义令牌的身份验证和自定义授权

时间:2016-02-26 12:13:05

标签: spring-boot spring-security

大家好我们正在我的应用程序中使用spring boot和spring security开发应用程序进行身份验证我使用自定义令牌,并且我能够成功验证用户身份。 现在我想为我的应用程序添加自定义授权我希望通过以下方式授权:

应用程序的用户存储在数据库中,角色和与角色相关的相应权限将存储在数据库中。我在网上经历了很多文章,但在所有文章中,用户的角色通常都在preAuthorize方法中进行硬编码,如preAuthorize(hasRole( Role_admin))或preAuthorize(hasRole(Role_User))你可以帮我解决任何解决方案,以便将角色的值与保存在关系数据库中的角色进行比较,使用自定义的UserDetails服务我可以从数据库中获取用户对象但是,如果你有这方面的链接,请不要告诉我这个授权的事情吗?

我目前的安全配置如下:

@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();
    }
}

我的自定义userDetails服务如下:

@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 个答案:

答案 0 :(得分:0)

您可以使用 WebSecurityConfigurerAdapter ,您可以使用数据源通过sql进行身份验证。

完整示例

@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=?");
    }
}