Spring Security and Spring Session

擴展基於JSON登錄

因爲長時間位於服務器交互,致使客戶端與服務器超時,認證失效。但用戶不想跳轉到登錄界面進行登錄,指望在當前界面彈窗框進行登錄,而後進行下一步操做。java

解決方案:當服務端攔截到請求發現認證失效時,返回Code的值提示客戶端進行JSON登錄,客戶端登錄成功以後繼續上一步操做。redis

注:HTTP CODE不能返回302,此碼遊覽器會攔截自動轉到登錄頁面spring

實現方式:在Spring security中添加攔截器,攔截指定JSON請求進行登錄操做。json

/**
 * 支持JSON登錄
 * AuthenticationFilter that supports rest login(json login) and form login.
 */
@Slf4j
public class AuthenticationRestfullFilter extends UsernamePasswordAuthenticationFilter {

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

		//attempt Authentication when Content-Type is json
		if (MediaType.APPLICATION_JSON_UTF8_VALUE.equals(request.getContentType()) || MediaType.APPLICATION_JSON_VALUE.equals(request.getContentType())) {

			//use jackson to deserialize json 在這裏能夠使用jackson, 由於Security對它進行包裝
			ObjectMapper mapper = new ObjectMapper();
			UsernamePasswordAuthenticationToken authRequest = null;
			try (InputStream is = request.getInputStream()) {
				UsernamePasswordVm userDto = mapper.readValue(is, UsernamePasswordVm.class);
				authRequest = new UsernamePasswordAuthenticationToken(userDto.getUsername(), userDto.getPassword());
			} catch (IOException e) {
				log.warn(e.getMessage(), e);
				e.printStackTrace();
				authRequest = new UsernamePasswordAuthenticationToken("", "");
			} finally {
				setDetails(request, authRequest);
			}
			log.debug("User Rest login app !");
			return this.getAuthenticationManager().authenticate(authRequest);
		}
		return super.attemptAuthentication(request, response);

	}
}

@Getter
@Setter
public class UsernamePasswordVm {

	private String username;
	private String password;
	private Boolean rememberMe;
}

共享 Session

簡介:當應用演變成分佈式或者集羣時,用戶的請求可能會被負載到不一樣服務器,此時Web容器的會話不能通用,因此經過Spring Session實現共享用戶會話信息。服務器

解決方案: Spring Session 攔截用戶會話(包裝Http Request)信息,保存在一個指定的存儲地方,同時其餘服務器也能操做此數據,從而實現Session共享,提升應用的性能和併發量。session

實現方式:併發

@EnableRedisHttpSession(maxInactiveIntervalInSeconds="請求間隔最大週期,能夠理解爲Session Timeout")
public class StarUpAdminApp {
	
}

相關配置app

spring:
    http:
        encoding:
            charset: UTF-8
            enabled: true
            force: true
    session:
        store-type: redis
	    redis:
			flush-mode: on-save
            namespace: session
			database: 2
			host: 127.0.0.1
			lettuce:
				pool:
					max-active: 4
					max-wait: -1ms
					max-idle: 2
					min-idle: 0
相關文章
相關標籤/搜索