单点登录之实战CAS5.1.x(四) ——自定义验证类

前面提到了2个伏笔,一个是域验证获取不到详细信息,一个是MS SQL Server无法配置认证源,这两个问题都可以藉由自定义验证类来实现,同时使用自定义的认证类可以满足一些比较复杂的业务需求。

官方有一篇博客介绍了具体的做法:https://apereo.github.io/2017/02/02/cas51-authn-handlers/,稍微有一些简略,中间有些关键的东西可能会卡住。

首先建立一个空的java类库项目,引入cas的依赖,我偷懒就干脆把整个war包里100多个都引进来了,反正也不会打包打进去的对吧……

1 建立自己的验证类,cas有不少现成的验证类可以继承,我推荐继承官方博客里的AbstractUsernamePasswordAuthenticationHandler。

2 在authenticateUsernamePasswordInternal方法里写你自己的验证逻辑,这里正是我们大显身手的地方,域验证、抓取域信息、连接MSSQL数据库?统统不在话下。

@Override
protected HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential upc, final String originalPassword) throws GeneralSecurityException, PreventedException {
    if (upc.getUsername() == "admin" && upc.getPassword() == "admin") {
        Map propMap = new HashMap();
        propMap.put("addr", "Shanghai");
        propMap.put("job", "Engineer");
        propMap.put("mobile", "13800000000");
        return createHandlerResult(upc, principalFactory.createPrincipal(upc.getUsername(), propMap), null);
    }
    throw new FailedLoginException("Sorry, login attemp failed.");
}

3 返回成功凭证时不要忘了带上详细信息:

return createHandlerResult(upc, principalFactory.createPrincipal(upc.getUsername(), propMap), null);

这里的propMap就是Java客户端可以拿到的详细信息了,DotNet是拿不到的,大家可以变通一下把用户名变成详细信息这样返回:

return createHandlerResult(upc, principalFactory.createPrincipal(base64(propMap), propMap), null);

4 建立自己的Configuration类,继承AuthenticationEventExecutionPlanConfigurer。

@Configuration("MyAuthenticationConfiguration")
@EnableConfigurationProperties(CasConfigurationProperties.class)
public class MyAuthenticationConfiguration implements AuthenticationEventExecutionPlanConfigurer {

    @Autowired
    private CasConfigurationProperties casProperties;

    @Autowired
    @Qualifier("servicesManager")
    private ServicesManager servicesManager;

    @Bean
    public AuthenticationHandler myAuthenticationHandler() {
        final MyAuthenticationHandler handler = new MyAuthenticationHandler(MyAuthenticationHandler.class.getSimpleName(), servicesManager, new DefaultPrincipalFactory(), 10);
        return handler;
    }

    @Override
    public void configureAuthenticationExecutionPlan(final AuthenticationEventExecutionPlan plan) {
        plan.registerAuthenticationHandler(myAuthenticationHandler());
    }
}

5 在META-INF文件夹下建立一个spring.factories文件,写入:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.custom.cas.MyAuthenticationConfiguration

6 打包并放入webapps下cas的lib目录即可。

坑8:自定义的验证类和在property中配置的验证类不冲突,按优先级依次验证并返回,但是cas似乎不会为自定义验证类做属性合并,就是说如果你在配置中配置了多个源,每个源的属性是可以自动合并的,但自定义验证类则不会,cas对其置之不理,不知道是我没研究好还是哪里配置有问题,已经懒得去研究了……

转载于:https://my.oschina.net/viperwhip/blog/1528647

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值