|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +package com.microsoft.azure.msalwebsample; |
| 5 | + |
| 6 | +import java.net.MalformedURLException; |
| 7 | +import java.net.URI; |
| 8 | +import java.util.Collections; |
| 9 | +import java.util.Map; |
| 10 | +import java.util.concurrent.CompletableFuture; |
| 11 | +import java.util.concurrent.ExecutionException; |
| 12 | +import java.util.concurrent.Future; |
| 13 | +import javax.annotation.PostConstruct; |
| 14 | +import javax.naming.ServiceUnavailableException; |
| 15 | +import javax.servlet.http.HttpServletRequest; |
| 16 | + |
| 17 | +import com.microsoft.aad.msal4j.*; |
| 18 | +import com.nimbusds.oauth2.sdk.AuthorizationCode; |
| 19 | +import com.nimbusds.openid.connect.sdk.AuthenticationResponse; |
| 20 | +import com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse; |
| 21 | +import lombok.Getter; |
| 22 | +import org.springframework.beans.factory.annotation.Autowired; |
| 23 | +import org.springframework.stereotype.Component; |
| 24 | + |
| 25 | +@Component |
| 26 | +@Getter |
| 27 | +class AuthHelper { |
| 28 | + |
| 29 | + static final String PRINCIPAL_SESSION_NAME = "principal"; |
| 30 | + static final String TOKEN_CACHE_SESSION_ATTRIBUTE = "token_cache"; |
| 31 | + static final String END_SESSION_ENDPOINT = "https://login.microsoftonline.com/common/oauth2/v2.0/logout"; |
| 32 | + |
| 33 | + private String clientId; |
| 34 | + private String clientSecret; |
| 35 | + private String authority; |
| 36 | + private String redirectUri; |
| 37 | + |
| 38 | + @Autowired |
| 39 | + BasicConfiguration configuration; |
| 40 | + |
| 41 | + @PostConstruct |
| 42 | + public void init() { |
| 43 | + clientId = configuration.getClientId(); |
| 44 | + authority = configuration.getAuthority(); |
| 45 | + clientSecret = configuration.getSecretKey(); |
| 46 | + redirectUri = configuration.getRedirectUri(); |
| 47 | + } |
| 48 | + |
| 49 | + private ConfidentialClientApplication createClientApplication() throws MalformedURLException { |
| 50 | + return ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.create(clientSecret)). |
| 51 | + authority(authority). |
| 52 | + build(); |
| 53 | + } |
| 54 | + |
| 55 | + IAuthenticationResult getAuthResultBySilentFlow(HttpServletRequest httpRequest) throws Throwable { |
| 56 | + IAuthenticationResult result = AuthHelper.getAuthSessionObject(httpRequest); |
| 57 | + |
| 58 | + IAuthenticationResult updatedResult; |
| 59 | + ConfidentialClientApplication app; |
| 60 | + try { |
| 61 | + app = createClientApplication(); |
| 62 | + |
| 63 | + Object tokenCache = httpRequest.getSession().getAttribute("token_cache"); |
| 64 | + if(tokenCache != null){ |
| 65 | + app.tokenCache().deserialize(tokenCache.toString()); |
| 66 | + } |
| 67 | + |
| 68 | + SilentParameters parameters = SilentParameters.builder( |
| 69 | + Collections.singleton("https://graph.microsoft.com/.default"), |
| 70 | + result.account()).build(); |
| 71 | + |
| 72 | + CompletableFuture<IAuthenticationResult> future = app.acquireTokenSilently(parameters); |
| 73 | + |
| 74 | + updatedResult = future.get(); |
| 75 | + } catch (ExecutionException e) { |
| 76 | + throw e.getCause(); |
| 77 | + } |
| 78 | + |
| 79 | + if (updatedResult == null) { |
| 80 | + throw new ServiceUnavailableException("authentication result was null"); |
| 81 | + } |
| 82 | + |
| 83 | + //update session with latest token cache |
| 84 | + storeTokenCacheInSession(httpRequest, app.tokenCache().serialize()); |
| 85 | + |
| 86 | + return updatedResult; |
| 87 | + } |
| 88 | + |
| 89 | + IAuthenticationResult getAuthResultByAuthCode( |
| 90 | + HttpServletRequest httpServletRequest, |
| 91 | + AuthorizationCode authorizationCode, |
| 92 | + String currentUri) throws Throwable { |
| 93 | + |
| 94 | + IAuthenticationResult result; |
| 95 | + ConfidentialClientApplication app; |
| 96 | + try { |
| 97 | + app = createClientApplication(); |
| 98 | + |
| 99 | + String authCode = authorizationCode.getValue(); |
| 100 | + AuthorizationCodeParameters parameters = AuthorizationCodeParameters.builder( |
| 101 | + authCode, |
| 102 | + new URI(currentUri)). |
| 103 | + build(); |
| 104 | + |
| 105 | + Future<IAuthenticationResult> future = app.acquireToken(parameters); |
| 106 | + |
| 107 | + result = future.get(); |
| 108 | + } catch (ExecutionException e) { |
| 109 | + throw e.getCause(); |
| 110 | + } |
| 111 | + |
| 112 | + if (result == null) { |
| 113 | + throw new ServiceUnavailableException("authentication result was null"); |
| 114 | + } |
| 115 | + |
| 116 | + storeTokenCacheInSession(httpServletRequest, app.tokenCache().serialize()); |
| 117 | + |
| 118 | + return result; |
| 119 | + } |
| 120 | + |
| 121 | + private void storeTokenCacheInSession(HttpServletRequest httpServletRequest, String tokenCache){ |
| 122 | + httpServletRequest.getSession().setAttribute(AuthHelper.TOKEN_CACHE_SESSION_ATTRIBUTE, tokenCache); |
| 123 | + } |
| 124 | + |
| 125 | + void setSessionPrincipal(HttpServletRequest httpRequest, IAuthenticationResult result) { |
| 126 | + httpRequest.getSession().setAttribute(AuthHelper.PRINCIPAL_SESSION_NAME, result); |
| 127 | + } |
| 128 | + |
| 129 | + void removePrincipalFromSession(HttpServletRequest httpRequest) { |
| 130 | + httpRequest.getSession().removeAttribute(AuthHelper.PRINCIPAL_SESSION_NAME); |
| 131 | + } |
| 132 | + |
| 133 | + void updateAuthDataUsingSilentFlow(HttpServletRequest httpRequest) throws Throwable { |
| 134 | + IAuthenticationResult authResult = getAuthResultBySilentFlow(httpRequest); |
| 135 | + setSessionPrincipal(httpRequest, authResult); |
| 136 | + } |
| 137 | + |
| 138 | + static boolean isAuthenticationSuccessful(AuthenticationResponse authResponse) { |
| 139 | + return authResponse instanceof AuthenticationSuccessResponse; |
| 140 | + } |
| 141 | + |
| 142 | + static boolean isAuthenticated(HttpServletRequest request) { |
| 143 | + return request.getSession().getAttribute(PRINCIPAL_SESSION_NAME) != null; |
| 144 | + } |
| 145 | + |
| 146 | + static IAuthenticationResult getAuthSessionObject(HttpServletRequest request) { |
| 147 | + Object principalSession = request.getSession().getAttribute(PRINCIPAL_SESSION_NAME); |
| 148 | + if(principalSession instanceof IAuthenticationResult){ |
| 149 | + return (IAuthenticationResult) principalSession; |
| 150 | + } else { |
| 151 | + throw new IllegalStateException(); |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + static boolean containsAuthenticationCode(HttpServletRequest httpRequest) { |
| 156 | + Map<String, String[]> httpParameters = httpRequest.getParameterMap(); |
| 157 | + |
| 158 | + boolean isPostRequest = httpRequest.getMethod().equalsIgnoreCase("POST"); |
| 159 | + boolean containsErrorData = httpParameters.containsKey("error"); |
| 160 | + boolean containIdToken = httpParameters.containsKey("id_token"); |
| 161 | + boolean containsCode = httpParameters.containsKey("code"); |
| 162 | + |
| 163 | + return isPostRequest && containsErrorData || containsCode || containIdToken; |
| 164 | + } |
| 165 | +} |
0 commit comments