Jakarta EE 8 安全 > Wildfly 26 Elytron - 角色未设置

Jakarta EE 8 Security > Wildfly 26 Elytron - Role not being set

我正在尝试使用 Jakarta EE 8 Security 设置一个简单的 JSF 登录,我已将登录页面实现为自定义表单,如下所示:

@ApplicationScoped
@CustomFormAuthenticationMechanismDefinition(
    loginToContinue = @LoginToContinue(
        loginPage = "/user-login.xhtml",
        useForwardToLogin = false,
        errorPage = ""
    )
)
@FacesConfig(version = FacesConfig.Version.JSF_2_3)
public class UserLoginConfig{
}

用户区域由以下 servlet 保护并定义了一个角色 'user':

@WebServlet("/user/*")
@DeclareRoles({"user"})
@ServletSecurity(@HttpConstraint(rolesAllowed = "user"))
public class UserLoginServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

}

简单的 JSF 表单提交到 LoginBacking bean

@Named
@ViewScoped
public class LoginBean implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private String password;
 
    private String email;
 
    @Inject private SecurityContext securityContext;
    @Inject private Logger log;
    
    public void login() throws IOException {

        ExternalContext externalContext = Faces.getExternalContext();
        AuthenticationStatus status = securityContext.authenticate(
            (HttpServletRequest) externalContext.getRequest(),
            (HttpServletResponse) externalContext.getResponse(),
            AuthenticationParameters.withParams()
              .credential(new UsernamePasswordCredential(email, password))
        );
        switch (status) {
            case SEND_CONTINUE:
                Faces.getContext().responseComplete();
                break;
            case SEND_FAILURE:
                Faces.getContext().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "Login failed", null));
                break;
            case SUCCESS:
                Faces.getContext().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_INFO, "Login succeed", null));
                externalContext.redirect(externalContext.getRequestContextPath() + "/user/home.xhtml");
                break;
            case NOT_DONE:
        }
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
    
    
}

并且支持 bean 触发在自定义 ItentityStore

中实现的身份验证方法
@ApplicationScoped
public class MyIdentityStore implements IdentityStore {
    
    @Inject private UserDAOQueries userDAOQueries;
    @Inject private PasswordEncryptorEntities passwordEncryptor;

    @Override
    public int priority() {
        return 90;
    }

    @Override
    public Set<ValidationType> validationTypes() {
        return EnumSet.of(ValidationType.VALIDATE);
    }
    
    @Override
    public CredentialValidationResult validate(Credential credential) {
 
        UsernamePasswordCredential login = (UsernamePasswordCredential) credential;
 
        User user = userDAOQueries.findNonDeletedByEmail(login.getCaller());
        if (user!=null) {
            if(passwordEncryptor.isPasswordCorrect(login.getPasswordAsString(), user.getPassword())){
                Set<String> roles = new HashSet<String>();
                roles.add("user");
                
                return new CredentialValidationResult(login.getCaller(), roles);
            }else {
                return CredentialValidationResult.INVALID_RESULT;
            }
            
        } else {
            return CredentialValidationResult.NOT_VALIDATED_RESULT;
        }
    }

    @Override
    public Set<String> getCallerGroups(CredentialValidationResult validationResult) {
        Set<String> roles = new HashSet<String>();
        if(validationResult.getStatus().equals(Status.VALID)) {
            roles.add("user");
        }
        return roles;
    }
}

一切正常,用户被成功转发到 /user/home.xhtml 页面,但是我随后从服务器收到 403 Forbidden 响应。 查看 org.wildfly.security TRACE,我可以看到 'user' 角色在身份验证后没有传递给容器(或者它们没有被正确映射)。

11:47:16,055 TRACE [org.wildfly.security] (default task-4) Handling CallerPrincipalCallback
11:47:16,055 TRACE [org.wildfly.security] (default task-4) Original Principal = 'javax.security.enterprise.CallerPrincipal@317242d5', Caller Name = 'null', Resulting Principal = 'javax.security.enterprise.CallerPrincipal@317242d5'
11:47:16,056 TRACE [org.wildfly.security] (default task-4) Role mapping: principal [javax.security.enterprise.CallerPrincipal@317242d5] -> decoded roles [] -> domain decoded roles [] -> realm mapped roles [] -> domain mapped roles []
11:47:16,057 INFO  [io.undertow.accesslog] (default task-4) [14/Apr/2022:11:47:16 +0100] "POST /user-login.xhtml HTTP/1.1" 302 - - https HTTP/1.1
11:47:16,057 TRACE [org.wildfly.security.http.servlet] (default task-4) ServerAuthContext.validateRequest returned AuthStatus=AuthStatus.SEND_CONTINUE
11:47:16,065 TRACE [org.wildfly.security.http.servlet] (default task-4) Created ServletSecurityContextImpl enableJapi=true, integratedJaspi=false, applicationContext=my-webapp 
11:47:16,065 TRACE [org.wildfly.security] (default task-4) Handling CallerPrincipalCallback
11:47:16,065 TRACE [org.wildfly.security] (default task-4) Original Principal = 'javax.security.enterprise.CallerPrincipal@317242d5', Caller Name = 'null', Resulting Principal = 'javax.security.enterprise.CallerPrincipal@317242d5'
11:47:16,066 TRACE [org.wildfly.security] (default task-4) Role mapping: principal [javax.security.enterprise.CallerPrincipal@317242d5] -> decoded roles [] -> domain decoded roles [] -> realm mapped roles [] -> domain mapped roles []
11:47:16,066 TRACE [org.wildfly.security.http.servlet] (default task-4) ServerAuthContext.validateRequest returned AuthStatus=AuthStatus.SUCCESS
11:47:16,066 TRACE [org.wildfly.security] (default task-4) No roles request of CallbackHandler.
11:47:16,066 TRACE [org.wildfly.security.http.servlet] (default task-4) Storing SecurityIdentity in HttpSession
11:47:16,066 TRACE [org.wildfly.security] (default task-4) Role mapping: principal [javax.security.enterprise.CallerPrincipal@317242d5] -> decoded roles [] -> domain decoded roles [] -> realm mapped roles [] -> domain mapped roles []
11:47:16,068 TRACE [org.wildfly.security] (default task-4) Role mapping: principal [javax.security.enterprise.CallerPrincipal@317242d5] -> decoded roles [] -> domain decoded roles [] -> realm mapped roles [] -> domain mapped roles []
11:47:16,068 TRACE [org.wildfly.security] (default task-4) Permission mapping: identity [javax.security.enterprise.CallerPrincipal@317242d5] with roles [] implies ("javax.security.jacc.WebResourcePermission" "/user/home.xhtml" "GET") = false
11:47:16,069 INFO  [io.undertow.accesslog] (default task-4) [14/Apr/2022:11:47:16 +0100] "GET /user/home.xhtml HTTP/1.1" 403 68 - https HTTP/1.1

我怀疑我在 elytron 子系统中缺少一些配置,我在 jboss-web.xml

中定义了一个自定义安全域 <security-domain>other</security-domain>

在 undertow 配置中,我定义了一个应用程序安全域:

<application-security-domain name="other" security-domain="ApplicationDomain" enable-jaspi="true" integrated-jaspi="false"/>

在 Elytron 中,我将 ApplicationDomain 配置如下:

<security-domain name="ApplicationDomain" default-realm="ApplicationRealm" permission-mapper="default-permission-mapper">
                    <realm name="ApplicationRealm" role-decoder="groups-to-roles"/>
                    <realm name="local"/>
                </security-domain>

使用默认权限映射器如下:

<simple-permission-mapper name="default-permission-mapper">
                    <permission-mapping>
                        <role name="user"/>
                        <permission class-name="org.wildfly.security.auth.permission.LoginPermission"/>
                    </permission-mapping>
                </simple-permission-mapper>

我也尝试过使用 from-roles-attribute 角色解码器,但似乎不起作用

基本上我只是想告诉 Wildfly 用户已经登录并分配了 'x' 个角色...

也许您缺少 EJB3 子系统的配置以将安全域名映射到 Elytron 安全域?

/subsystem=ejb3/application-security-domain=other:add(security-domain=ApplicationDomain)

好的,如果有人正在寻找这个问题的答案,如果您将 @CustomFormAuthenticationMechanismDefinition 与自定义 IdentityStore 一起使用,您需要实现两个 IdentityStore 的覆盖验证方法的方法(就像我上面显示的那样) ) 和另一个通过重写 getCallerGroups 方法和设置 ValidationType.PROVIDE_GROUPS 来分配 roles/groups 的方法......然后将角色分配给主体,一切都很好

更新:不需要 2 个身份存储,只是根本不覆盖 ValidationType,它可以同时执行这两项操作