我只是迁移到spring mvc版本5.0.1.RELEASE但突然在eclipse中STS WebMvcConfigurerAdapter被标记为已弃用
public class MvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
// to serve static .html pages...
registry.addResourceHandler("/static/**").addResourceLocations("/resources/static/");
}
....
}
Run Code Online (Sandbox Code Playgroud)
我怎么能删除这个!
我试图在另一个应用程序(spring-boot应用程序)上调用REST端点(angularjs).应用程序在以下主机和端口上运行.
http://localhost:8080http://localhost:50029我也在使用spring-securityspring-boot应用程序.从HTML应用程序,我可以对REST应用程序进行身份验证,但此后,我仍然无法访问任何REST端点.例如,我有一个如下定义的angularjs服务.
adminServices.factory('AdminService', ['$resource', '$http', 'conf', function($resource, $http, conf) {
var s = {};
s.isAdminLoggedIn = function(data) {
return $http({
method: 'GET',
url: 'http://localhost:8080/api/admin/isloggedin',
withCredentials: true,
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
});
};
s.login = function(username, password) {
var u = 'username=' + encodeURI(username);
var p = 'password=' + encodeURI(password);
var r = 'remember_me=1';
var data = u + '&' + p + '&' + r;
return $http({
method: 'POST',
url: 'http://localhost:8080/login',
data: …Run Code Online (Sandbox Code Playgroud) 我对弹簧安全URL的CORS过滤器有问题.它没有设置Access-Control-Allow-Origin和属于spring sec(登录/注销)或由Spring Security过滤的URL上的其他公开标头.
这是配置.
CORS:
@Configuration
@EnableWebMvc
public class MyWebMvcConfig extends WebMvcConfigurerAdapter {
********some irrelevant configs************
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/*").allowedOrigins("*").allowedMethods("GET", "POST", "OPTIONS", "PUT")
.allowedHeaders("Content-Type", "X-Requested-With", "accept", "Origin", "Access-Control-Request-Method",
"Access-Control-Request-Headers")
.exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")
.allowCredentials(true).maxAge(3600);
}
}
Run Code Online (Sandbox Code Playgroud)
安全:
@Configuration
@EnableWebSecurity
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).and()
.formLogin()
.successHandler(ajaxSuccessHandler)
.failureHandler(ajaxFailureHandler)
.loginProcessingUrl("/authentication")
.passwordParameter("password")
.usernameParameter("username")
.and()
.logout()
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true)
.logoutUrl("/logout")
.logoutSuccessUrl("/")
.and()
.csrf().disable()
.anonymous().disable()
.authorizeRequests()
.antMatchers("/authentication").permitAll()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/admin/*").access("hasRole('ROLE_ADMIN')")
.antMatchers("/user/*").access("hasRole('ROLE_USER')");
}
} …Run Code Online (Sandbox Code Playgroud) 我正在 Spring Boot 之上构建一个 React 应用程序。当我尝试向 localhost:8080 发出 put 请求时,我的浏览器出现了这些错误
跨域请求被阻止:同源策略不允许读取位于 http://localhost:8080/products 的远程资源。(原因:缺少 CORS 标头“Access-Control-Allow-Origin”)。
跨域请求被阻止:同源策略不允许读取位于 http://localhost:8080/products 的远程资源。(原因:CORS请求没有成功)
我已经在我的服务器端为 localhost 3000 设置了@CrossOrigin。
通过添加标头、代理甚至在任何地方使用 firefox CORS 来解决这个问题已经有一段时间了。似乎没有任何工作。
请看下面我的前端代码
import React, { Component } from "react";
import { Card, Form, Button } from "react-bootstrap";
import axios from "axios";
import Toasting from "./Toasting";
export default class AddProducts extends Component {
constructor(props) {
super(props);
this.state = this.startState;
this.state.toast = false;
this.productChange = this.productChange.bind(this);
this.submitProduct = this.submitProduct.bind(this);
var config = {
headers: {'Access-Control-Allow-Origin': '*'}
}; …Run Code Online (Sandbox Code Playgroud) 我正在通过 JWT 授权使用 Spring 构建一个平台。在网关服务中,我有用于解析令牌的自定义过滤器(基于 BasicAuthenticationFilter),但应该仅针对安全配置中标记的路由调用它,以便将.authenticated()任何人都可以访问的路由添加到WebSecurity.ignoring().
问题是添加路径以WebSecurity.ignoring()同时禁用 CORS 配置,并且OPTIONS请求不会返回Access-Control-*标头。
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
// Auth service
.antMatchers("/auth/login", "/auth/renew")
.permitAll()
.antMatchers("/auth/logout", "/auth/session/**")
.authenticated()
// User service
.antMatchers(HttpMethod.POST, "/user/")
.permitAll()
.antMatchers( "/user/confirm/**", "/user/recover", "/user/validate/**")
.permitAll()
.antMatchers("/user/", "/user/change/**")
.authenticated()
// further part of routes...
http
.formLogin()
.disable()
.logout()
.disable();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilter(new JwtAuthenticationFilter(authenticationManager(), jwtKey));
http.csrf().disable();
http.cors();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
// Auth service …Run Code Online (Sandbox Code Playgroud) 我已经从 Spring Boot 2.5 升级到 3.1,它附带了 Spring Security 6.1.1。对登录身份验证 REST 服务的调用工作正常,但对需要身份验证令牌的其他 REST 控制器的所有请求都被 CORS 策略阻止。
我已按照 Springs 文档中的说明禁用 CORS,但它不起作用。 https://docs.spring.io/spring-security/reference/reactive/integrations/cors.html#page-title
这是我当前的配置:
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.addAllowedOriginPattern("*");
configuration.setAllowedMethods(Arrays.asList("GET","POST","PUT","PATCH","DELETE","OPTIONS"));
configuration.setAllowCredentials(false);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
//.cors(cors -> cors.disable()) <<--- does not work as documented
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(request -> request
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers(SYS_ADMIN_PATTERNS).hasAuthority("SYSTEM_ADMIN")
.requestMatchers("/api/v1/**").authenticated()
)
.sessionManagement(manager -> manager.sessionCreationPolicy(STATELESS))
.authenticationProvider(authenticationProvider())
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
return http.build(); …Run Code Online (Sandbox Code Playgroud) 我正在使用带有OAuth2(版本:4.0.4.RELEASE)和spring(版本:4.3.1.RELEASE)的spring security.
我正在开发Angular的前端,我正在使用grunt connect:dev(http://127.0.0.1:9000).当我尝试通过localhost地址登录时,一切正常,但是从其他地方我收到错误:
"XMLHttpRequest无法加载http:// localhost:8084/oauth/token?client_id = MY_CLIENT_ID.对预检请求的响应未通过访问控制检查:请求的资源上没有"Access-Control-Allow-Origin"标头.因此,不允许来源" http://127.0.0.1:9000 "访问.响应的HTTP状态代码为401."
我在WebMvcConfigurerAdapter(如下所示)中配置了映射(Overrided public void addCorsMappings(CorsRegistry registry)),但它仍然不适用于http://127.0.0.1:9000.
registry.addMapping("/**")
.allowedOrigins("http://127.0.0.1:9000")
.allowedMethods("POST", "OPTIONS", "GET", "DELETE", "PUT")
.allowedHeaders("X-Requested-With,Origin,Content-Type,Accept,Authorization")
.allowCredentials(true).maxAge(3600);
Run Code Online (Sandbox Code Playgroud)
配置基于:https://spring.io/guides/gs/rest-service-cors/
请指出正确的解决方案来解决这个问题.
这是一个返回所有区对象的控制器
CORS 策略已阻止在 ' http://localhost:8080/从源 ' http://localhost:3000 '访问 XMLHttpRequest :请求的资源上不存在 'Access-Control-Allow-Origin' 标头。
package com.ministry.demo.controller;
import com.ministry.demo.model.District;
import com.ministry.demo.repository.DistrictRepository;
import com.ministry.demo.service.DistrictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping(path = "district")
public class DistrictController {
@Autowired
DistrictService service;
@GetMapping(path = "getAll")
List<District> getAllDistrict(){
return service.getAllDistricts();
}
}
Run Code Online (Sandbox Code Playgroud) spring-boot ×6
cors ×5
spring ×5
java ×3
spring-mvc ×3
angularjs ×2
reactjs ×2
controller ×1
jwt ×1
react-native ×1
rest ×1