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

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

Introduction

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

Prototype

public void setDetails(Object details) 

Source Link

Usage

From source file:org.axonframework.samples.trader.webui.security.TraderAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!supports(authentication.getClass())) {
        return null;
    }//from w  ww.j a  v a  2  s.c  o m
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String username = token.getName();
    String password = String.valueOf(token.getCredentials());
    FutureCallback<UserAccount> accountCallback = new FutureCallback<UserAccount>();
    AuthenticateUserCommand command = new AuthenticateUserCommand(username, password.toCharArray());
    try {
        commandBus.dispatch(new GenericCommandMessage<AuthenticateUserCommand>(command), accountCallback);
        // the bean validating interceptor is defined as a dispatch interceptor, meaning it is executed before
        // the command is dispatched.
    } catch (StructuralCommandValidationFailedException e) {
        return null;
    }
    UserAccount account;
    try {
        account = accountCallback.get();
        if (account == null) {
            throw new BadCredentialsException("Invalid username and/or password");
        }
    } catch (InterruptedException e) {
        throw new AuthenticationServiceException("Credentials could not be verified", e);
    } catch (ExecutionException e) {
        throw new AuthenticationServiceException("Credentials could not be verified", e);
    }

    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(account,
            authentication.getCredentials(), userAuthorities);
    result.setDetails(authentication.getDetails());
    return result;
}

From source file:ph.fingra.statisticsweb.service.MemberServiceImpl.java

public void update(Member member) {
    if (!StringUtils.isEmpty(member.getPassword())) {
        member.setPassword(passwordEncoder.encode(member.getPassword()));
    }//w  w  w .  ja  v  a 2  s .co m
    memberDao.update(member);
    UserDetails newPrincipal = new FingraphUser(get(member.getMemberid()));
    Authentication currentAuth = SecurityContextHolder.getContext().getAuthentication();
    UsernamePasswordAuthenticationToken newAuth = new UsernamePasswordAuthenticationToken(newPrincipal,
            currentAuth.getCredentials(), newPrincipal.getAuthorities());
    newAuth.setDetails(currentAuth.getDetails());
    SecurityContextHolder.getContext().setAuthentication(newAuth);
}

From source file:com.gm.wine.web.LoginvalidateAction.java

@Override
public String execute() throws Exception {
    HttpServletRequest request = Struts2Utils.getRequest();
    String loginName = request.getParameter("loginName");
    String password = request.getParameter("password");
    UserVO u = new UserVO();

    try {/*from   w  w w.jav a  2  s . co  m*/
        User user = userManager.getUserByUsername(loginName);
        if (user != null) {
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(loginName,
                    password);
            token.setDetails(new WebAuthenticationDetails(request));
            Authentication authenticatedUser = authenticationManager.authenticate(token);

            SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
            request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                    SecurityContextHolder.getContext());
            u.setErrorCode(GlobalMessage.SUCCESS_CODE);
            u.setErrorMessage("?");
            u.setId(user.getId());
            u.setLoginName(user.getLoginName());
            u.setName(user.getName());
        } else {
            u.setErrorCode(GlobalMessage.ERROR_CODE);
            u.setErrorMessage("?");
        }
    } catch (AuthenticationException e) {
        e.printStackTrace();
        u.setErrorCode(GlobalMessage.ERROR_CODE);
        u.setErrorMessage("?");
    }

    data = new Gson().toJson(u);
    return SUCCESS;
}

From source file:com.seyren.core.security.AuthenticationTokenFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (!seyrenConfig.isSecurityEnabled()) {
        SecurityContextHolder.getContext().setAuthentication(new SecurityDisabledAuthentication());
    } else {//from w  w  w .jav a 2s. com
        HttpServletRequest httpRequest = this.getAsHttpRequest(request);

        String authToken = this.extractAuthTokenFromRequest(httpRequest);
        String userName = Token.getUserNameFromToken(authToken);

        if (userName != null) {
            UserDetails userDetails = this.userService.loadUserByUsername(userName);

            if (Token.validateToken(authToken, userDetails)) {

                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
                SecurityContextHolder.getContext().setAuthentication(authentication);

            }
        }
    }

    chain.doFilter(request, response);
}

From source file:nl.surfnet.coin.api.basic.MockBasicAuthenticationManager.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
            authentication.getPrincipal(), authentication.getCredentials(),
            Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")));
    token.setDetails(authentication.getDetails());
    return token;
}

From source file:com.ai.bss.webui.security.AiBssAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!supports(authentication.getClass())) {
        return null;
    }// www .  j a  v a2  s.  c o m
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String username = token.getName();
    String password = String.valueOf(token.getCredentials());
    FutureCallback<UserAccount> accountCallback = new FutureCallback<UserAccount>();
    AuthenticateUserCommand command = new AuthenticateUserCommand(username, password.toCharArray());
    try {
        //            commandBus.dispatch(new GenericCommandMessage<AuthenticateUserCommand>(command), accountCallback);
        // the bean validating interceptor is defined as a dispatch interceptor, meaning it is executed before
        // the command is dispatched.
    } catch (StructuralCommandValidationFailedException e) {
        e.printStackTrace();
        return null;
    }
    UserAccount account;
    try {
        account = accountCallback.get();
        if (account == null) {
            throw new BadCredentialsException("Invalid username and/or password");
        }
    } catch (InterruptedException e) {
        throw new AuthenticationServiceException("Credentials could not be verified", e);
    } catch (ExecutionException e) {
        throw new AuthenticationServiceException("Credentials could not be verified", e);
    }

    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(account,
            authentication.getCredentials(), userAuthorities);
    result.setDetails(authentication.getDetails());
    return result;
}

From source file:org.musicrecital.webapp.services.impl.SpringSecurityContext.java

public void login(User user) {
    if (user == null) {
        throw new IllegalArgumentException("User cannot be null");
    }//from w ww . ja v  a2 s. c o m

    UsernamePasswordAuthenticationToken loggedIn = new UsernamePasswordAuthenticationToken(user,
            user.getConfirmPassword(), user.getAuthorities());

    loggedIn.setDetails(user);
    SecurityContextHolder.getContext().setAuthentication(loggedIn);

}

From source file:org.xaloon.wicket.security.spring.external.ExternalAuthenticationProvider.java

private Authentication createExternalAuthenticationToken(Authentication authentication,
        AuthenticationToken initialToken) {
    User user = userDao.newUser();// w  w  w .  j a  va  2  s.c  o  m
    user.setUsername(authentication.getName());
    user.setExternal(true);
    externalParameterResolver.resolve(initialToken, user);

    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.add(new SimpleGrantedAuthority(SecurityAuthorities.AUTHENTICATED_USER));

    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(
            authentication.getPrincipal(), authentication.getCredentials(), authorities);
    result.setDetails(user);
    return result;
}

From source file:org.zalando.stups.oauth2.spring.server.AbstractAuthenticationExtractor.java

@Override
public OAuth2Authentication extractAuthentication(final Map<String, Object> map, final String clientId) {
    UsernamePasswordAuthenticationToken user = new UsernamePasswordAuthenticationToken(getPrincipal(map), "N/A",
            AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));
    user.setDetails(map);

    // at the moment there is other way
    Set<String> scopes = resolveScopes(map);

    ///* w ww  .j  a  va  2 s. c  o m*/
    OAuth2Request request = new OAuth2Request(null, clientId, null, true, scopes, null, null, null, null);
    return new OAuth2Authentication(request, user);
}

From source file:com.cfitzarl.cfjwed.core.security.SecurityContextLoader.java

/**
 * This method does all the heavy work in retrieving the context out of Redis. It inspects the servlet request
 * and tries to scrape the authentication token out of a header. If the header is missing or the token is not
 * found, an empty {@link SecurityContext} is returned, effectively telling Spring that the current request is
 * coming from an anonymous, unauthenticated actor.
 *
 * @param requestResponseHolder the request container
 * @return a security context//ww w .j av a2 s.c  om
 */
@Override
public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
    HttpServletRequest request = requestResponseHolder.getRequest();
    String tokenParam = coalesce(request.getHeader(SessionConstant.AUTH_TOKEN_HEADER),
            request.getParameter(SessionConstant.AUTH_TOKEN_PARAM));

    SecurityContext securityContext = new SecurityContextImpl();

    if (tokenParam == null || !redisService.exists(tokenParam)) {
        return securityContext;
    }

    String serializedAuthData = redisService.get(tokenParam);
    AuthenticationDTO dto;

    try {
        dto = new ObjectMapper().readValue(serializedAuthData, AuthenticationDTO.class);
    } catch (IOException e) {
        LOGGER.error("Error deserializing auth DTO", e);
        return securityContext;
    }

    Account account = accountDao.findByEmail(dto.getEmail());

    Collection<GrantedAuthority> gal = Collections.singletonList(new SimpleGrantedAuthority(dto.getRole()));
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(account.getId(), null,
            gal);
    token.setDetails(dto.getCsrf());

    securityContext.setAuthentication(token);

    return securityContext;
}