首页 > 解决方案 > Spring Angular 身份验证失败

问题描述

我的基本身份验证课程是:

@Configuration
@EnableWebSecurity
public class BasicAuthConfiguration
    extends WebSecurityConfigurerAdapter {


@Override
protected void configure(HttpSecurity http)
        throws Exception {
    http
            .httpBasic()
            .and()
            .authorizeRequests()
            .antMatchers("/login").permitAll()
            .anyRequest().authenticated()
            .and().cors().and().csrf()
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());

}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    final CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(ImmutableList.of("*"));
    configuration.setAllowedMethods(ImmutableList.of("HEAD",
            "GET", "POST", "PUT", "DELETE", "PATCH"));
    // setAllowCredentials(true) is important, otherwise:
    // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
    configuration.setAllowCredentials(true);
    // setAllowedHeaders is important! Without it, OPTIONS preflight request
    // will fail with 403 Invalid CORS request
    configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type", "X-XSS-Protection", "X-Content-Type-Options"));
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}
}

我的测试休息控制器是:

@Api(value="BMT test", description="BMT test system")
@RestController
@RequestMapping("/bmt/api/v1")
public class TestRestController {

@CrossOrigin(origins="*", maxAge=3600)
@GetMapping("/test/get")
public String getTest() {
    return "test";
}

@CrossOrigin(origins="*", maxAge=3600)
@PostMapping ("/test/post")
public String getTest2(String param) {
    return "test";
}

}

在有角的网站上,我有:

   public logUser(userLogin: string, password: string): any {
    const token = this.createBasicAuthToken('user', 'user')
    const httpOptions = {
        headers: new HttpHeaders({
            'Authorization': token
        })
    };
    return this.http.post(`http://localhost:8080/bmt/api/v1/test/post`,{},
        httpOptions).subscribe(
        data => console.log('success', data),
        error => console.log('oops', error)
    );


}

public createBasicAuthToken(userLogin: String, password: String): string {
    return 'Basic ' + window.btoa(userLogin + ':' + password);
}

但是 IDK 为什么我可以通过邮递员去连接以获取方法,但我可以从同一个控制器获取方法。但是,如果我尝试连接以获取角度,我无论如何都做不到。我不知道。

我需要spring boot / angular 5,6,7(我可以轻松更新)身份验证系统,但无论我尝试什么都失败了。有什么建议吗?

标签: angularspringspring-security

解决方案


您正在将用户和密码传递给logUser方法,而无需对其进行任何操作。

如果要在请求中使用基本身份验证,则必须Authorization在请求标头中设置。但首先您必须创建基本的身份验证令牌表单用户和密码。

用户名和密码用一个冒号 (:) 组合。这意味着用户名本身不能包含冒号。生成的字符串被编码为八位字节序列。用于此编码的字符集默认情况下未指定,只要它与 US-ASCII 兼容,但服务器可能会通过发送 charset 参数来建议使用 UTF-8。[7] 生成的字符串使用 Base64 的变体进行编码。然后将授权方法和空格(例如“Basic”)添加到编码字符串之前。见维基百科

像这样的东西:token = 'Basic ' + window.btoa(userLogin+':'+password);

尝试这个:

public logUser(userLogin: string, password: string): any {
  const token = 'Basic ' + window.btoa(userLogin+':'+password)`
  const httpOptions = {
    headers: new HttpHeaders({
      'Authorization': token
    })
  };
return this.http.post(`http://localhost:8080/bmt/api/v1/test/post`,
    {}, httpOptions).subscribe(
    data => console.log('success', data),
    error => console.log('oops', error)
);

并记住传递httpOptions您的请求。


推荐阅读