角度とスプリングセキュリティが新しくなりました。角度認証フォームページから基本認証を使用して残りのエンドポイントにログインしようとすると、CORSに問題があります。私の角度コードはhttp://localhost:4200で、残りはhttp://localhost:8181にあります。私の角度のあるログインフォームは、ログインコントローラで指定したhttp://localhost:8181/tokenへのリクエストを試みます。 -スプリングCORSと角度が動作しません:HTTPステータスコード403エラー
ロードに失敗しましたhttp://localhost:8181/token:プリフライト要求に対する応答がアクセス制御チェックに合格していません:いいえ 'Access-Control-Allow-Origin'ヘッダーがありません。サーバー側にコルス構成を追加しましたが、要求されたリソースに存在します。 Origin 'http://localhost:4200'はアクセスできません。応答は、HTTPステータスコード403
(角度)login.service.tsを有していた: -
@Injectable()
export class LoginService {
constructor(private http: Http) {}
sendCredential(username: string, password: string) {
const url = 'http://localhost:8181/token';
const encodedCredential = username + ':' + password;
const basicHeader = 'Basic ' + btoa(encodedCredential);
const headers = new Headers();
headers.append('Content-Type', 'application/x-wwww-form-urlencoded');
headers.append('Authorization' , basicHeader);
const opts = new RequestOptions({headers: headers});
return this.http.get(url, opts);
}
}
(スプリング)SecurityConfig.java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final String[] PUBLIC_MATCHERS = {
"/css/**",
"/js/**",
"/image/**",
"/book/**",
"/user/**"
};
@Override
protected void configure(HttpSecurity http) throws Exception{
http
.cors().and()
.csrf().disable()
.httpBasic()
.and()
.authorizeRequests()
.antMatchers(PUBLIC_MATCHERS)
.permitAll()
.anyRequest()
.authenticated();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET","POST","DELETE","PUT","OPTIONS"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userSecurityService).passwordEncoder(passwordEncoder());
}
LoginController.java
@RestController
public class LoginController {
@Autowired
private UserService userService;
@RequestMapping("/token")
public Map<String, String> token(HttpSession session, HttpServletRequest request) {
String remoteHost = request.getRemoteHost();
int portNumber = request.getRemotePort();
String remoteAddr = request.getRemoteAddr();
System.out.println(remoteHost + ":" + portNumber);
System.out.println(remoteAddr);
return Collections.singletonMap("token", session.getId());
}
}
CORSは(https://spring.io/understanding/CORS)無効にしているようだ – Zooly
上記のコードブロックでCORSの設定をSecurityConfigクラスに追加しました –
問題はあなたの認証メカニズムにあり、何らかの形でユーザーを認証できません。したがって、私は、クラスがFilterインターフェイスを実装し、春のCorConfigurationSourceの代わりにCorsの処理のためのすべてのリクエスト/レスポンスに対してfilterChain.doFilterを実行する従来のアプローチを使用すると、403ステータス –