如何在Spring Security + Angular中处理401错误?

mccptt67  于 2023-10-20  发布在  Spring
关注(0)|答案(2)|浏览(138)

我正在学习如何使用spring security和angular进行登录身份验证的教程,但是每当我运行angular程序并尝试登录时,我都会收到401错误。我觉得这是一个CORS问题,并创建了一个CORS过滤器类,这是一个类似问题的解决方案,但我仍然得到同样的错误。登录细节是正确的,因为我使用相同的凭据登录到localhost:8080的后端,但当我试图登录使用前端我得到以下错误的索引。
错误代码:
请求URL:http://localhost:8080/login
申请方式:得到
验证码:401
远程地址:[::1]:8080
推荐人政策:降级时无引用
访问控制允许标头:access_token,authorization,content-type
访问控制允许方法:POST、PUT、GET、OPTIONS、DELETE
访问控制允许来源:*
访问控制最长期限:4200
缓存控制:无缓存、无存储、最长使用期限=0、必须重新验证
Connection:keep-alive
内容长度:0
日期:2020年7月28日星期二07:47:34 GMT
到期时间:0
Keep-Alive:timeout=60
编译指示:无缓存
不同:来源
不同:访问控制请求方法
不同:访问控制请求头
WWW认证:基础领域=“领域”
WWW认证:基础领域=“领域”
X内容类型选项:无嗅闻
X-框架-选项:否认
X-XSS-保护:1;模式=块
接受:应用程序/json,文本/普通,/
接受编码:压缩,缩小,br
接受语言:en-GB、en-US; q= 0.9,en;q=0.8
授权:基本cml 6 YW 5 hOmp 0 MTQz
Connection:keep-alive
主机:localhost:8080
来源:http://localhost:4200
参考:http://localhost:4200/login
Sec-Fetch-Dest(二级提取目标):空
Sec-Fetch-模式:CORS
Sec-Fetch-站点:同址
用户代理:Mozilla/5.0(Linux; Android 6.0; Nexus 5 Build/MRA58N)
AppleWebKit/537.36(KHTML,like Gecko)Chrome/84.0.4147.89移动的Safari/537.36
我试过:
Angular 2 Spring Boot Login CORS Problems
教育课程:
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();

        }
8iwquhpp

8iwquhpp1#

看起来您没有从Spring安全性中排除登录API。每当我们启用Spring Security 时,我们都必须配置不应强制实施安全性的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.
    }
nukf8bse

nukf8bse2#

谢谢你的评论代码为我工作:)

http.cors().and().csrf().
                disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**")
                .permitAll()
                .anyRequest()
                .fullyAuthenticated()
                .and()
                .httpBasic();

相关问题