首页 > 解决方案 > 使用 oauth2.0 的 EWS 现代身份验证:远程服务器返回错误:(401)未授权

问题描述

我正在尝试使用 microsoft graph 访问令牌对 Outlook 邮箱(用于从应用程序发送邮件)进行现代身份验证。我成功地从下面的代码中获取了访问令牌:

   public class AuthTokenAccess {

public AuthTokenAccess() {}

public static String getAccessToken(String tenantId, String clientId, String clientSecret, String scope)
         {
    String endpoint = String.format("https://login.microsoftonline.com/%s/oauth2/token", tenantId);
    String postBody = String.format("grant_type=client_credentials&client_id=%s&client_secret=%s&resource=%s&scope=%s",
            clientId, clientSecret, "https://management.azure.com/", scope);
    String accessToken = null;
    try{
        HttpURLConnection conn = (HttpURLConnection) new URL(endpoint).openConnection();
    
    
        conn.setRequestMethod("POST");
    
    conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setDoOutput(true);
    conn.getOutputStream().write(postBody.getBytes());
    conn.connect();
    JsonFactory factory = new JsonFactory();
    JsonParser parser = factory.createParser(conn.getInputStream());
    //String accessToken = null;
    while (parser.nextToken() != JsonToken.END_OBJECT) {
        String name = parser.getCurrentName();
        if ("access_token".equals(name)) {
            parser.nextToken();
            accessToken = parser.getText();
        }
    }
    }catch(Exception e) {
        
        
    }
    return accessToken;
}

获得访问令牌后,我将其发送到 ExchangeService:

  public ExchangeService getExchangeServiceObj(String emailId, String token, String emailServerURI) throws URISyntaxException {

    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
        
        if(service != null) {
            service.getHttpHeaders().put("Authorization", "Bearer " + token);
            service.getHttpHeaders().put("X-AnchorMailbox", emailId);
            service.setUrl(new URI(emailServerURI));   //https://outlook.office365.com/EWS/Exchange.asmx
        }
    
    LOGGER.debug("getExchangeServiceObj() {}.", "ends");
    return service;
}

在这里,我得到了 ExchangeService 对象,但是当我尝试发送邮件时microsoft.exchange.webservices.data.core.service.item.EmailMessage.sendAndSaveCopy() 抛出异常

  public void sendMail(String toMail, String ccMail, String subject, String body, String pathOfFileToAttach) {

        ExchangeService emailService = getExchangeServiceObj(
                ResourceUtils.getPropertyValue("email_user"), 
                token, 
                ResourceUtils.getPropertyValue("ews_server"));

        if(!StringUtils.hasText(toMail)) { 
            toMail = ccMail;
        }
        EmailMessage emessage = new EmailMessage(emailService);
        
        emessage.setSubject(subject);
        String strBodyMessage = body;
        strBodyMessage = strBodyMessage + "<br /><br />";
        LOGGER.info("Body: {} ", body);
        MessageBody msg = new MessageBody(BodyType.HTML, strBodyMessage);
        emessage.setBody(msg);
        
        emessage.sendAndSaveCopy();
        LOGGER.info("Email send {}", "sucessfully");
    } catch(Exception e) {
        LOGGER.error(Constants.ERROR_STACK_TRACE, e);
        throw new CommonException(e);
    }
}

尝试使用以下范围: “https://outlook.office.com/EWS.AccessAsUser.All”“https://graph.microsoft.com/.default”

以下是我使用上述代码获得的访问令牌:

{“aud”:“https://management.azure.com/”,“iss”:“https://sts.windows.net/3863b7d0-213d-40f3-a4d0-6cd90452245a/”,“iat”:1628068305 ,“nbf”:1628068305,“exp”:1628072205,“aio”:“E2ZgYEjcvsaipUV1wxwxrne/9F4XAAA=”,“appid”:“055eb578-4716-4901-861b-92f2469dac9c”,“appidacr”:“1”,“idp” ": "https://sts.windows.net/3863b7d0-213d-40f3-a4d0-6cd90452245a/", "oid": "33688cee-e16e-4d11-8ae0-a804805ea007", "rh": "0.AUYA0LdjOD0h80Ck0GzZBFIkWni1XgUGAAAwF. ”,“子”:“33688cee-e16e-4d11-8ae0-a804805ea007”,“tid”:“3863b7d0-213d-40f3-a4d0-6cd90452245a”,“uti”:“nZUVod_e3EuO_T-Ter-_AQ”,“ver”:“1.0”,“xms_tcdt”:1626687774 }

如您所见,范围不包含在令牌中。获取令牌时是否需要传递任何其他内容。

Azure 活动目录设置:

  1. 注册应用程序 2.创建客户端密码 3.添加重定向 URL 在此处输入图像描述

  2. 添加权限 在此处输入图像描述

有人可以在这里帮助我吗,我在哪里做错了,或者是其他任何其他方式使它工作。谢谢

标签: spring-bootoauth-2.0azure-active-directoryexchangewebservicesmicrosoft-exchange

解决方案


我可以在这里看到一些问题,首先您使用客户端凭据流程,这要求您分配应用程序权限并且您只有委托权限,使用 EWS 唯一可以使用的应用程序权限是 full_access_as_app 请参阅https://docs.microsoft.com/ en-us/exchange/client-developer/exchange-web-services/how-to-authenticate-an-ews-application-by-using-oauth(仅限应用部分)

        String endpoint = String.format("https://login.microsoftonline.com/%s/oauth2/token", tenantId);
String postBody = String.format("grant_type=client_credentials&client_id=%s&client_secret=%s&resource=%s&scope=%s",
        clientId, clientSecret, "https://management.azure.com/", scope);

您在此处混合 V1 和 V2 身份验证(请参阅https://nicolgit.github.io/AzureAD-Endopoint-V1-vs-V2-comparison/)对于 v1 端点不起作用(范围将被忽略),例如什么您在https://login.microsoftonline.com/%s/oauth2/token中拥有的是 V1 身份验证端点,因此您的请求不应仅包括资源范围,并且该资源应为https://outlook.office.com


推荐阅读