如何在 Spring 安全性中配置 api 和 ui 以防止未经授权的请求

How to configure api and ui from unauthorized request in Spring Security

我是 Spring 安全方面的新手,所以请原谅任何不明确的地方。我有这个 Spring 引导项目,配置 Java。

项目有一个 UI (my-app) 和一个 Rest API (my-app/api)。我想用 Spring 安全保护两者,我成功地保护了 UI 部分。当未经授权的用户试图请求禁止的资源时,将被重定向到登录页面。我的问题是当我试图保护 Rest API 时。通过以下设置,我保护了 UI 部分。

 http
            .authorizeRequests()
            .antMatchers("/login", "/about", "/resource/**").permitAll()
            .anyRequest().authenticated()
        .and()
            .formLogin() 
            .loginPage("/login") 
            .permitAll()
            .failureUrl("/login?error=true")
        .and()
            .logout()
            .logoutSuccessUrl("/login")

UI 受到很好的保护,注销和登录错误重定向到登录页面,唯一的警告是禁止访问 API,returns 登录 HTML 文本。 使用下一个设置

 http.antMatcher("/my-app/**")
            .authorizeRequests().anyRequest().authenticated();

只有 API 受到保护,并且在任何未经授权的请求中,它 returns 一个 JSON 错误(这是期望的行为),并且没有 redirect/html 文字打印。我知道我的 API 已获得身份验证,因为我使用 Bearer 令牌(Oauth2 密码授予类型)并且运行良好。

我在混合两种设置以获得所需结果时遇到问题。

欢迎提出任何建议。

您可以使用

中定义的多个 http 安全配置

https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#multiple-httpsecurity