栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

SpringSecurity-自定义自动身份验证

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringSecurity-自定义自动身份验证

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

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

并非如此,您可以根据需要使用预身份验证

PreAuthenticatedAuthenticationToken
从请求中创建。只是做我的另外一个问题说明几件事情。

首先扩展

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拆分为List of
SimpleGrantedAuthority
或任何其他
GrantedAuthority
实现。另外,推荐使用List并优于List
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"    >  <property name="authenticationManager" ref="authenticationManager" /></bean><bean id="preauthAuthProvider" >  <property name="preAuthenticatedUserDetailsService">    <bean  />  </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参考手册是您的朋友!



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/399973.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号