我基于spring-security-pac4j-demo编写了使用spring-security与pac4j和CAS集成的web应用程序,并具有以下依赖项:
compile "org.pac4j:pac4j-core:1.8.8"
compile "org.pac4j:pac4j-cas:1.8.8"
compile "org.pac4j:spring-security-pac4j:1.4.3"
compile "org.springframework.security:spring-security-core:4.1.0.RELEASE"
然而,当我试图升级到spring-security-pac4j的 2.0.0版本时,我意识到该方法完全改变了。在我使用自定义类UserDetailService:
加载用户角色之前@Component("userDetailsService")
public class UserDetailsService implements AuthenticationUserDetailsService<ClientAuthenticationToken> {
private final Logger log = LoggerFactory.getLogger(UserDetailsService.class);
@Inject
private UserRepository userRepository;
@Override
@Transactional
public UserDetails loadUserDetails(ClientAuthenticationToken token) throws UsernameNotFoundException {
String username = token.getUserProfile().getId().toLowerCase();
log.debug("Authenticating {}", username);
Optional<User> userFromDatabase = userRepository.findOneByUsername(username);
if (!userFromDatabase.isPresent()) {
throw new UsernameNotFoundException("User " + username + " was not found in the database");
} else if (!userFromDatabase.get().getActivated()) {
throw new UserNotActivatedException("User " + username + " was not activated");
}
Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
for (Authority authority : userFromDatabase.get().getAuthorities()) {
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(authority.getName());
grantedAuthorities.add(grantedAuthority);
}
return new org.springframework.security.core.userdetails.User(username,username, grantedAuthorities);
}
}
通过一些额外的配置,spring-security正在检查带@Secured注释的控制器上的用户角色访问权限。
@Controller
@RequestMapping("/app/*")
public class SecureController {
@Secured("ROLE_ADMIN")
@RequestMapping("/secure/admins")
public String admins(Model model) {
model.addAttribute("roleName", "ROLE_ADMIN");
return "secure";
}
@Secured("ROLE_USER")
@RequestMapping("/secure/users")
public String users(Model model) {
model.addAttribute("roleName", "ROLE_USER");
return "secure";
}
}
使用spring-security-pac4j的版本2.0.0,即使查看演示,我仍然不知道从哪里开始,以便使用新版本的pac4j更新我的项目,并使其与@Secured注释一起工作。如果有人能提供任何提示和/或指导,我将不胜感激。
我是pac4j和spring-security-pac4j的创建者
是的,2.0版本确实不同,但这是必要的,以便从所有pac4j特性中受益。
CAS认证成功后,将创建CasProfile
并将其保存在安全上下文中(在Pac4jAuthentication
令牌中)。要为您的配置文件计算特定的角色(例如,通过从数据库中获取它们),您需要创建一个新的AuthorizationGenerator
并将其附加到客户端:casClient.addAuthorizationGenerator(myAuthGenerator);