Example usage for org.springframework.security.web.authentication.preauth PreAuthenticatedAuthenticationToken PreAuthenticatedAuthenticationToken

List of usage examples for org.springframework.security.web.authentication.preauth PreAuthenticatedAuthenticationToken PreAuthenticatedAuthenticationToken

Introduction

In this page you can find the example usage for org.springframework.security.web.authentication.preauth PreAuthenticatedAuthenticationToken PreAuthenticatedAuthenticationToken.

Prototype

public PreAuthenticatedAuthenticationToken(Object aPrincipal, Object aCredentials,
        Collection<? extends GrantedAuthority> anAuthorities) 

Source Link

Document

Constructor used for an authentication response.

Usage

From source file:com.todo.backend.security.JWTUtils.java

public static Authentication getAuthentication(String token, String secretKey) {

    final Claims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();
    final Long userId = Long.valueOf(claims.getSubject());
    final String userRole = claims.get(AUTHORITIES_KEY).toString();

    return new PreAuthenticatedAuthenticationToken(userId, null,
            Collections.singletonList(new SimpleGrantedAuthority(userRole)));
}

From source file:com.netflix.spinnaker.fiat.shared.FiatAuthenticationFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    Authentication auth = AuthenticatedRequest.getSpinnakerUser()
            .map(username -> (Authentication) new PreAuthenticatedAuthenticationToken(username, null,
                    new ArrayList<>()))
            .orElseGet(() -> new AnonymousAuthenticationToken("anonymous", "anonymous",
                    AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));

    val ctx = SecurityContextHolder.createEmptyContext();
    ctx.setAuthentication(auth);//from   w w w . j  ava 2s  .  co m
    SecurityContextHolder.setContext(ctx);
    log.debug("Set SecurityContext to user: {}", auth.getPrincipal().toString());
    chain.doFilter(request, response);
}

From source file:com.hortonworks.example.ambari.AmbariSsoFilter.java

public void doHttpFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    String xAuthToken = Util.getAuthToken(request);
    if (xAuthToken != null) {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        Authentication authentication = new PreAuthenticatedAuthenticationToken(xAuthToken, null, authorities);
        SecurityContextHolder.getContext().setAuthentication(authentication);
    } else {//from  w w  w .  j a  v a2 s. co m
        SecurityContextHolder.getContext().setAuthentication(null);
    }
    chain.doFilter(request, response);
}

From source file:com.lll.util.SpringSecurityUtils.java

/**
 * UserDetails?Security Context./*from   www . j  a v  a 2  s.  c  o m*/
 * 
 * @param userDetails ??.
 * @param request ?IP??.
 */
public static void saveUserDetailsToContext(UserDetails userDetails, HttpServletRequest request) {
    PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(userDetails,
            userDetails.getPassword(), userDetails.getAuthorities());

    authentication.setDetails(new WebAuthenticationDetails(request));

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

From source file:ch.wisv.areafiftylan.security.TokenAuthenticationFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    String xAuth = ((HttpServletRequest) request).getHeader("X-Auth-Token");

    if (!Strings.isNullOrEmpty(xAuth)) {
        AuthenticationToken authenticationToken = extractOptional(
                authenticationTokenRepository.findByToken(xAuth), response);
        if (authenticationToken.isValid()) {
            User user = authenticationToken.getUser();
            SecurityContextHolder.getContext().setAuthentication(
                    new PreAuthenticatedAuthenticationToken(user, "N/A", user.getAuthorities()));
        } else {/*w ww.j  a  va  2s  . c om*/
            ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token Expired");
        }
    }
    chain.doFilter(request, response);
}

From source file:net.maritimecloud.identityregistry.controllers.TokenGenerator.java

/**
 * Helper function of build fake PreAuthenticatedAuthenticationToken - used for x509 authentication
 * @param orgMrn/*from  w  w  w .  j  a v a 2 s . c  o m*/
 * @param roles
 * @param permissions
 * @return
 */
public static PreAuthenticatedAuthenticationToken generatePreAuthenticatedAuthenticationToken(String orgMrn,
        String roles, String permissions) {
    Collection<GrantedAuthority> authorities = generateGrantedAuthority(roles);
    InetOrgPerson.Essence essence = new InetOrgPerson.Essence();
    String username = "urn:mrn:mcl:user:dma:dmauser";
    essence.setUsername(username);
    essence.setUid(username);
    essence.setDn("O=" + orgMrn);
    essence.setO(orgMrn);
    essence.setCn(new String[] { "dmauser" });
    essence.setAuthorities(authorities);

    PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
            essence.createUserDetails(), null, authorities);
    return token;
}

From source file:com.example.AuthenticationController.java

@PostMapping("/factor")
public void accept(@RequestParam String factor, Principal principal, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    if (!"red".equals(factor)) {
        response.sendRedirect("/factor?error=true");
        return;//www .jav  a 2  s. c  om
    }
    Authentication authentication = (Authentication) principal;
    Collection<GrantedAuthority> authorities = new ArrayList<>(authentication.getAuthorities());
    authorities.add(new SimpleGrantedAuthority("ROLE_FACTOR"));
    PreAuthenticatedAuthenticationToken successful = new PreAuthenticatedAuthenticationToken(
            authentication.getPrincipal(), authentication.getCredentials(), authorities);
    successful.setDetails(authentication.getDetails());
    SecurityContextHolder.getContext().setAuthentication(successful);
    handler.onAuthenticationSuccess(request, response, successful);
}

From source file:com.katsu.springframework.security.authentication.dni.DniAuthenticationProvider.java

private PreAuthenticatedAuthenticationToken createSuccessAuthentication(AbstractAuthenticationToken auth,
        UserDetails upat, Collection<? extends GrantedAuthority> roles) {
    PreAuthenticatedAuthenticationToken result = new PreAuthenticatedAuthenticationToken(upat,
            upat.getAuthorities(), roles);
    result.setDetails(auth.getDetails());
    return result;
}

From source file:com.rosy.bill.security.SpringSecurityUtils.java

/**
 * UserDetails?Security Context./*  w w  w  . j a v a  2  s  .  c o  m*/
 * 
 * @param userDetails ??.
 * @param request ?IP??,?Null.
 */
public static void saveUserDetailsToContext(UserDetails userDetails, HttpServletRequest request) {
    PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(userDetails,
            userDetails.getPassword(), userDetails.getAuthorities());

    if (request != null) {
        authentication.setDetails(new WebAuthenticationDetails(request));
    }

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

From source file:net.maritimecloud.identityregistry.controllers.LogoControllerTest.java

@Test
public void deleteLogo() throws Exception {

    assertNumberOfLogos(0);//  w ww . j  a  v  a2 s.com

    Organization org = new Organization();
    org.setMrn("urn:mrn:mcl:org:dma");
    org.setAddress("Carl Jakobsensvej 31, 2500 Valby");
    org.setCountry("Denmark");
    org.setUrl("http://dma.dk");
    org.setEmail("dma@dma.dk");
    org.setName("Danish Maritime Authority");
    org.setApproved(true);
    Logo logo = new Logo();
    logo.setImage(new byte[] { 1, 2, 3 });
    org.setLogo(logo);

    orgRepo.save(org);

    // fiddle with security to be able to call the delete method
    InetOrgPerson person = mock(InetOrgPerson.class);
    when(person.getO()).then(invocation -> org.getMrn());
    Authentication previousAuth = SecurityContextHolder.getContext().getAuthentication();
    SecurityContextHolder.getContext().setAuthentication(new PreAuthenticatedAuthenticationToken(person, "",
            Lists.newArrayList(new SimpleGrantedAuthority("ROLE_ORG_ADMIN"))));

    try {
        logoController.deleteLogo(new MockHttpServletRequest("DELETE", "/path"), org.getMrn());

        Organization reloaded = orgRepo.findByMrn(org.getMrn());
        assertNull("Logo should be deleted", reloaded.getLogo());

        assertNumberOfLogos(0);
    } finally {
        SecurityContextHolder.getContext().setAuthentication(previousAuth);
    }
}