java 使用山姆史蒂文斯TOTP -不能让它工作

ar7v8xwq  于 2023-02-20  发布在  Java
关注(0)|答案(2)|浏览(169)

我在GitHub上找到了一个生成和检查令牌的项目(TOTP)。我试着让它工作,但是失败了。下面是代码:

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dev.samstevens.totp.code.CodeGenerator;
import dev.samstevens.totp.code.CodeVerifier;
import dev.samstevens.totp.code.DefaultCodeGenerator;
import dev.samstevens.totp.code.DefaultCodeVerifier;
import dev.samstevens.totp.code.HashingAlgorithm;
import dev.samstevens.totp.exceptions.CodeGenerationException;
import dev.samstevens.totp.exceptions.QrGenerationException;
import dev.samstevens.totp.qr.QrData;
import dev.samstevens.totp.qr.QrGenerator;
import dev.samstevens.totp.qr.ZxingPngQrGenerator;
import dev.samstevens.totp.secret.DefaultSecretGenerator;
import dev.samstevens.totp.secret.SecretGenerator;
import dev.samstevens.totp.time.SystemTimeProvider;
import dev.samstevens.totp.time.TimeProvider;
import dev.samstevens.totp.recovery.RecoveryCodeGenerator;

import static dev.samstevens.totp.util.Utils.getDataUriForImage;

/**
 * Servlet implementation class TwoFactorAuthentication
 */
public class TwoFactorAuthentication extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TwoFactorAuthentication() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
        
        
        //SecretGenerator secretGenerator = new DefaultSecretGenerator();
        //String secret = secretGenerator.generate();
        String secret = "XAFXRG3TNMLHENVAQTD5ZJOTC2MHTIVE";
        
        QrData data = new QrData.Builder()
                   .label("dummyuser@dummy.com")
                   .secret(secret)
                   .issuer("PORTAL")
                   .algorithm(HashingAlgorithm.SHA256) // More on this below
                   .digits(6)
                   .period(60)
                   .build();
        
        String code = request.getQueryString().replace("code=", "");
        response.getWriter().append("\r\nCode: " + code);//.append(request.getContextPath());
        
        TimeProvider timeProvider = new SystemTimeProvider();
        CodeGenerator codeGenerator = new DefaultCodeGenerator(HashingAlgorithm.SHA256);
        DefaultCodeVerifier verifier = new DefaultCodeVerifier(codeGenerator, timeProvider);
        verifier.setTimePeriod(60);
        verifier.setAllowedTimePeriodDiscrepancy(2);

        // secret = the shared secret for the user
        // code = the code submitted by the user
        boolean successful = verifier.isValidCode(secret, code);
        if (successful) System.out.println(successful);
        response.getWriter().append("\r\nResult: " + successful);//.append(request.getContextPath());
        
        try {
            QrGenerator generator = new ZxingPngQrGenerator();
            byte[] imageData = generator.generate(data);
            String mimeType = generator.getImageMimeType();
            String dataUri = getDataUriForImage(imageData, mimeType);
            response.getWriter().append("\r\ndataUri: " + dataUri);//.append(request.getContextPath());
        } catch (QrGenerationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

我使用上面的项目生成了QR码,并将其扫描到验证器应用程序中为我生成令牌。无论我给表单输入什么代码,验证器应用程序都会失败。有人能解释一下我做错了什么吗?

64jmpszr

64jmpszr1#

我最近在使用Google身份验证器应用程序时遇到了同样的问题。事实证明,一些身份验证器应用程序会自动忽略URI中的perioddigits参数。对于Google身份验证器,它只是分别默认为306
这会导致代码验证失败,因为生成代码的应用和验证实用程序使用不同的参数。

lrpiutwd

lrpiutwd2#

考虑到codeVerifier.isValidCode方法接收secret作为第一个参数,接收otp代码作为第二个参数,在我的例子中,它做的是相反的操作。
我的代码:

public UserDto validateOtp(Long userId, LoginDto loginDto) {
        var user = findUserIfExists(userId);
        var isValidOtp = codeVerifier.isValidCode(user.getSecret2FA(),loginDto.getOtp().toString());
        if (!isValidOtp) {
            throw new UnauthorizedException("Invalid Otp");
        }

        return converterObject(user, UserDto.class);
    }

相关问题