【问题标题】:spring boot spring security custom token based authentication and custom authorizationspring boot spring security 基于自定义令牌的身份验证和自定义授权
【发布时间】:2016-06-09 15:38:11
【问题描述】:

大家好,我正在开发应用程序,在我的应用程序中使用 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如下:

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

}

【问题讨论】:

    标签: spring-boot spring-security


    【解决方案1】:

    您可以使用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=?");
        }
    }
    

    【讨论】:

    • 您好 wcong 感谢您看到已编辑的问题的回复,您能建议我任何答案吗
    • 我还需要输入有关如何从 securityconfigs http.authorizeRequests().antmatchers().hasRole("Role_Admin") Role_Admin's field from database 中的数据库中获取值以及如何在方法级别检查相同的输入PreAuthorize 注释的安全性
    猜你喜欢
    • 2020-12-05
    • 2018-12-11
    • 2021-04-21
    • 2012-10-25
    • 2014-04-20
    • 2014-12-13
    • 2016-09-05
    • 2016-11-30
    • 2016-08-05
    相关资源
    最近更新 更多