Example usage for org.springframework.security.authentication AbstractAuthenticationToken setDetails

List of usage examples for org.springframework.security.authentication AbstractAuthenticationToken setDetails

Introduction

In this page you can find the example usage for org.springframework.security.authentication AbstractAuthenticationToken setDetails.

Prototype

public void setDetails(Object details) 

Source Link

Usage

From source file:springchat.rest.AuthenticationRest.java

@RequestMapping(value = "/rest/auth", method = RequestMethod.POST, produces = { "application/json" })
@ResponseBody/*from  w  w w .j a  va 2  s . c  o m*/
public AuthenticationResultDto postUser(@RequestParam("user") String user, HttpServletRequest request) {
    AuthenticationResultDto dto = new AuthenticationResultDto();
    dto.setSessionId(request.getSession().getId());
    try {
        // Must be called from request filtered by Spring Security, otherwise SecurityContextHolder is not updated
        AbstractAuthenticationToken token = new UsernamePasswordAuthenticationToken(user, "");
        token.setDetails(new WebAuthenticationDetails(request));
        Authentication authentication = authenticationManager.authenticate(token);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        dto.setSuccess(Boolean.TRUE);
        request.getSession().setAttribute("authenticated", Boolean.TRUE);
    } catch (Exception e) {
        SecurityContextHolder.getContext().setAuthentication(null);
        dto.setSuccess(Boolean.FALSE);
        request.getSession().setAttribute("authenticated", Boolean.FALSE);
    }
    return dto;
}

From source file:at.ac.univie.isc.asio.security.HttpMethodRestrictionFilter.java

@Override
public void doFilter(final ServletRequest servletRequest, final ServletResponse response,
        final FilterChain chain) throws IOException, ServletException {
    final HttpServletRequest request = (HttpServletRequest) servletRequest;
    final Authentication authentication = org.springframework.security.core.context.SecurityContextHolder
            .getContext().getAuthentication();
    if (authentication != null && HttpMethod.GET.name().equalsIgnoreCase(request.getMethod())) {
        logger.debug("applying " + RESTRICTION + " to " + authentication);
        Set<GrantedAuthority> restricted = RESTRICTION.mapAuthorities(authentication.getAuthorities());
        if (restricted.isEmpty()) { // anonymous and remember me tokens require at least one authority
            restricted = Collections.<GrantedAuthority>singleton(Role.NONE);
        }//from   w  ww  .j ava2 s  . c om
        if (!restricted.containsAll(authentication.getAuthorities())) {
            final AbstractAuthenticationToken replacement = copy(authentication, restricted);
            replacement.setDetails(authentication.getDetails());
            logger.debug("injecting " + replacement);
            org.springframework.security.core.context.SecurityContextHolder.getContext()
                    .setAuthentication(replacement);
        } else {
            logger.debug("skip restricting " + authentication + " as it contains no restricted authorities");
        }
    } else {
        logger.debug("skip restricting " + authentication + " on HTTP method " + request.getMethod());
    }
    chain.doFilter(request, response);
}

From source file:it.smartcommunitylab.aac.controller.LegacyNativeAuthController.java

protected ModelAndView processNativeAuth(Device device, HttpServletRequest request,
        HttpServletResponse response, String authority) throws UnsupportedEncodingException {
    Map<String, Object> model = new HashMap<String, Object>();
    String clientId = request.getParameter(OAuth2Utils.CLIENT_ID);
    if (clientId == null || clientId.isEmpty()) {
        model.put("message", "Missing client_id");
        return new ModelAndView("oauth_error", model);
    }//from  ww w . j  av a2s  . co  m
    // each time create new OAuth request
    ClientAppBasic client = clientDetailsAdapter.getByClientId(clientId);
    AACOAuthRequest oauthRequest = new AACOAuthRequest(request, device, client.getScope(),
            client.getDisplayName());

    List<NameValuePair> pairs = URLEncodedUtils
            .parse(URI.create(request.getRequestURI() + "?" + request.getQueryString()), "UTF-8");

    String target = prepareRedirect(request, "/oauth/authorize");
    it.smartcommunitylab.aac.model.User userEntity = providerServiceAdapter.updateNativeUser(authority,
            request.getParameter("token"), toMap(pairs));
    List<GrantedAuthority> list = roleManager.buildAuthorities(userEntity);

    UserDetails user = new User(userEntity.getId().toString(), "", list);
    AbstractAuthenticationToken a = new AACAuthenticationToken(user, null, authority, list);
    a.setDetails(oauthRequest);
    SecurityContextHolder.getContext().setAuthentication(a);

    if (rememberMeServices != null) {
        rememberMeServices.loginSuccess(request, response, a);
    }

    return new ModelAndView("redirect:" + target);
}

From source file:com.skywell.social.custom.OAuth2AuthenticationProcessingFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    final boolean debug = logger.isDebugEnabled();
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    try {/*  ww  w . j av a2  s  . c om*/

        Authentication authentication = tokenExtractor.extract(request);

        if (authentication == null) {
            if (stateless && isAuthenticated()) {
                if (debug) {
                    logger.debug("Clearing security context.");
                }
                SecurityContextHolder.clearContext();
            }
            if (debug) {
                logger.debug("No token in request, will continue chain.");
            }
        } else {
            request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal());
            if (authentication instanceof AbstractAuthenticationToken) {
                AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken) authentication;
                needsDetails.setDetails(authenticationDetailsSource.buildDetails(request));
            }
            User user = userRepository.findByAccessToken(authentication.getName());
            UsernamePasswordAuthenticationToken authenticate = new UsernamePasswordAuthenticationToken(
                    user.getProviderUserId(), user.getAccessToken(), user.getAuthorities());
            authenticate.setDetails(authentication.getDetails());

            SecurityContextHolder.getContext().setAuthentication(authenticate);

        }
    } catch (OAuth2Exception failed) {
        SecurityContextHolder.clearContext();

        if (debug) {
            logger.debug("Authentication request failed: " + failed);
        }
        eventPublisher.publishAuthenticationFailure(new BadCredentialsException(failed.getMessage(), failed),
                new PreAuthenticatedAuthenticationToken("access-token", "N/A"));

        authenticationEntryPoint.commence(request, response,
                new InsufficientAuthenticationException(failed.getMessage(), failed));

        return;
    }

    chain.doFilter(request, response);
}

From source file:com.gfactor.web.wicket.context.ProviderManager.java

/**
 * Copies the authentication details from a source Authentication object to a destination one, provided the
 * latter does not already have one set.
 *
 * @param source source authentication//from  w  ww .  ja  v  a2  s  . co  m
 * @param dest the destination authentication object
 */
private void copyDetails(Authentication source, Authentication dest) {
    if ((dest instanceof AbstractAuthenticationToken) && (dest.getDetails() == null)) {
        AbstractAuthenticationToken token = (AbstractAuthenticationToken) dest;

        token.setDetails(source.getDetails());
    }
}

From source file:eu.trentorise.smartcampus.permissionprovider.controller.AuthController.java

/**
 * Handles the redirection to the specified target after the login has been
 * performed. Given the user data collected during the login, updates the
 * user information in DB and populates the security context with the user
 * credentials.//from  w  w  w  . j av a 2 s. co m
 * 
 * @param authorityUrl
 *            the authority used by the user to sign in.
 * @param target
 *            target functionality address.
 * @param req
 * @return
 * @throws Exception
 */
@RequestMapping("/eauth/{authorityUrl}")
public ModelAndView forward(@PathVariable String authorityUrl, @RequestParam(required = false) String target,
        HttpServletRequest req, HttpServletResponse res) throws Exception {
    List<GrantedAuthority> list = Collections
            .<GrantedAuthority>singletonList(new SimpleGrantedAuthority("ROLE_USER"));

    String nTarget = (String) req.getSession().getAttribute("redirect");
    if (nTarget == null)
        return new ModelAndView("redirect:/logout");

    String clientId = (String) req.getSession().getAttribute("client_id");
    if (clientId != null) {
        Set<String> idps = clientDetailsAdapter.getIdentityProviders(clientId);
        if (!idps.contains(authorityUrl)) {
            Map<String, Object> model = new HashMap<String, Object>();
            model.put("message", "incorrect identity provider for the app");
            return new ModelAndView("oauth_error", model);
        }
    }

    // HOOK for testing
    if (testMode && target == null) {
        target = "/eauth/" + authorityUrl + "?target=" + URLEncoder.encode(nTarget, "UTF8")
                + "&OIDC_CLAIM_email=my@mail&OIDC_CLAIM_given_name=name&OIDC_CLAIM_family_name=surname";
    } else {

        if (!testMode && nTarget != null) {
            target = nTarget;
        }

        Authentication old = SecurityContextHolder.getContext().getAuthentication();
        if (old != null && old instanceof UsernamePasswordAuthenticationToken) {
            if (!authorityUrl.equals(old.getDetails())) {
                new SecurityContextLogoutHandler().logout(req, res, old);
                SecurityContextHolder.getContext().setAuthentication(null);

                req.getSession().setAttribute("redirect", target);
                req.getSession().setAttribute("client_id", clientId);

                return new ModelAndView("redirect:/eauth/" + authorityUrl);
                //               return new ModelAndView("redirect:/logout");
            }
        }

        List<NameValuePair> pairs = URLEncodedUtils.parse(URI.create(nTarget), "UTF-8");

        eu.trentorise.smartcampus.permissionprovider.model.User userEntity = null;
        if (old != null && old instanceof UsernamePasswordAuthenticationToken) {
            String userId = old.getName();
            userEntity = userRepository.findOne(Long.parseLong(userId));
        } else {
            userEntity = providerServiceAdapter.updateUser(authorityUrl, toMap(pairs), req);
        }

        UserDetails user = new User(userEntity.getId().toString(), "", list);

        AbstractAuthenticationToken a = new UsernamePasswordAuthenticationToken(user, null, list);
        a.setDetails(authorityUrl);

        SecurityContextHolder.getContext().setAuthentication(a);

    }
    return new ModelAndView("redirect:" + target);
}

From source file:it.smartcommunitylab.aac.controller.AuthController.java

/**
 * Handles the redirection to the specified target after the login has been
 * performed. Given the user data collected during the login, updates the
 * user information in DB and populates the security context with the user
 * credentials./* w w w.  j a  va 2s . c o m*/
 * 
 * @param authorityUrl
 *            the authority used by the user to sign in.
 * @param target
 *            target functionality address.
 * @param req
 * @return
 * @throws Exception
 */
@RequestMapping("/eauth/{authorityUrl}")
public ModelAndView forward(@PathVariable String authorityUrl, @RequestParam(required = false) String target,
        HttpServletRequest req, HttpServletResponse res) {

    String nTarget = (String) req.getSession().getAttribute("redirect");
    if (nTarget == null)
        return new ModelAndView("redirect:/logout");

    String clientId = (String) req.getSession().getAttribute(OAuth2Utils.CLIENT_ID);
    if (clientId != null) {
        Set<String> idps = clientDetailsAdapter.getIdentityProviders(clientId);
        if (!idps.contains(authorityUrl)) {
            Map<String, Object> model = new HashMap<String, Object>();
            model.put("message", "incorrect identity provider for the app");
            return new ModelAndView("oauth_error", model);
        }
    }

    AACOAuthRequest oauthRequest = (AACOAuthRequest) req.getSession()
            .getAttribute(Config.SESSION_ATTR_AAC_OAUTH_REQUEST);
    if (oauthRequest != null) {
        oauthRequest.setAuthority(authorityUrl);
        req.getSession().setAttribute(Config.SESSION_ATTR_AAC_OAUTH_REQUEST, oauthRequest);
    }

    target = nTarget;

    Authentication old = SecurityContextHolder.getContext().getAuthentication();
    if (old != null && old instanceof AACAuthenticationToken) {
        AACOAuthRequest oldDetails = (AACOAuthRequest) old.getDetails();
        if (oldDetails != null && !authorityUrl.equals(oldDetails.getAuthority())) {
            new SecurityContextLogoutHandler().logout(req, res, old);
            SecurityContextHolder.getContext().setAuthentication(null);

            req.getSession().setAttribute("redirect", target);
            req.getSession().setAttribute(OAuth2Utils.CLIENT_ID, clientId);

            return new ModelAndView("redirect:" + Utils.filterRedirectURL(authorityUrl));
        }
    }

    List<NameValuePair> pairs = URLEncodedUtils.parse(URI.create(nTarget), "UTF-8");

    it.smartcommunitylab.aac.model.User userEntity = null;
    if (old != null
            && (old instanceof AACAuthenticationToken || old instanceof RememberMeAuthenticationToken)) {
        String userId = old.getName();
        userEntity = userRepository.findOne(Long.parseLong(userId));
    } else {
        userEntity = providerServiceAdapter.updateUser(authorityUrl, toMap(pairs), req);
    }

    List<GrantedAuthority> list = roleManager.buildAuthorities(userEntity);

    UserDetails user = new User(userEntity.getId().toString(), "", list);
    AbstractAuthenticationToken a = new AACAuthenticationToken(user, null, authorityUrl, list);
    a.setDetails(oauthRequest);

    SecurityContextHolder.getContext().setAuthentication(a);

    if (rememberMeServices != null) {
        rememberMeServices.loginSuccess(req, res, a);
    }

    return new ModelAndView("redirect:" + target);
}

From source file:it.smartcommunitylab.aac.controller.AuthController.java

/**
 * Entry point for resource access authorization request. Redirects to the
 * login page. In addition to standard OAuth parameters, it is possible to
 * specify a comma-separated list of authorities to be used for login as
 * 'authorities' parameter//from w  w w  . j  a  va2  s  . c  o m
 * 
 * @param req
 * @return
 * @throws Exception
 */
@RequestMapping("/eauth/authorize")
public ModelAndView authorise(Device device, HttpServletRequest req,
        @RequestParam(value = "authorities", required = false) String loginAuthorities) throws Exception {
    Map<String, Object> model = new HashMap<String, Object>();

    String clientId = req.getParameter(OAuth2Utils.CLIENT_ID);
    if (clientId == null || clientId.isEmpty()) {
        model.put("message", "Missing client_id");
        return new ModelAndView("oauth_error", model);
    }
    // each time create new OAuth request
    ClientAppBasic client = clientDetailsAdapter.getByClientId(clientId);
    AACOAuthRequest oauthRequest = new AACOAuthRequest(req, device, client.getScope(), client.getDisplayName());
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null && auth.getAuthorities() != null
            && auth.getAuthorities().stream()
                    .anyMatch(a -> a.getAuthority().equals(AUTHORITY.ROLE_USER.toString()))
            && req.getSession().getAttribute(Config.SESSION_ATTR_AAC_OAUTH_REQUEST) != null) {
        AACOAuthRequest old = (AACOAuthRequest) req.getSession()
                .getAttribute(Config.SESSION_ATTR_AAC_OAUTH_REQUEST);
        oauthRequest.setAuthority(old.getAuthority());
        // update existing session data
        AbstractAuthenticationToken a = new AACAuthenticationToken(auth.getPrincipal(), null,
                oauthRequest.getAuthority(), auth.getAuthorities());
        a.setDetails(oauthRequest);
        SecurityContextHolder.getContext().setAuthentication(a);
    }
    if (StringUtils.isEmpty(oauthRequest.getAuthority()) && loginAuthorities != null) {
        oauthRequest.setAuthority(loginAuthorities.split(",")[0].trim());
    }
    req.getSession().setAttribute(Config.SESSION_ATTR_AAC_OAUTH_REQUEST, oauthRequest);

    String target = prepareRedirect(req, "/eauth/pre-authorize");
    return new ModelAndView("redirect:" + target);
}

From source file:com.bac.accountserviceapp.AccountServiceApp.java

@Override
public Authentication login(AbstractAuthenticationToken authentication) {

    Objects.requireNonNull(authenticationManager, noAuthManagerMsg);
    Objects.requireNonNull(authentication, noAuthenticationMsg);

    try {//from   w w w.  ja  va2  s. co  m
        authentication = (AbstractAuthenticationToken) authenticationManager.authenticate(authentication);
    } catch (ProviderNotFoundException e) {
        logger.warn("No authentication provider available for principal: '{}'", authentication.getPrincipal());
        authentication.setDetails(NO_PROVIDER);
        return authentication;
    } catch (BadCredentialsException | IllegalArgumentException e) {
        logger.warn("Unable to authenticate for principal: '{}'", authentication.getPrincipal());
        authentication.setDetails(BAD_CREDENTIALS);
        return authentication;
    } catch (UsernameNotFoundException e) {
        logger.warn("Unable to authenticate for principal: '{}'", e.getMessage());
        authentication.setDetails(UNKNOWN_PRINCIPAL);
        return authentication;
    } catch (DisabledException e) {
        logger.warn("Principal is disabled: '{}'", authentication.getPrincipal());
        authentication.setDetails(DISABLED_PRINCIPAL);
        return authentication;
    }
    authentication.setDetails(AUTHENTICATED);
    return authentication;
}