List of usage examples for org.springframework.security.core Authentication setAuthenticated
void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException;
From source file:mx.edu.um.mateo.general.test.BaseTest.java
public Authentication authenticate(UserDetails principal, String credentials, List<GrantedAuthority> authorities) { Authentication authentication = new TestingAuthenticationToken(principal, credentials, authorities); authentication.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(authentication); return authentication; }
From source file:it.av.youeat.web.security.FacebookAuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { HttpServletRequest request = (HttpServletRequest) authentication.getPrincipal(); FacebookJaxbRestClient authClient;// w ww .j a va2 s. c o m try { authClient = bookAuthHandler.getAuthenticatedClient(request); String facebookSession = authClient.getCacheSessionKey(); long facebookUserId = authClient.users_getLoggedInUser(); Eater eater = eaterService.getBySocialUID(Long.toString(facebookUserId), SocialType.FACEBOOK); checkAndCreateUser(authClient, facebookUserId, eater); eater = eaterService.getBySocialUID(Long.toString(facebookUserId), SocialType.FACEBOOK); eater.setSocialSessionKey(facebookSession); Authentication authenticationToReturn = new FacebookAuthenticationToken(new UserDetailsImpl(eater)); authenticationToReturn.setAuthenticated(true); return authenticationToReturn; } catch (Exception e) { log.info("Facebook session not available"); } return authentication; }
From source file:eu.cloud4soa.frontend.commons.server.security.C4sAuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = (String) authentication.getPrincipal(); String password = (String) authentication.getCredentials(); UserInstance userInstance;/*w w w. j a v a2 s . com*/ try { userInstance = userService.authenticateUser(username, password); } catch (Throwable e) { if (e.getMessage().contains("wrong username") || e.getMessage().contains("No user instance")) throw new BadCredentialsException("Bad username or password."); String msg = "An error occurred while authenticating user '" + Strings.defaultString(username) + "': " + e.getMessage(); logger.debug(msg, e); throw new BadCredentialsException(msg, e); } Authentication auth = new C4sUserAuthentication(loadUserByUsername(username).getAuthorities(), authentication, userInstance.getUriId()); auth.setAuthenticated(true); return auth; }
From source file:com.example.AzureADResponseFilter.java
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try {/*from w w w .ja v a2 s. c o m*/ String currentUri = AuthHelper.getCurrentUri(request); csrfToken = null; // check if user has a session if (!AuthHelper.isAuthenticated(request) && AuthHelper.containsAuthenticationData(request)) { // The current session does not have the authentication info and the request contains the authentication data. // This request comes from AzureAD login page after login process is completed. if (log.isTraceEnabled()) { log.trace("AuthHelper.isAuthenticated = false && AuthHelper.containsAuthenticationData = true"); } Map<String, String> params = new HashMap<String, String>(); for (String key : request.getParameterMap().keySet()) { params.put(key, request.getParameterMap().get(key)[0]); } String fullUrl = currentUri + (request.getQueryString() != null ? "?" + request.getQueryString() : ""); if (log.isTraceEnabled()) { log.trace("URL: " + fullUrl); } AuthenticationResponse authResponse = AuthenticationResponseParser.parse(new URI(fullUrl), params); if (log.isTraceEnabled()) { log.trace("authResponse = " + authResponse); } if (AuthHelper.isAuthenticationSuccessful(authResponse)) { if (log.isTraceEnabled()) { log.trace("AuthHelper.isAuthenticationSuccessful = true"); } // Retrieve authentication response. AuthenticationSuccessResponse oidcResponse = (AuthenticationSuccessResponse) authResponse; AuthenticationResult result = getAccessToken(oidcResponse.getAuthorizationCode(), currentUri); // Retrieve CSRF token (the state is our csrf token.) if (log.isDebugEnabled()) { log.debug("oidcResponse.getState() = " + oidcResponse.getState()); } csrfToken = oidcResponse.getState().getValue(); // Store authenticated principal to spring security context holder. Authentication anAuthentication = new PreAuthenticatedAuthenticationToken(result.getUserInfo(), null); anAuthentication.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(anAuthentication); if (log.isDebugEnabled()) { log.debug("SecurityContextHolder.getContext().getAuthentication() = " + SecurityContextHolder.getContext().getAuthentication()); } // Store authentication data to current session. AuthHelper.setAuthSessionObject(request, result); } else { if (log.isTraceEnabled()) { log.trace("AuthHelper.isAuthenticationSuccessful = false"); } AuthenticationErrorResponse oidcResponse = (AuthenticationErrorResponse) authResponse; throw new Exception(String.format("Request for auth code failed: %s - %s", oidcResponse.getErrorObject().getCode(), oidcResponse.getErrorObject().getDescription())); } } } catch (Throwable exc) { response.setStatus(500); request.setAttribute("error", exc.getMessage()); response.sendRedirect(((HttpServletRequest) request).getContextPath() + error); } if (csrfToken != null) { // When csrf token is retrieved, create a dummy request and put this csrf token to the header. if (log.isDebugEnabled()) { log.debug("Create a dummy request and put csrf token in its header {}", csrfToken); } filterChain.doFilter(new HttpServletRequestWrapper(request) { @Override public String getHeader(String name) { if ("X-CSRF-TOKEN".equals(name)) { if (log.isDebugEnabled()) { log.debug("Read csrf token from request header: {}", csrfToken); } return csrfToken; } return super.getHeader(name); } }, response); } else { filterChain.doFilter(request, response); } }
From source file:eu.trentorise.smartcampus.ac.provider.filters.SpringAcProvider.java
/** * Checks if the authentication token is yet valid * // w w w. ja v a 2 s. co m * @param authentication * spring authentication object * @return the authentication object with authenticated flag setted true if * authentication token is yet valid * @throws AuthenticationException */ @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String token = authentication.getPrincipal().toString(); try { boolean valid = WebClient.create(endpointUrl).path("/users/me/validity").header("AUTH_TOKEN", token) .accept("application/json").get(Boolean.class); if (!valid) { throw new BadCredentialsException("Authentication token is absent or expired"); } authentication.setAuthenticated(true); return authentication; } catch (WebApplicationException e) { throw new AuthenticationServiceException("Problem accessing AC provider service: " + e.getMessage()); } }
From source file:org.cloudfoundry.identity.uaa.authentication.manager.ScopeAuthenticationManager.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (authentication instanceof OAuth2Authentication) { AuthorizationRequest creq = ((OAuth2Authentication) authentication).getAuthorizationRequest(); List<String> scopes = dedup(creq.getScope()); int matches = 0; int requiredMatches = getRequiredScopes().size(); for (String scope : scopes) { if (requiredScopes.contains(scope)) { matches++;//from w w w .j a v a2 s . co m } } if (matches == requiredMatches) { ((DefaultAuthorizationRequest) creq).setApproved(true); authentication.setAuthenticated(true); return authentication; } else if (isThrowOnNotAuthenticated()) { throw new InsufficientScopeException("Insufficient scopes"); } } else if (isThrowOnNotAuthenticated()) { throw new InvalidTokenException("Missing Oauth 2 authentication."); } return authentication; }
From source file:org.duracloud.account.app.controller.UserController.java
@RequestMapping(value = { "/profile" }, method = RequestMethod.GET) public ModelAndView profileRedirect() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth.isAuthenticated() && auth instanceof AnonymousAuthenticationToken) { //this check is necessary because on logout the browser is getting directed here //I'm not sure why the request is getting through - everything seems properly configured //in security-config.xml auth.setAuthenticated(false); return new ModelAndView("redirect:/users/profile"); }/*from ww w . j av a 2 s . c om*/ String username = auth.getName(); return new ModelAndView(formatUserRedirect(username)); }
From source file:eu.trentorise.smartcampus.aac.conf.OAuthAuthenticationProvider.java
/** * Check that the token is not empty, validate against the {@link TokenStore} if specified, * and if it is valid for the given scope (if specified) *///from w ww.j a v a2 s.com @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String token = (String) authentication.getPrincipal(); if (token == null || token.trim().isEmpty()) { throw new BadCredentialsException("Authentication token is absent"); } if (tokenStore != null && !tokenStore.validateToken(token)) { throw new BadCredentialsException("Authentication token is not valid"); } try { if (scope != null && aacURL != null && !new AACService(aacURL, null, null).isTokenApplicable(token, scope)) { throw new BadCredentialsException("Authentication token is not valid for the required scope"); } } catch (AACException e) { throw new BadCredentialsException("Failed to valdiate token scope: " + e.getMessage()); } authentication.setAuthenticated(true); return authentication; }
From source file:org.geonode.security.GeoNodeCookieProcessingFilter.java
/** * //from w ww . j a v a 2 s .co m * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest) request; final SecurityContext securityContext = SecurityContextHolder.getContext(); final Authentication existingAuth = securityContext.getAuthentication(); final String gnCookie = getGeoNodeCookieValue(httpRequest); final boolean alreadyAuthenticated = existingAuth != null && existingAuth.isAuthenticated(); final boolean anonymous = existingAuth == null || existingAuth instanceof AnonymousAuthenticationToken; // if logging in via geoserver web form, we want to short circuit the cookie // check below which might get triggered with an anon geonode cookie // the result looks like the login worked but because we replace the // auth below, it functionaly fails final boolean loggedInWithPassword = existingAuth instanceof UsernamePasswordAuthenticationToken && alreadyAuthenticated; final boolean hasPreviouslyValidatedGeoNodeCookie = (existingAuth instanceof GeoNodeSessionAuthToken) && existingAuth.getCredentials().equals(gnCookie); if (hasPreviouslyValidatedGeoNodeCookie) existingAuth.setAuthenticated(true); // if we still need to authenticate and we find the cookie, consult GeoNode for // an authentication final boolean authenticationRequired = (!alreadyAuthenticated || anonymous || !hasPreviouslyValidatedGeoNodeCookie); if (!loggedInWithPassword && authenticationRequired && gnCookie != null) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine( "Found GeoNode cookie - checking if we have the authorizations in cache or if we have to reload from GeoNode"); } try { Object principal = existingAuth == null ? null : existingAuth.getPrincipal(); Collection<? extends GrantedAuthority> authorities = existingAuth == null ? null : existingAuth.getAuthorities(); Authentication authRequest = new GeoNodeSessionAuthToken(principal, gnCookie, authorities); final Authentication authResult = getSecurityManager().authenticate(authRequest); LOGGER.log(Level.FINE, "authResult : {0}", authResult); securityContext.setAuthentication(authResult); } 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.trentorise.smartcampus.permissionprovider.controller.CookieCleaner.java
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { for (String s : cookieNames) { Cookie cookie = new Cookie(s, null); cookie.setPath("/"); cookie.setMaxAge(0);// w w w . j a v a2 s . com response.addCookie(cookie); cookie = new Cookie(s, null); cookie.setPath(request.getContextPath() + "/eauth/"); cookie.setMaxAge(0); response.addCookie(cookie); } if (request.getCookies() != null) { for (int i = 0; i < request.getCookies().length; i++) { Cookie cookie = request.getCookies()[i]; for (String s : cookieNames) { if (cookie.getName().startsWith(s)) { cookie = new Cookie(cookie.getName(), null); cookie.setPath("/"); cookie.setMaxAge(0); response.addCookie(cookie); cookie = new Cookie(cookie.getName(), null); cookie.setPath(request.getContextPath() + "/eauth/"); cookie.setMaxAge(0); response.addCookie(cookie); } } } } request.getSession().invalidate(); if (authentication != null) authentication.setAuthenticated(false); response.sendRedirect(request.getContextPath() + redirect); }