首页 文章

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

提问于
浏览
0

嗨,大家好我在我的应用程序中使用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

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

相关问题