如何处理 spring security + angular 中的 401 错误?

How to handle a 401 error in spring security + angular?

我正在学习如何使用 spring 安全和 angular 进行登录身份验证的教程,但是每当我 运行 angular 程序并尝试登录我收到 401 错误。我觉得这是一个 cors 问题并创建了一个 cors 过滤器 class 这是一个类似问题的解决方案,但我仍然遇到同样的错误。登录详细信息是正确的,因为我使用相同的凭据登录后端 localhost:8080 但是当我尝试使用 front-end 登录时,我在索引中收到以下错误。

错误:

请求URL:http://localhost:8080/login

请求方法:GET

状态码:401

远程地址:[::1]:8080

推荐人政策:no-referrer-when-downgrade

Access-Control-Allow-Headers:access_token,授权,content-type

Access-Control-Allow-Methods:POST、放置、获取、选项、删除

Access-Control-Allow-Origin: *

Access-Control-Max-Age: 4200

Cache-Control: no-cache, no-store, max-age=0, must-revalidate

连接:keep-alive

Content-Length: 0

日期:2020 年 7 月 28 日,星期二 07:47:34 GMT

过期:0

Keep-Alive: 超时=60

编译指示:no-cache

变化:来源

变化:Access-Control-Request-Method

变化:Access-Control-Request-Headers

WWW-Authenticate: 基本境界="境界"

WWW-Authenticate: 基本境界="境界"

X-Content-Type-Options: nosniff

X-Frame-Options:拒绝

X-XSS-Protection: 1;模式=块

接受:application/json、text/plain、/

Accept-Encoding: gzip, deflate, br

Accept-Language: en-GB,en-US;q=0.9,en;q=0.8

授权:Bascicml6YW5hOmp0MTQz

连接:keep-alive

主持人:localhost:8080

来源:http://localhost:4200

推荐人:http://localhost:4200/login

Sec-Fetch-Dest: 空

Sec-Fetch-Mode: cors

Sec-Fetch-Site: same-site

User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N)

AppleWebKit/537.36(KHTML,如 Gecko)Chrome/84.0.4147.89 移动 Safari/537.36

我试过:

教程:

https://www.youtube.com/watch?v=QV7ke4a7Lvc

spring 安全配置

@Configuration
public class SpringConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private CORSFilter myCorsFilter;


//CORS


    @Override
    protected void configure(HttpSecurity http) throws Exception {
     /*   http.cors().and().csrf().
                disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**")
                .permitAll()
                .anyRequest()
                .fullyAuthenticated()
                .and()
                .httpBasic();*/

        http.addFilterBefore(myCorsFilter, ChannelProcessingFilter .class);


        http.cors();
        http.csrf().disable();
        http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and()
                .httpBasic();
    }



    protected void configure(AuthenticationManagerBuilder auth) throws Exception{
        auth.inMemoryAuthentication()
                .withUser("java")
                .password("{noop}jt143").roles("USER");


    }
}


Corsfilter class


@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSFilter implements Filter {

    /**
     * CORS filter for http-request and response
     */
    public CORSFilter() {
    }

    /**
     * Do Filter on every http-request.
     */

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "4200");
        response.setHeader("Access-Control-Allow-Headers", "access_token, authorization, content-type");

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }

    /**
     * Destroy method
     */
    @Override
    public void destroy() {
    }

    /**
     * Initialize CORS filter
     */
    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }
}

@RestController
@CrossOrigin(origins = "*")
public class CashierController {



        @Autowired
        private CashierRepo repository;

        @GetMapping("/login")
        public String login(){
            return "authenticated";
        }


        @PostMapping("/addUser")
        public String saveCashier(@RequestBody Cashier cashier) {
            repository.save(cashier);
            return "Added user with user id : " + cashier.getUserId();

        }

您似乎没有将您的登录 API 排除在 Spring 安全之外。每当我们启用 spring 安全性时,我们都必须配置不应对其施加安全性的 URL 列表。示例 - 登录 api、html 文件、js 文件等。您可以通过将以下方法添加到您的 SpringConfig class

来完成此操作
@Override
    public void configure(WebSecurity web) throws Exception 
    {
        // Allow Login API to be accessed without authentication
        web.ignoring().antMatchers("/login").antMatchers(HttpMethod.OPTIONS, "/**"); // Request type options should be allowed.
    }