How to check if user belongs to certain AD group in java

后端 未结 3 626
Happy的楠姐
Happy的楠姐 2021-01-21 17:46

I know it must be a very easy question, but I am new to java and find it hard to get exact code that I need. What I need to be able to do is to get currently logged in username

3条回答
  •  余生分开走
    2021-01-21 17:53

    This can be done through the Java SE APIs without using the com.sun.* packages directly. Use Java Authentication and Authorization Service (JAAS) (javax.security.auth.* and javax.security.auth.login.*) to access this information. Create a JAAS config file with the following entry:

    sampleApp {
        com.sun.security.auth.module.NTLoginModule required debug=false;
    };
    

    Save that entry as sampleapp_jaas.config. Next set the system property so Java will look for the config file.

    -Djava.security.auth.login.config==sampleapp_jaas.config
    

    Note that the double equals has special meaning. See the com.sun.security.auth.login.ConfigFile for details on the load order.

    Then create LoginContext that will look for the entry in the JAAS config. Call login to populate the subject then access principals which represent the user groups.

    LoginContext l = new LoginContext("sampleApp");
    l.login();
    try {
        Subject s = l.getSubject();
        for (Principal p : s.getPrincipals()) {
            System.out.println(p);
        }
    } finally {
        l.logout();
    }
    

    Using this setup, Java will use the com.sun.security.auth.module.NTSystem class to get the information but none of your code will be hardwired to the non-standard APIs.

提交回复
热议问题