首页 > 解决方案 > 如何为以下方法编写单元测试 JWKS RSA 算法,使用 Java 中的 junit 或 mockito 验证签名和测试角色

问题描述

How to mock JWKS RSA Algorithm , validate signature and test roles using junit or mockito in Java for below method microsoftJwksUrl is an AzureActiveDirectory endpoint .

以下是需要模拟的方法:

如何模拟 JWKS RSA 算法,使用 Java 中的 junit 或 mockito 验证签名和测试角色,用于 AzureActiveDirectory 端点的以下方法 microsoftJwksUrl

public String[] getAadRoles(String token, String intendedAudience, String microsoftJwksUrl)
                    throws AadTokenAuthenticationFailedException {
                
                    //Decode AAD token
                    DecodedJWT jwt = JWT.decode(token);
                    //Get Provider from the endpoint : 
                      
               //microsoftJwksUrl=https://login.microsoftonline.com/common/discovery/v2.0/keys
                    JwkProvider provider = new UrlJwkProvider(new URL(microsoftJwksUrl));
                    Jwk jwk = provider.get(jwt.getKeyId());
                    Algorithm algorithm=Algorithm.RSA256((RSAPublicKey) jwk.getPublicKey(), null);
                    //Verify Algorithm
                    algorithm.verify(jwt);
                    String audience = jwt.getAudience().get(0);
                    Date expiresAt = jwt.getExpiresAt();
                    Date currentDateTime = new Date();
                    Claim roles = jwt.getClaim("roles");
        //checks if it's audience is correct and token is valid
                    if (audience.contentEquals(intendedAudience) && currentDateTime.before(expiresAt)) {
                        return roles!=null ? roles.asArray(String.class) : new String[] {};
        
                    } else {
                        String errorMessage = String.format("Token not valid for Audience {%s} "
                                        + ", with Expiry Time as {%s}.", audience,
                                expiresAt.toString());
                        LOG.error(errorMessage);
                        throw new AadTokenAuthenticationFailedException();
                    
                }
                
            }

标签: javaspring

解决方案


推荐阅读