Spring启动令牌身份验证

时间:2016-09-13 13:37:22

标签: java spring spring-security

我尝试为另一个应用程序登录Spring Boot应用程序并使用Spring Security生成令牌。我试图实现的目标:

  1. 将用户名和密码发送给REST控制器。
  2. 如果用户名和密码正常,我想生成30分钟到期时间的令牌并将其发回给用户。
  3. 令牌用于验证@PreAuthorized方法中的用户。
  4. 是否可以在Spring Security中实现此目的,还是应该手动创建?我不知道如何使用Spring Security保存像Spring会话这样的令牌。

1 个答案:

答案 0 :(得分:0)

我使用spring-boot-starter-parent version 1.5.7.RELEASE

我的方法不是一个完整的解决方案,但它可能对您有帮助。

您将能够发送用户/密码并获得一个SESSION cookie,然后可以进一步使用。

警告:

  • 您仍需要设置Cookie /令牌的到期时间。
  • 您需要自动执行登录过程 - 直接发送用户凭据(此方法提供login.html ...)。

如果您已经在pom中启用了 spring boot security

还添加以下内容以启用会话管理 redis作为HTTP会话存储(在您的pom中):

      <dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session</artifactId>
      </dependency>

      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
      </dependency> 

添加extends WebSecurityConfigurerAdapter的课程。您可能已经拥有:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true) // enable method-level authorization (@PreAuthorize("expression"))
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
     @Autowired
     public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("user").roles("USER").and()
                .withUser("admin").password("admin").roles("USER", "ADMIN");
     }

     @Override
     protected void configure(HttpSecurity http) throws Exception {
     http.authorizeRequests()
          .anyRequest().hasAnyRole("USER", "ADMIN").anyRequest().authenticated()
          .and()
          .httpBasic().disable();
  http
          .csrf().disable()
          .and()
          .formLogin()
          .usernameParameter("j_username")
          .passwordParameter("j_password")
          .loginPage("/login.html")
          .loginProcessingUrl("/j_spring_security_check")
          .defaultSuccessUrl("/#")
          .failureUrl("/loginNotSuccessfull.html")
          .permitAll();
}

我还有一个 redis 服务器作为HTTP会话存储(我刚刚使用redis:4-alpine图像和--protected-mode no以及--net=host启动了一个docker容器。) application.properties 中的以下属性:

spring.session.store-type=redis
spring.redis.host=localhost
spring.redis.port=6379

为了使其正常运行,我还添加了 HTTPSessionConfig 类来启用redis HTTP sessions

@EnableRedisHttpSession
public class HttpSessionConfig {

}

Spring引导处理所有必要的东西 - 将用户存储在redis中,检查SESSION等。

我希望这一切都按预期工作。

如果您有任何其他问题,请随时提出。

<强>更新

This link shows,如何使用嵌入式redis服务器。