Java Code Examples for org.springframework.web.context.request.RequestContextHolder#currentRequestAttributes()

The following examples show how to use org.springframework.web.context.request.RequestContextHolder#currentRequestAttributes() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RequestContextDecorator.java    From Milkomeda with MIT License 6 votes vote down vote up
@Override
public Runnable decorate(Runnable runnable) {
    RequestAttributes context;
    try {
        context = RequestContextHolder.currentRequestAttributes();
    } catch (Exception e) {
        return runnable;
    }
    RequestAttributes finalContext = context;
    return () -> {
        try {
            RequestContextHolder.setRequestAttributes(finalContext);
            runnable.run();
        } finally {
            RequestContextHolder.resetRequestAttributes();
        }
    };
}
 
Example 2
Source File: TokenRequiredAspect.java    From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License 6 votes vote down vote up
@Before("@annotation(tokenRequired)")
public void tokenRequiredWithAnnotation(TokenRequired tokenRequired) throws Throwable{
	
	ServletRequestAttributes reqAttributes = (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();
	HttpServletRequest request = reqAttributes.getRequest();
	
	// checks for token in request header
	String tokenInHeader = request.getHeader("token");
	
	if(StringUtils.isEmpty(tokenInHeader)){
		throw new IllegalArgumentException("Empty token");
	}
	
	Claims claims = Jwts.parser()         
		       .setSigningKey(DatatypeConverter.parseBase64Binary(SecurityServiceImpl.secretKey))
		       .parseClaimsJws(tokenInHeader).getBody();
	
	if(claims == null || claims.getSubject() == null){
		throw new IllegalArgumentException("Token Error : Claim is null");
	}
	
	if(!claims.getSubject().equalsIgnoreCase("packt")){
		throw new IllegalArgumentException("Subject doesn't match in the token");
	}
}
 
Example 3
Source File: MessageResourceExtension.java    From Spring-Boot-I18n-Pro with MIT License 6 votes vote down vote up
@Override
protected String resolveCodeWithoutArguments(String code, Locale locale) {
    // 获取request中设置的指定国际化文件名
    ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    final String i18File = (String) attr.getAttribute(I18N_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
    if (!StringUtils.isEmpty(i18File)) {
        //获取在basenameSet中匹配的国际化文件名
        String basename = getBasenameSet().stream()
                .filter(name -> StringUtils.endsWithIgnoreCase(name, i18File))
                .findFirst().orElse(null);
        if (!StringUtils.isEmpty(basename)) {
            //得到指定的国际化文件资源
            ResourceBundle bundle = getResourceBundle(basename, locale);
            if (bundle != null) {
                return getStringOrNull(bundle, code);
            }
        }
    }
    //如果指定i18文件夹中没有该国际化字段,返回null会在ParentMessageSource中查找
    return null;
}
 
Example 4
Source File: ContextCopyingDecorator.java    From staffjoy with MIT License 5 votes vote down vote up
@Override
public Runnable decorate(Runnable runnable) {
    RequestAttributes context = RequestContextHolder.currentRequestAttributes();
    return () -> {
        try {
            RequestContextHolder.setRequestAttributes(context);
            runnable.run();
        } finally {
            RequestContextHolder.resetRequestAttributes();
        }
    };
}
 
Example 5
Source File: ResultfulOpRecordAspect.java    From spring-cloud-gray with Apache License 2.0 5 votes vote down vote up
@AfterReturning(value = "pointcut()", returning = "result")
    public void doAfter(JoinPoint joinPoint, Object result) {

        RequestMapping requestMapping = getRequestMapping(joinPoint);
        if (!isSholdRecord(requestMapping)) {
            return;
        }


        OperateRecord operateRecord = new OperateRecord();
        operateRecord.setOperateTime(new Date());
        Signature signature = joinPoint.getSignature();
        operateRecord.setHandler(signature.getDeclaringType().getSimpleName() + "#" + signature.getName());
        operateRecord.setOperator(userModule.getCurrentUserId());

        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
//        if (requestAttributes != null) {
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
//            if (request != null) {
        operateRecord.setUri(request.getRequestURI());
        operateRecord.setHttpMethod(request.getMethod());
        operateRecord.setIp(WebUtils.getIpAddr(request));
        operateRecord.setQueryString(request.getQueryString());
//            }
//        }
        try {
            String HeadlerArgs = desensitizationArgs(request, joinPoint.getArgs());
            operateRecord.setHeadlerArgs(objectMapper.writeValueAsString(HeadlerArgs));
        } catch (Exception e) {
            log.warn(e.getMessage(), e);
        }
        if (result instanceof ApiRes) {
            ApiRes apiRes = (ApiRes) result;
            operateRecord.setApiResCode(apiRes.getCode());
            if (StringUtils.equals(apiRes.getCode(), ApiRes.CODE_SUCCESS)) {
                operateRecord.setOperateState(OperateRecord.OPERATE_STATE_SCUUESSED);
            }
        }
        operateAuditModule.recordOperate(operateRecord);
    }
 
Example 6
Source File: CustomTokenStore.java    From oauth-server with Apache License 2.0 5 votes vote down vote up
@Override
public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
    HashMap<String, Object> additionalInfo = new HashMap<>();
    ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    String sessionId = "";
    sessionId = attr.getRequest().getSession(true).getId();
    additionalInfo.put("createTime", new Date());
    additionalInfo.put("sessionId", sessionId);
    ((DefaultOAuth2AccessToken) token).setAdditionalInformation(additionalInfo);
    super.storeAccessToken(token, authentication);
}
 
Example 7
Source File: CSRTokenRequiredAspect.java    From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License 5 votes vote down vote up
@Before("@annotation(csrTokenRequired)")
public void adminTokenRequiredWithAnnotation(CSRTokenRequired csrTokenRequired) throws Throwable{
	
	ServletRequestAttributes reqAttributes = (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();
	HttpServletRequest request = reqAttributes.getRequest();
	
	// checks for token in request header
	String tokenInHeader = request.getHeader("token");
	
	if(StringUtils.isEmpty(tokenInHeader)){
		throw new IllegalArgumentException("Empty token");
	}		
	
	Claims claims = Jwts.parser()         
		       .setSigningKey(DatatypeConverter.parseBase64Binary(SecurityServiceImpl.secretKey))
		       .parseClaimsJws(tokenInHeader).getBody();
	
	if(claims == null || claims.getSubject() == null){
		throw new IllegalArgumentException("Token Error : Claim is null");
	}
	
	String subject = claims.getSubject();
	
	if(subject.split("=").length != 2 || new Integer(subject.split("=")[1]) != 2){
		throw new IllegalArgumentException("User is not authorized");
	}		
}
 
Example 8
Source File: ResultfulOpRecordAspect.java    From spring-cloud-gray with Apache License 2.0 5 votes vote down vote up
private boolean sholdFromRequest() {
    RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
    if (requestAttributes == null) {
        return false;
    }
    HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
    if (request == null) {
        return false;
    }
    return ArrayUtils.contains(recordMethods, request.getMethod());
}
 
Example 9
Source File: TokenRequiredAspect.java    From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License 5 votes vote down vote up
@Before("@annotation(tokenRequired)")
public void tokenRequiredWithAnnotation(TokenRequired tokenRequired) throws Throwable{
	
	System.out.println("Before tokenRequiredWithAnnotation");
	
	ServletRequestAttributes reqAttributes = (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();
	HttpServletRequest request = reqAttributes.getRequest();
	
	// checks for token in request header
	String tokenInHeader = request.getHeader("token");
	
	if(StringUtils.isEmpty(tokenInHeader)){
		throw new IllegalArgumentException("Empty token");
	}
	
	Claims claims = Jwts.parser()         
		       .setSigningKey(DatatypeConverter.parseBase64Binary(SecurityServiceImpl.secretKey))
		       .parseClaimsJws(tokenInHeader).getBody();
	
	if(claims == null || claims.getSubject() == null){
		throw new IllegalArgumentException("Token Error : Claim is null");
	}
	
	if(!claims.getSubject().equalsIgnoreCase("packt")){
		throw new IllegalArgumentException("Subject doesn't match in the token");
	}
}
 
Example 10
Source File: LoginSuccessListener.java    From spring-microservice-exam with MIT License 5 votes vote down vote up
/**
 *
 * 获取当前request
 *
 * @return ServletRequestAttributes
 * @author tangyi
 * @date 2019-11-12 00:15
 */
private static ServletRequestAttributes currentRequestAttributes() {
	try {
		RequestAttributes requestAttr = RequestContextHolder.currentRequestAttributes();
		if (!(requestAttr instanceof ServletRequestAttributes)) {
			throw new IllegalStateException("current request is not a servlet request");
		}
		return (ServletRequestAttributes) requestAttr;
	} catch (Exception e) {
		// do nothing
	}
	return null;
}
 
Example 11
Source File: WebApplicationContextUtils.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Return the current RequestAttributes instance as ServletRequestAttributes.
 * @see RequestContextHolder#currentRequestAttributes()
 */
private static ServletRequestAttributes currentRequestAttributes() {
	RequestAttributes requestAttr = RequestContextHolder.currentRequestAttributes();
	if (!(requestAttr instanceof ServletRequestAttributes)) {
		throw new IllegalStateException("Current request is not a servlet request");
	}
	return (ServletRequestAttributes) requestAttr;
}
 
Example 12
Source File: HttpServletUtil.java    From server with MIT License 4 votes vote down vote up
public static HttpServletRequest getCurrentHttpServletRequest() {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    return attributes.getRequest();
}
 
Example 13
Source File: SpringContextUtils.java    From LicenseDemo with Apache License 2.0 4 votes vote down vote up
/**
 * 获取HttpServletRequest
 * @return
 */
public static HttpServletRequest getRequest() {
	ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
	HttpServletRequest request = attributes.getRequest();
	return request;
}
 
Example 14
Source File: EgovHttpRequestHelper.java    From oslits with GNU General Public License v3.0 4 votes vote down vote up
public static HttpServletRequest getCurrentRequest() {
	ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
	
	return sra.getRequest();
}
 
Example 15
Source File: AsyncConfig.java    From OneBlog with GNU General Public License v3.0 4 votes vote down vote up
@Override
public <T> Future<T> submit(Callable<T> task) {
    return super.submit(new ContextAwareCallable(task, RequestContextHolder.currentRequestAttributes()));
}
 
Example 16
Source File: AsyncConfig.java    From OneBlog with GNU General Public License v3.0 4 votes vote down vote up
@Override
public <T> ListenableFuture<T> submitListenable(Callable<T> task) {
    return super.submitListenable(new ContextAwareCallable(task, RequestContextHolder.currentRequestAttributes()));
}
 
Example 17
Source File: SpringContextUtils.java    From LicenseDemo with Apache License 2.0 4 votes vote down vote up
/**
 * 获取HttpServletRequest
 * @return
 */
public static HttpServletRequest getRequest() {
	ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
	HttpServletRequest request = attributes.getRequest();
	return request;
}
 
Example 18
Source File: ContextAwareAsyncExecutor.java    From yue-library with Apache License 2.0 4 votes vote down vote up
@Override
public <T> Future<T> submit(Callable<T> task) {
    return super.submit(new ContextAwareCallable<T>(task, RequestContextHolder.currentRequestAttributes()));
}
 
Example 19
Source File: AuthTool.java    From frostmourne with MIT License 4 votes vote down vote up
public static HttpServletRequest currentRequest() {
    ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    return attr.getRequest();
}
 
Example 20
Source File: UrlUtil.java    From openvsx with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Get the base URL to use for API requests from the current servlet request.
 */
public static String getBaseUrl() {
    var requestAttrs = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    return getBaseUrl(requestAttrs.getRequest());
}