在spring boot应用程序中获取系统userinfo

时间:2017-04-28 16:16:22

标签: spring-boot spring-security

尝试在spring启动应用程序中实现SSO功能。 我需要获取当前登录的操作系统用户(窗口),以便在Active Directory中查找并检索角色。

我看过一些使用 SecurityContextHolder 的示例,但这似乎与具有集成身份验证机制的Web应用程序相关。

知道如何在spring应用程序中获取当前的Windows用户吗?

由于

1 个答案:

答案 0 :(得分:0)

尝试一下,可能适用于ie和chrome:

    public String  WindowsUserDemo(HttpServletRequest request, HttpServletResponse response) {
            String auth = request.getHeader("Authorization");
            if (auth == null) {
                response.setStatus(response.SC_UNAUTHORIZED);
                response.setHeader("WWW-Authenticate", "NTLM");
                try {
                    response.flushBuffer();
                } catch (IOException e) {
                    //e.printStackTrace();
                }
            }
            if (auth.startsWith("NTLM ")) {
                byte[] msg = new byte[0];
                try {
                    msg = new sun.misc.BASE64Decoder().decodeBuffer(auth.substring(5));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                int off = 0, length, offset;
                if (msg[8] == 1) {
                    byte z = 0;
                    byte[] msg1 = { (byte) 'N', (byte) 'T', (byte) 'L', (byte) 'M', (byte) 'S', (byte) 'S', (byte) 'P',
                            z, (byte) 2, z, z, z, z, z, z, z, (byte) 40, z, z, z, (byte) 1, (byte) 130, z, z, z,
                            (byte) 2, (byte) 2, (byte) 2, z, z, z, z, z, z, z, z, z, z, z, z };
                    response.setHeader("WWW-Authenticate", "NTLM " + new sun.misc.BASE64Encoder().encodeBuffer(msg1));
                    try {
                        response.sendError(response.SC_UNAUTHORIZED);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else if (msg[8] == 3) {
                    off = 30;

                    length = msg[off + 17] * 256 + msg[off + 16];
                    offset = msg[off + 19] * 256 + msg[off + 18];
                    String remoteHost = new String(msg, offset, length);

                    length = msg[off + 1] * 256 + msg[off];
                    offset = msg[off + 3] * 256 + msg[off + 2];
                    String domain = new String(msg, offset, length);

                    length = msg[off + 9] * 256 + msg[off + 8];
                    offset = msg[off + 11] * 256 + msg[off + 10];
                    String username = new String(msg, offset, length);

                    return remoteHost+"name:"+username+",domain:"+domain;
                }
            }
            return "error";
}