本文整理汇总了Java中org.springframework.security.web.authentication.session.SessionAuthenticationException类的典型用法代码示例。如果您正苦于以下问题:Java SessionAuthenticationException类的具体用法?Java SessionAuthenticationException怎么用?Java SessionAuthenticationException使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
SessionAuthenticationException类属于org.springframework.security.web.authentication.session包,在下文中一共展示了SessionAuthenticationException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: allowableSessionsExceeded
import org.springframework.security.web.authentication.session.SessionAuthenticationException; //导入依赖的package包/类
@Override
protected void allowableSessionsExceeded(List<SessionInformation> sessions, int allowableSessions,
SessionRegistry registry) throws SessionAuthenticationException {
SessionInformation leastRecentlyUsed = null;
for (SessionInformation session : sessions) {
if ((leastRecentlyUsed == null)
|| session.getLastRequest().before(leastRecentlyUsed.getLastRequest())) {
leastRecentlyUsed = session;
}
}
if(leastRecentlyUsed instanceof SessionInformationObject){
SessionInformationObject sessionObject=(SessionInformationObject)leastRecentlyUsed;
sessionObject.setKickAway(true);
}
leastRecentlyUsed.expireNow();
}
示例2: testUnsuccessfulAuthWithIncorrectUser
import org.springframework.security.web.authentication.session.SessionAuthenticationException; //导入依赖的package包/类
@Test(expected = SessionAuthenticationException.class)
public void testUnsuccessfulAuthWithIncorrectUser() throws IOException {
formLoginAuthenticationCsrfTokenInterceptor.setCredentialProvider(new CredentialProvider() {
@Override
public String getUsername() {
return "badUser";
}
@Override
public String getPassword() {
return credentialProvider.getPassword();
}
});
String result = authenticatedRestTemplate.getForObject("", String.class);
}
示例3: testUnsuccessfulAuthWithIncorrectPassword
import org.springframework.security.web.authentication.session.SessionAuthenticationException; //导入依赖的package包/类
@Test(expected = SessionAuthenticationException.class)
public void testUnsuccessfulAuthWithIncorrectPassword() throws IOException {
formLoginAuthenticationCsrfTokenInterceptor.setCredentialProvider(new CredentialProvider() {
@Override
public String getUsername() {
return credentialProvider.getUsername();
}
@Override
public String getPassword() {
return "bad password";
}
});
String result = authenticatedRestTemplate.getForObject("", String.class);
}
示例4: doFilter
import org.springframework.security.web.authentication.session.SessionAuthenticationException; //导入依赖的package包/类
public void doFilter(ServletRequest baseRequest, ServletResponse baseResponse, FilterChain chain) throws IOException, ServletException {
try {
super.doFilter(baseRequest, baseResponse, chain);
} catch (ServletException e) {
if (e.getCause() instanceof ServiceException) {
HttpServletRequest baseHttpRequest = (HttpServletRequest) baseRequest;
//if authentication is null and CSRF token is invalid, must be session time out
if (SecurityContextHolder.getContext().getAuthentication() == null) {
baseHttpRequest.setAttribute("sessionTimeout", true);
failureHandler.onAuthenticationFailure((HttpServletRequest) baseRequest, (HttpServletResponse) baseResponse, new SessionAuthenticationException("Session Time Out"));
} else {
throw e;
}
} else {
throw e;
}
}
}
示例5: sendMessageToAllUsers
import org.springframework.security.web.authentication.session.SessionAuthenticationException; //导入依赖的package包/类
/**
* Send the given message to all users after checking the authorization of the user.
* @param message The message to be sent.
* @param accessToken The oauth2 accessToken of the user.
* @return the message to the topic
* @throws Exception Thrown if not authorized for instance.
*/
@MessageMapping("/user-messages")
@SendTo("/topic/user-messages")
public MessageDto sendMessageToAllUsers(MessageDto message,
@Header("access_token") String accessToken) throws Exception {
OAuth2AccessToken oauth2accessToken = tokenStore.readAccessToken(accessToken);
if (oauth2accessToken != null) {
OAuth2Authentication authentication = tokenStore.readAuthentication(oauth2accessToken);
if (authentication != null && authentication.getAuthorities().contains(
new SimpleGrantedAuthority("ROLE_ADMIN"))) {
message.setSender(authentication.getUserAuthentication().getName());
log.debug("Sending message from {} to all users", message.getSender());
return message;
}
}
log.error("Unauthorized message from {} with content: {}",
message.getSender(), message.getText());
throw new SessionAuthenticationException("No valid access token found!");
}
示例6: retrieveUser
import org.springframework.security.web.authentication.session.SessionAuthenticationException; //导入依赖的package包/类
@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
final FirebaseAuthenticationToken authenticationToken = (FirebaseAuthenticationToken) authentication;
final CompletableFuture<FirebaseToken> future = new CompletableFuture<>();
firebaseAuth.verifyIdToken(authenticationToken.getToken()).addOnSuccessListener(future::complete);
try {
final FirebaseToken token = future.get();
return new FirebaseUserDetails(token.getEmail(), token.getUid());
} catch (InterruptedException | ExecutionException e) {
throw new SessionAuthenticationException(e.getMessage());
}
}
示例7: handleSessionRequired
import org.springframework.security.web.authentication.session.SessionAuthenticationException; //导入依赖的package包/类
@ExceptionHandler({
SessionLimitExceededException.class,
HttpSessionRequiredException.class,
SessionException.class,
SessionAuthenticationException.class,
})
public String handleSessionRequired(Exception e, RedirectAttributes attr){
attr.addFlashAttribute("error","Your session has been expired. Please log in again.");
return "redirect:/error";
}
示例8: handleSessionRequired
import org.springframework.security.web.authentication.session.SessionAuthenticationException; //导入依赖的package包/类
@ExceptionHandler({
HttpSessionRequiredException.class,
SessionException.class,
SessionAuthenticationException.class,
})
public String handleSessionRequired(Exception e, RedirectAttributes attr){
e.printStackTrace();
attr.addFlashAttribute("error","Your session has been expired. Please log in again.");
return "redirect:/oups";
}
示例9: injectCsrfTokenIntoHeader
import org.springframework.security.web.authentication.session.SessionAuthenticationException; //导入依赖的package包/类
/**
* @param request the request, containing method, URI, and headers
* @param csrfToken the CSRF token to be injected into the request header
*/
protected void injectCsrfTokenIntoHeader(HttpRequest request, CsrfToken csrfToken) {
if (csrfToken == null) {
throw new SessionAuthenticationException("There is no CSRF token to inject");
}
logger.debug("Injecting CSRF token into request {} header: {}", request.getURI(), csrfToken.getToken());
request.getHeaders().add(csrfToken.getHeaderName(), csrfToken.getToken());
}
示例10: startAuthenticationFlow
import org.springframework.security.web.authentication.session.SessionAuthenticationException; //导入依赖的package包/类
/**
* Starts the traditioanl form login authentication flow handshake.
* Consequencially, the cookie store (which contains the session id) and the
* CSRF token will be updated.
*
* @throws AuthenticationException
*/
protected synchronized void startAuthenticationFlow() throws AuthenticationException {
logger.debug("Getting authenticated session");
logger.debug("Start by loading up the login form to get a valid unauthenticated session and CSRF token");
ResponseEntity<String> loginResponseEntity = restTemplateForAuthenticationFlow.getForEntity(authRestTemplate.getURIForResource(formLoginConfig.getLoginFormPath()), String.class);
latestCsrfToken = getCsrfTokenFromLoginHtml(loginResponseEntity.getBody());
latestSessionIdForLatestCsrfToken = getAuthenticationSessionIdFromCookieStore();
logger.debug("Update CSRF token for interceptor ({}) from login form", latestCsrfToken.getToken());
MultiValueMap<String, Object> loginPostParams = new LinkedMultiValueMap<>();
loginPostParams.add("username", credentialProvider.getUsername());
loginPostParams.add("password", credentialProvider.getPassword());
logger.debug("Post to login url to startAuthenticationFlow with user={}, pwd={}", credentialProvider.getUsername(), credentialProvider.getPassword());
ResponseEntity<String> postLoginResponseEntity = restTemplateForAuthenticationFlow.postForEntity(authRestTemplate.getURIForResource(formLoginConfig.getLoginFormPath()), loginPostParams, String.class);
//TODO(P1) This current way of checking if authentication is successful is somewhat
// hacky. Bascailly it says that authentication is successful if a 302 is returned
// and the redirect (from location header) maps to the login redirect path from the config.
URI locationURI = URI.create(postLoginResponseEntity.getHeaders().get("Location").get(0));
String expectedLocation = resttemplateConfig.getContextPath() + "/" + formLoginConfig.getLoginRedirectPath();
if (postLoginResponseEntity.getStatusCode().equals(HttpStatus.FOUND)
&& expectedLocation.equals(locationURI.getPath())) {
latestCsrfToken = getCsrfTokenFromEndpoint(authRestTemplate.getURIForResource(formLoginConfig.getCsrfTokenPath()));
latestSessionIdForLatestCsrfToken = getAuthenticationSessionIdFromCookieStore();
logger.debug("Update CSRF token interceptor in AuthRestTempplate ({})", latestCsrfToken.getToken());
} else {
throw new SessionAuthenticationException("Authentication failed. Post login status code = " + postLoginResponseEntity.getStatusCode()
+ ", location = [" + locationURI.getPath() + "], expected location = [" + expectedLocation + "]");
}
}
示例11: getCsrfTokenFromLoginHtml
import org.springframework.security.web.authentication.session.SessionAuthenticationException; //导入依赖的package包/类
/**
* Gets the CSRF token from login html because the CSRF token endpoint needs
* to be authenticated first.
*
* @param loginHtml The login page HTML which contains the csrf token. It is
* assumed that the CSRF token is embedded on the page inside an input field
* with name matching
* {@link com.box.l10n.mojito.rest.resttemplate.FormLoginAuthenticationCsrfTokenInterceptor#CSRF_PARAM_NAME}
* @return
* @throws AuthenticationException
*/
protected CsrfToken getCsrfTokenFromLoginHtml(String loginHtml) throws AuthenticationException {
Pattern pattern = Pattern.compile("CSRF_TOKEN = '(.*?)';");
Matcher matcher = pattern.matcher(loginHtml);
if (matcher.find()) {
String csrfTokenString = matcher.group(1);
logger.debug("CSRF token from login html: {}", csrfTokenString);
return new DefaultCsrfToken(CSRF_HEADER_NAME,
CSRF_PARAM_NAME, csrfTokenString);
} else {
throw new SessionAuthenticationException("Could not find CSRF_TOKEN variable on login page");
}
}
示例12: allowableSessionsExceeded
import org.springframework.security.web.authentication.session.SessionAuthenticationException; //导入依赖的package包/类
/**
* This method has been copied from ConcurrentSessionControlStrategy and modified to
* better ensure that more that the allowed number of sessions are never valid
* at the same time.
*
* @see ConcurentSessionControlStrategy.allowableSessionsExceeded
*/
protected void allowableSessionsExceeded(List<SessionInformation> sessions,
int allowableSessions, SessionRegistry registry)
throws SessionAuthenticationException {
if (exceptionIfMaximumExceeded || (sessions == null)) {
throw new SessionAuthenticationException(messages.getMessage(
"ConcurrentSessionControlStrategy.exceededAllowed",
new Object[] {new Integer(allowableSessions)},
"Maximum sessions of {0} for this principal exceeded"));
}
//BEGIN CUSTOMIZATIONS
log.debug("allowableSessionExceeded. allowed: " + allowableSessions + " Current: " +
sessions.size());
//sort the session by recency, increasing
Collections.sort(sessions, comparator);
//note - sessions does not include the new session being authenticated
int sessionsToExpire = sessions.size() - allowableSessions + 1;
//remove the first sessionToExpire sessions from the sorted list
for (int i = 0; i < sessionsToExpire; i++) {
sessions.get(i).expireNow();
}
}
示例13: onAuthentication
import org.springframework.security.web.authentication.session.SessionAuthenticationException; //导入依赖的package包/类
@Override
public void onAuthentication(Authentication authentication,
HttpServletRequest request, HttpServletResponse response)
throws SessionAuthenticationException {
// Set the authentication in the current context
SecurityContextHolder.getContext().setAuthentication(authentication);
}
示例14: onAuthentication
import org.springframework.security.web.authentication.session.SessionAuthenticationException; //导入依赖的package包/类
@Override
public void onAuthentication(Authentication authentication,
HttpServletRequest request, HttpServletResponse response)
throws SessionAuthenticationException {
// Set the authentication in the current context
SecurityContextHolder.getContext().setAuthentication(authentication);
}
示例15: onAuthentication
import org.springframework.security.web.authentication.session.SessionAuthenticationException; //导入依赖的package包/类
@Override
public void onAuthentication(Authentication authentication,
HttpServletRequest request, HttpServletResponse response)
throws SessionAuthenticationException {
// Set the authentication in the current context
SecurityContextHolder.getContext().setAuthentication(authentication);
}