- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在构建一个带有 Spring Boot 后端的 Angular 2 应用程序。几天来,我一直在尝试解决 CORS 预检的问题。根据这个topic ,它应该像这样与 CORS 过滤器一起工作:
@Component
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "authorization, content-type, xsrf-token");
response.addHeader("Access-Control-Expose-Headers", "xsrf-token");
if ("OPTIONS".equals(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
filterChain.doFilter(request, response);
}
}
}
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class)
.headers()
.frameOptions().disable()
.and()
.authorizeRequests()
.antMatchers("/", "/home", "/register", "/login").permitAll()
.antMatchers("/cottages").authenticated();
}
}
角度前端:
import {Injectable} from '@angular/core';
import {Headers, Http} from "@angular/http";
import {AppSettings} from "../app.settings";
import { URLSearchParams } from '@angular/http'
import {User} from "../_models/_index";
import {Observable} from "rxjs";
@Injectable()
export class AuthenticationService {
private headers = new Headers({'Content-Type': 'application/json'});
private tokenHeaders = new Headers({
'Content-Type': 'application/json',
'client_id': 'xxx',
'client_secret': 'xxx'});
constructor(private http: Http) {
}
login(user: User) {
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('username', user.username);
urlSearchParams.append('password', user.password);
let body = urlSearchParams.toString();
return this.http.post(AppSettings.getApiUrl() + "oauth/token", body, { withCredentials: true, headers: this.tokenHeaders })
.map((responseData) => {
return responseData.json();
})
.map((item: any) => {
return new User(item);
})
.catch((error: any) => Observable.of(error.json().error || 'Server error'));
}
}
我尝试了在 this 上找到的其他配置以及 Spring 文档中的其他来源。
我总是收到这个错误信息:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/oauth/token. (Reason: CORS preflight channel did not succeed).
向我自己的 Controller 发出简单的 CORS 请求,例如注册用户,效果很好。
谁能给我解释一下我做错了什么?我的 Java 或 Typescript 代码是否有错误?
编辑:
授权服务器配置:
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("my-trusted-client").authorizedGrantTypes("client_credentials", "password")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT").scopes("read", "write", "trust")
.resourceIds("oauth2-resource").accessTokenValiditySeconds(5000).secret("xxx");
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.checkTokenAccess("isAuthenticated()");
}
}
最佳答案
我终于找到了解决问题的方法。双方都有几个错误(Angular/Java Spring Boot,安全)。我将在这里发布我的工作代码并进行解释。我将从后端开始:
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/users").permitAll().anyRequest()
.authenticated()
.and()
.csrf().disable()
}
}
根据 spring.io 教程,WebSecurityConfiguration 是我工作的更好选择 - 它也可以与 ResourceServerConfiguration 一起使用。老实说,我不知道有什么区别(什么时候必须使用这个,什么时候必须使用另一个)。
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCorsFilter implements Filter {
public SimpleCorsFilter() {
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, content-type");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
}
没有这个 CorsFilter,我只能从服务器获得 OPTIONS 响应。
我不会更改上面发布的 AuthorizationServerConfiguration。
实际上,大多数错误都发生在 Angular/Frontend 方面。这对我有用:
@Injectable()
export class AuthenticationService {
private headers = new Headers({'Content-Type': 'application/json'});
private auth64 = btoa("my-trusted-client:secret");
private tokenHeaders = new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic '+this.auth64
});
constructor(private http: Http) {
}
login(user: User) {
let body = new URLSearchParams();
body.append('grant_type', 'password');
body.append('username', user.username);
body.append('password', user.password);
return this.http.post(AppSettings.getApiUrl() + "oauth/token", body, {headers: this.tokenHeaders})
.map(data => {
console.log("it works!");
}, error => {
console.log(error.json());
});
}
之前的映射有问题。它总是导致预检 CORS 问题。我没有收到此映射的预检错误消息 - 即使我不使用 CORS 过滤器 - 但您需要 CORS 过滤器才能从服务器获取 OPTIONS 响应以外的内容。
为此,我收到了以下错误消息(在 JSON 响应中):“访问此资源需要完全身份验证”
为了解决这个问题,我执行了以下步骤:
也许有其他/更好的方法来解决这些问题,但这段代码对我来说工作正常 - 也许它可以帮助这里的其他人:-)
关于typescript - CORS 预检 channel 在 Spring Security 中未成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44295642/
我很好奇为什么以下不起作用。一般select用default:防止死锁,但在这种情况下不是: package main import "fmt" func main () { a := mak
我一生都无法弄清楚如何切换图像排序。图像以 (x,x,3) 格式读取,theano 要求它是 (3,x,x) 格式。我尝试更改顺序numpy.array([img[:,:,i] for i in ra
我正在向 libnl 发送单个 SSID 和频率进行扫描,但我得到了多个扫描结果以及我请求的 SSID 和频率,但我需要单个扫描结果(仅适用于请求的 SSID),如何实现这一点。请帮助我,我也发送了我
我是 Golang 的新手,但正在努力理解这门伟大的语言!请帮帮我.. 我有 2 个 channel 。 “进”和“出” channel in, out := make(chan Work),
例如我有这段代码: package main import ( "fmt" ) func main() { c1 := make(chan interface{}) close
我们使用以下调用来获取经过身份验证的用户的 ChannelID,它适用于大多数情况。一些 YouTube 用户将他们的 channel 连接到 Google+ 信息页,但在这种情况下,我们的一位用户无
case 'sinfo': const sinfo = new Discord.MessageEmbed() .addField('Server Name 🔎 :', message.guild.n
我需要让所有 channel 来创建一个 bunker 命令,这使得所有 channel 都是只读的。 最佳答案 他们变了Client.servers至 Client.guilds在 newer ve
为什么当第二个值通过另一个 go routine 发送并且没有收到发送的第一个值时, channel c 没有缓冲? package main import "fmt" func sum(s []in
据我所知,内置的 split 会将一个 3 channel Mat 拆分为三个 1 channel Mat。结果,这三个 Mat 只是具有一些不同强度的灰度。 我的意图是获得三个 3 channel
如何检测当前的 RAM 配置?我需要询问 Windows RAM 当前是在单 channel 、双 channel 还是四 channel 中运行。 我搜索了很多,并没有在这个网站或其他网站上找到任何
我需要拆分一个多 channel wav 文件并将每个 channel 编码为 mp3 文件。 我知道 gtresamer 的 deinterleave 插件,但我不确定如何将它用于 wav 文件以及
关闭。这个问题需要details or clarity .它目前不接受答案。 想要改进这个问题吗? 通过 editing this post 添加详细信息并澄清问题. 关闭 8 年前。 Improve
我正在尝试运行 Hyperledger Fabric 网络,它由单个订购者、单个对等节点和一个 cli 组成。为了学习启动 Hyperledger Fabric 网络的过程,从创建与加密相关的工件到将
我在 Laravel 中使用事件广播。我正在使用基于角色的通知访问权限。我有用于广播的自定义 auth guard。当用户连接到 channel 时,客户端将具有内部权限的 access_token
我正在编写一个使用 Elixir Channels 来处理实时事件的应用程序。我知道每个客户端将打开 1 个套接字,并且可以在其上多路复用多个 channel 。所以我的应用程序是一个聊天应用程序,其
我有一些 .wav 文件,我想转换它们的频率 (fs) 和 channel 数 (nchannels)。我在jupyter笔记本python3.6上使用ffmpeg。我使用了以下命令并且它有效。 cm
我有一个视频渲染器,它需要两个 H265 流(YUV420),我需要烘焙它们以使它们中的一个与另一个形成 alpha 蒙版。这一切都已解决并且效果很好,但是如果我按照此处的说明进行操作: ffmpeg
我运行此命令以便能够将 udp 直播流传输到可使用正在构建的移动应用程序播放的 http 直播流。 它只是一个只有音频流的流。 ffmpeg -i udp://@localhost:1111 -map
我在我的 discord.js 机器人中创建了 nuke 命令,它创建了具有相同名称、权限、主题等的 channel ,并删除了“原始” channel 。但是有一个问题,如何使 channel 与“
我是一名优秀的程序员,十分优秀!