Ruby CAS Server自定义邮箱认证方式

古明煦
2023-12-01

Ruby CAS Server 部署起来很方便,最近基本上都用这个做SSO。今天遇到一个需求,要与用户的邮箱绑定起来,查了下资料,自己写了一个基于邮箱的认证器。

由于邮箱认证只能验证用户名和口令的正确性,用户的附加信息仍然需要从相应的数据库中提取,这里用的是mongodb。

我是下载的源代码(点击打开链接),如果是Gem安装应该也差不太多吧。在源代码目录下,进入 lib/casserver/authenticators 目录,新建一个文件 mail.rb。

require 'casserver/authenticators/base'
require 'net/smtp'
  
# Basic Mail SMTP authenticator.
class CASServer::Authenticators::Mail < CASServer::Authenticators::Base
  def validate(credentials)
    read_standard_credentials(credentials)

    return false if @password.blank?

    raise CASServer::AuthenticatorError, "Cannot validate credentials because the authenticator hasn't yet been configured" unless @options
    raise CASServer::AuthenticatorError, "Invalid E-Mail authenticator configuration!" unless @options[:mail]
    raise CASServer::AuthenticatorError, "You must specify a smtp server host and domain in the E-Mail configuration!" unless @options[:mail][:domain] || @options[:mail][:server]

    raise CASServer::AuthenticatorError, "The username '#{@username}' contains invalid characters." if (@username =~ /[*\(\)\0\/]/)

    @mail = Net::SMTP.start(@options[:mail][:server], @options[:mail][:port] || 25)
    @options[:mail][:domain] ||= @options[:mail][:server]

    begin
      auth = @mail.authenticate(@username, @password, @options[:mail][:auth_type].to_sym)
      @mail.finish

      create_extra_attributes
      return auth.status == "235"
    rescue => e
      raise CASServer::AuthenticatorError,
        "E-Mail authentication failed with '#{e}'. Check your authenticator configuration."
    end
  end
  
  private
  def create_extra_attributes
    require 'mongo'
    connection = Mongo::Connection.new(@options[:mongo][:server], @options[:mongo][:port] || 27017, :safe => true)
    db = connection.db(@options[:mongo][:db])
    users = db[@options[:mongo][:doc]].find(:login => @username).to_a

    attrs = {}
    users.each do |user|
      @options[:extra_attributes].each do |k,field|
        attrs[k] = attrs[k] || []
        attrs[k] << user[field]
      end
    end

    @extra_attributes = attrs
  end
end

在 /etc/rubycas-server/config.yml 配置文件中加入以下认证配置:

authenticator:
  class: CASServer::Authenticators::Mail
  mail:
    server: mail.cnpc
    auth_type: login
  mongo:
    server: localhost
    db: statbook-service
    doc: users
  extra_attributes:
    displayName: name
    email: email

重启 rubycas-server 命令后,访问登录页面测试是否成功。

来自于开源软件,也许对CAS用户有一定的帮助,不敢藏私,遂与大家分享。

 类似资料: