我正在制作一个Spring MVC Web应用程序。我有一个登录页面和一个仪表板页面。任何试图访问仪表板JSP的人都必须登录:
这是我的Spring Security配置:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity
@Import({SpringConfiguration.class})
public class SecurityContext extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
// authorizeRequests() -> use-expresions = "true"
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/createaccount","/error", "/register", "/login", "/newaccount", "/resources/**").permitAll()
.antMatchers("/**", "/*", "/").authenticated()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/dashboard")
.loginProcessingUrl("/j_spring_security_check")
.usernameParameter("username")
.passwordParameter("password")
.failureUrl("/login?error=true")
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login")
.invalidateHttpSession(true)
.and()
.csrf();
// Upon starting the application, it prints the asdfasdf so I know the SecurityContext is loaded
System.out.println("asdfasdf");
}
// Equivalent of jdbc-user-service in XML
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery("SELECT username, password, enabled FROM Users WHERE username=?")
.authoritiesByUsernameQuery("SELECT username, authority FROM authorities where username=?");
}
}
正如您所看到的,我有一些允许任何人访问的端点,例如/login
,/register
,但所有其他网址都要求对其进行身份验证。当我启动应用程序时,如果我尝试转到仪表板页面,我可以正常访问它而无需登录,这不是我想要的。
我的问题是,如果他们未登录/验证,我希望尝试访问仪表板的人员被发送到登录页面。
我试图完全避免使用XML并且仅使用Java来配置我的应用程序,是否有人知道我做错了什么?我几乎可以肯定我的SecurityContext出了问题。
我可能还包括我正在尝试转换为Java配置样式的上下文XML
<security:authentication-manager>
<security:jdbc-user-service
data-source-ref="dataSource"
users-by-username-query="select username, password, enabled from Users where username=?"
authorities-by-username-query="select username, authority from Authority where username =? " />
</security:authentication-provider>
</security:authentication-manager>
<security:http use-expressions="true">
<security:intercept-url pattern="/newaccount"
access="permitAll" />
<security:intercept-url pattern="/accountcreated"
access="permitAll" />
<security:intercept-url pattern="/createaccount"
access="permitAll" />
<security:intercept-url pattern="/error"
access="permitAll" />
<security:intercept-url pattern="/resources/**"
access="permitAll" />
<security:intercept-url pattern="/login"
access="permitAll" />
<security:intercept-url pattern="/setemote"
access="isAuthenticated()" />
<security:intercept-url pattern="/**"
access="isAuthenticated()" />
<security:intercept-url pattern="/*"
access="isAuthenticated()" />
<security:form-login login-page="/login"
default-target-url="/" login-processing-url="/j_spring_security_check"
username-parameter="username" password-parameter="password"
authentication-failure-url="/login?error=true" />
<security:csrf />
</security:http>