当前位置: 代码网 > it编程>编程语言>Java > spring security如何扩展自定义登录

spring security如何扩展自定义登录

2024年11月15日 Java 我要评论
背景spring security 默认给我们提供了一套用户名密码登录的的逻辑实现,在很多时候根本不满足我们实际开发的要求,所以我们经常需要对它认证模块进行扩展,那么如何扩展我们的认证方式呢,这篇文章

背景

spring security 默认给我们提供了一套用户名密码登录的的逻辑实现,在很多时候根本不满足我们实际开发的要求,所以我们经常需要对它认证模块进行扩展,那么如何扩展我们的认证方式呢,这篇文章将会给你一个较为完整的解答。

认证原理

spring security使用了一种基于过滤器链的认证原理来保护应用程序。它提供了一组过滤器,这些过滤器按照特定的顺序对每个请求进行处理。

认证过程中的主要步骤如下:

  1. 用户发送认证请求到应用程序。
  2. 应用程序将请求发送给spring security的过滤器链。
  3. 过滤器链依次处理请求,直到找到可以处理该请求的过滤器。
  4. 找到处理请求的过滤器后,该过滤器会验证用户的凭证(如用户名和密码)。
  5. 如果凭证有效,则生成一个已认证的安全上下文,并将其保存在spring security的上下文存储中。
  6. 如果凭证无效,则返回认证失败的信息给用户。
  7. 认证成功后,用户可以继续访问受保护的资源。

在认证过程中,spring security还提供了灵活的配置选项,可以根据特定的需求进行自定义配置,例如使用不同的认证提供程序、自定义身份验证逻辑等。

总结起来,spring security的认证原理是通过一组过滤器链来处理认证请求,验证用户凭证并生成认证的安全上下文,以保护应用程序的资源。

具体实现原理

spring security的认证实现原理主要涉及以下几个核心概念和组件:

  • 用户提供的凭证:用户在进行认证时,需要提供其身份凭证,如用户名和密码。
  • 认证提供程序(authentication provider):认证提供程序是spring security中的重要组件,负责验证用户提供的凭证。它使用用户提供的凭证与系统中存储的凭证进行比对,并决定是否通过认证。spring
  • security提供了多种内置的认证提供程序,如基于数据库的jdbc认证提供程序、ldap认证提供程序、inmemory认证提供程序等。同时也支持自定义认证提供程序。
  • 用户详情服务(userdetailsservice):用户详情服务是spring security中的接口,负责获取用户的详细信息,如用户的权限、角色等。认证提供程序在验证用户凭证后,会使用用户详情服务获取用户的详细信息,并构建一个认证对象(authentication)。
  • 认证对象(authentication):认证对象是spring security中表示已认证用户的对象。它包含了用户的身份信息、凭证信息、权限信息等。认证对象由认证提供程序生成,并将其保存在securitycontextholder的上下文存储中。
  • 认证过滤器链(authentication filter chain):认证过滤器链是spring security中的过滤器组成的链条,负责处理认证请求。每个过滤器都会对请求进行处理,并根据需要进行认证、授权和其他安全操作。在认证过程中,认证过滤器链会根据请求的url匹配合适的过滤器进行处理。
  • 安全上下文(security context):安全上下文是spring security中用于保存已认证用户信息的容器。它以threadlocal的方式存储,可以通过securitycontextholder来访问和操作。安全上下文中保存了当前的认证对象,可以在应用程序的任何地方获取已认证用户的信息。

总结起来,spring security的认证实现原理是通过认证提供程序验证用户提供的凭证,使用用户详情服务获取用户的详细信息,并构建一个认证对象,然后将该认证对象保存在安全上下文中。

认证过滤器链负责处理认证请求,并根据需要进行认证、授权和其他安全操作。

通过这种方式,spring security实现了对应用程序进行认证和授权的功能。

如何实现自定义认证的功能

要自定义spring security的认证模块,你可以按照以下步骤进行:

  • 创建一个自定义的认证提供程序(authentication provider)类,该类实现了org.springframework.security.authentication.authenticationprovider接口。在该类中,你可以编写你自己的认证逻辑,比如验证用户名和密码是否匹配。
  • 实现userdetailsservice接口来获取用户的详细信息。你可以根据自己的需求,从数据库、ldap等数据源中获取用户信息,并返回一个userdetails对象。
  • 在配置类(通常是继承自websecurityconfigureradapter的类)中,覆盖configure(authenticationmanagerbuilder auth)方法。在该方法中,你可以指定使用你自定义的认证提供程序和用户详情服务来进行认证。
  • 在上述配置类中,覆盖configure(httpsecurity http)方法来配置认证过滤器链。你可以根据需要添加和配置各种过滤器,例如表单登录过滤器、基于token的认证过滤器等。

下面根据微信小程序登录来实现一个自定义模块的接口:

定义token信息类

public class jscodeauthenticationtoken extends abstractauthenticationtoken {
    private static final long serialversionuid = 5615450055779559101l;
    private string code;

    /**
     * creates a token with the supplied array of authorities.
     *
     * @param authorities the collection of <tt>grantedauthority</tt>s for the principal
     *                    represented by this authentication object.
     */
    public jscodeauthenticationtoken(collection<? extends grantedauthority> authorities, string code) {
        super(authorities);
        this.code = code;
    }

    public jscodeauthenticationtoken(string code) {
        this(collections.emptylist(), code);
    }

    @override
    public object getcredentials() {
        return null;
    }

    @override
    public object getprincipal() {
        return code;
    }

    public void setauthenticated(boolean isauthenticated) throws illegalargumentexception {
        if (isauthenticated) {
            throw new illegalargumentexception(
                    "cannot set this token to trusted - use constructor which takes a grantedauthority list instead");
        }

        super.setauthenticated(false);
    }

    @override
    public void erasecredentials() {
        super.erasecredentials();
    }
}

从代码中我们可以看出我们需要创建一个相关的token类来继承 abstractauthenticationtoken 类,并实现相关的方法

abstractauthenticationtoken 的定义

  • spring security框架中的一个抽象类,用于表示身份验证请求令牌。它用于封装用户凭据或其他必要的信息来进行用户身份验证。
  • abstractauthenticationtoken的子类负责提供特定的身份验证细节,例如用户名和密码、基于令牌的身份验证令牌等。这些子类通常包含获取器和设置器,用于访问和修改身份验证细节。
  • abstractauthenticationtoken还提供了一组方法来管理身份验证状态,例如设置已认证标志、检索与已认证用户关联的权限以及管理与身份验证过程相关的其他详细信息。

abstractauthenticationtoken 的工作原理

  • 当用户请求进行身份验证时,spring security将创建一个实现abstractauthenticationtoken的具体子类对象,并将其中的身份验证信息进行填充。然后,该身份验证令牌将被传递给身份验证管理器进行进一步的身份验证处理。
  • 身份验证管理器将检查身份验证令牌,并根据所配置的身份验证策略和安全规则,对用户进行身份验证。在身份验证过程中,身份验证管理器可能会调用相关的身份验证提供者,比如用户名密码身份验证提供者或令牌身份验证提供者,来验证用户的凭据信息。
  • 一旦用户通过身份验证,身份验证管理器将更新abstractauthenticationtoken中的已认证标志和权限信息,并将其返回给应用程序。在后续的请求中,应用程序可以根据需要访问身份验证令牌中的身份验证信息和权限信息,以实现不同的业务逻辑和访问控制。

定义一个接收参数的filter

@slf4j
public class jscodeauthenticationfilter extends abstractauthenticationprocessingfilter {
    private static string jscode = "code";

    private static boolean postonly = true;

    protected jscodeauthenticationfilter(wechatproperties properties) {
        super(new antpathrequestmatcher(properties.getauthurl(), "post"));
    }

    @override
    public authentication attemptauthentication(httpservletrequest request, httpservletresponse response) throws authenticationexception, ioexception, servletexception {
        if (postonly && !request.getmethod().equalsignorecase("post")) {
            throw new authenticationserviceexception("该接口不支持:" + request.getmethod());
        }

        string code = obtaincode(request);
        code = code.trim();
        log.info("得到的code:{}", code);
        jscodeauthenticationtoken authenticationtokenrequest = new jscodeauthenticationtoken(code);
        setdetails(request, authenticationtokenrequest);
        return this.getauthenticationmanager().authenticate(authenticationtokenrequest);
    }

    public string obtaincode(httpservletrequest request) {
        if (request.getheader("content-type").contains("application/json")) {
            return obtaincodejson(request, jscode);
        }

        return request.getparameter(jscode);
    }

    public string obtaincodejson(httpservletrequest request, string param) {
        stringbuilder builder = new stringbuilder();
        string line = null;
        string code = null;
        try{
            bufferedreader reader = request.getreader();
            while ((line = reader.readline()) != null) {
                builder.append(line);
            }

            map<string, string> map = jsonutils.fromstring(builder.tostring(), map.class, string.class, string.class);
            code = map.get(param);
        }catch (runtimeexception | ioexception e) {
            throw new authenticationserviceexception("获取参数失败");
        }

        return code;
    }

    /**
     * provided so that subclasses may configure what is put into the
     * authentication request's details property.
     *
     * @param request     that an authentication request is being created for
     * @param authrequest the authentication request object that should have its details
     *                    set
     */
    protected void setdetails(httpservletrequest request, jscodeauthenticationtoken authrequest) {
        authrequest.setdetails(authenticationdetailssource.builddetails(request));
    }

从上面的代码可以看出,我们需要定义一个filter 类继承 abstractauthenticationprocessingfilter 来获取前端传输的参数

abstractauthenticationprocessingfilter的定义

  • abstractauthenticationprocessingfilter是spring security框架中的一个过滤器,用于处理用户认证的相关操作。

abstractauthenticationprocessingfilter的功能有哪些

  • 拦截用户发起的认证请求,并交给authenticationmanager来进行身份验证。
  • 通过调用authenticationmanager完成身份验证后,将认证结果封装成authentication对象。
  • 将认证结果传递给abstractauthenticationprocessingfilter的成功或失败处理器进行处理。
  • 处理认证成功或失败的逻辑,例如生成并返回认证成功的jwt token、跳转到特定页面、返回错误信息等。

定义相关的provider 类

public class jscodeauthenticationprovider implements authenticationprovider {

    private wxoauth2service wechatservice;

    private userdetailsservice userdetailsservice;

    private wxmpproperties wxmpproperties;

    public jscodeauthenticationprovider(wxoauth2service wechatservice, wxmpproperties wxmpproperties) {
        this.wechatservice = wechatservice;
        this.wxmpproperties = wxmpproperties;
    }

    @override
    public authentication authenticate(authentication authentication) throws authenticationexception {
        jscodeauthenticationtoken token = (jscodeauthenticationtoken) authentication;
        string code = (string) token.getprincipal();
        log.info("得到的code:{}", code);
        if (stringutils.isblank(code)) {
            throw new authenticationserviceexception("jscode 不能为空");
        }

        wxoauth2accesstoken wxoauth2accesstoken;
        try {
            wxoauth2accesstoken = wechatservice.getaccesstoken(wxmpproperties.getappid(), wxmpproperties.getsecret(), code);
        } catch (wxerrorexception e) {
            throw new authenticationserviceexception("授权登录失败");
        }



        wechatdetailsservice wechatdetailsservice = (wechatdetailsservice)userdetailsservice;
        userdetails details = wechatdetailsservice.loadbytoken(wxoauth2accesstoken.getopenid(), wxoauth2accesstoken.getaccesstoken());
        if (details == null) {
            throw new authenticationserviceexception("无法获取公众号用户");
        }

        jscodeauthenticationtoken authenticationresult = new jscodeauthenticationtoken(details.getusername());
        authenticationresult.setdetails(token.getdetails());
        return authenticationresult;
    }

    @override
    public boolean supports(class<?> authentication) {
        return jscodeauthenticationtoken.class.isassignablefrom(authentication);
    }

    public void setuserdetailsservice(userdetailsservice userdetailsservice) {
        this.userdetailsservice = userdetailsservice;
    }
}

authenticationprovider 的定义

authenticationprovider是spring security框架中的一个接口,用于身份验证的核心组件。

它的定义如下:

public interface authenticationprovider {
 authentication authenticate(authentication authentication) throws authenticationexception;
 boolean supports(class<?> authentication);
}

它包含两个方法:

  • authenticate(authentication authentication):该方法用于执行身份验证过程。输入参数authentication是一个封装了用户认证信息的authentication对象,包括用户名、密码等信息。该方法返回一个认证成功的authentication对象,或者抛出authenticationexception异常表示认证失败。
  • supports(class<?> authentication):该方法用于判断是否支持给定类型的认证请求。输入参数authentication是要被验证的对象类型,通常是usernamepasswordauthenticationtoken或jwtauthenticationtoken等。该方法返回一个boolean值,表示是否支持该类型的认证请求。

authenticationprovider可以自定义实现,用于实现不同的身份验证逻辑。开发者可以通过实现该接口,并覆盖其中的方法来定制化身份验证过程,例如从数据库查询用户信息并进行密码校验等。

在spring security的配置中,可以通过authenticationmanagerbuilder来注册和配置authenticationprovider的实例,以供身份验证使用。

定义相关配置类

@component
@enableconfigurationproperties(wxmpproperties.class)
public class jscodeauthenticationsecurityconfig  extends securityconfigureradapter<defaultsecurityfilterchain, httpsecurity> {
    @autowired
    private userdetailsservice userdetailsservice;

    @autowired
    private authenticationsuccesshandler jscodeauthenticationsuccesshandler;

    @autowired
    private authenticationfailurehandler jscodeauthenticationfailurehandler;

    @autowired
    private wxoauth2service wechatservice;

    @autowired
    private wechatproperties wechatproperties;

    @autowired
    private wxmpproperties wxmpproperties;

    @override
    public void configure(httpsecurity http) throws exception {
        jscodeauthenticationfilter mobilepasswordauthenticationfilter = new jscodeauthenticationfilter(wechatproperties);
        mobilepasswordauthenticationfilter.setauthenticationsuccesshandler(jscodeauthenticationsuccesshandler);
        mobilepasswordauthenticationfilter.setauthenticationfailurehandler(jscodeauthenticationfailurehandler);
        mobilepasswordauthenticationfilter.setauthenticationmanager(http.getsharedobject(authenticationmanager.class));
        jscodeauthenticationprovider provider = new jscodeauthenticationprovider(wechatservice, wxmpproperties);
        provider.setuserdetailsservice(userdetailsservice);
        // 将当前服务注册到 mobilepasswordauthenticationfilter 连之后
        http.authenticationprovider(provider).addfilterafter(mobilepasswordauthenticationfilter, usernamepasswordauthenticationfilter.class);
    }
}

securityconfigureradapter 的定义

securityconfigureradapter是spring security提供的一个抽象类,用于简化配置和定制化spring security的行为。

它是一个适配器模式,继承自securityconfigurer接口,并提供了一些默认实现方法,用于提供给开发者灵活地配置和扩展spring security。

securityconfigureradapter的定义如下:

public abstract class securityconfigureradapter<o extends securityfilterchain, b extends securitybuilder<o>> implements securityconfigurer<o, b> {
 // 提供一个空实现的configure方法,供子类进行覆盖定制
  public void configure(b builder) throws exception {}
 // 提供一个空实现的init方法,供子类进行覆盖定制 
 public void init(b builder) throws exception {}
 // 提供一个空实现的configure方法,供子类进行覆盖定制 
 public void configure(o object) throws exception {}
 // 提供一个空实现的postprocess方法,供子类进行覆盖定制 
 protected void postprocess(o object) throws exception {}
}

开发者可以继承securityconfigureradapter,并重写其中的方法来实现自定义的安全配置。常见的用法是在websecurityconfigureradapter中继承securityconfigureradapter,并重写configure方法来配置spring security的行为,例如定义认证规则、权限控制等。通过继承securityconfigureradapter可以避免直接实现securityconfigurer接口时需要实现所有方法的繁琐操作。

整体配置

    public void configure(httpsecurity http) throws exception {
        string[] auth = stringutils.split( securityproperties.getauthurl(), ",");
        http.formlogin().failurehandler(authenticationfailurehandler)
                .successhandler(authenticationsuccesshandler)
                .loginprocessingurl(securityconstants.default_login_processing_url_form)
                .loginpage(securityconstants.default_unauthentication_url)
                .and().apply(jscodeauthenticationsecurityconfig)
                .and().apply(usernameauthenticationsecurityconfig())
                .and().authorizerequests().antmatchers(auth).authenticated()
                .and().authorizerequests().anyrequest().permitall()
                .and().csrf().disable();
    }

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com