[英]Spring boot token authentication
我試圖登錄另一個應用程序的Spring Boot應用程序並使用Spring Security生成令牌。 我想要達到的目標:
@PreAuthorized
方法中驗證用戶。 是在Spring Security中實現這一目標的方法還是應該手動進行? 我不知道如何使用Spring Security保存像Spring session這樣的令牌。
我使用spring-boot-starter-parent版本1.5.7.RELEASE 。
我的方法不是完整的解決方案,但可能會對您有所幫助。
您將能夠發送用戶/密碼並獲得SESSION cookie,然后可以將其進一步使用。
警告:
如果您已經在pom中啟用了spring boot安全性 。
還添加以下內容以啟用會話管理並將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會話 :
@EnableRedisHttpSession
public class HttpSessionConfig {
}
Spring Boot處理所有必要的東西-將用戶存儲在Redis中,檢查SESSION等。
我希望一切都按預期進行。
如果您還有其他問題,請隨時提問。
更新:
該鏈接顯示了如何使用嵌入式Redis服務器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.