List of usage examples for org.springframework.security.core Authentication isAuthenticated
boolean isAuthenticated();
AuthenticationManager
. From source file:org.osiam.auth.login.oauth.OsiamResourceOwnerPasswordTokenGranter.java
@Override protected OAuth2Authentication getOAuth2Authentication(AuthorizationRequest clientToken) { Map<String, String> parameters = clientToken.getAuthorizationParameters(); String username = parameters.get("username"); String password = parameters.get("password"); Authentication userAuth = new InternalAuthentication(username, password, new ArrayList<GrantedAuthority>()); try {//from ww w . j ava 2 s.c o m userAuth = authenticationManager.authenticate(userAuth); } catch (AccountStatusException ase) { // covers expired, locked, disabled cases (mentioned in section 5.2, draft 31) throw new InvalidGrantException(ase.getMessage(), ase); } catch (BadCredentialsException e) { // If the username/password are wrong the spec says we should send 400/bad grant throw new InvalidGrantException(e.getMessage(), e); } if (userAuth == null || !userAuth.isAuthenticated()) { throw new InvalidGrantException("Could not authenticate user: " + username); } DefaultAuthorizationRequest request = new DefaultAuthorizationRequest(clientToken); request.remove(Arrays.asList("password")); return new OAuth2Authentication(request, userAuth); }
From source file:org.taverna.server.master.TavernaServerSupport.java
private boolean isSuperUser() { try {//from ww w . jav a 2 s. co m Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth == null || !auth.isAuthenticated()) return false; UserDetails details = (UserDetails) auth.getPrincipal(); if (log.isDebugEnabled()) log.debug("checking for admin role for user <" + auth.getName() + "> in collection " + details.getAuthorities()); return details.getAuthorities().contains(ADMIN); } catch (ClassCastException e) { return false; } }
From source file:info.raack.appliancelabeler.web.MainController.java
private String getUserId(HttpServletRequest request, HttpServletResponse response, boolean trueId) { // extract userid from spring security Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((trueId && userDetails.getTrueUserId() == null) || (!trueId && userDetails.getEffectiveUserId() == null)) { if (auth != null && auth.isAuthenticated() && !(auth instanceof AnonymousAuthenticationToken)) { // user is already logged in via spring security String userId = null; if (auth instanceof RememberMeAuthenticationToken) { userId = ((OAuthUserDetails) auth.getPrincipal()).getUsername(); } else { userId = (String) auth.getPrincipal(); }// w w w .ja v a 2 s.c o m userDetails.setUserId(userId); return userId; } else if (auth == null || !auth.isAuthenticated() || auth instanceof AnonymousAuthenticationToken) { logger.info( "User is not logged in, so let's get their info by accessing the stepgreen service userinfo uri and forcing a login"); StepgreenUserDetails capturedDetails = null; try { capturedDetails = dataService.getStepgreenUserInfo(); logger.debug("Got user id: " + capturedDetails.getTrueUserId()); OAuthAutomaticAuthenticationToken token = new OAuthAutomaticAuthenticationToken( capturedDetails.getTrueUserId()); // generate session if one does not exist request.getSession(); SecurityContextHolder.getContext().setAuthentication(token); request.getSession().setAttribute( HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext()); // add email to session, so that the remember me services can remember it request.getSession().setAttribute(HttpSessionAndDatabaseOAuthRemeberMeServices.EMAIL_ATTRIBUTE, capturedDetails.getEmail()); // remember the new authentication rememberMeServices.loginSuccess(request, response, token); userDetails.setUserId(capturedDetails.getTrueUserId()); return capturedDetails.getTrueUserId(); } catch (Exception e) { throw new RuntimeException("Could not get user id from stepgreen", e); } } else { throw new RuntimeException("Could not get user id"); } } else { return userDetails.getEffectiveUserId(); } }
From source file:com.companyname.services.OnLogoutHandler.java
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { logger.info("Logout handler invoked"); PlatCookieService cookieService = new PlatCookieService(); cookieService.setAccessTokenCookieName(getAccessTokenCookieName()); cookieService.setRefreshTokenCookieName(getRefreshTokenCookieName()); cookieService.setAgentHostCookieName(getAgentHostCookieName()); cookieService.setCookieDomain(getCookieDomain()); cookieService.setCookiePath(getCookiePath(request)); cookieService.setTokenService(getTokenService()); // will take the tokens values out of the store if (cookieService.removeTokenValues(request, authentication)) { logger.info("OAuth2 tokens are revoked from DB store after logging out."); }//from ww w . ja v a2 s . c o m // clear tokens on cookies cookieService.invalidateCookies(request, response); logger.info("Oauth2 tokens cookies are cancelled after logging out"); // if user still logged in, then invalidate the authentication token from the context if (authentication != null && authentication.isAuthenticated()) { logger.info("Invalidating the authentication token in the security context."); SecurityContextHolder.getContext().setAuthentication(null); } }
From source file:org.smartplatforms.openid.connect.token.SmartTofuUserApprovalHandler.java
/** * Check if the user has already stored a positive approval decision for this site; or if the * site is whitelisted, approve it automatically. * //w w w.j a v a2 s. c o m * Otherwise, return false so that the user will see the approval page and can make their own decision. * * @param authorizationRequest the incoming authorization request * @param userAuthentication the Principal representing the currently-logged-in user * * @return true if the site is approved, false otherwise */ @Override public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { // if this request is already approved, pass that info through // (this flag may be set by updateBeforeApproval, which can also do funny things with scopes, etc) if (authorizationRequest.isApproved()) { return true; } else { // if not, check to see if the user has approved it if (Boolean.parseBoolean(authorizationRequest.getApprovalParameters().get("user_oauth_approval"))) { // TODO: make parameter name configurable? // check the value of the CSRF parameter if (authorizationRequest.getExtensions().get(CSRF) != null) { if (authorizationRequest.getExtensions().get(CSRF) .equals(authorizationRequest.getApprovalParameters().get(CSRF))) { // make sure the user is actually authenticated return userAuthentication.isAuthenticated(); } } } // if the above doesn't pass, it's not yet approved return false; } }
From source file:se.kth.csc.config.MockAuthConfig.java
@Bean @Autowired//from www . j a v a 2s .c o m public AuthenticationProvider authenticationProvider( final AuthenticationUserDetailsService<Authentication> authenticationUserDetailsService) { return new AuthenticationProvider() { @Override public Authentication authenticate(final Authentication authentication) throws AuthenticationException { final UserDetails userDetails = authenticationUserDetailsService.loadUserDetails(authentication); return new Authentication() { @Override public Collection<? extends GrantedAuthority> getAuthorities() { return userDetails.getAuthorities(); } @Override public Object getCredentials() { return authentication.getCredentials(); } @Override public Object getDetails() { return authentication.getDetails(); } public UserDetails getUserDetails() { return userDetails; } @Override public Object getPrincipal() { return userDetails; } @Override public boolean isAuthenticated() { return authentication.isAuthenticated(); } @Override public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { authentication.setAuthenticated(isAuthenticated); } @Override public String getName() { return authentication.getName(); } }; } @Override public boolean supports(Class<?> authentication) { return true; } }; }
From source file:org.cloudfoundry.identity.uaa.oauth.token.UaaTokenServicesTests.java
@Test public void testLoadAuthenticationForAUser() { DefaultAuthorizationRequest authorizationRequest = new DefaultAuthorizationRequest("client", Arrays.asList(new String[] { "read", "write" })); authorizationRequest.setResourceIds(new HashSet<String>(Arrays.asList(new String[] { "scim", "clients" }))); Map<String, String> azParameters = new HashMap<String, String>( authorizationRequest.getAuthorizationParameters()); azParameters.put("grant_type", "authorization_code"); authorizationRequest.setAuthorizationParameters(azParameters); Authentication userAuthentication = new UsernamePasswordAuthenticationToken( new UaaPrincipal(new UaaUser("jdsa", "password", "jdsa@vmware.com", null, null)), "n/a", null); OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest, userAuthentication); OAuth2AccessToken accessToken = testCreateAccessTokenForAUser(authentication, false); OAuth2Authentication loadedAuthentication = tokenServices.loadAuthentication(accessToken.getValue()); assertEquals(UaaAuthority.USER_AUTHORITIES, loadedAuthentication.getAuthorities()); assertEquals("jdsa", loadedAuthentication.getName()); UaaPrincipal uaaPrincipal = new UaaPrincipal(new UaaUser("12345", "jdsa", "password", "jdsa@vmware.com", UaaAuthority.USER_AUTHORITIES, null, null, null, null)); assertEquals(uaaPrincipal, loadedAuthentication.getPrincipal()); assertNull(loadedAuthentication.getDetails()); Authentication userAuth = loadedAuthentication.getUserAuthentication(); assertEquals("jdsa", userAuth.getName()); assertEquals(uaaPrincipal, userAuth.getPrincipal()); assertTrue(userAuth.isAuthenticated()); }
From source file:com.telefonica.euro_iaas.sdc.rest.auth.OpenStackAuthenticationFilter.java
/** * (non-Javadoc) @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, * javax.servlet.FilterChain)./*w w w. j a v a2s .co m*/ */ public final void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException { final boolean debug = logger.isDebugEnabled(); final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; String header = request.getHeader(OPENSTACK_HEADER_TOKEN); String pathInfo = request.getPathInfo(); logger.debug(header); logger.debug(pathInfo); MDC.put("txId", ((HttpServletRequest) req).getSession().getId()); if (pathInfo != null && (pathInfo.equals("/") || pathInfo.equals("/extensions"))) { /** * It is not needed to authenticate these operations */ logger.debug("Operation does not need to Authenticate"); } else { if (header == null) { header = ""; } try { String token = header; if ("".equals(token)) { String str = "Missing token header"; logger.info(str); throw new BadCredentialsException(str); } String tenantId = request.getHeader(OPENSTACK_HEADER_TENANTID); String txId = request.getHeader("txId"); if (txId != null) { MDC.put("txId", txId); } logger.debug(tenantId); logger.debug(token); // String tenantId = request.getPathInfo().split("/")[3]; if (debug) { logger.debug("OpenStack Authentication Authorization header " + "found for user '" + token + "' and tenant " + tenantId); } UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(token, tenantId); authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); Authentication authResult = authenticationManager.authenticate(authRequest); if (debug) { logger.debug("Authentication success: " + authResult); } // check AUTH-TOKEN and VDC are the same String uri = request.getRequestURI(); logger.debug("URI: " + uri); if (uri.contains("vdc") && !uri.contains(tenantId)) { String str = "Bad credentials for requested VDC"; logger.info(str); throw new AccessDeniedException(str); } UserDetails user = (UserDetails) authResult.getPrincipal(); logger.debug("User: " + user.getUsername()); logger.debug("Token: " + user.getPassword()); if (authResult.isAuthenticated()) { SecurityContextHolder.getContext().setAuthentication(authRequest); } // SecurityContextHolder.setStrategyName("MODE_INHERITABLETHREADLOCAL"); rememberMeServices.loginSuccess(request, response, authResult); onSuccessfulAuthentication(request, response, authResult); } catch (AuthenticationException failed) { SecurityContextHolder.clearContext(); if (debug) { logger.debug("Authentication request for failed: " + failed); } rememberMeServices.loginFail(request, response); onUnsuccessfulAuthentication(request, response, failed); if (ignoreFailure) { chain.doFilter(request, response); } else { authenticationEntryPoint.commence(request, response, failed); } return; } catch (AccessDeniedException ex) { throw ex; } catch (Exception ex) { SecurityContextHolder.clearContext(); if (debug) { logger.debug("Authentication exception: " + ex); } rememberMeServices.loginFail(request, response); if (ignoreFailure) { chain.doFilter(request, response); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); } return; } String keystoneURL = systemPropertiesProvider.getProperty(SystemPropertiesProvider.KEYSTONE_URL); response.addHeader("Www-Authenticate", "Keystone uri='" + keystoneURL + "'"); } // TODO jesuspg: question:add APIException chain.doFilter(request, response); }
From source file:com.telefonica.euro_iaas.paasmanager.rest.auth.OpenStackAuthenticationFilter.java
/** * (non-Javadoc) @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, * javax.servlet.FilterChain).//from ww w . ja v a 2s. co m */ public final void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException { final boolean debug = logger.isDebugEnabled(); final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; String headerToken = request.getHeader(OPENSTACK_HEADER_TOKEN); String pathInfo = request.getPathInfo(); logger.debug(headerToken); logger.debug(pathInfo); // first of all, check HTTP if exists accept header if (!validateAcceptHeader(request, response)) { return; } MDC.put("txId", ((HttpServletRequest) req).getSession().getId()); if (pathInfo != null && (pathInfo.equals("/") || pathInfo.equals("/extensions"))) { /** * It is not needed to authenticate these operations */ logger.debug("Operation does not need to Authenticate"); } else { if (headerToken == null) { headerToken = ""; } try { String token = headerToken; if ("".equals(token)) { String str = "Missing token header"; logger.info(str); throw new BadCredentialsException(str); } String tenantId = request.getHeader(OPENSTACK_HEADER_TENANTID); logger.debug(tenantId); logger.debug(token); // String tenantId = request.getPathInfo().split("/")[3]; if (debug) { logger.debug("OpenStack Authentication Authorization header " + "found for user '" + token + "' and tenant " + tenantId); } UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(token, tenantId); authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); Authentication authResult = authenticationManager.authenticate(authRequest); if (debug) { logger.debug("Authentication success: " + authResult); } // check AUTH-TOKEN and VDC are the same String uri = request.getRequestURI(); logger.debug("URI: " + uri); if (uri.contains("vdc") && !uri.contains(tenantId)) { String str = "Bad credentials for requested VDC"; logger.info(str); throw new AccessDeniedException(str); } UserDetails user = (UserDetails) authResult.getPrincipal(); logger.debug("User: " + user.getUsername()); logger.debug("Token: " + user.getPassword()); if (authResult.isAuthenticated()) { SecurityContextHolder.getContext().setAuthentication(authRequest); } // SecurityContextHolder.setStrategyName("MODE_INHERITABLETHREADLOCAL"); rememberMeServices.loginSuccess(request, response, authResult); onSuccessfulAuthentication(request, response, authResult); } catch (AuthenticationException failed) { SecurityContextHolder.clearContext(); if (debug) { logger.debug("Authentication request for failed: " + failed); } rememberMeServices.loginFail(request, response); onUnsuccessfulAuthentication(request, response, failed); if (ignoreFailure) { chain.doFilter(request, response); } else { authenticationEntryPoint.commence(request, response, failed); } return; } catch (AccessDeniedException ex) { throw ex; } catch (Exception ex) { SecurityContextHolder.clearContext(); if (debug) { logger.debug("Authentication exception: " + ex); } rememberMeServices.loginFail(request, response); if (ignoreFailure) { chain.doFilter(request, response); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); } return; } String keystoneURL = systemPropertiesProvider.getProperty(SystemPropertiesProvider.KEYSTONE_URL); response.addHeader("Www-Authenticate", "Keystone uri='" + keystoneURL + "'"); } // TODO jesuspg: question:add APIException chain.doFilter(request, response); }