Example usage for org.springframework.security.authentication ProviderManager authenticate

List of usage examples for org.springframework.security.authentication ProviderManager authenticate

Introduction

In this page you can find the example usage for org.springframework.security.authentication ProviderManager authenticate.

Prototype

public Authentication authenticate(Authentication authentication) throws AuthenticationException 

Source Link

Document

Attempts to authenticate the passed Authentication object.

Usage

From source file:org.red5.server.plugin.admin.client.AuthClientRegistry.java

@SuppressWarnings("unchecked")
@Override//from   w  w  w  . j a v  a 2 s  .co m
public IClient newClient(Object[] params) throws ClientNotFoundException, ClientRejectedException {
    log.debug("New client - params: {}, {}, {}", params);

    if (params == null || params.length == 0) {
        log.warn("Client didn't pass a username.");
        throw new ClientRejectedException();
    }

    String username, passwd;
    if (params[0] instanceof HashMap) {
        // Win FP sends HashMap
        HashMap userWin = (HashMap) params[0];
        username = (String) userWin.get(0);
        passwd = (String) userWin.get(1);
    } else if (params[0] instanceof ArrayList) {
        // Mac FP sends ArrayList
        ArrayList userMac = (ArrayList) params[0];
        username = (String) userMac.get(0);
        passwd = (String) userMac.get(1);
    } else {
        throw new ClientRejectedException();
    }

    UsernamePasswordAuthenticationToken t = new UsernamePasswordAuthenticationToken(username, passwd);

    masterScope = Red5.getConnectionLocal().getScope();

    ProviderManager mgr = (ProviderManager) masterScope.getContext().getBean("authenticationManager");
    try {
        log.debug("Checking password: {}", passwd);
        t = (UsernamePasswordAuthenticationToken) mgr.authenticate(t);
    } catch (BadCredentialsException ex) {
        log.debug("{}", ex);
        throw new ClientRejectedException();
    }

    if (t.isAuthenticated()) {
        client = new AuthClient(nextId(), this);
        addClient(client);
        client.setAttribute("authInformation", t);
        log.debug("Authenticated client - username: {}, id: {}", new Object[] { username, client.getId() });
    }

    return client;
}

From source file:org.red5.demo.auth.Red5SpringAuthenticationHandler.java

public boolean appConnect(IConnection conn, Object[] params) {
    log.info("appConnect");
    // start with negative result
    boolean result = false;
    log.debug("Connection: {}", conn);
    log.debug("Params: {}", params);
    // start off with the status being bad authentication
    String status = badAuth;/* www. ja va  2  s.  co m*/
    // get the connection parameters
    Map<String, Object> connectionParams = conn.getConnectParams();
    log.debug("Connection params: {}", connectionParams);
    if (!connectionParams.containsKey("queryString")) {
        //set as missing auth notification
        status = rejectMissingAuth;
    } else {
        //get the raw query string
        String rawQueryString = (String) connectionParams.get("queryString");
        try {
            //parse into a usable query string
            UrlQueryStringMap<String, String> queryString = UrlQueryStringMap.parse(rawQueryString);
            log.debug("Query string: {}", queryString);
            //get the values we want
            String userName = queryString.get("user");
            log.debug("User: {}", userName);
            // do a user lookup
            AggregatedUserDetailsService userDetailsService = (AggregatedUserDetailsService) applicationContext
                    .getBean("aggregatedUserDetailsService");
            // this will throw an exception if the user cant be located by name
            UserDetails userDetails = userDetailsService.loadUserByUsername(userName);
            // get the authentication "style"
            String authmod = queryString.get("authmod");
            log.debug("Authmod: {}", authmod);
            //make sure they requested red5 auth
            if ("red5".equals(authmod)) {
                String response = queryString.get("response");
                if (response != null) {
                    response = queryString.get("response").replace(' ', '+');
                }
                log.debug("Response: {}", response);
                //try the querystring first
                String sessionId = queryString.get("sessionid");
                if (sessionId == null) {
                    //get the session id - try conn next
                    sessionId = ((RTMPConnection) conn).getSessionId();
                    if (sessionId == null) {
                        //use attribute
                        if (conn.hasAttribute("sessionId")) {
                            sessionId = conn.getStringAttribute("sessionId");
                        } else {
                            sessionId = SessionManager.getSessionId();
                            conn.setAttribute("sessionId", sessionId);
                        }
                    }
                }
                log.debug("Session id: {}", sessionId);
                String challenge = null;
                if (response != null) {
                    //look up challenge (gets and removes at the same time)
                    challenge = sessionChallenges.remove(sessionId);
                    // get the password
                    String password = userDetails.getPassword();
                    log.debug("Users password: {}", password);
                    //generate response hash to compare
                    String responseHash = calculateHMACSHA256(challenge, password);
                    log.debug("Generated response: {}", responseHash);
                    log.debug("Generated response: {}", response);
                    //decode both hashes before we compare otherwise we will have issues like
                    //4+5WioxdBLhx4qajIybxkBkynDsv7KxtNzqj4V/VbzU != 4+5WioxdBLhx4qajIybxkBkynDsv7KxtNzqj4V/VbzU=                    
                    if (Arrays.areEqual(Base64.decodeBase64(responseHash.getBytes()),
                            Base64.decodeBase64(response.getBytes()))) {
                        // everything matches so now do the actual authentication
                        // get the authentication manager
                        ProviderManager authManager = (ProviderManager) applicationContext
                                .getBean("authManager");
                        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                                userName, password);
                        Authentication auth = null;
                        try {
                            auth = authManager.authenticate(token);
                            log.info("Authentication result: {}\ndetails: {}", auth.isAuthenticated(), auth);
                            result = auth.isAuthenticated();
                            // set the authenticated user into the context (thread-local)
                            if (result) {
                                SecurityContextHolder.getContext().setAuthentication(auth);
                            }
                        } catch (Exception ex) {
                            log.warn("Problem during auth attempt: {}", ex);
                        }
                    }
                } else if (authmod != null && userName != null) {
                    // generate a challenge
                    challenge = calculateHMACSHA256(salt, sessionId);
                    // store the generated data
                    sessionChallenges.put(sessionId, challenge);
                    // set as rejected
                    status = String.format(
                            "[ AccessManager.Reject ] : [ authmod=red5 ] : ?reason=needauth&user=%s&sessionid=%s&challenge=%s",
                            userName, sessionId, challenge);
                }
                log.debug("Challenge: {}", challenge);
            } else {
                status = invalidAuthMod;
            }
        } catch (UsernameNotFoundException ex) {
            status = noSuchUser;
        } catch (Exception e) {
            log.error("Error authenticating", e);
        }
    }
    //send the status object
    log.debug("Status: {}", status);
    if (!result) {
        throw new ClientRejectedException(status);
    }
    return result;
}

From source file:org.red5.webapps.admin.handler.Red5AuthenticationHandler.java

public boolean appConnect(IConnection conn, Object[] params) {
    log.info("appConnect");
    // start with negative result
    boolean result = false;
    log.debug("Connection: {}", conn);
    log.debug("Params: {}", params);
    // start off with the status being bad authentication
    String status = badAuth;/*w  w w.j  a  va 2 s .  co  m*/
    // get the connection parameters
    Map<String, Object> connectionParams = conn.getConnectParams();
    log.debug("Connection params: {}", connectionParams);
    if (!connectionParams.containsKey("queryString")) {
        //set as missing auth notification
        status = rejectMissingAuth;
    } else {
        //get the raw query string
        String rawQueryString = (String) connectionParams.get("queryString");
        try {
            //parse into a usable query string
            UrlQueryStringMap<String, String> queryString = UrlQueryStringMap.parse(rawQueryString);
            log.debug("Query string: {}", queryString);
            //get the values we want
            String userName = queryString.get("user");
            log.debug("User: {}", userName);
            // do a user lookup
            AggregatedUserDetailsService userDetailsService = (AggregatedUserDetailsService) applicationContext
                    .getBean("aggregatedUserDetailsService");
            // this will throw an exception if the user cant be located by name
            UserDetails userDetails = userDetailsService.loadUserByUsername(userName);
            // get the authentication "style"
            String authmod = queryString.get("authmod");
            log.debug("Authmod: {}", authmod);
            //make sure they requested red5 auth
            if ("red5".equals(authmod)) {
                String response = queryString.get("response");
                if (response != null) {
                    response = queryString.get("response").replace(' ', '+');
                }
                log.debug("Response: {}", response);
                //try the querystring first
                String sessionId = queryString.get("sessionid");
                if (sessionId == null) {
                    //get the session id - try conn next
                    sessionId = ((RTMPConnection) conn).getSessionId();
                    if (sessionId == null) {
                        //use attribute
                        if (conn.hasAttribute("sessionId")) {
                            sessionId = conn.getStringAttribute("sessionId");
                        } else {
                            sessionId = SessionManager.getSessionId();
                            conn.setAttribute("sessionId", sessionId);
                        }
                    }
                }
                log.debug("Session id: {}", sessionId);
                String challenge = null;
                if (response != null) {
                    //look up challenge (gets and removes at the same time)
                    challenge = sessionChallenges.remove(sessionId);
                    // get the password
                    String password = userDetails.getPassword();
                    log.debug("Users password: {}", password);
                    //generate response hash to compare
                    String responseHash = calculateHMACSHA256(challenge, password);
                    log.debug("Generated response: {}", responseHash);
                    log.debug("Generated response: {}", response);
                    //decode both hashes before we compare otherwise we will have issues like
                    //4+5WioxdBLhx4qajIybxkBkynDsv7KxtNzqj4V/VbzU != 4+5WioxdBLhx4qajIybxkBkynDsv7KxtNzqj4V/VbzU=                    
                    if (Arrays.areEqual(Base64.decodeBase64(responseHash.getBytes()),
                            Base64.decodeBase64(response.getBytes()))) {
                        // everything matches so now do the actual authentication
                        // get the authentication manager
                        ProviderManager authManager = (ProviderManager) applicationContext
                                .getBean("authenticationManager");
                        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                                userName, password);
                        Authentication auth = null;
                        try {
                            auth = authManager.authenticate(token);
                            log.info("Authentication result: {}\ndetails: {}", auth.isAuthenticated(), auth);
                            result = auth.isAuthenticated();
                            // set the authenticated user into the context (thread-local)
                            if (result) {
                                SecurityContextHolder.getContext().setAuthentication(auth);
                            }
                        } catch (Exception ex) {
                            log.warn("Problem during auth attempt: {}", ex);
                        }
                    }
                } else if (authmod != null && userName != null) {
                    // generate a challenge
                    challenge = calculateHMACSHA256(salt, sessionId);
                    // store the generated data
                    sessionChallenges.put(sessionId, challenge);
                    // set as rejected
                    status = String.format(
                            "[ AccessManager.Reject ] : [ authmod=red5 ] : ?reason=needauth&user=%s&sessionid=%s&challenge=%s",
                            userName, sessionId, challenge);
                }
                log.debug("Challenge: {}", challenge);
            } else {
                status = invalidAuthMod;
            }
        } catch (UsernameNotFoundException ex) {
            status = noSuchUser;
        } catch (Exception e) {
            log.error("Error authenticating", e);
        }
    }
    //send the status object
    log.debug("Status: {}", status);
    if (!result) {
        throw new ClientRejectedException(status);
    }
    return result;
}