0
您好我正在開發應用程序使用春季啓動和春季安全在我的應用程序進行身份驗證我使用自定義令牌,我能夠成功地驗證用戶。 現在我想給我的應用程序添加自定義授權我想以下列方式授權:春季啓動彈簧安全自定義令牌基於身份驗證和自定義授權
應用程序的用戶存儲在數據庫中,角色和與角色相關聯的相應權限將存儲在數據庫中。我經歷了很多關於net,但是在用戶的所有文章角色中,通常在像preAuthorize(hasRole(Role_admin))或preAuthorize(hasRole(Role_User))這樣的preAuthorize方法中對其進行硬編碼,請幫助我解決任何解決方案,以便將角色的價值與那些被保存在關係型數據庫中,具有自定義的UserDetails服務我能夠從數據庫中獲取User對象,但不能獲得這個授權的東西,請讓我知道你是否有任何鏈接?
我當前的安全配置如下:
@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;
}
}
嗨wcong感謝回覆通過看編輯的問題,請您建議我任何答案 –
也是我需要關於如何採取從數據庫值securityconfigs http.authorizeRequests()輸入。antmatchers( ).hasRole(「Role_Admin」)來自數據庫的Role_Admin字段以及如何使用PreAuthorize註釋檢查方法級安全性中的相同 –