【问题标题】:Spring Security Token Authentication + JSESSIONSpring Security 令牌认证 + JSESSION
【发布时间】:2015-10-12 18:48:48
【问题描述】:

除了传统的基于 cookie / JSESSION 的身份验证之外,是否可以使用基于令牌(无状态)的身份验证?

场景:

应用程序已经有一个现有的 Spring MVC + Thymeleaf 实现,用作管理/超级用户门户。当你登录时,你会得到一个 JESSIONID。我们需要使用 Jersey (JAX-RS) 创建一个 RESTful API 以供客户端使用。它必须是无国籍的。本质上,我们仍然需要 Spring MVC + Thymeleaf 部分,但现在需要公开一个使用无状态身份验证的 API 以供使用。这对 Spring Security 可行吗?

【问题讨论】:

    标签: java spring spring-mvc spring-security


    【解决方案1】:

    Spring Security 支持在同一个应用程序中进行多种配置。例如,假设无状态服务完全位于 URL /api/ 下。您可以为XML based configuration 使用以下大纲:

    <http pattern="/api/**" create-session="stateless">
        <intercept-url pattern="/**" access="hasRole('ADMIN')" />
        <http-basic />
    </http>
    
    <http>
        <intercept-url pattern="/**" access="authenticated" />
        <form-login login-page="/login" default-target-url="/home.htm"/>
        <logout />
    </http>
    

    Java Configuration

    @EnableWebSecurity
    public class MultiHttpSecurityConfig {
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) { 1
            auth
                .inMemoryAuthentication()
                    .withUser("user").password("password").roles("USER").and()
                    .withUser("admin").password("password").roles("USER", "ADMIN");
        }
    
        @Configuration
        @Order(1)                                                        2
        public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
            protected void configure(HttpSecurity http) throws Exception {
                http
                    .antMatcher("/api/**")                               3
                    .authorizeRequests()
                        .anyRequest().hasRole("ADMIN")
                        .and()
                    .httpBasic();
            }
        }
    
        @Configuration                                                   4
        public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
    
            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http
                    .authorizeRequests()
                        .anyRequest().authenticated()
                        .and()
                    .formLogin();
            }
        }
    }
    

    【讨论】:

    • 哇,太好了,我不知道你能做到这一点,这会很好。我在想我将不得不拆分为多个生成两个 WAR 文件的 maven 模块。这好多了。
    猜你喜欢
    • 2013-08-10
    • 2014-04-04
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 1970-01-01
    • 2016-03-22
    相关资源
    最近更新 更多