简体   繁体   English

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

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

I faced with a problem configuration Spring Security for single page application. 我在为单页应用程序配置Spring Security时遇到问题。

So, defualt config looks like 所以,默认配置看起来像

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


}

From the documentation for the methods for Login().loginPage("/login") says the it use for redirecting to the login page. 从Login()。loginPage(“ / login”)方法的文档中可以得知,它用于重定向到登录页面。 For single page this configuration doesn't relevant. 对于单页,此配置不相关。 How I should configure spring for single page application? 如何为单页应用程序配置spring? I mean how to configure login, logout in controller and in configuration file. 我的意思是如何在控制器和配置文件中配置登录,注销。

Spring Lemon can be a complete example for this, but let me summarize the things below. Spring Lemon可能是一个完整的示例,但让我总结一下以下内容。

By default, when a user successfully logs in, Spring Security redirects him to the home page. 默认情况下,当用户成功登录时,Spring Security会将其重定向到主页。 When a login fails, or after a successful logout, the user is redirected back to the login page. 登录失败或成功注销后,用户将被重定向回登录页面。 Also, on trying to access URLs for which a user does not have sufficient rights, he is redirected to the login page. 同样,在尝试访问用户没有足够权限的URL时,他将被重定向到登录页面。

As you say, this behavior won't suit for single page applications. 如您所说,此行为不适用于单页应用程序。 Your API should instead send a 200 response along with the user data, or a 4xx response. 您的API应该发送200响应以及用户数据或4xx响应。 This can be done by supplying your own handlers, like this: 这可以通过提供自己的处理程序来完成,如下所示:

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

You will find many examples in the Internet on how to code these handler classes. 您将在Internet上找到许多有关如何编写这些处理程序类的示例。 For example, in the spring-lemon project, these are coded as below. 例如,在spring-lemon项目中,这些代码如下所示。

Authentication Success Handler 身份验证成功处理程序

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

In summary, it returns a 200 response with the JSONified current-user in the response data. 总而言之,它会在响应数据中返回一个200响应的JSONified current-user。

Authentication Failure Handler 身份验证失败处理程序

In fact, there is no need to code a class for the authentication failure handler - the SimpleUrlAuthenticationFailureHandler provided by Spring, if instantiated without any arguments, works as desired. 实际上,不需要为身份验证失败处理程序编写类-由Spring提供的SimpleUrlAuthenticationFailureHandler ,如果在不带任何参数的情况下对其进行实例化,则可以按预期工作。

Logout Success Handler 注销成功处理程序

public class LemonLogoutSuccessHandler
    implements LogoutSuccessHandler {

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

          response.setStatus(HttpServletResponse.SC_OK);
    }
}

For a detailed example, referring Spring Lemon's LemonWebSecurityConfig class and other classes in it's security packages of various modules can be helpful. 有关详细示例,请参考Spring Lemon的LemonWebSecurityConfig类以及各个模块的安全性包中的其他类,这可能会有所帮助。

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

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