Spring-security / Grails应用程序-未调用自定义WebSecurity配置

时间:2019-02-08 15:55:06

标签: authentication grails spring-security oauth-2.0 servlet-filters

我的项目基于Grail 2.5.6和Spring插件。我正在尝试创建自定义身份验证提供程序,过滤器和令牌,以扩展它们各自的基本类。

this.getAuthenticationManager().authenticate(authRequest)

在我的过滤器中,身份验证管理器始终为null。因此,它不能在null对象上引发authenticate()引发。当我在authenticationManager上调试时,它列出了其他提供程序名称,但我的自定义名称除外。

这是我的自定义网络安全配置

@Configuration
@EnableGlobalMethodSecurity(securedEnabled=true)
public class CustomWebSecurityConfig extends WebSecurityConfigurerAdapter {

OrbisAuthenticationProvider orbisAuthenticationProvider

public CustomWebSecurityConfig() {
    super()

    log.debug "configure custom security"
    print("configure custom security")
}

@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    print("configure method 1")
    log.debug "configure method 1"
    auth.authenticationProvider(orbisAuthenticationProvider)
}

@Bean(name= BeanIds.AUTHENTICATION_MANAGER)
@Override
AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean()
}

@Bean
OrbisAuthenticationFilter orbisAuthenticationProvider() throws Exception {
    log.debug "orbis Authentication provider"
    OrbisAuthenticationProvider orbisAuthenticationProvider = new OrbisAuthenticationProvider(authenticationManagerBean())
    return orbisAuthenticationProvider
}

@Bean
@Autowired
public OrbisAuthenticationFilter orbisAuthenticationFilter() throws Exception {

    print("configure orbis filtr")

    OrbisAuthenticationFilter oaf = new OrbisAuthenticationFilter()
    oaf.setAuthenticationManager(authenticationManagerBean())
    oaf.setFilterProcessesUrl("j_orbis_security_check")
    oaf.setUsernameParameter("email")
    oaf.setPasswordParameter("password")

    oaf.setAuthenticationSuccessHandler(new SavedRequestAwareAuthenticationSuccessHandler()
            .setDefaultTargetUrl("/oauth/authorize"))

    oaf.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler()
            .setDefaultFailureUrl("/loginWithOrbis"))

    oaf.afterPropertiesSet()

    return oaf
}

}

在调试时,似乎没有任何这些方法被调用。注释似乎不足以引起注意。我也尝试过@ComponentScan。

我是否必须将此安全配置注入某处?如何在过滤器中使用authManager?

OrbisAuthFilter

class OrbisAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

//    @Autowired
OrbisAuthenticationProvider orbisAuthenticationProvider

OrbisAuthenticationFilter() {
    super("/j_orbis_security_check")

    orbisAuthenticationProvider = new OrbisAuthenticationProvider()

}

void afterPropertiesSet() {
    assert authenticationManager != null, 'authenticationManager must be specified'
}

@Override
Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    String username = request.getParameter("email")
    String password = request.getParameter("password")
    String accessCode = request.getParameter("accessCode")
    OrbisAuthenticationToken authRequestForAuthentication = new OrbisAuthenticationToken(username, password, accessCode)

    // This throws error because getAuthenticationManager returns null
    // authRequestForAuthentication = this.getAuthenticationManager.authenticate(authRequestForAuthentication)

    //This works if I instantiate the orbis provider object in the constructor
    authRequestForAuthentication = this.orbisAuthenticationProvider.authenticate(authRequestForAuthentication)

    SecurityContextHolder.getContext().setAuthentication(authRequestForAuthentication)
    return authRequestForAuthentication
}

protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) {
    authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
}

@Override
@Autowired
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
    super.setAuthenticationManager(authenticationManager);
    }
}

OrbisAuthProvider

class OrbisAuthenticationProvider implements AuthenticationProvider {

@Override
Authentication authenticate(Authentication authentication) throws AuthenticationException {

    OrbisAuthenticationToken orbisAuth = (OrbisAuthenticationToken) authentication

    String username = orbisAuth.principal
    String password = orbisAuth.credentials
    String orbisAccessCode = orbisAuth.orbisAccessCode
    def urlToUse = 'https://coopstatus.neu.edu/sail_api/full.aspx?' + 'ac=' + orbisAccessCode + '&e='+ username + '&p=' + password
    HttpClient httpClient = DefaultHttpClient.newInstance()
    HttpGet getRequest = new HttpGet(urlToUse)
    HttpResponse httpResponse = httpClient.execute(getRequest)

    JSONObject orbisResponse = new JSONObject(httpResponse.getEntity().getContent().getText())

//        if(orbisResponse.get("IsFound")) {
//            //Return error not authenticated
//        }

    Collection<GrantedAuthority> orbisUserGrantedAuthorities = getLDAPUserAuthorities(orbisResponse.get("Email"))
    orbisAuth = new OrbisAuthenticationToken(username, password, orbisAccessCode, orbisUserGrantedAuthorities)

    return orbisAuth
}

private Collection<GrantedAuthority> getLDAPUserAuthorities(String username) {
    LDAPUserDetails currentLdapUserDetails
    try {
        currentLdapUserDetails = new LDAPUserDetailsService().loadUserByOrbisUsername(username)
        log.debug currentLdapUserDetails
    } catch(org.springframework.security.core.userdetails.UsernameNotFoundException e) {
        log.error("User " + username + " not found in ldap", e)
    }

    Collection<GrantedAuthority> authorities = new ArrayList<>()
    for (String authority : currentLdapUserDetails.authorities) {
        authorities.add(new SimpleGrantedAuthority(authority))
    }

    return authorities
}

@Override
public boolean supports(Class<?> authentication) {
    return (OrbisAuthenticationToken.class
            .isAssignableFrom(authentication));
}
}

Resources.groovy

import edu.neu.security.OrbisAuthenticationFilter
import edu.neu.security.OrbisAuthenticationProvider
beans = {
    userDetailsService(edu.neu.security.LDAPUserDetailsService)

    orbisAuthenticationProvider(OrbisAuthenticationProvider)

    orbisAuthenticationFilter(OrbisAuthenticationFilter) {
        orbisAuthenticationProvider = ref("orbisAuthenticationProvider")
        requiresAuthenticationRequestMatcher = ref('filterProcessUrlRequestMatcher')
    // This throws error during startup. Unable to init bean 
    // authenicationManager = ref("authenicationManager")
}

    myOAuth2ProviderFilter(OAuth2ProviderFilters) {
      //grailsApplication = ref('grailsApplication')
      // properties
    }
}

我遵循了该项目中的一些概念:https://github.com/ppazos/cabolabs-ehrserver/

即使执行了整个过程并使用身份验证设置了securityContext,当我按oauth / authorize获取Authorization_Code时,它也会重定向回'/ login / auth'。仍然不知道用户已通过身份验证。

1 个答案:

答案 0 :(得分:0)

将身份验证提供程序添加到AuthenticationManagerBuilder bean(来自AuthenticationConfiguration)时,将不会使用您声明的身份验证管理器bean。

尝试:

@Configuration
@EnableGlobalMethodSecurity(securedEnabled=true)
public class CustomWebSecurityConfig {

    OrbisAuthenticationProvider lwoAuthProvider;

    public CustomWebSecurityConfig() {
        //
    }


    @Bean(name= BeanIds.AUTHENTICATION_MANAGER)
    AuthenticationManager authenticationManagerBean() throws Exception {
        return new ProviderManager(Arrays.asList(lwoAuthProvider));

}

您的AuthenticationManager bean应该被拾取并将用于方法安全性。如果它是由Spring管理的,也可以在过滤器中@Autowire进行过滤,也可以在实例化过滤器的@Autowire类中的@Configuration进行过滤。

注意:上面的类不会创建任何Spring Security过滤器。 (无论如何都没有创建过滤器链-您没有使用@EnableWebSecurity注释您的类)