我尝试为另一个应用程序登录Spring Boot应用程序并使用Spring Security生成令牌。我试图实现的目标:
@PreAuthorized
方法中的用户。是否可以在Spring Security中实现此目的,还是应该手动创建?我不知道如何使用Spring Security保存像Spring会话这样的令牌。
答案 0 :(得分:0)
我使用spring-boot-starter-parent version 1.5.7.RELEASE 。
我的方法不是一个完整的解决方案,但它可能对您有帮助。
您将能够发送用户/密码并获得一个SESSION cookie,然后可以进一步使用。
警告:
如果您已经在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服务器。