Cas和Spring例子:我不明白"setUserDetailsService"

Cas and Spring example: I don't understand "setUserDetailsService"

在这个例子中:https://www.baeldung.com/spring-security-cas-sso

有这段代码:

@Bean
public CasAuthenticationProvider casAuthenticationProvider() {

    CasAuthenticationProvider provider = new CasAuthenticationProvider();
    provider.setServiceProperties(serviceProperties());
    provider.setTicketValidator(ticketValidator());
    provider.setUserDetailsService(
      s -> new User("casuser", "Mellon", true, true, true, true,
        AuthorityUtils.createAuthorityList("ROLE_ADMIN")));
    provider.setKey("CAS_PROVIDER_LOCALHOST_9000");
    return provider;
}

我不明白这部分:

provider.setUserDetailsService(
      s -> new User("casuser", "Mellon", true, true, true, true,
        AuthorityUtils.createAuthorityList("ROLE_ADMIN")));
  1. 我们应该在这里放什么?我是否应该创建自己的 UserDetailsS​​ervice(如果是,如何创建?)?我预计会有一些 'default cas user detail service'...
  2. 这段代码是如何工作的?创建用户以提供 UserDetailsS​​ervice ?

这就是 Spring 安全在高级别上的工作方式。

用户尝试通过某种类型的 UI(例如 CAS 的一部分)进行身份验证。 UI 会将 username/password 传递给 Spring。 Spring 最终会调用 UserDetailService.loadUserByUsername 并将用户名传递给它,如果用户存在,UserDetailService 将 return 非空 UserDetails。如果为 null UserDetails 或具有不同密码 Spring 的非 null 将无法通过身份验证。

CAS 只是一个身份验证服务器,它没有公开如何存储用户。您可以选择使用 LDAP 或数据库。该选择基于 UserDetailService 的不同实现。再看看javadoc。它包含您可以使用的默认实现列表。

请参阅链接教程的第 5 部分。它显示了如何更改 CAS 和 Spring Boot 应用程序以使用数据库作为用户存储。这里的关键是,为了让后端与 CAS 服务器一起针对存储在数据库中的用户进行工作,两者都需要适当地配置,以便根据数据库查找用户。 CAS 通过 application.properties 配置,Spring 通过 UserDetailService 启动。

现在在评论中回答您的问题:

why should the client bother about how cas server store the users ?

客户不必理会 UserDetailService。它仅供受 CAS 保护的后端服务使用。

Just to be sure that I get it tight: if I just need to know 'is that user connected?' then CAS is enough and I will never use UserDetailService. But if I need some information about the user (name, telephone etc..) then I call the UserDetailService to load it (from db, ldap or whatever).

是也不是。您不需要将密码存储在 UserDetails 中,但您需要能够 return UserDetails 才能成功通过 CAS 身份验证的用户。从您的链接教程中查看此部分:

Note again that the principal in the database that the server uses must be the same as that of the client applications.