提问者:小点点

spring安全+Angular一个401错误怎么处理?


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

错误:

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

请求方法:GET

状态代码:401

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

推荐人策略:降级时不推荐人

access-control-allow-headers:access_token、authorization、content-t

access-control-allow-methods:POST,PUT,GET,OPTIONS,

Access-Control-Allow-Origine:*

Access-Control-Max-Age:4200

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

连接:keep-alive

内容-长度:0

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

过期:0

keep-alive:timeout=60

pragma:无缓存

变化:原点

变:Access-Control-Request-Method

变:Access-Control-Request-Headers

www-authenticate:Basic realm=“realm”

www-authenticate:Basic realm=“realm”

X-content-type-options:nosniff

X-Frame-Options:拒绝

X-XSS-保护:1;模式=块

Accept:application/json、text/plain、/

接受编码:gzip,deflate,br

接受语言:en-GB,EN-US;q=0.9,EN;q=0.8

授权:Basiccml6YW5hOmp0MTQz

连接:keep-alive

主机:本地主机:8080

来源:http://localhost:4200

引用人:http://localhost:4200/login

sec-fetch-dest:空

SEC-FETCH-MODE:cors

sec-fetch-site:same-site

用户代理:Mozilla/5.0(Linux;Android 6.0;Nexus 5 Build/MRA58N)

AppleWebKit/537.36(KHTML,like Gecko)Chrome/84.0.4147.89 Mobile Safari/537.36

我试过:

Angular 2 spring boot登录CORS问题

教程:

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类


@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();

        }

共1个答案

匿名用户

似乎您没有将您的登录API排除在spring安全之外。无论何时,我们启用spring安全性,我们都必须配置不应为其施加安全性的URL列表。示例-登录api、html文件、js文件等。您可以通过将下面的方法添加到SpringConfig类中来完成此操作

@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.
    }