1/* 2 * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23package login; 24 25import java.security.Principal; 26import javax.security.auth.login.LoginContext; 27import javax.security.auth.login.LoginException; 28import com.sun.security.auth.UserPrincipal; 29 30public class JaasClientWithDefaultHandler { 31 32 private static final String USER_NAME = "testUser"; 33 private static final String LOGIN_CONTEXT = "ModularLoginConf"; 34 private static final String CBH_PROP = "auth.login.defaultCallbackHandler"; 35 36 public static void main(String[] args) { 37 try { 38 java.security.Security.setProperty(CBH_PROP, args[0]); 39 LoginContext lc = new LoginContext(LOGIN_CONTEXT); 40 lc.login(); 41 checkPrincipal(lc, true); 42 lc.logout(); 43 checkPrincipal(lc, false); 44 } catch (LoginException le) { 45 throw new RuntimeException(le); 46 } 47 System.out.println("Test passed."); 48 49 } 50 51 /* 52 * Verify principal for the test user. 53 */ 54 private static void checkPrincipal(LoginContext loginContext, 55 boolean principalShouldExist) { 56 if (!principalShouldExist) { 57 if (loginContext.getSubject().getPrincipals().size() != 0) { 58 throw new RuntimeException("Test failed. Principal was not " 59 + "cleared."); 60 } 61 return; 62 } 63 for (Principal p : loginContext.getSubject().getPrincipals()) { 64 if (p instanceof UserPrincipal 65 && USER_NAME.equals(p.getName())) { 66 //Proper principal was found, return. 67 return; 68 } 69 } 70 throw new RuntimeException("Test failed. UserPrincipal " 71 + USER_NAME + " expected."); 72 } 73 74} 75