Viewed   87 times

I am running a network. Here I have a domain controller (DC) I just installed IIS6 , PHP and Mysql on it. every thing is working fine.:)

Now I want to bring up a script on this local website. The first problem is that I want to detect which one of network users (active directory users) are logged in with PHP. I mean it is enough for me when the user is logged in to windows there is no need for another authentication.

I was wondering if I could just use a function or something... that its output is the AD username and user group.

 Answers

1

If you've set IIS to authenticate users one or more of these should contain the username:

$_SERVER['LOGON_USER']
$_SERVER['AUTH_USER']
$_SERVER['REDIRECT_LOGON_USER']
$_SERVER['REDIRECT_AUTH_USER']
Wednesday, November 30, 2022
3

As you run it from server itself, and you just want to read I would try to use :

...
if(ldap_bind($ldap))
...

According to PHP documentation if bind_rdn and bind_password are not specified, an anonymous bind is attempted.

Then if your anonymous logon is refused (this should not be, because running under IIS on the server your code is at least executed as a domain user) you will find there how to enable anonymous LDAP binds to Windows Server. This used to work forme on W2K8, Inever test it on W2K12.

Wednesday, November 23, 2022
 
1

Java EE 8 and up

If you're on Java EE 8 or newer, put @RememberMe on a custom HttpAuthenticationMechanism along with a RememberMeIdentityStore.

@ApplicationScoped
@AutoApplySession
@RememberMe
public class CustomAuthenticationMechanism implements HttpAuthenticationMechanism {

    @Inject
    private IdentityStore identityStore;

    @Override
    public AuthenticationStatus validateRequest(HttpServletRequest request, HttpServletResponse response, HttpMessageContext context) {
        Credential credential = context.getAuthParameters().getCredential();

        if (credential != null) {
            return context.notifyContainerAboutLogin(identityStore.validate(credential));
        }
        else {
            return context.doNothing();
        }
    }
}
public class CustomIdentityStore implements RememberMeIdentityStore {

    @Inject
    private UserService userService; // This is your own EJB.
    
    @Inject
    private LoginTokenService loginTokenService; // This is your own EJB.
    
    @Override
    public CredentialValidationResult validate(RememberMeCredential credential) {
        Optional<User> user = userService.findByLoginToken(credential.getToken());
        if (user.isPresent()) {
            return new CredentialValidationResult(new CallerPrincipal(user.getEmail()));
        }
        else {
            return CredentialValidationResult.INVALID_RESULT;
        }
    }

    @Override
    public String generateLoginToken(CallerPrincipal callerPrincipal, Set<String> groups) {
        return loginTokenService.generateLoginToken(callerPrincipal.getName());
    }

    @Override
    public void removeLoginToken(String token) {
        loginTokenService.removeLoginToken(token);
    }

}

You can find a real world example in the Java EE Kickoff Application.


Java EE 6/7

If you're on Java EE 6 or 7, homegrow a long-living cookie to track the unique client and use the Servlet 3.0 API provided programmatic login HttpServletRequest#login() when the user is not logged-in but the cookie is present.

This is the easiest to achieve if you create another DB table with a java.util.UUID value as PK and the ID of the user in question as FK.

Assume the following login form:

<form action="login" method="post">
    <input type="text" name="username" />
    <input type="password" name="password" />
    <input type="checkbox" name="remember" value="true" />
    <input type="submit" />
</form>

And the following in doPost() method of a Servlet which is mapped on /login:

String username = request.getParameter("username");
String password = hash(request.getParameter("password"));
boolean remember = "true".equals(request.getParameter("remember"));
User user = userService.find(username, password);

if (user != null) {
    request.login(user.getUsername(), user.getPassword()); // Password should already be the hashed variant.
    request.getSession().setAttribute("user", user);

    if (remember) {
        String uuid = UUID.randomUUID().toString();
        rememberMeService.save(uuid, user);
        addCookie(response, COOKIE_NAME, uuid, COOKIE_AGE);
    } else {
        rememberMeService.delete(user);
        removeCookie(response, COOKIE_NAME);
    }
}

(the COOKIE_NAME should be the unique cookie name, e.g. "remember" and the COOKIE_AGE should be the age in seconds, e.g. 2592000 for 30 days)

Here's how the doFilter() method of a Filter which is mapped on restricted pages could look like:

HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
User user = request.getSession().getAttribute("user");

if (user == null) {
    String uuid = getCookieValue(request, COOKIE_NAME);

    if (uuid != null) {
        user = rememberMeService.find(uuid);

        if (user != null) {
            request.login(user.getUsername(), user.getPassword());
            request.getSession().setAttribute("user", user); // Login.
            addCookie(response, COOKIE_NAME, uuid, COOKIE_AGE); // Extends age.
        } else {
            removeCookie(response, COOKIE_NAME);
        }
    }
}

if (user == null) {
    response.sendRedirect("login");
} else {
    chain.doFilter(req, res);
}

In combination with those cookie helper methods (too bad they are missing in Servlet API):

public static String getCookieValue(HttpServletRequest request, String name) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (name.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
    }
    return null;
}

public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
    Cookie cookie = new Cookie(name, value);
    cookie.setPath("/");
    cookie.setMaxAge(maxAge);
    response.addCookie(cookie);
}

public static void removeCookie(HttpServletResponse response, String name) {
    addCookie(response, name, null, 0);
}

Although the UUID is extremely hard to brute-force, you could provide the user an option to lock the "remember" option to user's IP address (request.getRemoteAddr()) and store/compare it in the database as well. This makes it a tad more robust. Also, having an "expiration date" stored in the database would be useful.

It's also a good practice to replace the UUID value whenever the user has changed its password.


Java EE 5 or below

Please, upgrade.

Saturday, August 27, 2022
 
5

you'll need to create a service that returns your user information

angular.module('app').factory('Authentication', function ($resource) {
    var resource = $resource('/user', {}, {
        query: {
            method: 'GET',
            cache: true
        }
    });
    return resource.get().$promise;
});

* note that you'll need to create and endpoint that will send you the user data as json using web api

once you got it done you'll be able to use it in any controller (let's assume you have a homecontroller, it could be a headercontroller or any other)

angular.module('app').controller('HomeController', ['$scope', 'Authentication', function ($scope, Authentication) {
    $scope.authentication = Authentication;
}]);

then use it in your view like:

<span >Logged In As: {{authentication.user.username}} </span>

EDIT:

your api controller as you suggested could be like

public HttpResponseMessage Get()
    {
        var userId = getCurrentUserId(); //something like that
        using (var context = new ApplicationDbContext())
        {
            ApplicationUser user = new ApplicationUser();
            user = context.ApplicationUsers.SingleOrDefault(x=>x.id==userId);
            return user;
        }

    }

try to read http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization

for routing try to read this article (I guess you are using web api 2)

http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

Sunday, November 13, 2022
 
eric_l
 
3

Well, seems like no one is interested in looking at this question :). I'm assuming IIS + Node.js + Active Directory is an edge case. Here's how I ended up solving this one:

  1. Add a special user to the Active Directory that can only be logged into from the IIS machine (bonus: limit the IP/process/access of that user).
  2. Add the AD details, user name, and password to config.json file (see snippet).
    Make sure you add the file to .gitignore so it won't end up in repo.
  3. Use node-ActiveDirectory to first sign in as the user from step 1, and then ask for the groups of the logged in user (see snippet).
Friday, November 25, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :