我正在尝试将spring会话集成到我的spring安全应用程序中。当我这样做时,如果登录时出现错误(例如凭据错误),则登录页面无法显示实际错误。田野 SPRING_SECURITY_LAST_EXCEPTION
似乎被 Spring 会议抹去了。
我的相关代码都非常基本和标准。首先,我设置了httpsession注入:
@EnableJdbcHttpSession
public class HttpSessionConfig
{
@Bean("sessionDataSource")
public EmbeddedDatabase sessionDataSource()
{
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2).addScript("org/springframework/session/jdbc/schema-h2.sql").build();
}
@Bean
public PlatformTransactionManager transactionManager(@Qualifier("sessionDataSource") DataSource sessionDataSource)
{
return new DataSourceTransactionManager(sessionDataSource);
}
}
public class HttpSessionInitializer extends AbstractHttpSessionApplicationInitializer
{}
然后我将会话配置添加到主初始值设定项中,我需要按照中的示例这样做https://docs.spring.io/spring-session/docs/current/reference/html5/guides/java-security.html
public class TomcatInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
@Override
protected Class<?>[] getRootConfigClasses()
{
return new Class[] {<others>, WebSecurityConfig.class, HttpSessionConfig.class};
}
}
然后我有了我的spring安全设置(所有现有代码):
@Order(1)
public class WebSecurityInitializer extends AbstractSecurityWebApplicationInitializer
{
public WebSecurityInitializer()
{
super();
}
}
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{
@Override
protected void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests()
<various ant matchers>
.and().formLogin().loginPage("/login").permitAll()
}
}
你会注意到 @Order(1)
注解。我确实在某个地方读到,spring会话初始值设定项需要先执行,但如果我更改此顺序,则会立即出现错误:
19-Jun-2021 16:36:50.253 SEVERE [http-nio-8080-exec-1] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [dispatcher] in context with path [] threw exception
org.springframework.dao.TransientDataAccessResourceException: PreparedStatementCallback; SQL [INSERT INTO SPRING_SESSION (PRIMARY_ID, SESSION_ID, CREATION_TIME, LAST_ACCESS_TIME, MAX_INACTIVE_INTERVAL, EXPIRY_TIME, PRINCIPAL_NAME) VALUES (?, ?, ?, ?, ?, ?, ?)]; (conn=8) No database selected; nested exception is java.sql.SQLTransientConnectionException: (conn=8) No database selected
at org.springframework.jdbc.support.SQLExceptionSubclassTranslator.doTranslate(SQLExceptionSubclassTranslator.java:70)
最后是我使用thymeleaf的登录屏幕:
<div th:if="${session.SPRING_SECURITY_LAST_EXCEPTION} != null and ${param.error}">
<p class="text-danger">[[${session.SPRING_SECURITY_LAST_EXCEPTION.message}]]</p>
</div>
<div th:if="${param.error}">
<p class="text-danger">An error that we couldn't see</p>
</div>
``` `session.SPRING_SECURITY_LAST_EXCEPTION` 始终计算为null,因此显示错误的错误消息。在将spring会话添加到构建之前,没有发生这种情况。我感觉由于登录失败,spring会话正在清除会话信息。我只是在出错时使用基本的重定向登录 `/login?error` 它使用所有标准的内部Spring类。有什么想法吗?
暂无答案!
目前还没有任何答案,快来回答吧!