【问题标题】:Spring Angular authentication failSpring Angular 身份验证失败
【发布时间】:2020-02-06 19:24:12
【问题描述】:

我的基本身份验证类是:

@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(我可以轻松更新)身份验证系统,但无论我尝试什么都失败了。有什么建议吗?

【问题讨论】:

    标签: angular spring spring-security


    【解决方案1】:

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

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

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

    类似: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

    【讨论】:

    • 我的错-我删除了方法调用-我之前做过-我还有401:/
    • 如果查看devTool网络请求,header中授权设置是否正确?
    • 我更新了问题。我们发送“Basic SOMETHINGENCODED”作为标题我有问题,当我使用邮递员时,我也有 POST 映射的问题。我认为这里的 Spring 也有问题
    • 一般情况下,您应该在 API 端点中使用 ResponseEntity 类型的响应。并且请求的正文可以通过@RequestBody 来实现。例如在 post 端点 public ResponseEntity<String> getTest2(@RequestBody String(or some other type) param) { return ResponseEntity.ok("test"); }
    • .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());当我将其删除时开始工作:/该死的在哪里可以找到教程角度+通过令牌进行的弹簧启动身份验证:P
    猜你喜欢
    • 2017-09-07
    • 2021-06-24
    • 2017-12-06
    • 2017-10-03
    • 2015-07-28
    • 1970-01-01
    • 1970-01-01
    • 2022-08-16
    • 2014-01-24
    相关资源
    最近更新 更多