@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
MyUserDetailsService myUserDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/index").permitAll();
http.authorizeRequests().antMatchers("/main").permitAll();
http.formLogin().loginPage("/login").permitAll().successHandler(successHandler());
http
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); // Session is STATELESS
}我将spring security sessionpolicy设置为STATLESS
因为我使用JWT,所以无状态会更好,但无状态会导致一个问题
在胸腺叶中显示认证对象是不可能的
<h1>[[${#authentication }]]</h1>如果我更改了会话策略,我可以显示身份验证对象
但这不是我想要的
总之
当spring的会话策略是无状态时,我可以将身份验证对象与胸腺叶一起使用吗
发布于 2020-10-20 04:37:41
基于表单的登录需要会话,因此标记为无状态将意味着用户不可用。您可能会看到这个页面,因为它被标记为permitAll,这意味着不需要用户来查看它。
要解决这个问题,您可以切换到一种也是无状态的身份验证形式(即,它包含在每个请求中)。例如:
// @formatter:off
http
.authorizeRequests()
.mvcMatchers("/index", "/main").permitAll()
.and()
.httpBasic()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// @formatter:on我也不确定主题叶模板使用的语法。对于我来说,我使用了这样的东西:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Test</title>
</head>
<body>
<h1 th:text="${authentication?.name}"></h1>
</body>
</html>然后,我使用以下代码将Authentication公开为模型属性:
@Controller
public class IndexController {
@GetMapping("/")
String index() {
return "index";
}
@ModelAttribute
Authentication authentication(Authentication authentication) {
return authentication;
}
}我有一个测试来验证它的工作。
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class DemoApplicationTests {
@Autowired
TestRestTemplate rest;
@Test
void indexWhenAnonymous() throws Exception{
ResponseEntity<String> result = rest.exchange(RequestEntity.get(URI.create("/")).build(), String.class);
assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(result.getBody()).doesNotContain("user");
}
@Test
void indexWhenAuthenticated() throws Exception{
ResponseEntity<String> result = rest.exchange(RequestEntity.get(URI.create("/")).headers(h -> h.setBasicAuth("user", "password")).build(), String.class);
assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(result.getBody()).contains("user");
}
}您可以在https://github.com/rwinch/spring-security-sample/tree/display-auth-stateless-thymeleaf上找到完整的示例,它允许使用用户名user和密码password登录。
https://stackoverflow.com/questions/64429464
复制相似问题