关于Spring.io官网Spring Session Restful example的问题

问题描述

当使用SpringBoot提供Restful接口服务时,可以非常方便快速地通过SpringBoot来发布。然而需要考虑的问题:

  • 使用安全机制
  • 使用外在数据库保存session

针对安全机制,官网提供了一个demo:
官网demo地址为:http://docs.spring.io/spring-session/docs/current/reference/html5/guides/rest.html
然而该demo,还是存在两个问题:

  • 每次authentication都不能正常验证
  • 该demo使用而是嵌入式的redis server数据库

解决方案

添加外在Redis数据库

在src/main/resources/application.properties 添加如下配置内容:

# REDIS (RedisProperties)
spring.redis.host=10.10.2.176
spring.redis.port=6379
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1

这样就可以在代码中设置Redis Server的地址和端口了。
代码结构如下:
这里写图片描述
具体代码如下,我对HttpSessionConfig.java获取Redis Server的部分进行了更改,从而可以使用external redis server。此外对我build.gradle的security依赖部分进行了改动,如下所示:

    // security related
    compile('org.springframework.boot:spring-boot-starter-security:1.2.2.RELEASE')
    //compile('org.springframework.security:spring-security-config:3.2.6.RELEASE')
    //compile('org.springframework.security:spring-security-web:3.2.6.RELEASE')

HttpSessionConfig.java

package org.wshare.wsdc.config.session;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.session.Session;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.http.HeaderHttpSessionStrategy;
import org.springframework.session.web.http.HttpSessionStrategy;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * org.wshare.wsdc.config
 * Created by shun
 * 2015/3/19.
 */

@Configuration
@EnableRedisHttpSession
public class HttpSessionConfig {
    @Autowired
    ApplicationContext applicationContext;

    @Bean
    public JedisConnectionFactory connectionFactory() {
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
        String redisHost = applicationContext.getEnvironment().getProperty("spring.redis.host");
        String redisPort = applicationContext.getEnvironment().getProperty("spring.redis.port");
        jedisConnectionFactory.setHostName(redisHost);
        jedisConnectionFactory.setPort(Integer.parseInt(redisPort));
        return jedisConnectionFactory;
    }

    @Bean
    public HttpSessionStrategy httpSessionStrategy() {
        return new HeaderHttpSessionStrategy();
    }
}

HttpSessionInitializer.java

package org.wshare.wsdc.config.session;

import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer;
import org.wshare.wsdc.config.session.HttpSessionConfig;

/**
 * org.wshare.wsdc.config
 * Created by shun
 * 2015/3/19.
 */

public class HttpSessionInitializer extends AbstractHttpSessionApplicationInitializer {
    // this will help initialize and load HttpSessionConfig class, this ensures that out
    // servlet container (ie. tomcat) uses the springSessionRepositoryFilter for every
    // request
    public HttpSessionInitializer() {
        super(HttpSessionConfig.class);
    }
}

SecurityConfig.java

/*
 * Copyright 2002-2014 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.wshare.wsdc.config.session;

/**
 * @author Rob Winch
 */

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .httpBasic();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}

SecurityInitializer.java

/*
 * Copyright 2002-2014 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.wshare.wsdc.config.session;

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

/**
 * @author Rob Winch
 */
public class SecurityInitializer extends
        AbstractSecurityWebApplicationInitializer {

}

mvc/MvcConfig.java

/*
 * Copyright 2002-2014 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.wshare.wsdc.config.session.mvc;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

/**
 * @author Rob Winch
 */
@Configuration
@EnableWebMvc
@ComponentScan
public class MvcConfig {
}

mvc/MvcInitializer.java

/*
 * Copyright 2002-2014 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.wshare.wsdc.config.session.mvc;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import org.wshare.wsdc.config.session.HttpSessionConfig;
import org.wshare.wsdc.config.session.SecurityConfig;

/**
 * @author Rob Winch
 */
public class MvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    // tag::config[]
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] {SecurityConfig.class, HttpSessionConfig.class};
    }
    // end::config[]

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { MvcConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值