Spring Security 禁用登录页面/重定向

标签 spring spring-security

有没有办法禁用 Spring Security 和登录页面的重定向。我的要求指定登录应该是导航菜单的一部分。

例子:

enter image description here

因此没有专门的登录页面。登录信息需要通过 Ajax 提交。如果发生错误,它应该返回指定错误的 JSON 并使用正确的 HTTP 状态代码。如果身份验证检查它应该返回 200,然后 javascript 可以从那里处理它。

我希望这是有道理的,除非有任何更简单的方法可以使用 Spring Security 来实现这一点。我对 Spring Security 没有太多经验。我认为这必须是一种常见的做法,但我没有找到太多。

当前的 spring 安全配置

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/", "/public/**").permitAll()
                .antMatchers("/about").permitAll()
                .anyRequest().fullyAuthenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .failureUrl("/login?error")
                .usernameParameter("email")
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/logout")
                .deleteCookies("remember-me")
                .logoutSuccessUrl("/")
                .permitAll()
                .and()
                .rememberMe();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(new BCryptPasswordEncoder());
    }

更新:

我尝试使用 HttpBasic(),但不管怎样,它都会要求登录凭据,而且它丑陋的浏览器弹出窗口对最终用户来说是 Not Acceptable 。看来我可能需要扩展 AuthenticationEntryPoint。

归根结底,我需要 Spring 安全性发送回 JSON,说明身份验证成功或失败。

最佳答案

重定向行为来自 SavedRequestAwareAuthenticationSuccessHandler其中is the default success handler .因此,删除重定向的一个简单解决方案是编写您自己的成功处理程序。例如

http.formLogin().successHandler(new AuthenticationSuccessHandler() {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
       //do nothing
    }
});

关于Spring Security 禁用登录页面/重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31714585/

相关文章:

java - Spring Boot 使用 Spring Profile 忽略来自 Java 配置类的 bean

java - Spring Boot Controller 中未发生正则表达式验证

带有 Spring Security 插件和 Salted 密码的 Grails

java - 如何使用 postman 将用户登录详细信息传递给 Spring Boot Rest API

java - Spring Security + JSR 250 + EJB 3.1 不工作

java - 属性引用异常 : No property ids found for type

spring - 在Grails中使用Spring Security限制内容访问

javascript - 语法错误: Unexpected token S, AngularJS,Spring

POST 上的 Spring 重定向

java - Spring Security/expired-url 无重定向 url