将 Angular 与 JWT 的 Spring Boot 连接时出现 CORS 错误
Posted
技术标签:
【中文标题】将 Angular 与 JWT 的 Spring Boot 连接时出现 CORS 错误【英文标题】:CORS error while connecting Angular with spring boot for JWT 【发布时间】:2020-07-02 12:27:52 【问题描述】:这是我在登录时遇到的浏览器控制台中的错误(对服务器进行后调用
我正在尝试使用 REST 连接 Angular 和 Spring Boot 以实现 JWT 身份验证和授权。
这是我的 Angular 服务,它对 Spring Boot (http://localhost:8080/login) 进行登录调用,这是 Spring Boot 通过 spring-starter-security 提供的默认 /login 页面(* 我认为 *)
export class JwtService
constructor(private _http: HttpClient)
submitData(credential)
credential = JSON.stringify(credential);
let reqHeader = new HttpHeaders();
return this._http.post("http://localhost:8080/login",credential);
下面是我的spring boot安全配置类
@EnableWebSecurity
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter
implements WebMvcConfigurer
private CustomAdminUserDetailService adminUserService;
private AdminDao adminDao;
public SecurityConfiguration(CustomAdminUserDetailService adminUserService, AdminDao adminDao)
super();
this.adminUserService = adminUserService;
this.adminDao = adminDao;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception
auth.authenticationProvider(authenticationProvider());
@Override
protected void configure(HttpSecurity http) throws Exception
http.csrf().disable()
.addFilter(new JwtAuthenticationFilter(authenticationManager()))
.addFilter(new JwtAuthorizationFilter(authenticationManager(), this.adminDao))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests().antMatchers("/login").permitAll()
.antMatchers("/home").hasRole("ADMIN");
@Bean
DaoAuthenticationProvider authenticationProvider()
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(adminUserService);
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
return daoAuthenticationProvider;
@Bean
PasswordEncoder passwordEncoder()
return new BCryptPasswordEncoder();
@Override
public void addCorsMappings(CorsRegistry registry)
registry.addMapping("*").allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowedOrigins("http://localhost:4200/");
WebMvcConfigurer.super.addCorsMappings(registry);
我已经用邮递员对其进行了测试,它工作正常,按预期给出了正确的响应和 Bearer 令牌,但它不适用于 Angular
这是我用 Postman 测试时的截图
我也尝试在请求中包含 Allow-cross-origin 标头作为
export class JwtService
constructor(private _http: HttpClient)
submitData(credential)
credential = JSON.stringify(credential);
let reqHeader = new HttpHeaders();
reqHeader.set('Access-Control-Allow-Origin','*');
return this._http.post("http://localhost:8080/login",credential,headers:reqHeader);
这是我的/home
的restcontroller(我没有包括/login
,因为spring boot 默认提供它'我可能是错的,我不确定')
@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class AdminController
@GetMapping("/home")
public String welcome()
return "Hello world";
我尝试使用 spring boot 进行调试,这就是我得到的,
2020-03-21 21:41:14.087[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[ngodb.net:27017][0;39m [36morg.mongodb.driver.cluster [0;39m [2m:[0;39m Checking status of clustertest-shard-00-01-rmt6q.mongodb.net:27017
[2m2020-03-21 21:41:14.087[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[ngodb.net:27017][0;39m [36morg.mongodb.driver.protocol.command [0;39m [2m:[0;39m Sending command '"ismaster": 1, "$db": "admin", "$clusterTime": "clusterTime": "$timestamp": "t": 1584807064, "i": 1, "signature": "hash": "$binary": "base64": "Qwv788i1WPfmVGkKUUq6jwsgR2U=", "subType": "00", "keyId": 6803351677173760002' with request id 284 to database admin on connection [connectionIdlocalValue:6, serverValue:139947] to server clustertest-shard-00-01-rmt6q.mongodb.net:27017
[2m2020-03-21 21:41:14.350[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[ngodb.net:27017][0;39m [36morg.mongodb.driver.protocol.command [0;39m [2m:[0;39m Execution of command with request id 284 completed successfully in 262.49 ms on connection [connectionIdlocalValue:6, serverValue:139947] to server clustertest-shard-00-01-rmt6q.mongodb.net:27017
[2m2020-03-21 21:41:14.351[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[ngodb.net:27017][0;39m [36morg.mongodb.driver.cluster [0;39m [2m:[0;39m Updating cluster description to type=REPLICA_SET, servers=[address=clustertest-shard-00-00-rmt6q.mongodb.net:27017, type=REPLICA_SET_SECONDARY, TagSet[Tagname='nodeType', value='ELECTABLE', Tagname='provider', value='AWS', Tagname='region', value='US_EAST_1'], roundTripTime=336.3 ms, state=CONNECTED, address=clustertest-shard-00-01-rmt6q.mongodb.net:27017, type=REPLICA_SET_SECONDARY, TagSet[Tagname='nodeType', value='ELECTABLE', Tagname='provider', value='AWS', Tagname='region', value='US_EAST_1'], roundTripTime=303.9 ms, state=CONNECTED, address=clustertest-shard-00-02-rmt6q.mongodb.net:27017, type=REPLICA_SET_PRIMARY, TagSet[Tagname='nodeType', value='ELECTABLE', Tagname='provider', value='AWS', Tagname='region', value='US_EAST_1'], roundTripTime=335.4 ms, state=CONNECTED]
[2m2020-03-21 21:41:14.784[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[ngodb.net:27017][0;39m [36morg.mongodb.driver.cluster [0;39m [2m:[0;39m Checking status of clustertest-shard-00-02-rmt6q.mongodb.net:27017
[2m2020-03-21 21:41:14.784[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[ngodb.net:27017][0;39m [36morg.mongodb.driver.protocol.command [0;39m [2m:[0;39m Sending command '"ismaster": 1, "$db": "admin", "$clusterTime": "clusterTime": "$timestamp": "t": 1584807064, "i": 1, "signature": "hash": "$binary": "base64": "Qwv788i1WPfmVGkKUUq6jwsgR2U=", "subType": "00", "keyId": 6803351677173760002' with request id 285 to database admin on connection [connectionIdlocalValue:7, serverValue:157822] to server clustertest-shard-00-02-rmt6q.mongodb.net:27017
[2m2020-03-21 21:41:14.786[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[ngodb.net:27017][0;39m [36morg.mongodb.driver.cluster [0;39m [2m:[0;39m Checking status of clustertest-shard-00-00-rmt6q.mongodb.net:27017
[2m2020-03-21 21:41:14.786[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[ngodb.net:27017][0;39m [36morg.mongodb.driver.protocol.command [0;39m [2m:[0;39m Sending command '"ismaster": 1, "$db": "admin", "$clusterTime": "clusterTime": "$timestamp": "t": 1584807064, "i": 1, "signature": "hash": "$binary": "base64": "Qwv788i1WPfmVGkKUUq6jwsgR2U=", "subType": "00", "keyId": 6803351677173760002' with request id 286 to database admin on connection [connectionIdlocalValue:5, serverValue:145988] to server clustertest-shard-00-00-rmt6q.mongodb.net:27017
[2m2020-03-21 21:41:15.135[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[ngodb.net:27017][0;39m [36morg.mongodb.driver.protocol.command [0;39m [2m:[0;39m Execution of command with request id 285 completed successfully in 351.23 ms on connection [connectionIdlocalValue:7, serverValue:157822] to server clustertest-shard-00-02-rmt6q.mongodb.net:27017
[2m2020-03-21 21:41:15.136[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[ngodb.net:27017][0;39m [36morg.mongodb.driver.protocol.command [0;39m [2m:[0;39m Execution of command with request id 286 completed successfully in 349.71 ms on connection [connectionIdlocalValue:5, serverValue:145988] to server clustertest-shard-00-00-rmt6q.mongodb.net:27017
[2m2020-03-21 21:41:15.136[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[ngodb.net:27017][0;39m [36morg.mongodb.driver.cluster [0;39m [2m:[0;39m Updating cluster description to type=REPLICA_SET, servers=[address=clustertest-shard-00-00-rmt6q.mongodb.net:27017, type=REPLICA_SET_SECONDARY, TagSet[Tagname='nodeType', value='ELECTABLE', Tagname='provider', value='AWS', Tagname='region', value='US_EAST_1'], roundTripTime=336.3 ms, state=CONNECTED, address=clustertest-shard-00-01-rmt6q.mongodb.net:27017, type=REPLICA_SET_SECONDARY, TagSet[Tagname='nodeType', value='ELECTABLE', Tagname='provider', value='AWS', Tagname='region', value='US_EAST_1'], roundTripTime=303.9 ms, state=CONNECTED, address=clustertest-shard-00-02-rmt6q.mongodb.net:27017, type=REPLICA_SET_PRIMARY, TagSet[Tagname='nodeType', value='ELECTABLE', Tagname='provider', value='AWS', Tagname='region', value='US_EAST_1'], roundTripTime=338.7 ms, state=CONNECTED]
[2m2020-03-21 21:41:15.136[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[ngodb.net:27017][0;39m [36morg.mongodb.driver.cluster [0;39m [2m:[0;39m Updating cluster description to type=REPLICA_SET, servers=[address=clustertest-shard-00-00-rmt6q.mongodb.net:27017, type=REPLICA_SET_SECONDARY, TagSet[Tagname='nodeType', value='ELECTABLE', Tagname='provider', value='AWS', Tagname='region', value='US_EAST_1'], roundTripTime=339.1 ms, state=CONNECTED, address=clustertest-shard-00-01-rmt6q.mongodb.net:27017, type=REPLICA_SET_SECONDARY, TagSet[Tagname='nodeType', value='ELECTABLE', Tagname='provider', value='AWS', Tagname='region', value='US_EAST_1'], roundTripTime=303.9 ms, state=CONNECTED, address=clustertest-shard-00-02-rmt6q.mongodb.net:27017, type=REPLICA_SET_PRIMARY, TagSet[Tagname='nodeType', value='ELECTABLE', Tagname='provider', value='AWS', Tagname='region', value='US_EAST_1'], roundTripTime=338.7 ms, state=CONNECTED]
[2m2020-03-21 21:41:17.794[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[o-8080-Acceptor][0;39m [36mo.apache.tomcat.util.threads.LimitLatch [0;39m [2m:[0;39m Counting up[http-nio-8080-Acceptor] latch=1
[2m2020-03-21 21:41:17.795[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mo.a.tomcat.util.net.SocketWrapperBase [0;39m [2m:[0;39m Socket: [org.apache.tomcat.util.net.NioEndpoint$NiosocketWrapper@4050f960:org.apache.tomcat.util.net.NioChannel@22fe2d9:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8080 remote=/0:0:0:0:0:0:0:1:56785]], Read from buffer: [0]
[2m2020-03-21 21:41:17.795[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36morg.apache.tomcat.util.net.NioEndpoint [0;39m [2m:[0;39m Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@4050f960:org.apache.tomcat.util.net.NioChannel@22fe2d9:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8080 remote=/0:0:0:0:0:0:0:1:56785]], Read direct from socket: [544]
[2m2020-03-21 21:41:17.795[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mo.a.coyote.http11.Http11InputBuffer [0;39m [2m:[0;39m Received [POST /login HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 39
Accept: application/json, text/plain, */*
Sec-Fetch-Dest: empty
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/80.0.3987.149 Safari/537.36
Content-Type: text/plain
Origin: http://localhost:4200
Sec-Fetch-Site: same-site
Sec-Fetch-Mode: cors
Referer: http://localhost:4200/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
"username":"nachu","password":"nachu"]
[2m2020-03-21 21:41:17.796[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mo.a.c.authenticator.AuthenticatorBase [0;39m [2m:[0;39m Security checking request POST /login
[2m2020-03-21 21:41:17.797[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36morg.apache.catalina.realm.RealmBase [0;39m [2m:[0;39m No applicable constraints defined
[2m2020-03-21 21:41:17.797[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mo.a.c.authenticator.AuthenticatorBase [0;39m [2m:[0;39m Not subject to any constraint
[2m2020-03-21 21:41:17.797[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mo.s.security.web.FilterChainProxy [0;39m [2m:[0;39m /login at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
[2m2020-03-21 21:41:17.798[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mo.s.security.web.FilterChainProxy [0;39m [2m:[0;39m /login at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
[2m2020-03-21 21:41:17.798[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mo.s.security.web.FilterChainProxy [0;39m [2m:[0;39m /login at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
[2m2020-03-21 21:41:17.798[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mo.s.security.web.FilterChainProxy [0;39m [2m:[0;39m /login at position 4 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
[2m2020-03-21 21:41:17.798[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mo.s.s.web.util.matcher.OrRequestMatcher [0;39m [2m:[0;39m Trying to match using Ant [pattern='/logout', GET]
[2m2020-03-21 21:41:17.798[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mo.s.s.w.u.matcher.AntPathRequestMatcher [0;39m [2m:[0;39m Request 'POST /login' doesn't match 'GET /logout'
[2m2020-03-21 21:41:17.798[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mo.s.s.web.util.matcher.OrRequestMatcher [0;39m [2m:[0;39m Trying to match using Ant [pattern='/logout', POST]
[2m2020-03-21 21:41:17.798[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mo.s.s.w.u.matcher.AntPathRequestMatcher [0;39m [2m:[0;39m Checking match of request : '/login'; against '/logout'
[2m2020-03-21 21:41:17.798[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mo.s.s.web.util.matcher.OrRequestMatcher [0;39m [2m:[0;39m Trying to match using Ant [pattern='/logout', PUT]
[2m2020-03-21 21:41:17.798[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mo.s.s.w.u.matcher.AntPathRequestMatcher [0;39m [2m:[0;39m Request 'POST /login' doesn't match 'PUT /logout'
[2m2020-03-21 21:41:17.798[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mo.s.s.web.util.matcher.OrRequestMatcher [0;39m [2m:[0;39m Trying to match using Ant [pattern='/logout', DELETE]
[2m2020-03-21 21:41:17.798[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mo.s.s.w.u.matcher.AntPathRequestMatcher [0;39m [2m:[0;39m Request 'POST /login' doesn't match 'DELETE /logout'
[2m2020-03-21 21:41:17.798[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mo.s.s.web.util.matcher.OrRequestMatcher [0;39m [2m:[0;39m No matches found
[2m2020-03-21 21:41:17.798[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mo.s.security.web.FilterChainProxy [0;39m [2m:[0;39m /login at position 5 of 12 in additional filter chain; firing Filter: 'JwtAuthenticationFilter'
[2m2020-03-21 21:41:17.798[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mo.s.s.w.u.matcher.AntPathRequestMatcher [0;39m [2m:[0;39m Checking match of request : '/login'; against '/login'
[2m2020-03-21 21:41:17.798[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mc.n.p.util.JwtAuthenticationFilter [0;39m [2m:[0;39m Request is to process authentication
in attempt authentication
spring boot generating token to authenticate authentication
[2m2020-03-21 21:41:17.802[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mo.s.s.authentication.ProviderManager [0;39m [2m:[0;39m Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
[2m2020-03-21 21:41:17.802[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mo.s.d.m.r.query.StringBasedMongoQuery [0;39m [2m:[0;39m Created query Documentusername=nachu for Document fields.
[2m2020-03-21 21:41:17.803[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mo.s.data.mongodb.core.MongoTemplate [0;39m [2m:[0;39m find using query: "username" : "nachu" fields: Document for class: class com.nachu.project.repository.AdminUser in collection: admin_user
[2m2020-03-21 21:41:17.805[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36morg.mongodb.driver.protocol.command [0;39m [2m:[0;39m Sending command '"find": "admin_user", "filter": "username": "nachu", "limit": 2, "$db": "school", "$clusterTime": "clusterTime": "$timestamp": "t": 1584807074, "i": 1, "signature": "hash": "$binary": "base64": "Mb5v7hdn1UfUpwhsk+1/C1JJTi8=", "subType": "00", "keyId": 6803351677173760002, "lsid": "id": "$binary": "base64": "9QYFHA01TUyDwe0kXrY5DQ==", "subType": "04"' with request id 287 to database school on connection [connectionIdlocalValue:8, serverValue:150674] to server clustertest-shard-00-02-rmt6q.mongodb.net:27017
[2m2020-03-21 21:41:18.079[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36morg.mongodb.driver.protocol.command [0;39m [2m:[0;39m Execution of command with request id 287 completed successfully in 273.69 ms on connection [connectionIdlocalValue:8, serverValue:150674] to server clustertest-shard-00-02-rmt6q.mongodb.net:27017
User role is : [ADMIN]
spring boot successfully authentication the user
generating jwt token
sending response to the user
[2m2020-03-21 21:41:18.441[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mo.s.s.w.header.writers.HstsHeaderWriter [0;39m [2m:[0;39m Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@22d45307
[2m2020-03-21 21:41:18.441[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36ms.s.w.c.SecurityContextPersistenceFilter[0;39m [2m:[0;39m SecurityContextHolder now cleared, as request processing completed
[2m2020-03-21 21:41:18.442[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mo.a.tomcat.util.net.SocketWrapperBase [0;39m [2m:[0;39m Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@4050f960:org.apache.tomcat.util.net.NioChannel@22fe2d9:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8080 remote=/0:0:0:0:0:0:0:1:56785]], Read from buffer: [0]
[2m2020-03-21 21:41:18.442[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36morg.apache.tomcat.util.net.NioEndpoint [0;39m [2m:[0;39m Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@4050f960:org.apache.tomcat.util.net.NioChannel@22fe2d9:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8080 remote=/0:0:0:0:0:0:0:1:56785]], Read direct from socket: [0]
[2m2020-03-21 21:41:18.443[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36mo.apache.coyote.http11.Http11Processor [0;39m [2m:[0;39m Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@4050f960:org.apache.tomcat.util.net.NioChannel@22fe2d9:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8080 remote=/0:0:0:0:0:0:0:1:56785]], Status in: [OPEN_READ], State out: [OPEN]
[2m2020-03-21 21:41:18.444[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[nio-8080-exec-3][0;39m [36morg.apache.tomcat.util.net.NioEndpoint [0;39m [2m:[0;39m Registered read interest for [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@4050f960:org.apache.tomcat.util.net.NioChannel@22fe2d9:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8080 remote=/0:0:0:0:0:0:0:1:56785]]
[2m2020-03-21 21:41:22.323[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[on(4)-127.0.0.1][0;39m [36msun.rmi.transport.tcp [0;39m [2m:[0;39m RMI TCP Connection(4)-127.0.0.1: accepted socket from [127.0.0.1:56788]
[2m2020-03-21 21:41:22.323[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[on(4)-127.0.0.1][0;39m [36msun.rmi.transport.tcp [0;39m [2m:[0;39m RMI TCP Connection(4)-127.0.0.1: (port 56134) op = 80
[2m2020-03-21 21:41:22.334[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[on(5)-127.0.0.1][0;39m [36msun.rmi.transport.tcp [0;39m [2m:[0;39m RMI TCP Connection(5)-127.0.0.1: accepted socket from [127.0.0.1:56790]
[2m2020-03-21 21:41:22.339[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[on(5)-127.0.0.1][0;39m [36msun.rmi.transport.tcp [0;39m [2m:[0;39m RMI TCP Connection(5)-127.0.0.1: (port 56135) op = 80
[2m2020-03-21 21:41:22.339[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[on(5)-127.0.0.1][0;39m [36msun.rmi.loader [0;39m [2m:[0;39m RMI TCP Connection(5)-127.0.0.1: name = "[Ljava.rmi.server.ObjID;", codebase = "", defaultLoader = sun.misc.Launcher$ExtClassLoader@25a78f17
[2m2020-03-21 21:41:22.339[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[on(5)-127.0.0.1][0;39m [36msun.rmi.loader [0;39m [2m:[0;39m RMI TCP Connection(5)-127.0.0.1: name = "java.rmi.server.ObjID", codebase = "", defaultLoader = sun.misc.Launcher$ExtClassLoader@25a78f17
[2m2020-03-21 21:41:22.339[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[on(5)-127.0.0.1][0;39m [36msun.rmi.loader [0;39m [2m:[0;39m RMI TCP Connection(5)-127.0.0.1: name = "java.rmi.server.UID", codebase = "", defaultLoader = sun.misc.Launcher$ExtClassLoader@25a78f17
[2m2020-03-21 21:41:22.340[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[on(5)-127.0.0.1][0;39m [36msun.rmi.loader [0;39m [2m:[0;39m RMI TCP Connection(5)-127.0.0.1: name = "java.rmi.dgc.Lease", codebase = "", defaultLoader = sun.misc.Launcher$ExtClassLoader@25a78f17
[2m2020-03-21 21:41:22.340[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[on(5)-127.0.0.1][0;39m [36msun.rmi.loader [0;39m [2m:[0;39m RMI TCP Connection(5)-127.0.0.1: name = "java.rmi.dgc.VMID", codebase = "", defaultLoader = sun.misc.Launcher$ExtClassLoader@25a78f17
[2m2020-03-21 21:41:22.340[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[on(5)-127.0.0.1][0;39m [36msun.rmi.loader [0;39m [2m:[0;39m RMI TCP Connection(5)-127.0.0.1: name = "[B", codebase = "", defaultLoader = sun.misc.Launcher$ExtClassLoader@25a78f17
[2m2020-03-21 21:41:22.341[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[on(4)-127.0.0.1][0;39m [36msun.rmi.transport.tcp [0;39m [2m:[0;39m RMI TCP Connection(4)-127.0.0.1: (port 56134) op = 82
[2m2020-03-21 21:41:22.341[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[on(4)-127.0.0.1][0;39m [36msun.rmi.transport.tcp [0;39m [2m:[0;39m RMI TCP Connection(4)-127.0.0.1: (port 56134) op = 84
[2m2020-03-21 21:41:22.342[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[on(5)-127.0.0.1][0;39m [36msun.rmi.transport.tcp [0;39m [2m:[0;39m RMI TCP Connection(5)-127.0.0.1: (port 56135) op = 80
[2m2020-03-21 21:41:22.346[0;39m [32mDEBUG[0;39m [35m10132[0;39m [2m---[0;39m [2m[on(5)-127.0.0.1][0;39m [36msun.rmi.transport.tcp [0;39m [2m:[0;39m RMI TCP Connection(5)-127.0.0.1: (port 56135) op = 80
这是我正在使用的 AuthenticationFilter 类
public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter
private AuthenticationManager authenticationManager;
public JwtAuthenticationFilter(AuthenticationManager authenticationManager)
// super();
System.out.println("in constructor");
this.authenticationManager = authenticationManager;
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException
System.out.println("in attempt authentication");
LoginViewModel credentials = null;
try
credentials = new ObjectMapper().readValue(request.getInputStream(), LoginViewModel.class);
catch (JsonParseException e)
System.out.println("in json parse");
e.printStackTrace();
catch (JsonMappingException e)
System.out.println("in json map");
e.printStackTrace();
catch (IOException e)
System.out.println("in io exception");
e.printStackTrace();
System.out.println("spring boot generating token to authenticate authentication");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
credentials.getUsername(),
credentials.getPassword(),
new ArrayList<>());
Authentication auth = authenticationManager.authenticate(token);
return auth;
@Override
protected void successfulAuthentication(
HttpServletRequest request,
HttpServletResponse response,
FilterChain chain,
Authentication authResult) throws IOException, ServletException
System.out.println("spring boot successfully authentication the user");
System.out.println("generating jwt token");
User user = (User) authResult.getPrincipal();
String token = JWT.create()
.withSubject(user.getUsername())
.withExpiresAt(new Date(System.currentTimeMillis()+ 1000 * 60 * 60 * 1))
.sign(Algorithm.HMAC512("adhfjhewr******fk23"));
response.addHeader("Authorization", "Bearer "+token);
System.out.println("sending response to the user");
请求中的标头是
POST /login HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 39
Accept: application/json, text/plain, */*
Sec-Fetch-Dest: empty
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36
Content-Type: text/plain
Origin: http://localhost:4200
Sec-Fetch-Site: same-site
Sec-Fetch-Mode: cors
Referer: http://localhost:4200/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
如何是第一个问题,但为什么更重要
我们将不胜感激。谢谢
【问题讨论】:
嗨,欢迎来到 SO。我已将您的图片放入其中,但其中一些包含代码。如果您可以仅用代码而不是图片替换它们会更好。这也适用于日志输出,请。如果我犯了任何错误,请在 cmets 中告诉我。谢谢。 你能在网络标签中显示消息吗?在请求标头中传递的来源是什么? @AkhilSurapuram 我在问题中包含了 Network Tab 和 Request Header。 您的前端 javascript 代码没有在请求中添加授权请求标头。 @sideshowbarker 授权是下一步,但在这里我遇到了身份验证问题。 【参考方案1】:您应该在后端启用CORS
。
Angular 应用程序在 http://localhost:4200
提供服务,浏览器拒绝向另一个域(在本例中为 http://localhost:8080
)发出请求。More information on CORS.
因此,您应该在您的后端应用中将您的前端网址列入白名单。
您可以通过在 Application
类中添加一些行来使用 Spring Boot 轻松做到这一点:
@SpringBootApplication
public class Application implements WebMvcConfigurer
...
/**
* CORS configuration
*/
@Override
public void addCorsMappings(CorsRegistry registry)
registry.addMapping("/**")
.allowedOrigins(
"http://localhost:4200"
)
.allowedMethods(
"GET",
"PUT",
"POST",
"DELETE",
"PATCH",
"OPTIONS"
);
...
您还应该检查您的 Spring Security 配置。
CORS 应该通过WebSecurityConfigurerAdapter
启用:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
@Override
protected void configure(HttpSecurity http) throws Exception
http.cors().and()...
更多详情Spring official documentation
【讨论】:
尽管我在 SecurityConfiguration 类中完成了该操作,但我确实尝试将它添加到 主应用程序类,但它也不起作用给出同样的错误。 请分享您的 Spring Boot 安全配置 我刚刚添加了,现在你可以查看我的SecurityConfiguration Class 我刚刚用额外的 Spring 安全配置编辑了我的答案,你必须启用CORS
。
我按照你的解释添加了 cors() 但它也不起作用,给出了同样的错误@Override protected void configure(HttpSecurity http) throws Exception http.csrf().disable() .cors() .and() .addFilter(new JwtAuthenticationFilter(authenticationManager())) .addFilter(new JwtAuthorizationFilter(authenticationManager(), this.adminDao)) .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests().antMatchers(HttpMethod.POST,"/login").permitAll() .antMatchers("/home").hasRole("ADMIN");
【参考方案2】:
我在 addCorsMappings() 方法中误写了 * 而不是 /**
现在方法看起来像
@Override
public void addCorsMappings(CorsRegistry registry)
registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowedOrigins("http://localhost:4200","http://localhost:8080");
WebMvcConfigurer.super.addCorsMappings(registry);
此外,在此之后 Angular 客户端无法获取响应并获得 null 在响应中,所以我将其修改为
submitData(credential)
credential = JSON.stringify(credential);
return this._http.post("http://localhost:8080/login",credential,observe: 'response');
现在我得到了 Http 响应。
我希望这对其他人有所帮助。
感谢所有试图解决我的问题并付出宝贵时间的人。
【讨论】:
以上是关于将 Angular 与 JWT 的 Spring Boot 连接时出现 CORS 错误的主要内容,如果未能解决你的问题,请参考以下文章
Spring boot、JWT 和 Angular 不起作用:方法 put 的 HTTP 状态代码 403 错误
Angular2 Spring Boot JWT 缺少响应标头
问题让 Spring Boot 的 jwt 变为 Angular