首页 > 解决方案 > 可以用groovy设置spring boot的附加参数吗?

问题描述

我是 groovy 和 spring boot 的新手。我开始使用 spring boot 登录。我需要将两个附加参数传递给CustomAuthToken类。我只能通过一个。当我将其他变量分配给某个值时,验证失败。

这是我的代码。

CustomAuthFilter.groovy

Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

    if (!request.post) {
        throw new AuthenticationServiceException("not supported: $request.method")
    }
    String username = (obtainUsername(request) ?: '').trim()
    String password = (obtainPassword(request) ?: '').trim()
    String extrafield1 = request.getParameter("extrafield1")
    String extrafield2 = request.getParameter("extrafield2")


        def authentication = new CustomAuthToken(username, password, extrafield1, null, false, false, false)

    HttpSession session = request.getSession(false)
    if (session || getAllowSessionCreation()) {
        request.session['SPRING_SECURITY_LAST_USERNAME_KEY'] = TextEscapeUtils.escapeEntities(username)
    }

    return getAuthenticationManager().authenticate(authentication)
}

CustomAuthToken.groovy

CustomAuthToken(Object principal, Object credentials, String extrafield1, String PVM, Boolean isAccept, Boolean isLogEnabled, Boolean is3PLEnabled) {
    super(principal, credentials)
    extra1 = extrafield1
}

它正在工作,我可以访问 extra1 字段。但是当我尝试传递另一个参数时它不起作用。

CustomAuthToken(Object principal, Object credentials, String extrafield1, String extrafield2, String PVM, Boolean isAccept, Boolean isLogEnabled, Boolean is3PLEnabled) {
    super(principal, credentials)
    extra1 = extrafield1
    extra2 = extrafield2
}

当我尝试这个 extra2 正在通过时。但身份验证失败。任何人都可以对此有所了解吗?

标签: javaspringgroovyspring-security

解决方案


我的猜测是

CustomAuthToken extends UsernamePasswordAuthenticationToken

如果是这种情况,您需要将super构造函数调用从

super(principal, credentials)

super(principal, credentials, Collections.emptyList())

你看,你正在调用的构造函数集合authenticated=false

public UsernamePasswordAuthenticationToken(Object principal, Object credentials) {
    super(null);
    this.principal = principal;
    this.credentials = credentials;
    setAuthenticated(false);
}

所以你想调用正确的构造函数

public UsernamePasswordAuthenticationToken(Object principal, Object credentials,
        Collection<? extends GrantedAuthority> authorities) {
    super(authorities);
    this.principal = principal;
    this.credentials = credentials;
    super.setAuthenticated(true); // must use super, as we override
}

推荐阅读