我正在尝试使用JavaConfig代替Spring配置的XML配置.我想@PreAuthorization用于声明访问权限.
我的Spring Security Config看起来像这样:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity( prePostEnabled = true )
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void registerAuthentication( AuthenticationManagerBuilder auth ) throws Exception {
auth
.inMemoryAuthentication()
.withUser( "user" ).password( "password" ).roles( "USER" );
}
}
Run Code Online (Sandbox Code Playgroud)
但是,这不起作用.部署Web应用程序后,我收到错误消息Error creating bean with name 'methodSecurityInterceptor' defined in class path resource.
经过一些研究,我发现我必须将aopalliance库添加到我的项目中.不幸的是,这并没有解决我的问题.
这是完整的堆栈跟踪:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'methodSecurityInterceptor' defined in class path resource [org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method …Run Code Online (Sandbox Code Playgroud) spring spring-security pre-authentication spring-java-config
如何使用javaconfig(无XML)专门为摘要式身份验证配置Spring 4.0和Spring Security(3.2.0)?我正在使用下面的配置类,但所有请求都被HTTP 401拒绝,"Nonce应该产生两个令牌,但是(...消息就在那里停止)".
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfigurationDigest extends WebSecurityConfigurerAdapter
{
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
{
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests().antMatchers("/**").authenticated().and().addFilter(digestAuthenticationFilter(digestEntryPoint()));
}
@Override
@Bean
public UserDetailsService userDetailsServiceBean() throws Exception
{
return super.userDetailsServiceBean();
}
public DigestAuthenticationFilter digestAuthenticationFilter(DigestAuthenticationEntryPoint digestAuthenticationEntryPoint) throws Exception
{
DigestAuthenticationFilter digestAuthenticationFilter = new DigestAuthenticationFilter();
digestAuthenticationFilter.setAuthenticationEntryPoint(digestEntryPoint());
digestAuthenticationFilter.setUserDetailsService(userDetailsServiceBean());
return digestAuthenticationFilter;
}
@Bean
public DigestAuthenticationEntryPoint digestEntryPoint()
{
DigestAuthenticationEntryPoint digestAuthenticationEntryPoint = new DigestAuthenticationEntryPoint();
digestAuthenticationEntryPoint.setKey("mykey");
digestAuthenticationEntryPoint.setRealmName("myrealm");
return digestAuthenticationEntryPoint;
}
}
Run Code Online (Sandbox Code Playgroud)
我试图通过包含标题在客户端授权: …
java spring spring-security digest-authentication spring-java-config
我使用dao身份验证和自定义身份验证过滤器搜索了Spring安全示例,但是我发现,所有示例都使用xml文件配置,
我的问题是如何配置自定义过滤器,即UsernamePasswordAuthenticationFilter
我的基于xml的securityConfig文件如下所示:
<http auto-config="false" use-expressions="true">
<intercept-url pattern="/" access="permitAll" />
<intercept-url pattern="/auth/login.html" access="permitAll" />
<intercept-url pattern="/auth/logout.html" access="permitAll" />
<intercept-url pattern="/auth/accessDenied.html" access="permitAll" />
<intercept-url pattern="/admin/**" access="hasAnyRole('ROLE_ADMIN')" />
<intercept-url pattern="/user/**" access="hasAnyRole('ROLE_USER','ROLE_ADMIN')" />
<access-denied-handler error-page="/auth/accessDenied.html"/>
<form-login login-page='/auth/login.html'
default-target-url="/"
authentication-success-handler-ref="myAuthenticationSuccessHandler"
authentication-failure-url="/auth/loginfailed.html" />
<logout success-handler-ref="myLogoutSuccessHandler"
invalidate-session="true" delete-cookies="JSESSIONID" />
<remember-me key="uniqueAndSecret" token-validity-seconds="86400" />
<session-management session-fixation-protection="migrateSession"
session-authentication-error-url="/auth/loginfailed.html">
<concurrency-control max-sessions="1"
error-if-maximum-exceeded="true"
expired-url="/auth/login.html"
session-registry-alias="sessionRegistry"/>
</session-management>
</http>
<beans:bean id="myAuthenticationSuccessHandler"
class="com.asn.handler.AsnUrlAuthenticationSuccessHandler" />
<beans:bean id="myLogoutSuccessHandler"
class="com.asn.handler.AsnLogoutSuccessHandler" />
<beans:bean id="userDetailsService" class="com.asn.service.UserDetailsServiceImpl"/>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="userDetailsService">
<password-encoder ref="encoder"/>
</authentication-provider>
<!-- <authentication-provider>
<user-service>
<user …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用java-config在spring批处理中配置Flow,这个流程基本上必须这样做:
执行init步骤(在数据库中添加记录),
然后执行一个decider来检查文件是否存在,
2.1.如果文件存在,它将执行加载作业(这是一个并行的一堆步骤的另一个流程)
我尝试进行此配置,但完成步骤永远不会运行:
Flow flow = new FlowBuilder<SimpleFlow>("commonFlow")
.start(stepBuilderFactory.get("initStep").tasklet(initTasklet).build())
.next(decider)
.on(FlowExecutionStatus.COMPLETED.getName())
.to(splitFlow)
.from(decider).on("*")
.end()
.next(stepBuilderFactory.get("finishStep").tasklet(finishTasklet).build())
.end();
Run Code Online (Sandbox Code Playgroud)
我可以让它按照下面的方式工作,但它根本不优雅:
Step finishStep = stepBuilderFactory.get("finishStep").tasklet(finishTasklet).build();
Flow flow = new FlowBuilder<SimpleFlow>("commonFlow")
.start(stepBuilderFactory.get("initStep").tasklet(initTasklet).build())
.next(decider)
.on(FlowExecutionStatus.COMPLETED.getName())
.to(splitFlow)
.next(finishStep)
.from(decider).on("*")
.to(finishStep)
.end();
Run Code Online (Sandbox Code Playgroud)
有人知道在使用java-config做出决定后执行步骤的正确方法是什么?
如何在java配置中用自定义过滤器替换默认过滤器?在 XML 中,例如:
<bean id="myFilter" class="lalalal.MyFilter">
<property name="authenticationManager" ref="authenticationManager"/>
</bean>
<security:http auto-config="true">
<security:custom-filter ref="myFilter" position="FORM_LOGIN_FILTER"/>
</security:http>
Run Code Online (Sandbox Code Playgroud)
关于 filterBefore、filterAfter 和默认过滤器继承我知道。
我将旧的xml/java配置转换为纯java配置.在xml中,我使用参数注入配置文件,如下所示:
<bean class="com.project.SpringRestConfiguration">
<property name="parameters" ref="parameters" />
</bean>
@Configuration
public class SpringRestConfiguration {
private Parameters parameters;
public void setParameters(Parameters parameters) {
this.parameters = parameters;
}
// @Bean definitions
...
}
Run Code Online (Sandbox Code Playgroud)
是否可以在javaconfig中注入参数?(无需使用自动装配!)
@Configuration
@Import(SpringRestConfiguration.class)
Run Code Online (Sandbox Code Playgroud)
编辑:使用@Import,我看不到有任何机会将参数注入SpringRestConfiguration
我正在关注Spring LDAP项目的示例,并尝试将xml配置转换为Java Configuration.
我正在尝试在LDAP服务器上执行CRUD操作.
我能够弄清楚以下几点,
这是应用程序的xml配置,我希望将其转换为Java Config.
<context:property-placeholder location="classpath:/ldap.properties"
system-properties-mode="OVERRIDE" />
<context:annotation-config />
<ldap:context-source id="contextSource" password="${sample.ldap.password}"
url="${sample.ldap.url}" username="${sample.ldap.userDn}" base="${sample.ldap.base}" />
<ldap:ldap-template id="ldapTemplate"
context-source-ref="contextSource" />
<!-- This will scan the org.springframework.ldap.samples.useradmin.domain
package for interfaces extending CrudRepository (in our case, LdapRepository),
automatically creating repository beans based on these interfaces. -->
<ldap:repositories base-package="com.cazysystems.appstore.model" />
<!-- This one will never be referenced directly, but the ldap:repositories
tag will make sure it will be 'wired in', because …Run Code Online (Sandbox Code Playgroud) 我有一个 bean,它实现了 ServletContextAware 和 BeanFactoryPostProcessor 接口。我需要在 ServletContext 完成初始化后将这个 bean 注册到 applicationContext 中,因为我使用了 servletContext 中的一些参数来初始化这个 bean。
我使用的是 Spring Boot,bean 名称是 SpringBeanProcessorServletAware。我已将其添加到配置 bean 中。
@Bean
public static SpringBeanProcessorServletAware springBeanProcessor() {
SpringBeanProcessorServletAware p = new SpringBeanProcessorServletAware();
return p;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是 bean 是在我的容器将servletContext设置为它之前创建的。然后我无法从servletContext获取参数。如何控制在我的servletContext完全创建后必须创建 bean ?
我正在使用基于Java的Spring Security。我已经创建了自定义访问决策投票人impl。
但是,当我运行该应用程序时,无法打开登录页面,因为它显示访问被拒绝。
在我添加了自定义访问决策投票人impl之后,就发生了这种情况。我猜问题是由于自定义AccessDecisionVoter中的以下代码。
if(authentication instanceof AnonymousAuthenticationToken)
return ACCESS_DENIED;
Run Code Online (Sandbox Code Playgroud)
但是我需要这样做,以便不检查未登录用户的权限。
它进入无限循环,登录页面,访问决策投票者,访问被拒绝,登录页面等等。
下面是spring安全配置代码。
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private AffirmativeBased accessDecisionManager;
@Bean
@Autowired
public AffirmativeBased accessDecisionManager(AccessDecisionVoterImpl accessDecisionVoter) {
List<AccessDecisionVoter<?>> accessDecisionVoters = new ArrayList<AccessDecisionVoter<?>>();
accessDecisionVoters.add(accessDecisionVoter);
AffirmativeBased accessDecisionManager = new AffirmativeBased(accessDecisionVoters);
return accessDecisionManager;
}
@Override
@Autowired
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder(){
PasswordEncoder passwordEncoder = new PasswordEncoder();
passwordEncoder.setStringDigester(stringDigester());
return passwordEncoder;
}
@Bean …Run Code Online (Sandbox Code Playgroud) java spring spring-security access-denied spring-java-config
具有以下弹簧安全配置:
http.antMatcher("/**/v1/public/company/employees/**")
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**/v1/public/company/employees/A").permitAll()
.antMatchers(HttpMethod.POST, "/**/v1/public/company/employees/B").permitAll()
.antMatchers("/**/v1/public/company/employees/**")
.authenticated()
.and()
.csrf()
.disable()
.addFilterBefore(customFilter, AbstractPreAuthenticatedProcessingFilter.class);
Run Code Online (Sandbox Code Playgroud)
如何从中排除公共端点(A和B)customFilter?
更新资料
使用方法:
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**/v1/public/company/employees/A")
.antMatchers(HttpMethod.POST, "/**/v1/public/company/employees/B")
}
Run Code Online (Sandbox Code Playgroud)
似乎足够,但我仍然不知道这是否是推荐的方式