繁体   English   中英

如何为单页应用程序配置Spring Security?

[英]How to configure Spring Security for a single page application?

我在为单页应用程序配置Spring Security时遇到问题。

所以,默认配置看起来像

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("customUserDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/", "/list").permitAll()
                .antMatchers("/admin/**").access("hasRole('ADMIN')")
                .and().formLogin().loginPage("/login").permitAll()
                .usernameParameter("ssoId").passwordParameter("password")
                .and().csrf()
                .and().exceptionHandling().accessDeniedPage("/Access_Denied");
    }

    @Bean(name="authenticationManager")
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


}

从Login()。loginPage(“ / login”)方法的文档中可以得知,它用于重定向到登录页面。 对于单页,此配置不相关。 如何为单页应用程序配置spring? 我的意思是如何在控制器和配置文件中配置登录,注销。

Spring Lemon可能是一个完整的示例,但让我总结一下以下内容。

默认情况下,当用户成功登录时,Spring Security会将其重定向到主页。 登录失败或成功注销后,用户将被重定向回登录页面。 同样,在尝试访问用户没有足够权限的URL时,他将被重定向到登录页面。

如您所说,此行为不适用于单页应用程序。 您的API应该发送200响应以及用户数据或4xx响应。 这可以通过提供自己的处理程序来完成,如下所示:

@Override
protected void configure(HttpSecurity http) throws Exception {
http
    .formLogin()
        ...
        .successHandler(your authentication success handler object)
        .failureHandler(your authentication failure handler object)
        .and()
    .logout()
        ...
        .logoutSuccessHandler(your logout success handler object)
        .and()
    .exceptionHandling()
        .authenticationEntryPoint(new Http403ForbiddenEntryPoint())
    ...
}

您将在Internet上找到许多有关如何编写这些处理程序类的示例。 例如,在spring-lemon项目中,这些代码如下所示。

身份验证成功处理程序

@Component
public class AuthenticationSuccessHandler
    extends SimpleUrlAuthenticationSuccessHandler {

    @Autowired    
    private ObjectMapper objectMapper;

    @Autowired    
    private LemonService<?,?> lemonService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
            HttpServletResponse response,
            Authentication authentication)
    throws IOException, ServletException {

        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);

        AbstractUser<?,?> currentUser = lemonService.userForClient();

        response.getOutputStream().print(
                objectMapper.writeValueAsString(currentUser));

        clearAuthenticationAttributes(request);
    }
}

总而言之,它会在响应数据中返回一个200响应的JSONified current-user。

身份验证失败处理程序

实际上,不需要为身份验证失败处理程序编写类-由Spring提供的SimpleUrlAuthenticationFailureHandler ,如果在不带任何参数的情况下对其进行实例化,则可以按预期工作。

注销成功处理程序

public class LemonLogoutSuccessHandler
    implements LogoutSuccessHandler {

    @Override
    public void onLogoutSuccess(HttpServletRequest request,
        HttpServletResponse response, Authentication authentication)
        throws IOException, ServletException {

          response.setStatus(HttpServletResponse.SC_OK);
    }
}

有关详细示例,请参考Spring Lemon的LemonWebSecurityConfig类以及各个模块的安全性包中的其他类,这可能会有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM