我想写授权使用的Spring安全。用户数据将保存在couchDB中。我在使访问方法成为可能方面遇到了问题。
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
@Transactional
public void deleteDriver(Driver driver) {
dataService.deleteDrivers(driver);
}..此批注@PreAuthorize不起作用。我写道:
<global-method-security secured-annotations="enabled" pre-post-annotations="enabled" jsr250-annotations="enabled"> 到Aplication context-security.xml中
发布于 2015-02-24 10:34:06
我打赌你已经解决了你的问题,但也许这可以帮助其他人...
1-应用程序的配置
您需要添加自己的UserDetailsService.实现
public class AppConfig extends WebMvcAutoConfiguration {
...
@Bean
public UserSecurityService userSecurityService() {
return new UserSecurityService();
}
...
}2用户实体
public class CustomUserDetail extends org.springframework.security.core.userdetails.User {
public CustomUserDetail(String username, String password, Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
}
}3- UserRepository
@Component
public class UserRepository extends CouchDbRepositorySupport<User> {
...
@View( name = "findUserByUsername", map = "function(doc) { if (doc.docType == 'User' ) emit( doc.username, doc._id ) }")
public User findUserByUsername(String username) {
return queryViewReturnSingleEntity("findUserByUsername",username);
}
...
}4- UserDetailsService,UserSecurityService的实施
public class UserSecurityService implements UserDetailsService {
@Autowired
private UserRepository userRepo;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException
{
//Spring user
UserDetails userDetails = null;
//CouchDB Object
User user = userRepo.getByUsername(username);
List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
String rol = user.getRol();
grantedAuths.add(new SimpleGrantedAuthority(rol));
if(user != null){
//Spring user implementation
userDetails = new CustomUserDetail(user.getUsername(), user.getPassword(), grantedAuths);
}
if (userDetails == null) {
throw new UsernameNotFoundException("User not found");
}
return userDetails;
}
}5-最后,您必须扩展GlobalMethodSecurityConfiguration
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
return expressionHandler;
}
}现在,您可以添加以下内容:
@PreAuthorize("hasRole('ROLE_SUPER_USER')")验证用户角色的访问权限。
https://stackoverflow.com/questions/3777702
复制相似问题