本文整理汇总了Java中org.springframework.web.cors.CorsUtils类的典型用法代码示例。如果您正苦于以下问题:Java CorsUtils类的具体用法?Java CorsUtils怎么用?Java CorsUtils使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
CorsUtils类属于org.springframework.web.cors包,在下文中一共展示了CorsUtils类的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: configure
import org.springframework.web.cors.CorsUtils; //导入依赖的package包/类
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
// we don't need CSRF because our token is invulnerable
.csrf().disable()
.authorizeRequests()
// All urls must be authenticated (filter for token always fires (/**)
.antMatchers(HttpMethod.OPTIONS, "/login").permitAll()
.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
.anyRequest().authenticated()
.and()
// Call our errorHandler if authentication/authorisation fails
.exceptionHandling()
.authenticationEntryPoint((httpServletRequest, httpServletResponse, e) -> httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"))
.and()
// don't create session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
// 添加一个过滤器 所有访问 /login 的请求交给 JWTLoginFilter 来处理 这个类处理所有的JWT相关内容
.and().addFilterBefore(new JwtAuthenticationTokenFilter("/login", authenticationManager()),
UsernamePasswordAuthenticationFilter.class)
// 添加一个过滤器验证其他请求的Token是否合法
.addFilterBefore(new JWTAuthenticationFilter(),
UsernamePasswordAuthenticationFilter.class);
// disable page caching
httpSecurity.headers().cacheControl();
}
示例2: doFilterInternal
import org.springframework.web.cors.CorsUtils; //导入依赖的package包/类
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
if (corsEnabled) {
if (CorsUtils.isCorsRequest(request)) {
response.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN, defaultIfBlank(request.getHeader(ORIGIN), "*"));
response.setHeader(ACCESS_CONTROL_ALLOW_METHODS, defaultIfBlank(request.getHeader(ACCESS_CONTROL_REQUEST_METHOD),
"HEAD, POST, PUT, GET, OPTIONS, DELETE"));
response.setHeader(ACCESS_CONTROL_ALLOW_HEADERS, defaultIfBlank(request.getHeader(ACCESS_CONTROL_REQUEST_HEADERS),
join(new String[]{CONTENT_TYPE, ACCEPT}, ',')));
response.setHeader(ACCESS_CONTROL_EXPOSE_HEADERS, LOCATION);
response.setHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
response.setHeader(ACCESS_CONTROL_MAX_AGE, "3601");
}
if (!CorsUtils.isPreFlightRequest(request)) {
filterChain.doFilter(request, response);
}
} else {
super.doFilterInternal(request, response, filterChain);
}
}
示例3: getHandler
import org.springframework.web.cors.CorsUtils; //导入依赖的package包/类
/**
* Look up a handler for the given request, falling back to the default
* handler if no specific one is found.
* @param request current HTTP request
* @return the corresponding handler instance, or the default handler
* @see #getHandlerInternal
*/
@Override
public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
Object handler = getHandlerInternal(request);
if (handler == null) {
handler = getDefaultHandler();
}
if (handler == null) {
return null;
}
// Bean name or resolved handler?
if (handler instanceof String) {
String handlerName = (String) handler;
handler = getApplicationContext().getBean(handlerName);
}
HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request);
if (CorsUtils.isCorsRequest(request)) {
CorsConfiguration globalConfig = this.corsConfigSource.getCorsConfiguration(request);
CorsConfiguration handlerConfig = getCorsConfiguration(handler, request);
CorsConfiguration config = (globalConfig != null ? globalConfig.combine(handlerConfig) : handlerConfig);
executionChain = getCorsHandlerExecutionChain(request, executionChain, config);
}
return executionChain;
}
示例4: doOptions
import org.springframework.web.cors.CorsUtils; //导入依赖的package包/类
/**
* Delegate OPTIONS requests to {@link #processRequest}, if desired.
* <p>Applies HttpServlet's standard OPTIONS processing otherwise,
* and also if there is still no 'Allow' header set after dispatching.
* @see #doService
*/
@Override
protected void doOptions(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (this.dispatchOptionsRequest || CorsUtils.isPreFlightRequest(request)) {
processRequest(request, response);
if (response.containsHeader("Allow")) {
// Proper OPTIONS response coming from a handler - we're done.
return;
}
}
// Use response wrapper for Servlet 2.5 compatibility where
// the getHeader() method does not exist
super.doOptions(request, new HttpServletResponseWrapper(response) {
@Override
public void setHeader(String name, String value) {
if ("Allow".equals(name)) {
value = (StringUtils.hasLength(value) ? value + ", " : "") + RequestMethod.PATCH.name();
}
super.setHeader(name, value);
}
});
}
示例5: configure
import org.springframework.web.cors.CorsUtils; //导入依赖的package包/类
@Override
public void configure(final HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic()
.disable()
.anonymous()
.and()
.requestMatchers()
.antMatchers("/api/**")
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and()
.authorizeRequests()
.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
.antMatchers("/api/health").permitAll()
.antMatchers(HttpMethod.GET, "/api/**").permitAll()
.antMatchers("/api/**").permitAll()
//FIXME: disabled oauth
.anyRequest().permitAll();
// @formatter:on
}
示例6: incomingRequestPreProcessed
import org.springframework.web.cors.CorsUtils; //导入依赖的package包/类
@Override
public boolean incomingRequestPreProcessed(HttpServletRequest theRequest, HttpServletResponse theResponse) {
if (CorsUtils.isCorsRequest(theRequest)) {
boolean isValid;
try {
isValid = myCorsProcessor.processRequest(myConfig, theRequest, theResponse);
} catch (IOException e) {
throw new InternalErrorException(e);
}
if (!isValid || CorsUtils.isPreFlightRequest(theRequest)) {
return false;
}
}
return super.incomingRequestPreProcessed(theRequest, theResponse);
}
示例7: configure
import org.springframework.web.cors.CorsUtils; //导入依赖的package包/类
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
.antMatchers("/admin/**").hasAnyRole(WebSecurityConfig.Roles.ADMIN, WebSecurityConfig.Roles.EDITOR);
}
示例8: getMatchingCondition
import org.springframework.web.cors.CorsUtils; //导入依赖的package包/类
/**
* Checks if all conditions in this request mapping info match the provided request and returns
* a potentially new request mapping info with conditions tailored to the current request.
* <p>For example the returned instance may contain the subset of URL patterns that match to
* the current request, sorted with best matching patterns on top.
* @return a new instance in case all conditions match; or {@code null} otherwise
*/
@Override
public RequestMappingInfo getMatchingCondition(HttpServletRequest request) {
RequestMethodsRequestCondition methods = this.methodsCondition.getMatchingCondition(request);
ParamsRequestCondition params = this.paramsCondition.getMatchingCondition(request);
HeadersRequestCondition headers = this.headersCondition.getMatchingCondition(request);
ConsumesRequestCondition consumes = this.consumesCondition.getMatchingCondition(request);
ProducesRequestCondition produces = this.producesCondition.getMatchingCondition(request);
if (methods == null || params == null || headers == null || consumes == null || produces == null) {
if (CorsUtils.isPreFlightRequest(request)) {
methods = getAccessControlRequestMethodCondition(request);
if (methods == null || params == null) {
return null;
}
}
else {
return null;
}
}
PatternsRequestCondition patterns = this.patternsCondition.getMatchingCondition(request);
if (patterns == null) {
return null;
}
RequestConditionHolder custom = this.customConditionHolder.getMatchingCondition(request);
if (custom == null) {
return null;
}
return new RequestMappingInfo(this.name, patterns,
methods, params, headers, consumes, produces, custom.getCondition());
}
示例9: lookupHandlerMethod
import org.springframework.web.cors.CorsUtils; //导入依赖的package包/类
/**
* Look up the best-matching handler method for the current request.
* If multiple matches are found, the best match is selected.
* @param lookupPath mapping lookup path within the current servlet mapping
* @param request the current request
* @return the best-matching handler method, or {@code null} if no match
* @see #handleMatch(Object, String, HttpServletRequest)
* @see #handleNoMatch(Set, String, HttpServletRequest)
*/
protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
List<Match> matches = new ArrayList<Match>();
List<T> directPathMatches = this.mappingRegistry.getMappingsByUrl(lookupPath);
if (directPathMatches != null) {
addMatchingMappings(directPathMatches, matches, request);
}
if (matches.isEmpty()) {
// No choice but to go through all mappings...
addMatchingMappings(this.mappingRegistry.getMappings().keySet(), matches, request);
}
if (!matches.isEmpty()) {
Comparator<Match> comparator = new MatchComparator(getMappingComparator(request));
Collections.sort(matches, comparator);
if (logger.isTraceEnabled()) {
logger.trace("Found " + matches.size() + " matching mapping(s) for [" +
lookupPath + "] : " + matches);
}
Match bestMatch = matches.get(0);
if (matches.size() > 1) {
if (CorsUtils.isPreFlightRequest(request)) {
return PREFLIGHT_AMBIGUOUS_MATCH;
}
Match secondBestMatch = matches.get(1);
if (comparator.compare(bestMatch, secondBestMatch) == 0) {
Method m1 = bestMatch.handlerMethod.getMethod();
Method m2 = secondBestMatch.handlerMethod.getMethod();
throw new IllegalStateException("Ambiguous handler methods mapped for HTTP path '" +
request.getRequestURL() + "': {" + m1 + ", " + m2 + "}");
}
}
handleMatch(bestMatch.mapping, lookupPath, request);
return bestMatch.handlerMethod;
}
else {
return handleNoMatch(this.mappingRegistry.getMappings().keySet(), lookupPath, request);
}
}
示例10: getCorsConfiguration
import org.springframework.web.cors.CorsUtils; //导入依赖的package包/类
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
if (!this.suppressCors && CorsUtils.isCorsRequest(request)) {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.addAllowedMethod("*");
config.setAllowCredentials(true);
config.setMaxAge(ONE_YEAR);
config.addAllowedHeader("*");
return config;
}
return null;
}
示例11: doFilterInternal
import org.springframework.web.cors.CorsUtils; //导入依赖的package包/类
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
if (CorsUtils.isCorsRequest(request)) {
CorsConfiguration corsConfiguration = this.configSource.getCorsConfiguration(request);
if (corsConfiguration != null) {
boolean isValid = this.processor.processRequest(corsConfiguration, request, response);
if (!isValid || CorsUtils.isPreFlightRequest(request)) {
return;
}
}
}
filterChain.doFilter(request, response);
}
示例12: getMatchingCondition
import org.springframework.web.cors.CorsUtils; //导入依赖的package包/类
/**
* Returns "this" instance if the request matches all expressions; or {@code null} otherwise.
*/
@Override
public ServerNameRequestCondition getMatchingCondition(HttpServletRequest request) {
// logger.info("getMatchingCondition:" + request.getRequestURI());
if (CorsUtils.isPreFlightRequest(request)) {
return PRE_FLIGHT_MATCH;
}
for (HeaderExpression expression : expressions) {
if (!expression.match(request)) {
return null;
}
}
return this;
}
示例13: configure
import org.springframework.web.cors.CorsUtils; //导入依赖的package包/类
@Override
protected void configure(HttpSecurity http) throws Exception {
AuthenticationEntryPoint entryPoint = entryPoint();
AdminRequestedAccessDeniedHandler accessDeniedHandler = new AdminRequestedAccessDeniedHandler(entryPoint);
http
.requiresChannel()
.requestMatchers(request -> request.getHeader("x-forwarded-port") != null).requiresSecure()
.and()
.exceptionHandling()
.authenticationEntryPoint(entryPoint)
.accessDeniedHandler(accessDeniedHandler)
.and()
.csrf()
.ignoringAntMatchers("/github/hooks/**").and()
.authorizeRequests()
.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
.mvcMatchers("/login/**", "/", "/about", "/faq").permitAll()
.mvcMatchers("/view/**").permitAll()
.mvcMatchers("/webjars/**", "/assets/**").permitAll()
.mvcMatchers("/github/hooks/**").permitAll()
.mvcMatchers("/admin","/admin/cla/link/**","/admin/help/**").hasRole("ADMIN")
.mvcMatchers("/admin/**","/manage/**").hasRole("CLA_AUTHOR")
.anyRequest().authenticated()
.and()
.logout()
.logoutSuccessUrl("/?logout");
}
示例14: configure
import org.springframework.web.cors.CorsUtils; //导入依赖的package包/类
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.requestMatchers(CorsUtils::isPreFlightRequest).permitAll();
}