2

我正在为当前使用 Spring Security 的 Spring MVC 应用程序寻找 keycloak 的步骤。

我想在 Sitewhere 中使用keycloak

4

1 回答 1

1

如果我能完整阅读 keycloak 的文档,我想这太简单了:)。无论如何,这是我在Sitewhere迁移到 keycloak 时所遵循的步骤。

  1. 按照 keycloak doc 中给出的步骤进行spring-security
  2. 如适配器安装中所述,将依赖项添加到 sitewhere-core 和 sitewhere-web pom.xml
  3. 还要在 sitewhere-web 的 pom.xml 中添加 jboss-logging 依赖项,因为 keycloak spring 适配器对 jboss-logging 具有硬编码依赖项。
  4. 按照 api 示例修改 applicationcontext.xml 以便它可以在 web 和 api 中使用 keycloak

    <sec:http pattern="/api/**"  entry-point-ref="keycloakAuthenticationEntryPoint">
    <sec:custom-filter ref="keycloakPreAuthActionsFilter" before="LOGOUT_FILTER" />
    <sec:custom-filter ref="keycloakAuthenticationProcessingFilter" before="FORM_LOGIN_FILTER" />
    

  5. 修改 LoginManager.java 如下

    public static IUser getCurrentlyLoggedInUser() throws SiteWhereException {
    Authentication KeyCloakAuth = SecurityContextHolder.getContext().getAuthentication();
    if (KeyCloakAuth == null) {
        throw new SiteWhereSystemException(ErrorCode.NotLoggedIn, ErrorLevel.ERROR,
                HttpServletResponse.SC_FORBIDDEN);
    }
    
    KeycloakAccount  keyAccount = ((KeycloakAuthenticationToken) KeyCloakAuth).getAccount();
    
    String username = keyAccount.getKeycloakSecurityContext().getIdToken().getPreferredUsername();
    String password = "";
    
    IUser user = SiteWhere.getServer().getUserManagement().authenticate(username, password);
    List<IGrantedAuthority> auths =
            SiteWhere.getServer().getUserManagement().getGrantedAuthorities(user.getUsername());
    SitewhereUserDetails details = new SitewhereUserDetails(user, auths);
    
    
    Authentication auth = new SitewhereAuthentication(details, password);
    
    if (!(auth instanceof SitewhereAuthentication)) {
        throw new SiteWhereException("Authentication was not of expected type: "
                + SitewhereAuthentication.class.getName() + " found " + auth.getClass().getName()
                + " instead.");
    }
    return (IUser) ((SitewhereAuthentication) auth).getPrincipal();
    

    }

  6. 因为,我们已经将我们的身份验证迁移到 keycloak,并且我们不会在 siter 中获取用户的凭据,最好在 IUserManagement 的身份验证方法中取消与密码验证相关的代码。以下是来自 MongoUserManagement.java 的示例

    public IUser authenticate(String username, String password) throws SiteWhereException {
    if (password == null) {
        throw new SiteWhereSystemException(ErrorCode.InvalidPassword, ErrorLevel.ERROR,
                HttpServletResponse.SC_BAD_REQUEST);
    }
    DBObject userObj = assertUser(username);
    String inPassword = SiteWherePersistence.encodePassoword(password);
    User match = MongoUser.fromDBObject(userObj);
    //nullify authentication since we are using keycloak
    /*if (!match.getHashedPassword().equals(inPassword)) {
        throw new SiteWhereSystemException(ErrorCode.InvalidPassword, ErrorLevel.ERROR,
                HttpServletResponse.SC_UNAUTHORIZED);
    }*/
    
    // Update last login date.
    match.setLastLogin(new Date());
    DBObject updated = MongoUser.toDBObject(match);
    DBCollection users = getMongoClient().getUsersCollection();
    BasicDBObject query = new BasicDBObject(MongoUser.PROP_USERNAME, username);
    MongoPersistence.update(users, query, updated);
    
    return match;}
    
  7. 确保您在 keycloak 中具有更特定于 sitewhere 的用户各自的角色。

  8. 更改您的主页,使其重定向到 keycloak 以进行身份​​验证。以下是重定向示例:

        Tracer.start(TracerCategory.AdminUserInterface, "login", LOGGER);
    try {
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("version", VersionHelper.getVersion());
        String keycloakConfig = environment.getProperty("AUTHSERVER_REDIRECTION_URL");          
        if (SiteWhere.getServer().getLifecycleStatus() == LifecycleStatus.Started) {
            return new ModelAndView("redirect:"+keycloakConfig);
        } else {
            ServerStartupException failure = SiteWhere.getServer().getServerStartupError();
            data.put("subsystem", failure.getDescription());
            data.put("component", failure.getComponent().getLifecycleError().getMessage());
            return new ModelAndView("noserver", data);
        }
    } finally {
        Tracer.stop(LOGGER);
    }
    
于 2015-10-20T11:25:54.957 回答