Spring Security - 自定义自动验证

时间:2012-09-18 14:01:51

标签: java spring spring-security

这是我的情景:

  • 一个网络应用程序为许多应用程序执行一种SSO
  • 登录用户而不是单击链接,应用程序发布了一个包含用户信息(名称,pwd [无用],角色)的文章,指向正确的应用程序
  • 我正在其中一个应用程序上实现SpringSecurity,以便从其功能(会话中的权限,其类提供的方法等)中受益。

所以,我需要开发一个自定义过滤器 - 我猜 - 它能够从请求中检索用户信息,从数据库检索,通过自定义 DetailsUserService ,进一步有关用户的信息(电子邮件等),然后根据从请求中检索到的角色对该用户进行身份验证。

我正在查看Pre-Authentication过滤器,但我不确定它是否是正确的选择。似乎这些对象在委托人已经在会话中时被使用,由一些先前的身份验证机制提出(是不是?)。

我认为,一旦确定了正确的过滤器,我应该在以下内容中执行:

GrantedAuthority[] ga= new GrantedAuthority[1];
ga[0] = new GrantedAuthorityImpl(myUser.getRole());

SecurityContext sc = SecurityContextHolder.getContext();
Authentication a = new UsernamePasswordAuthenticationToken(userName, userPwd, ga);
a = authenticationManager.authenticate(a);
sc.setAuthentication(a);

解决问题是否正确?你有建议帮我找到遗失的东西吗?

谢谢大家,

卢卡

此外:

嗨Xearxess!很抱歉再次打扰你,但似乎根据SpringSecurity 2.0.4翻译您的代码比我想象的更难:S问题是XML ...我尝试了不同的配置,但我总是遇到命名空间问题,缺少属性等等......

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:security="http://www.springframework.org/schema/security"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
              http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd">  

    <security:http>
        <security:intercept-url pattern="/**" access="isAuthenticated()" />
        <security:logout logout-url="/logout" logout-success-url="http://milan-ias-vs.usersad.everis.int/DMTest/" invalidate-session="true" />
        <security:custom-filter position="PRE_AUTH_FILTER" ref="preAuthenticatedProcessingFilter" />
    </security:http>

    <bean id="preAuthenticatedProcessingFilter" class="it.novartis.ram.authentication.PreAuthenticatedProcessingFilter">
        <custom-filter position="PRE_AUTH_FILTER"/>
        <property name="authenticationManager" ref="authenticationManager" />
    </bean>

    <bean id="preauthAuthProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
        <property name="preAuthenticatedUserDetailsService">
            <bean class="it.novartis.ram.authentication.PreAuthenticatedUserDetailsService" />
        </property>
    </bean>

    <security:authentication-manager alias="authenticationManager">
        <security:authentication-provider ref="preauthAuthProvider" />
    </security:authentication-manager>

</beans>

引用CUSTOM-FILTER元素的2行是两次不同的尝试,它们都被标记为错误。如何将过滤器的位置指定为属性?

auth manager定义的身份验证提供程序引用也标记为错误。我认为我也需要将它指定为属性,对吗?

希望你能给我最后的推动;) 再次感谢你,

卢卡

2 个答案:

答案 0 :(得分:19)

为了完整起见,在Spring Security 4中,事情略有改变。例如,强烈建议使用Java配置。通过这种方式,它可以更容易地与Spring Boot集成。

它遵循Java配置,等同于上面答案中给出的XML配置。

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(customAuthFilter(), AbstractPreAuthenticatedProcessingFilter.class)
            .authenticationProvider(preauthAuthProvider())
            .authorizeRequests()
            .anyRequest().authenticated();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(preauthAuthProvider());
    }

    @Bean
    public PreAuthenticatedAuthenticationProvider preauthAuthProvider() {
        PreAuthenticatedAuthenticationProvider preauthAuthProvider =
            new PreAuthenticatedAuthenticationProvider();
                preauthAuthProvider.setPreAuthenticatedUserDetailsService(
                    userDetailsServiceWrapper());
        return preauthAuthProvider;
    }

    @Bean
    public OnlyRolesPreAuthenticatedUserDetailsService userDetailsServiceWrapper() {
        OnlyRolesPreAuthenticatedUserDetailsService service =
            new MyPreAuthenticatedUserDetailsService();
        return service;
    }

    @Bean
    public MyPreAuthenticatedProcessingFilter customAuthFilter() throws Exception {
        MyPreAuthenticatedProcessingFilter filter = new MyPreAuthenticatedProcessingFilter();
        filter.setAuthenticationManager(authenticationManager());
        return filter;
    }
}

我认为上面的代码是值得的,因为互联网上的例子非常基础,Spring文档缺乏这些细节。

答案 1 :(得分:13)

是的,预身份验证方案正是您所需要的。

  

似乎这些对象预计会在校长时使用   已经在会议中,由一些以前的身份验证机制   (是不是?)。

实际上,您可以根据需要使用预身份验证从请求创建PreAuthenticatedAuthenticationToken。只需do few things I described in another question

首先扩展AbstractPreAuthenticatedProcessingFilter以从请求中获取用户名和角色:

public class MyPreAuthenticatedProcessingFilter
    extends AbstractPreAuthenticatedProcessingFilter {

  public MyPreAuthenticatedProcessingFilter(
      AuthenticationManager authenticationManager) {
    setAuthenticationDetailsSource(new MyAuthenticationDetailsSource());
  }

  @Override
  protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
    return "Anonymous";
  }

  @Override
  protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
    return "N/A";
  }

  public static class MyAuthenticationDetailsSource implements 
      AuthenticationDetailsSource<HttpServletRequest, MySessionUserDetails> {
    // roles probably should be encrypted somehow
    static final String ROLES_PARAMETER = "pre_auth_roles";

    @Override
    public MySessionUserDetails buildDetails(HttpServletRequest req) {
      // create container for pre-auth data
      return new MySessionUserDetails(req.getParameter(ROLES_PARAMETER));
    }
  }
}

MySessionUserDetails类会将spring分配给SimpleGrantedAuthority列表或任何其他GrantedAuthority实现。此外,建议使用列表,并且优于GrantedAuthority[]

其次,实施AuthenticationUserDetailsService

public class MyPreAuthenticatedUserDetailsService implements 
    AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> {

  @Override
  public UserDetails loadUserDetails(PreAuthenticatedAuthenticationToken token)
      throws UsernameNotFoundException {
    MySessionUserDetails sessionUserDetails =
        (MySessionUserDetails) token.getDetails();
    List<GrantedAuthority> authorities = sessionUserDetails.getAuthorities();
    return new User(token.getName(), "N/A", true, true, true, true, authorities);
  }
}

然后在你的XML连接块中:

<security:http use-expressions="true">
  <security:intercept-url pattern="/**" access="isAuthenticated()" />
  <security:custom-filter position="PRE_AUTH_FILTER"
      ref="myPreAuthenticationFilter" />
</security:http>

<bean id="myPreAuthenticationFilter"
    class="com.example.MyPreAuthenticatedProcessingFilter">
  <property name="authenticationManager" ref="authenticationManager" />
</bean>

<bean id="preauthAuthProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
  <property name="preAuthenticatedUserDetailsService">
    <bean class="com.example.MyPreAuthenticatedUserDetailsService" />
  </property>
</bean>

<security:authentication-manager alias="authenticationManager">
  <security:authentication-provider ref="preauthAuthProvider" />
</security:authentication-manager>

瞧!您应该在您的应用程序中使用经过身份验证的User委托人。

我在这里编写的代码需要Spring Security 3.1,如果您即将使用它,我强烈推荐它(它确实需要Spring 3.0.7+)。此外,Spring Security reference manual是您的朋友!