0

我想使用自定义身份验证提供程序将 spring 安全性(使用 Java 配置)添加到我的应用程序中,但是我无法使其工作。似乎 authenticationProvider 配置不正确,因为我无法调试到方法 authenticate(Authentication) 中,并且 println 不打印任何内容。每个请求都以 403 响应。

请任何人都可以帮助我解决这个问题,整个周末我都对此感到震惊。

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().authenticated();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(new AuthenticationProvider(){

            @Override
            public Authentication authenticate(Authentication arg0) throws AuthenticationException {
                System.out.println("authenticating...");
                return arg0;
            }

            @Override
            public boolean supports(Class<?> arg0) {
                return true;
            }

         });
    }
}
4

1 回答 1

1

如果身份验证成功,该类的 authenticate() 函数必须返回一个 UsernamePasswordAuthenticationToken 实例,否则返回 null。

**

org.springframework.security.authentication.ProviderManager 和配置是(设置它的提供者)自定义 org.springframework.security.authentication.AuthenticationProvider;这应该在其身份验证方法上返回一个身份验证,它应该使用 GrantedAuthority 进行设置

**

这是一个示例身份验证管理器代码,它设置权限并返回一个身份验证对象。

您可以尝试注入您拥有的 customAUthenticationProvider 类,然后在 configure 方法中使用它吗?

@Autowired
private CustomAuthenticationProvider customAuthenticationProvider;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(customAuthenticationProvider);
}

是否为 Spring 安全性准备了 Web xml 映射?

   <listener>
   <listener-class>
    org.springframework.web.context.ContextLoaderListener
   </listener-class>
 </listener>

 <!-- use the springSecurityFilterChain -->
<filter>

          <filter-name>springSecurityFilterChain</filter-name>

        <filter-      class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
   <!-- NOTE This does not specify its own configuration it is
     loaded by the ContextLoaderListener instead -->

   <!-- NOTE by default the filter name is used to
     look up the Spring Security Filter Chain if you like you
     can use any filter name you want, but you must specify
     the bean name instead in this instance. Since we use the
     springSecurityFilterChain as the filter name this is not
     necessary
<init-param>
    <param-name>targetBeanName</param-name>
    <param-value>springSecurityFilterChain</param-value>
</init-param> -->
</filter>
<filter-mapping>
   <filter-name>springSecurityFilterChain</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

这是一个示例 Spring 安全项目:https ://github.com/spring-projects/spring-security-javaconfig

于 2015-03-08T12:46:31.680 回答