有没有一种方法可以配置Spring Security(使用Java配置)以仅保护自定义页面,甚至可以在注解上工作?Spring Security安全自定义页面
这个想法是,我想保证自定义调用如/admin
和其他东西(没有硬编码安全配置中的每个调用),它是在控制器中设置的提到的注释,但其他的东西不应该使用完全认证。
有没有一种方法可以配置Spring Security(使用Java配置)以仅保护自定义页面,甚至可以在注解上工作?Spring Security安全自定义页面
这个想法是,我想保证自定义调用如/admin
和其他东西(没有硬编码安全配置中的每个调用),它是在控制器中设置的提到的注释,但其他的东西不应该使用完全认证。
我很难找到适合我的东西。这是诀窍,它也是非常可读的。
@Override
protected void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests()
.antMatchers("/admin/**").access("hasRole('ADMIN')")
.antMatchers("/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin();
}
和满级对于那些谁仍然不能在同一网页上
package com.your.package.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.*;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
@Override
protected void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests()
.antMatchers("/admin/**").access("hasRole('ADMIN')")
.antMatchers("/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
{
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
}
}
注意,不是调用formLogin()
方法将使默认的“/登录”返回404错误。
我不知道这是否回答你的问题,但你可以使用ant的匹配来识别特定页面,而忽略其他人在你的安全配置,像这样:
.antMatchers("/**").permitAll()
或
.antMatcher("/admin/**")
.authorizeRequests()
.anyRequest().authenticated()
http://stackoverflow.com/questions/35633194/spring-security-configuration-for-basic-authentication-and-form-login/35634692#35634692在这里你可以找到两个工作的例子,也许它有帮助。 – Andrei
感谢您的回复。第二个版本是我需要的,但仍然是更多的硬编码(“/ admin/**”)。 但是最终的结果是来自系统的“另一面” - 我简单地为Controller定义添加了 @PreAuthorize(“hasRole('ROLE_ANONYMOUS')”) ,这帮助我导出了主要调用从那些我需要额外的安全。 –
如果要完全删除java配置类中的硬编码值,可以使用常量定义一个抽象类,如ADMIN_PATH =“/ admin /”,并将其用于控制器和安全配置中,或者甚至可以更好地定义它在属性文件中。 – Andrei