List of usage examples for org.springframework.security.core Authentication isAuthenticated
boolean isAuthenticated();
AuthenticationManager
. From source file:org.red5.webapps.admin.handler.Red5AuthenticationHandler.java
public boolean appConnect(IConnection conn, Object[] params) { log.info("appConnect"); // start with negative result boolean result = false; log.debug("Connection: {}", conn); log.debug("Params: {}", params); // start off with the status being bad authentication String status = badAuth;// w ww . j a v a2 s .com // get the connection parameters Map<String, Object> connectionParams = conn.getConnectParams(); log.debug("Connection params: {}", connectionParams); if (!connectionParams.containsKey("queryString")) { //set as missing auth notification status = rejectMissingAuth; } else { //get the raw query string String rawQueryString = (String) connectionParams.get("queryString"); try { //parse into a usable query string UrlQueryStringMap<String, String> queryString = UrlQueryStringMap.parse(rawQueryString); log.debug("Query string: {}", queryString); //get the values we want String userName = queryString.get("user"); log.debug("User: {}", userName); // do a user lookup AggregatedUserDetailsService userDetailsService = (AggregatedUserDetailsService) applicationContext .getBean("aggregatedUserDetailsService"); // this will throw an exception if the user cant be located by name UserDetails userDetails = userDetailsService.loadUserByUsername(userName); // get the authentication "style" String authmod = queryString.get("authmod"); log.debug("Authmod: {}", authmod); //make sure they requested red5 auth if ("red5".equals(authmod)) { String response = queryString.get("response"); if (response != null) { response = queryString.get("response").replace(' ', '+'); } log.debug("Response: {}", response); //try the querystring first String sessionId = queryString.get("sessionid"); if (sessionId == null) { //get the session id - try conn next sessionId = ((RTMPConnection) conn).getSessionId(); if (sessionId == null) { //use attribute if (conn.hasAttribute("sessionId")) { sessionId = conn.getStringAttribute("sessionId"); } else { sessionId = SessionManager.getSessionId(); conn.setAttribute("sessionId", sessionId); } } } log.debug("Session id: {}", sessionId); String challenge = null; if (response != null) { //look up challenge (gets and removes at the same time) challenge = sessionChallenges.remove(sessionId); // get the password String password = userDetails.getPassword(); log.debug("Users password: {}", password); //generate response hash to compare String responseHash = calculateHMACSHA256(challenge, password); log.debug("Generated response: {}", responseHash); log.debug("Generated response: {}", response); //decode both hashes before we compare otherwise we will have issues like //4+5WioxdBLhx4qajIybxkBkynDsv7KxtNzqj4V/VbzU != 4+5WioxdBLhx4qajIybxkBkynDsv7KxtNzqj4V/VbzU= if (Arrays.areEqual(Base64.decodeBase64(responseHash.getBytes()), Base64.decodeBase64(response.getBytes()))) { // everything matches so now do the actual authentication // get the authentication manager ProviderManager authManager = (ProviderManager) applicationContext .getBean("authenticationManager"); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( userName, password); Authentication auth = null; try { auth = authManager.authenticate(token); log.info("Authentication result: {}\ndetails: {}", auth.isAuthenticated(), auth); result = auth.isAuthenticated(); // set the authenticated user into the context (thread-local) if (result) { SecurityContextHolder.getContext().setAuthentication(auth); } } catch (Exception ex) { log.warn("Problem during auth attempt: {}", ex); } } } else if (authmod != null && userName != null) { // generate a challenge challenge = calculateHMACSHA256(salt, sessionId); // store the generated data sessionChallenges.put(sessionId, challenge); // set as rejected status = String.format( "[ AccessManager.Reject ] : [ authmod=red5 ] : ?reason=needauth&user=%s&sessionid=%s&challenge=%s", userName, sessionId, challenge); } log.debug("Challenge: {}", challenge); } else { status = invalidAuthMod; } } catch (UsernameNotFoundException ex) { status = noSuchUser; } catch (Exception e) { log.error("Error authenticating", e); } } //send the status object log.debug("Status: {}", status); if (!result) { throw new ClientRejectedException(status); } return result; }
From source file:com.blstream.patronage.ctf.security.TokenHandler.java
/** * Allows automatic approval for a white list of clients in the implicit grant case. * * @param authorizationRequest The authorization request. * @param userAuthentication the current user authentication * * @return Whether the specified request has been approved by the current user. *//* w w w . j a v a 2s .c o m*/ @Override public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { if (logger.isDebugEnabled()) { logger.debug("---- isApproved"); } // If we are allowed to check existing approvals this will short circuit the decision if (useTokenServices && super.isApproved(authorizationRequest, userAuthentication)) { if (logger.isInfoEnabled()) { logger.info("return: true"); } return true; } if (!userAuthentication.isAuthenticated()) { if (logger.isInfoEnabled()) { logger.info("return: false"); } return false; } String flag = authorizationRequest.getApprovalParameters().get(AuthorizationRequest.USER_OAUTH_APPROVAL); boolean approved = flag != null && flag.toLowerCase().equals("true"); return approved || (authorizationRequest.getResponseTypes().contains("token") && autoApproveClients.contains(authorizationRequest.getClientId())); }
From source file:$.LoginServiceImpl.java
@PreAuthorize("permitAll") public User authenticate(Authentication authenticationToken) throws Exception { User user = null;/*from ww w. j av a2 s. com*/ Authentication authentication = null; try { authentication = authenticationManager.authenticate(authenticationToken); } catch (BadCredentialsException bce) { throw new BusinessException(ErrorCodes.ERROR_CODE_login_wrongcredentials); } catch (AuthenticationException ae) { throw new BusinessException(ErrorCodes.ERROR_CODE_unhandled, ae); } if (authentication != null && authentication.isAuthenticated()) { logger.info("authenticated user: {}", authenticationToken.getName()); //obatin user String username = authentication.getName(); //user is authenticated SecurityContextHolder.getContext().setAuthentication(authentication); //create user object user = new User(); user.setName(username); user.setLastLoggedDate(new Date()); } return user; }
From source file:org.devgateway.toolkit.forms.wicket.SSAuthenticatedWebSession.java
@Override public boolean authenticate(final String username, final String password) { boolean authenticated; try {//from w ww. jav a 2 s .c o m Authentication authentication = authenticationManager .authenticate(new UsernamePasswordAuthenticationToken(username, password)); SecurityContextHolder.getContext().setAuthentication(authentication); // httpSession.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, // SecurityContextHolder.getContext()); authenticated = authentication.isAuthenticated(); if (authenticated && rememberMeServices != null) { rememberMeServices.loginSuccess( (HttpServletRequest) RequestCycle.get().getRequest().getContainerRequest(), (HttpServletResponse) RequestCycle.get().getResponse().getContainerResponse(), authentication); } } catch (AuthenticationException e) { this.setAe(e); log.warn("User '{}' failed to login. Reason: {}", username, e.getMessage()); authenticated = false; } return authenticated; }
From source file:org.apache.coheigea.cxf.spring.security.authentication.SpringSecurityUTValidator.java
public Credential validate(Credential credential, RequestData data) throws WSSecurityException { if (credential == null || credential.getUsernametoken() == null) { throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noCredential"); }/* w w w . ja v a2s.c o m*/ // Validate the UsernameToken UsernameToken usernameToken = credential.getUsernametoken(); String pwType = usernameToken.getPasswordType(); if (log.isDebugEnabled()) { log.debug("UsernameToken user " + usernameToken.getName()); log.debug("UsernameToken password type " + pwType); } if (!WSConstants.PASSWORD_TEXT.equals(pwType)) { if (log.isDebugEnabled()) { log.debug("Authentication failed - digest passwords are not accepted"); } throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION); } if (usernameToken.getPassword() == null) { if (log.isDebugEnabled()) { log.debug("Authentication failed - no password was provided"); } throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION); } // Validate it via Spring Security // Set a Subject up UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken( usernameToken.getName(), usernameToken.getPassword()); Subject subject = new Subject(); subject.getPrincipals().add(authToken); Set<Authentication> authentications = subject.getPrincipals(Authentication.class); Authentication authenticated = null; try { authenticated = authenticationManager.authenticate(authentications.iterator().next()); } catch (AuthenticationException ex) { if (log.isDebugEnabled()) { log.debug(ex.getMessage(), ex); } throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION); } if (!authenticated.isAuthenticated()) { throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION); } for (GrantedAuthority authz : authenticated.getAuthorities()) { System.out.println("Granted: " + authz.getAuthority()); } // Authorize request if (accessDecisionManager != null && !requiredRoles.isEmpty()) { List<ConfigAttribute> attributes = SecurityConfig .createList(requiredRoles.toArray(new String[requiredRoles.size()])); for (ConfigAttribute attr : attributes) { System.out.println("Attr: " + attr.getAttribute()); } accessDecisionManager.decide(authenticated, this, attributes); } credential.setSubject(subject); return credential; }
From source file:org.springframework.cloud.dataflow.server.controller.AboutController.java
/** * Return meta information about the dataflow server. * * @return Detailed information about the enabled features, versions of implementation * libraries, and security configuration *//*from w w w. j ava 2s . co m*/ @RequestMapping(method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) public AboutResource getAboutResource() { final AboutResource aboutResource = new AboutResource(); final FeatureInfo featureInfo = new FeatureInfo(); featureInfo.setStreamsEnabled(featuresProperties.isStreamsEnabled()); featureInfo.setTasksEnabled(featuresProperties.isTasksEnabled()); featureInfo.setSchedulesEnabled(featuresProperties.isSchedulesEnabled()); featureInfo.setGrafanaEnabled(this.grafanaProperties.isGrafanaEnabled()); final VersionInfo versionInfo = getVersionInfo(); aboutResource.setFeatureInfo(featureInfo); aboutResource.setVersionInfo(versionInfo); final boolean authenticationEnabled = securityStateBean.isAuthenticationEnabled(); final SecurityInfo securityInfo = new SecurityInfo(); securityInfo.setAuthenticationEnabled(authenticationEnabled); if (authenticationEnabled && SecurityContextHolder.getContext() != null) { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (!(authentication instanceof AnonymousAuthenticationToken)) { securityInfo.setAuthenticated(authentication.isAuthenticated()); securityInfo.setUsername(authentication.getName()); for (Object authority : authentication.getAuthorities()) { final GrantedAuthority grantedAuthority = (GrantedAuthority) authority; securityInfo.addRole(grantedAuthority.getAuthority()); } } } aboutResource.setSecurityInfo(securityInfo); final RuntimeEnvironment runtimeEnvironment = new RuntimeEnvironment(); if (!authenticationEnabled || (authenticationEnabled && SecurityContextHolder.getContext().getAuthentication() != null)) { if (this.streamDeployer != null) { try { final RuntimeEnvironmentInfo deployerEnvironmentInfo = this.streamDeployer.environmentInfo(); final RuntimeEnvironmentDetails deployerInfo = new RuntimeEnvironmentDetails(); deployerInfo .setDeployerImplementationVersion(deployerEnvironmentInfo.getImplementationVersion()); deployerInfo.setDeployerName(deployerEnvironmentInfo.getImplementationName()); deployerInfo.setDeployerSpiVersion(deployerEnvironmentInfo.getSpiVersion()); deployerInfo.setJavaVersion(deployerEnvironmentInfo.getJavaVersion()); deployerInfo.setPlatformApiVersion(deployerEnvironmentInfo.getPlatformApiVersion()); deployerInfo.setPlatformClientVersion(deployerEnvironmentInfo.getPlatformClientVersion()); deployerInfo.setPlatformHostVersion(deployerEnvironmentInfo.getPlatformHostVersion()); deployerInfo.setPlatformSpecificInfo(deployerEnvironmentInfo.getPlatformSpecificInfo()); deployerInfo.setPlatformHostVersion(deployerEnvironmentInfo.getPlatformHostVersion()); deployerInfo.setPlatformType(deployerEnvironmentInfo.getPlatformType()); deployerInfo.setSpringBootVersion(deployerEnvironmentInfo.getSpringBootVersion()); deployerInfo.setSpringVersion(deployerEnvironmentInfo.getSpringVersion()); runtimeEnvironment.setAppDeployer(deployerInfo); } catch (ResourceAccessException rae) { logger.warn("Skipper Server is not accessible", rae); } } if (this.launcherRepository != null) { final List<RuntimeEnvironmentDetails> taskLauncherInfoList = new ArrayList<RuntimeEnvironmentDetails>(); for (Launcher launcher : this.launcherRepository.findAll()) { TaskLauncher taskLauncher = launcher.getTaskLauncher(); RuntimeEnvironmentDetails taskLauncherInfo = new RuntimeEnvironmentDetails(); final RuntimeEnvironmentInfo taskLauncherEnvironmentInfo = taskLauncher.environmentInfo(); taskLauncherInfo.setDeployerImplementationVersion( taskLauncherEnvironmentInfo.getImplementationVersion()); taskLauncherInfo.setDeployerName(taskLauncherEnvironmentInfo.getImplementationName()); taskLauncherInfo.setDeployerSpiVersion(taskLauncherEnvironmentInfo.getSpiVersion()); taskLauncherInfo.setJavaVersion(taskLauncherEnvironmentInfo.getJavaVersion()); taskLauncherInfo.setPlatformApiVersion(taskLauncherEnvironmentInfo.getPlatformApiVersion()); taskLauncherInfo .setPlatformClientVersion(taskLauncherEnvironmentInfo.getPlatformClientVersion()); taskLauncherInfo.setPlatformHostVersion(taskLauncherEnvironmentInfo.getPlatformHostVersion()); taskLauncherInfo.setPlatformSpecificInfo(taskLauncherEnvironmentInfo.getPlatformSpecificInfo()); taskLauncherInfo.setPlatformHostVersion(taskLauncherEnvironmentInfo.getPlatformHostVersion()); taskLauncherInfo.setPlatformType(taskLauncherEnvironmentInfo.getPlatformType()); taskLauncherInfo.setSpringBootVersion(taskLauncherEnvironmentInfo.getSpringBootVersion()); taskLauncherInfo.setSpringVersion(taskLauncherEnvironmentInfo.getSpringVersion()); taskLauncherInfoList.add(taskLauncherInfo); } runtimeEnvironment.setTaskLaunchers(taskLauncherInfoList); } } aboutResource.setRuntimeEnvironment(runtimeEnvironment); if (this.grafanaProperties.isGrafanaEnabled()) { final GrafanaInfo grafanaInfo = new GrafanaInfo(); grafanaInfo.setUrl(this.grafanaProperties.getUrl()); grafanaInfo.setRefreshInterval(this.grafanaProperties.getRefreshInterval()); aboutResource.setGrafanaInfo(grafanaInfo); } aboutResource.add(ControllerLinkBuilder.linkTo(AboutController.class).withSelfRel()); return aboutResource; }
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);// w w w.j av a 2 s . co m return new ModelAndView("redirect:/users/profile"); } String username = auth.getName(); return new ModelAndView(formatUserRedirect(username)); }
From source file:org.mule.modules.basicauthsecurity.strategy.JDBCSecurityProvider.java
public void validate(String auth, List<String> acceptedRoles) throws UnauthorizedException { List<GrantedAuthority> list = new ArrayList<GrantedAuthority>(); for (String role : acceptedRoles) { list.add(new SimpleGrantedAuthority(role)); }/*from ww w. ja va 2 s.c om*/ UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(getUser(auth), getPass(auth), list); Authentication authResult = providerManager.authenticate(authRequest); Boolean containsKey = false; for (GrantedAuthority grantedAuthority : authResult.getAuthorities()) { if (authRequest.getAuthorities().contains(grantedAuthority)) { containsKey = true; } } if (!containsKey) { throw new UnauthorizedException("result"); } if (!authResult.isAuthenticated()) { throw new UnauthorizedException("result"); } }
From source file:ru.org.linux.auth.LoginController.java
@RequestMapping(value = "/ajax_login_process", method = RequestMethod.POST) @ResponseBody// w ww. ja va 2s . c o m public LoginStatus loginAjax(@RequestParam("nick") final String username, @RequestParam("passwd") final String password, HttpServletRequest request, HttpServletResponse response) { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password); try { UserDetailsImpl details = (UserDetailsImpl) userDetailsService.loadUserByUsername(username); token.setDetails(details); Authentication auth = authenticationManager.authenticate(token); UserDetailsImpl userDetails = (UserDetailsImpl) auth.getDetails(); if (!userDetails.getUser().isActivated()) { return new LoginStatus(false, "User not activated"); } SecurityContextHolder.getContext().setAuthentication(auth); rememberMeServices.loginSuccess(request, response, auth); AuthUtil.updateLastLogin(auth, userDao); return new LoginStatus(auth.isAuthenticated(), auth.getName()); } catch (LockedException e) { return new LoginStatus(false, "User locked"); } catch (UsernameNotFoundException e) { return new LoginStatus(false, "Bad credentials"); } catch (BadCredentialsException e) { return new LoginStatus(false, e.getMessage()); } }
From source file:org.cloudfoundry.identity.uaa.login.ChainedAuthenticationManager.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (authentication == null) { return authentication; }// www . j a va 2 s. co m UsernamePasswordAuthenticationToken output = null; if (authentication instanceof UsernamePasswordAuthenticationToken) { output = (UsernamePasswordAuthenticationToken) authentication; } else { output = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), authentication.getAuthorities()); output.setAuthenticated(authentication.isAuthenticated()); output.setDetails(authentication.getDetails()); } boolean authenticated = false; Authentication auth = null; AuthenticationException lastException = null; for (int i = 0; i < delegates.length && (!authenticated); i++) { try { if (logger.isDebugEnabled()) { logger.debug( "Attempting chained authentication of " + output + " with manager:" + delegates[i]); } auth = delegates[i].authenticate(output); authenticated = auth.isAuthenticated(); } catch (AuthenticationException x) { if (logger.isDebugEnabled()) { logger.debug("Chained authentication exception:", x); } lastException = x; } if (logger.isDebugEnabled()) { logger.debug("Chained Authentication status of " + output + " with manager:" + delegates[i] + "; Authenticated:" + authenticated); } } if (authenticated) { return auth; } else if (lastException != null) { //we had at least one authentication exception, throw it throw lastException; } else { //not authenticated, but return the last of the result return auth; } }