SpringSecurity - 自定义自动认证 [英] SpringSecurity - Custom automatic authentication

查看:22
本文介绍了SpringSecurity - 自定义自动认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的场景:

  • 一个网络应用程序为许多应用程序执行某种 SSO
  • 登录的用户点击链接后,该应用会向正确的应用发布包含用户信息(姓名、密码 [无用]、角色)的帖子
  • 我正在其中一个应用程序上实施 SpringSecurity 以从其强大功能(会话中的权限、其类提供的方法等)中受益

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

So, I need to develop a custom filter - I guess - that is able to retrieve user informations from request, retrieve from database, through a custom DetailsUserService, further information about the user (email, etc...) and then perform authentication of that user, according to the role retrieved from the request.

我正在查看预认证 过滤器,但我不确定它是否是正确的选择.当主体已经在会话中时,这些对象似乎应该被使用,由一些以前的身份验证机制放置(对吗?).

I was looking at Pre-Authentication filters, but I'm not sure that it is the right choice. It seems that those object are expected to be used when the principal is already in session, put by some previous authentication machanism (is it right?).

我认为,一旦确定了正确的过滤器,我应该需要执行以下操作:

I think that, once identified the correct filter, I should need to perform within something like:

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);

这是解决我的问题的正确方向吗?你有什么建议可以帮助我找到缺少的东西吗?

Is it the proper direction to solve my problem? Do you have suggestions to help me find what's missing?

谢谢大家,

卢卡

附加:

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

Hi Xearxess! Sorry to bother you again but it seems that the translation of your code according to SpringSecurity 2.0.4 is more difficult than I thought :S The problem is the XML... I tried different configuration but I ran always into namespace problems, missing attributes, etc...

<?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 行是两次不同的尝试,都签名为错误.如何将过滤器的位置指定为属性?

The 2 rows referencing CUSTOM-FILTER element are two different tries, both of them signed as error. How can I specify the position of my filter as a property?

关于身份验证管理器定义的身份验证提供程序引用也被标记为错误.我想我也需要像属性一样指定它,对吗?

Also the authentication provider reference on auth manager definition is marked as error. I think that I need to specify it like a property too, right?

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

Hope you can give me the last push ;) Thank you again,

卢卡

推荐答案

是的,预身份验证方案正是您正在寻找的.

Yes, Pre-Authentication Scenarios are exactly what you are looking for.

似乎这些对象应该在主体时使用已在会话中,由某些先前的身份验证机制放置(是吗?).

It seems that those object are expected to be used when the principal is already in session, put by some previous authentication machanism (is it right?).

不是真的,你可以使用预认证来创建 PreAuthenticatedAuthenticationToken 来自请求,如您所愿.只需做一些我在另一个问题中描述的事情.

Not really, you can use Pre-Authentication to create PreAuthenticatedAuthenticationToken from request, as you want. Just do few things I described in another question.

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

First extend AbstractPreAuthenticatedProcessingFilter to obtain username and roles from request:

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 实现.此外,推荐使用 List 并且优于 GrantedAuthority[].

MySessionUserDetails class will split spring with roles to List of SimpleGrantedAuthority or any other GrantedAuthority implementation. Also, List is recommended and superior to GrantedAuthority[].

二、实现AuthenticationUserDetailsS​​ervice:

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 中将块连接在一起:

Then in your XML connect blocks together:

<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 主体在您的应用程序中使用.

And voila! You should have authenticated User principal to use in your application.

我在这里编写的代码需要 Spring Security 3.1,如果您要使用它,我强烈建议您使用它(它确实需要 Spring 3.0.7+).另外,Spring Security 参考手册 是你的朋友!

Code I written here requires Spring Security 3.1 which I strongly recommend if you're about to using it (it does requrire Spring 3.0.7+). Also, Spring Security reference manual is your friend!

这篇关于SpringSecurity - 自定义自动认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆