본문 바로가기
FullStack/21. Java

Azure Active Directory SSO - 로그인 코드(2)

by nakanara 2023. 9. 29.
반응형

로그인을 위한 소스입니다.

환경에 필요한 설정 정보는 이전 글을 참고하세요.

2023.09.29 - [FullStack/21. Java] - Azure Active Directory SSO - 연동 준비(1)

기본 샘플이 SpringBoot로 구성된 예제가 많아서 SpringBoot로 구성되지 않은 환경에서는 소스 구현과 라이브러리 버전을 맞추기가 어려웠습니다.

참고 소스

https://github.com/Azure-Samples/ms-identity-java-servlet-webapp-authentication/tree/main/1-Authentication/sign-in

라이브러리

<!-- MSAL4J -->
<dependency>
    <groupId>com.microsoft.azure</groupId>
    <artifactId>msal4j</artifactId>
    <version>1.9.1</version>
</dependency>

<!-- Some distributions of Java SDK do not include javax servlets. -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
</dependency>

<!-- For JSTL on frontend pages -->
<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

<!-- For decrypting JWT -->
<dependency>
    <groupId>com.nimbusds</groupId>
    <artifactId>nimbus-jose-jwt</artifactId>
    <version>9.0.1</version>
</dependency>

<!-- For MS Graph -->
<dependency>
    <groupId>com.microsoft.graph</groupId>
    <artifactId>microsoft-graph</artifactId>
    <version>5.5.0</version>
</dependency>

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-identity</artifactId>
    <version>1.10.0</version>
</dependency>

<dependency>
    <groupId>com.google.code.findbugs</groupId>
    <artifactId>jsr305</artifactId>
    <version>3.0.2</version>
</dependency>

로그인 처리

@WebServlet(name = "AADRedirectServlet", urlPatterns = "/auth/redirect")
public class AADRedirectServlet extends HttpServlet {
    private static Logger logger = Logger.getLogger(AADRedirectServlet.class.getName());

    @Override
    protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
            throws ServletException, IOException {
        logger.debug("Request has come with params {}", req.getQueryString());

        try {
            IdentityContextAdapterServlet identityContextAdapterServlet = new IdentityContextAdapterServlet(req, resp);
            AuthHelper.processAADCallback(identityContextAdapterServlet);
            Log.biz.info("redirecting to home page.");

            // 세션 저장
            identityContextAdapterServlet.saveContext();

            IdentityContextData context = identityContextAdapterServlet.getContext();


            final HashMap<String, String> filteredClaims = AuthUtils.filterClaims(context);

            logger.info("identify={}", filteredClaims);

            // 사용자 ID 추출
            // 이메일로 추출
            String userId = filteredClaims.get("preferred_username");

            Log.biz.info("userId={}", userId);

            AuthUtils authUtils = new AuthUtils();
            // 로그인 처리
            authUtils.login(req, resp, userId);

        } catch (AuthException ex) {
            // 계정 없는 경우 오류 발생.
            // 처리 필요
            logger.err(ex.getMessage());
            logger.err(Arrays.toString(ex.getStackTrace()));
            logger.info("redirecting to error page to display auth error to user.");
            resp.sendRedirect(resp.encodeRedirectURL(String.format(req.getContextPath() + "/auth_error_details?details=%s", ex.getMessage())));
        }
    }
}
반응형