Example usage for org.springframework.security.core Authentication isAuthenticated

List of usage examples for org.springframework.security.core Authentication isAuthenticated

Introduction

In this page you can find the example usage for org.springframework.security.core Authentication isAuthenticated.

Prototype

boolean isAuthenticated();

Source Link

Document

Used to indicate to AbstractSecurityInterceptor whether it should present the authentication token to the AuthenticationManager.

Usage

From source file:com.github.djabry.platform.vaadin.presenter.SideBarPresenter.java

@PostConstruct
public void initView() {
    Authentication authentication = security.getAuthentication();
    boolean authenticated = false;
    if (authentication != null) {
        authenticated = authentication.isAuthenticated();
    }/*from www  . j a  v  a 2 s .  com*/

    //getView().setSidebarVisible(authenticated);
    getView().setSidebarVisible(false);
}

From source file:com.mothsoft.alexis.web.security.TermsOfServiceFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {
    final HttpSession session = request.getSession(false);

    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null || !authentication.isAuthenticated()
            || ANONYMOUS_USER.equals(authentication.getName()) || isStaticContent(request)) {
        chain.doFilter(request, response);
        return;//from w ww  .  java2 s.co m
    }

    if (session.getAttribute(TOS_KEY) == null) {
        final UserAuthenticationDetails details = (UserAuthenticationDetails) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal();
        final Long userId = details.getUserId();
        final User user = this.userService.getUser(userId);

        if (user.getTosAcceptDate() != null) {
            session.setAttribute(TOS_KEY, user.getTosAcceptDate());
        }
    }

    if (session.getAttribute(TOS_KEY) == null && !request.getRequestURI().equals(TERMS_OF_SERVICE_URI)) {
        response.sendRedirect(TERMS_OF_SERVICE_URI);
        return;
    }

    chain.doFilter(request, response);
}

From source file:com.github.cmis4j.ws.CmisUsernameTokenValidator.java

@Override
protected void verifyPlaintextPassword(UsernameToken usernameToken, RequestData data)
        throws WSSecurityException {
    String username = String.valueOf(usernameToken.getName());
    String password = String.valueOf(usernameToken.getPassword());
    Authentication authentication = new UsernamePasswordAuthenticationToken(username, password);
    authentication = authenticationManager.authenticate(authentication);
    if (!authentication.isAuthenticated()) {
        throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION);
    }/*w w w . j  a  v  a 2 s . c  o  m*/

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

From source file:org.geonode.security.GeoNodeAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication, HttpServletRequest request)
        throws AuthenticationException {
    this.client.setRequestUrl("http://" + request.getServerName() + "/");
    if (authentication instanceof UsernamePasswordAuthenticationToken) {
        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
        String username = token.getName();
        String password = (String) token.getCredentials();

        // ignore this - let the other provider(s) handle things
        if (GeoServerUser.ROOT_USERNAME.equals(username)
                && GeoServerUser.DEFAULT_ADMIN_PASSWD.equals(username)) {
            return null;
        }/*from ww  w  .  j av a2  s  . c om*/

        try {
            if (username == "" && password == null) {
                return client.authenticateAnonymous();
            } else {
                // if an anonymous session cookie exists in the request but
                // the user is logging in via the admin or other form mechanism,
                // it's possible that the GeoNodeCookieProcessingFilter will
                // 'overwrite' the credentials... it will check for this
                Authentication auth = client.authenticateUserPwd(username, password);
                if (auth.isAuthenticated()) {
                    SecurityContextHolder.getContext().setAuthentication(auth);
                }
                return auth;
            }
        } catch (IOException e) {
            throw new AuthenticationServiceException(
                    "Communication with GeoNode failed (UsernamePasswordAuthenticationToken)", e);
        }
    } else if (authentication instanceof GeoNodeSessionAuthToken) {
        try {
            return client.authenticateCookie((String) authentication.getCredentials());
        } catch (IOException e) {
            throw new AuthenticationServiceException(
                    "Communication with GeoNode failed (GeoNodeSessionAuthToken)", e);
        }
    } else if (authentication instanceof AnonymousGeoNodeAuthenticationToken) {
        try {
            return client.authenticateAnonymous();
        } catch (IOException e) {
            throw new AuthenticationServiceException(
                    "Communication with GeoNode failed (AnonymousGeoNodeAuthenticationToken)", e);
        }
    } else {
        throw new IllegalArgumentException(
                "GeoNodeAuthenticationProvider accepts only UsernamePasswordAuthenticationToken and GeoNodeSessionAuthToken; received "
                        + authentication);
    }
}

From source file:de.knightsoftnet.validators.server.security.AuthSuccessHandler.java

@Override
public void onAuthenticationSuccess(final HttpServletRequest prequest, final HttpServletResponse presponse,
        final Authentication pauthentication) throws IOException, ServletException {
    this.csrfCookieHandler.setCookie(prequest, presponse);

    if (pauthentication.isAuthenticated()) {
        presponse.setStatus(HttpServletResponse.SC_OK);
        LOGGER.info("User is authenticated!");
        LOGGER.debug(pauthentication.toString());

        final PrintWriter writer = presponse.getWriter();
        this.mapper.writeValue(writer,
                this.userDetailsConverter.convert((UserDetails) pauthentication.getPrincipal()));
        writer.flush();//  ww  w  .j a  v a 2 s. c  o m
    } else {
        presponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}

From source file:org.geonode.security.GeoNodeAnonymousProcessingFilter.java

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

    final SecurityContext securityContext = SecurityContextHolder.getContext();
    final Authentication existingAuth = securityContext.getAuthentication();

    final boolean authenticationRequired = existingAuth == null || !existingAuth.isAuthenticated();

    if (authenticationRequired) {
        try {/*from w  w  w  . j  a  v  a 2s.com*/
            Object principal = existingAuth == null ? null : existingAuth.getPrincipal();
            Collection<? extends GrantedAuthority> authorities = existingAuth == null ? null
                    : existingAuth.getAuthorities();
            Authentication authRequest = new AnonymousGeoNodeAuthenticationToken(principal, authorities);
            final Authentication authResult = getSecurityManager().authenticate(authRequest);
            securityContext.setAuthentication(authResult);
            LOGGER.finer("GeoNode Anonymous filter kicked in.");
        } catch (AuthenticationException e) {
            // we just go ahead and fall back on basic authentication
            LOGGER.log(Level.WARNING, "Error connecting to the GeoNode server for authentication purposes", e);
        }
    }

    // move forward along the chain
    chain.doFilter(request, response);
}

From source file:eu.freme.common.security.AuthenticationController.java

@RequestMapping(value = "/authenticate", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<String> authenticate(
        @RequestHeader(value = "X-Auth-Username", required = true) String username,
        @RequestHeader(value = "X-Auth-Password", required = true) String password) {

    UsernamePasswordAuthenticationToken requestAuthentication = new UsernamePasswordAuthenticationToken(
            username, password);/* w w  w.ja  v a 2s .c o m*/
    Authentication resultOfAuthentication = null;
    try {
        Authentication responseAuthentication = authenticationManager.authenticate(requestAuthentication);
        if (responseAuthentication == null || !responseAuthentication.isAuthenticated()) {
            throw new AuthenticationFailedException();
        }
        logger.debug("User successfully authenticated");
        resultOfAuthentication = responseAuthentication;
    } catch (Exception e) {
        logger.error(e);
        throw new AuthenticationFailedException();
    }

    SecurityContextHolder.getContext().setAuthentication(resultOfAuthentication);

    Token token = (Token) resultOfAuthentication.getDetails();

    JSONObject json = new JSONObject();
    json.put("token", token.getToken());

    ResponseEntity<String> response = new ResponseEntity<String>(json.toString(), HttpStatus.OK);
    return response;

}

From source file:com.ram.topup.business.service.authentication.impl.AuthenticationServiceImpl.java

@Override
public UserProfile login(String username, String password) {
    try {/*from ww  w  . jav  a  2 s . co  m*/
        Authentication authenticate = authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        if (authenticate.isAuthenticated()) {
            SecurityContextHolder.getContext().setAuthentication(authenticate);
            return ((ExtendedUserDetailsImpl) authenticate.getPrincipal()).getUser().toUserProfile();
        } else {
            throw new TopupException("Authentication Failed with username=" + username);
        }
    } catch (AuthenticationException e) {
        throw new TopupException("Authentication Error Occured", e);
    }

}

From source file:org.parancoe.plugins.security.SecureInterceptor.java

/**
 * Put in the Mapped Diagnostic Context (MDC) the infos on the logged user.
 * So these infos can be showed in the log, using the %X{key} format sequence in the log layout.
 *//*www  . ja v a  2 s  . c o m*/
private void populateMDC() {
    String username = "unknown";
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null && authentication.isAuthenticated()) {
        username = authentication.getName();
    }
    MDC.put(USERNAME_MDC_KEY, username);
}

From source file:org.keycloak.adapters.springsecurity.authentication.DirectAccessGrantAuthenticationProviderTest.java

@Ignore
@Test//w w w .j a va2s.co m
public void testAuthenticate() throws Exception {
    DirectAccessGrantToken token = new DirectAccessGrantToken(AppConfig.KNOWN_USERNAME,
            AppConfig.KNOWN_PASSWORD);
    Authentication authenication = directAccessGrantAuthenticationProvider.authenticate(token);
    assertNotNull(authenication);
    assertTrue(authenication.isAuthenticated());
}