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

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

Introduction

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

Prototype

Authentication authenticate(Authentication authentication) throws AuthenticationException;

Source Link

Document

Attempts to authenticate the passed Authentication object, returning a fully populated Authentication object (including granted authorities) if successful.

Usage

From source file:net.cristcost.study.services.ServiceTestUtil.java

private static SecurityContext authenticate(PrintWriter writer, HttpServletRequest request,
        AuthenticationManager authenticationManager) {

    SecurityContext initialContext = SecurityContextHolder.getContext();

    if (request.getParameter("user") != null) {

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                request.getParameter("user"), request.getParameter("pass"));
        try {//www  .  j a v a 2s  . co  m
            Authentication authentication = authenticationManager.authenticate(authRequest);
            SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            writer.println("Authenticating user: " + request.getParameter("user"));
        } catch (AuthenticationException e) {
            writer.println("! Error while Authenticating: " + e.getMessage());
        }
        writer.println();
    }

    return initialContext;
}

From source file:org.runway.utils.AuthenticationUtils.java

public static void autoLogin(User user, HttpServletRequest request,
        AuthenticationManager authenticationManager) {

    //           GrantedAuthority[] grantedAuthorities = new GrantedAuthority[] { new GrantedAuthorityImpl(
    //             user.getAuthority()) };

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(),
            user.getPassword(), user.getAuthorities());

    // generate session if one doesn't exist
    HttpSession session = request.getSession();

    token.setDetails(new WebAuthenticationDetails(request));
    Authentication authenticatedUser = authenticationManager.authenticate(token);

    SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
    // setting role to the session
    session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            SecurityContextHolder.getContext());

}

From source file:org.vaadin.spring.security.test.DefaultSecurityConfiguration.java

@Bean(name = VaadinSecurityConfiguration.Beans.AUTHENTICATION_MANAGER)
public AuthenticationManager createAuthenticationManager() {
    AuthenticationManager am = mock(AuthenticationManager.class);
    when(am.authenticate(any(Authentication.class))).thenAnswer(new Answer<Authentication>() {
        public Authentication answer(InvocationOnMock invocation) throws Throwable {
            return (Authentication) invocation.getArguments()[0];
        }//from   w  w  w  . j  av  a 2 s . com
    });

    return am;
}

From source file:org.cloudfoundry.identity.uaa.authentication.AuthzAuthenticationFilterTests.java

@Test
public void authenticatesValidUser() throws Exception {

    String msg = "{ \"username\":\"marissa\", \"password\":\"koala\"}";

    AuthenticationManager am = mock(AuthenticationManager.class);
    Authentication result = mock(Authentication.class);
    when(am.authenticate(any(AuthzAuthenticationRequest.class))).thenReturn(result);
    AuthzAuthenticationFilter filter = new AuthzAuthenticationFilter(am);

    MockHttpServletRequest request = new MockHttpServletRequest("POST", "/oauth/authorize");
    request.setParameter("credentials", msg);
    MockHttpServletResponse response = new MockHttpServletResponse();

    filter.doFilter(request, response, new MockFilterChain());

}

From source file:com.morevaadin.vaadin7.springsecurity.service.AuthenticationService.java

public void handleAuthentication(String login, String password, HttpServletRequest httpRequest) {

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(login, password);

    token.setDetails(new WebAuthenticationDetails(httpRequest));

    ServletContext servletContext = httpRequest.getSession().getServletContext();

    WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

    AuthenticationManager authManager = wac.getBean(AuthenticationManager.class);

    Authentication authentication = authManager.authenticate(token);

    SecurityContextHolder.getContext().setAuthentication(authentication);
}

From source file:com.application.model.dao.AuthenticationService.java

public void handleAuthentication(String login, String password, HttpServletRequest httpRequest) {

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(login, password);

    token.setDetails(new WebAuthenticationDetails(httpRequest));

    ServletContext servletContext = httpRequest.getSession().getServletContext();

    WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

    AuthenticationManager authManager = wac.getBean(AuthenticationManager.class);

    Authentication authentication = authManager.authenticate(token);

    SecurityContextHolder.getContext().setAuthentication(authentication);

}

From source file:org.chance.SampleSecureApplicationTests.java

@Before
public void init() {
    AuthenticationManager authenticationManager = this.context.getBean(AuthenticationManager.class);
    this.authentication = authenticationManager
            .authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
}

From source file:org.jasig.springframework.security.portlet.authentication.PortletAuthenticationProcessingFilterTest.java

/**
 * Create an authentication manager which returns the passed in object.
 *//*from   w  w  w .java 2 s  . c  om*/
private AuthenticationManager createAuthenticationManager() {
    AuthenticationManager am = mock(AuthenticationManager.class);
    when(am.authenticate(any(Authentication.class))).thenAnswer(new Answer<Authentication>() {
        public Authentication answer(InvocationOnMock invocation) throws Throwable {
            return (Authentication) invocation.getArguments()[0];
        }
    });

    return am;
}

From source file:at.plechinger.spring.security.scribe.ScribeAuthenticationFilter.java

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {

    String callbackUrl = request.getRequestURL().append("?").append(request.getQueryString()).toString();

    LOG.log(Level.DEBUG, "callbackUrl " + callbackUrl);

    String configMatch = request.getParameter(configMatchParameter);

    LOG.log(Level.DEBUG, "configMatch: " + configMatch);

    ProviderConfiguration providerConfiguration = getMatchedProviderConfiguration(configMatch);

    HttpSession session = request.getSession(true);

    ServiceBuilder serviceBuilder = new ServiceBuilder().provider(providerConfiguration.getApiClass())
            .apiKey(providerConfiguration.getApiKey()).apiSecret(providerConfiguration.getApiSecret())
            .callback(callbackUrl);//from   w ww . j a  v a  2s.  com

    //enable debug logging if enabled
    if (LOG.getLevel() == Level.DEBUG) {
        LOG.log(Level.DEBUG, "enable scribe debug mode");
        serviceBuilder.debug();
    }

    OAuthService oAuthService = serviceBuilder.build();

    if (!providerConfiguration.isAuthCodeProvided(request)) {
        Token requestToken = null;
        try {
            requestToken = oAuthService.getRequestToken();
        } catch (UnsupportedOperationException e) {
            //some networks dont support request tokens (eg. Facebook)
        }

        String authUrl = oAuthService.getAuthorizationUrl(requestToken);

        session.setAttribute(SESSION_TOKEN, requestToken);
        response.sendRedirect(authUrl);
        return null;
    } else {
        ScribeAuthentication scribeAuthentication = new ScribeAuthentication();
        String authCode = providerConfiguration.getAuthCode(request);
        Verifier verifier = new Verifier(authCode);
        Token requestToken = (Token) session.getAttribute(SESSION_TOKEN);

        Token accessToken = oAuthService.getAccessToken(requestToken, verifier);
        scribeAuthentication.setScribeToken(accessToken);
        scribeAuthentication.setRedirectUrl(callbackUrl);

        scribeAuthentication.setDetails(this.authenticationDetailsSource.buildDetails(request));

        scribeAuthentication.setProviderConfiguration(providerConfiguration);
        AuthenticationManager authenticationManager = this.getAuthenticationManager();
        Authentication success = authenticationManager.authenticate(scribeAuthentication);

        return success;
    }
}

From source file:org.web4thejob.security.SpringSecurityService.java

@Override
@SuppressWarnings("unchecked")
public <T> T authenticate(String username, String password) {
    Authentication authentication = new UsernamePasswordAuthenticationToken(username, password);
    AuthenticationManager authenticationManager = ContextUtil.getBean(BEAN_AUTHENTICATION_MANAGER,
            AuthenticationManager.class);

    try {//  www .j  a  v  a2 s.c o  m
        return (T) authenticationManager.authenticate(authentication);
    } catch (AuthenticationException e) {
        return null;
    }
}