當我嘗試在后端獲取用戶名時
@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/persons")
public class PersonController {
...
@PostMapping
public ResponseEntity<PersonDto> addPerson(@RequestBody PersonDto objectDto, @AuthenticationPrincipal Principal principal){
System.out.println(principal.getName());
我有一個錯誤
2021-10-27 23:30:39.309 ERROR 10744 --- [nio-8081-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
我可以看到前端正在發送 JWT 令牌(不要看我手動將它添加到標頭的“accessToken”)。
POST /persons HTTP/1.1
Host: localhost:8081
Connection: keep-alive
Content-Length: 217
sec-ch-ua: "Chromium";v="94", "Google Chrome";v="94", ";Not A Brand";v="99"
accessToken: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJHaWVuZWsiLCJpYXQiOjE2MzUzNjg1MjQsImV4cCI6MTYzNTQ1NDkyNH0.leuqnc-8fHNBVhTmukruom-RudxicWP3ykkMyMiapwY8bBVCFLwlNssXNK-gyo0RHig9d-dg83-QG9LDqVO9VA
sec-ch-ua-mobile: ?0
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36
Content-Type: application/json
Accept: application/json, text/plain, */*
x-access-token: Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJHaWVuZWsiLCJpYXQiOjE2MzUzNjg1MjQsImV4cCI6MTYzNTQ1NDkyNH0.leuqnc-8fHNBVhTmukruom-RudxicWP3ykkMyMiapwY8bBVCFLwlNssXNK-gyo0RHig9d-dg83-QG9LDqVO9VA
sec-ch-ua-platform: "Windows"
Origin: http://localhost:4200
Sec-Fetch-Site: same-site
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
Referer: http://localhost:4200/
Accept-Encoding: gzip, deflate, br
Accept-Language: pl-PL,pl;q=0.9,en-US;q=0.8,en;q=0.7
后端看不到的原因是什么?
附加安全配置 - 如果您需要更多詳細資訊,請告訴我
package pl.portal.randkowy.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.core.userdetails.UserDetailsService;
@Configuration
@EnableWebSecurity(debug=true)
@EnableGlobalMethodSecurity(
// securedEnabled = true,
// jsr250Enabled = true,
prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsService userDetailsService;
@Autowired
private AuthEntryPointJwt unauthorizedHandler;
@Bean
public AuthTokenFilter authenticationJwtTokenFilter() {
return new AuthTokenFilter();
}
@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests().antMatchers("/api/auth/**").permitAll()
.antMatchers("/api/test/**").permitAll()
.antMatchers("/persons").permitAll()
.antMatchers("/persons/**").permitAll()
.antMatchers("/preferences/**").permitAll()
.antMatchers("/interests/**").permitAll()
.antMatchers("/secretdata/**").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
當我嘗試以這種方式檢查時
@PostMapping
public ResponseEntity<PersonDto> addPerson(@RequestBody PersonDto objectDto, Principal principal){
//zalogowany u?ytkownik
Object principal2 = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
System.out.println("--------------------------------------*****************");
if (principal2 instanceof UserDetailsImpl) {
String username = ((UserDetailsImpl)principal2).getUsername();
System.out.println(username);
} else {
String username = principal2.toString();
System.out.println(username);
}
System.out.println("--------------------------------------*****************");
我有
--------------------------------------*****************
anonymousUser
--------------------------------------*****************
為什么 Spring Security 不讀取此令牌?它在登錄程式后發送到前端,所以應該沒問題。Spring 應該從這個 x-access-token 選項進入標題嗎?
編輯:我在除錯程序中發現 jwt 為空,但為什么 - 我可以看到該請求包含在前端的 jwt 令牌中?

uj5u.com熱心網友回復:
除錯到您parseJwt(request)的應用程式中以查看您的應用程式如何從請求中提取令牌。的做法access token是:它通常在Authorization標題中并以Bearer
Request headers
Authorization: Bearer access-token
uj5u.com熱心網友回復:
嘗試像這樣更改 webSecurityConfig
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests().antMatchers("/api/auth/**").permitAll()
.antMatchers("/api/test/**").permitAll()
.antMatchers("/persons/**").permitAll()
.antMatchers("/preferences/**").permitAll()
.antMatchers("/interests/**").permitAll()
.antMatchers("/secretdata/**").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/342772.html
上一篇:如何將SpringBoot與AmazonNeptune資料庫結合使用?
下一篇:資料通過ajax標記白名單
