Spring Security 自定义过滤器

2024-05-17

我想自定义 Spring security 3.0.5 并将登录 URL 更改为 /login 而不是 /j_spring_security_check。

我需要做的是允许登录“/”目录并保护“/admin/report.html”页面。

首先,我使用教程和 Spring Security 源代码创建自己的过滤器:

public class MyFilter extends AbstractAuthenticationProcessingFilter {
    private static final String DEFAULT_FILTER_PROCESSES_URL = "/login";
    private static final String POST = "POST";
    public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "j_username";
    public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "j_password";
    public static final String SPRING_SECURITY_LAST_USERNAME_KEY = "SPRING_SECURITY_LAST_USERNAME";

    private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY;
    private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY;

    protected MyFilter() {
        super(DEFAULT_FILTER_PROCESSES_URL);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) 
                          throws AuthenticationException, IOException, ServletException {
        String username = obtainUsername(request);
        String password = obtainPassword(request);

        if (username == null) {
            username = "";
        }

        if (password == null) {
            password = "";
        }

        username = username.trim();
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
        HttpSession session = request.getSession(false);
        if (session != null || getAllowSessionCreation()) {
            request.getSession().setAttribute(SPRING_SECURITY_LAST_USERNAME_KEY, TextEscapeUtils.escapeEntities(username));
        }
        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }

    protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain chain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) res;
        if (request.getMethod().equals(POST)) {
            // If the incoming request is a POST, then we send it up
            // to the AbstractAuthenticationProcessingFilter.
            super.doFilter(request, response, chain);
        } else {
            // If it's a GET, we ignore this request and send it
            // to the next filter in the chain.  In this case, that
            // pretty much means the request will hit the /login
            // controller which will process the request to show the
            // login page.
            chain.doFilter(request, response);
        }
    }

    protected String obtainUsername(HttpServletRequest request) {
        return request.getParameter(usernameParameter);
    }

    protected String obtainPassword(HttpServletRequest request) {
        return request.getParameter(passwordParameter);
    }
}

之后我在 xml 中进行了以下更改

 <security:http auto-config="true">
        <!--<session-management session-fixation-protection="none"/>-->
        <security:custom-filter ref="myFilter" before="FORM_LOGIN_FILTER"/>
        <security:intercept-url pattern="/admin/login.jsp*" filters="none"/>
        <security:intercept-url pattern="/admin/report.html" access="ROLE_ADMIN"/>
        <security:form-login login-page="/admin/login.jsp" login-processing-url="/login" always-use-default-target="true"/>
        <security:logout logout-url="/logout" logout-success-url="/login.jsp" invalidate-session="true"/>
    </security:http>   
<security:authentication-manager alias="authenticationManager">
  <security:authentication-provider>
    <security:password-encoder hash="md5" />
    <security:user-service>
    <!-- peter/opal -->
      <security:user name="peter" password="22b5c9accc6e1ba628cedc63a72d57f8" authorities="ROLE_ADMIN" />
     </security:user-service>
  </security:authentication-provider>
</security:authentication-manager>
<bean id="myFilter" class="com.vanilla.springMVC.controllers.MyFilter">
<property name="authenticationManager" ref="authenticationManager"/>
</bean>

然后我的代码就有了 JSP。

<form action="../login" method="post">
    <label for="j_username">Username</label>
    <input type="text" name="j_username" id="j_username" />
    <br/>
    <label for="j_password">Password</label>
    <input type="password" name="j_password" id="j_password"/>
    <br/>
    <input type='checkbox' name='_spring_security_remember_me'/> Remember me on this computer.
    <br/>
    <input type="submit" value="Login"/>
</form>

当尝试导航到 /admin/report.html 时,我被重定向到登录页面。 但提交凭据后我得到:

HTTP Status 404 - /SpringMVC/login/

type Status report

message /SpringMVC/login/

description The requested resource (/SpringMVC/login/) is not available.

看起来我的配置有问题,但我不知道是什么原因造成的。 你能帮我吗?


我在这方面迟了大约 12 个月,但为了自定义 Spring Security 表单登录的登录 URL,您不需要创建自己的过滤器。 form-login 标签的属性之一允许您设置自定义 URL。事实上,您还可以使用 form-login 标记的属性更改默认的 j_username 和 j_password 字段名称。这是一个例子:

<form-login login-page="/login" login-processing-url="/login.do" default-target-url="/" always-use-default-target="true" authentication-failure-url="/login?error=1" username-parameter="username" password-parameter="password"/>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring Security 自定义过滤器 的相关文章

随机推荐

  • 多个值文件中包含多个列表的 Helm 图表

    我有一个包含以下内容的values yaml abc env name name01 value value01 name name02 value value02 我有另一个值文件values dev yaml 我在使用 f安装时添加它
  • 无法在带有 QSortFilterProxyModel 的 QTreeView 的点击信号中使用 itemFromIndex

    我有一个 QTreeView 在视图和 QStandardItemModel 之间有一个 QSortFilterProxyModel 来对树进行排序 然后我想通过 clicked 信号对视图中的点击进行操作 模型 视图的设置类似于 mymo
  • 有没有一种方法可以将python对象直接存储在mongoDB中而不需要序列化它们

    我在某处读到过 您可以使用 BSON 将 python 对象 更具体地说是字典 作为二进制文件存储在 MongoDB 中 但是现在我找不到任何与此相关的文档 有人知道具体如何做到这一点吗 没有办法在不序列化的情况下将对象存储在文件 数据库
  • Gradlew 使用 Git Bash 打印控制字符

    我在 Intellij Idea Community Edition 2020 中使用 git bash 作为集成终端 下载的Gradlew是5 2 1 当我运行类似的东西时gradlew build It prints some rand
  • createImage(int width, int height) 的问题

    我有以下代码 作为游戏的一部分每 10 毫秒运行一次 private void gameRender if dbImage null createImage returns null if GraphicsEnvironment isHea
  • 滚动时输入自动完成位置错误(chrome)

    我在输入文本的默认自动完成功能方面遇到了一些麻烦 滚动时它不会相应移动 我希望自动完成文本保留在输入的正下方 有办法做到这一点吗 我在 Chrome 浏览器版本 57 0 2987 133 中发生这种情况 fiddle https jsfi
  • 将 {sitename} 参数传递给 MVC 控制器操作

    我怎样才能检索站点范围的 URL 参数在路线中而不用参数使每个控制器操作混乱 我的问题类似于这个问题 https stackoverflow com questions 235118 asp net mvc route to usernam
  • 如何用流程图表示递归函数?

    我需要在流程图上表示递归函数 我的问题是我不知道如何指示该函数可以一次在多个元素上调用自身 例如扫描图形的函数 有人有什么建议吗 在流程图中 您通常不会为循环之类的内容添加多次调用 您只需指示可以重复调用代码 直到满足条件为止 因此 对于递
  • 是否可以检测 lambda 捕获组中是否有“this”?

    在 c 17 中 是否可以进行模板元编程来检测 this 是否是捕获组的一部分 还是在运行时 我有一个 A 类 它接受 lambda 以供以后调用 然而 如果拥有 A 的对象 B 在它提供给 A 的 lambda 中捕获 this 那么它可
  • Java Runtime.getRuntime().freeMemory() 问题

    我搜索并看到了一些线程 但没有一个能够解决我遇到的具体问题 我正在尝试使用以下方式监视我的内存使用情况Runtime getRuntime freeMemory Runtime getRuntime maxMemory and Runtim
  • 有没有办法通过chrome的resourceType获取所有mime类型

    chrome api中有多种resourceType类型 例如 文档 样式表 图像 媒体 字体 脚本 TextTrack XHR Fetch EventSource WebSocket Manifest 其他 现在我想知道resourceT
  • 使用 .NET 中的类型化数据集将 SQL 参数传递给 IN() 子句

    首先道歉 因为该网站上有类似的问题 但没有一个直接回答这个问题 我在 VS 2010 中使用类型化数据集 我在数据集中创建一个 TableAdapter 查询如下 SELECT from Table WHERE ID IN IDs 现在如果
  • 在 Bluehost 共享主机上发送电子邮件

    我已经使用 gmail smtp 在本地服务器上测试了 Laravel 电子邮件 并且工作正常 MAIL DRIVER smtp MAIL HOST smtp gmail com MAIL PORT 587 MAIL USERNAM ema
  • 如何展平列表?

    我怎样才能轻松地压平List在达特 例如 var a 1 2 3 a b c true false true var b 1 2 3 a b c true false true 我该如何转向a into b 即变成一个List包含所有这些值
  • 无法在 JavaScript for 循环中读取 null 的属性“长度”

    我正在尝试制作一个像 Stack Overflow 那样的 Markdown 编辑器 如果我实际上没有在文本区域中键入星号和包含短语的 http 我会收到标题中列出的此错误 如果我只输入包含星号的短语 则错误指的是这一行 if linkif
  • Laravel 广播:通知与事件

    我阅读了 laravel 文档Events and Notifications 似乎我们可以触发一个事件 并从该事件中触发 使用ShouldBroadcast接口 将其广播到我理解的 laravel echo 另一方面我们可以使用通知via
  • 有没有办法禁用网站上表单的自动填写? [复制]

    这个问题在这里已经有答案了 我最近才学会使用创建网站HTML and PHP 我创建了一个网站 其中有一个测验 要求人们随机翻译单词 用户将他们的答案输入到表格中 网站评估答案是否正确 现在 当一个问题在一个会话中被问两次时 就会出现自动填
  • 如何在Eclipse中集成CSS预处理? [关闭]

    Closed 此问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我想在 Eclipse 中编辑 SCSS 文件 最好使用语法突出显示 scss files 我发现这些资
  • 如果其中一台机器死机,TCP 连接如何终止?

    如果两个主机 A 和 B 之间建立了 TCP 连接 假设主机 A 已向主机 B 发送了 5 个八位字节 然后主机 B 崩溃了 由于未知原因 主机 A 将等待确认 但如果没有收到确认 将重新发送八位字节并减小发送者窗口大小 这将重复几次 直到
  • Spring Security 自定义过滤器

    我想自定义 Spring security 3 0 5 并将登录 URL 更改为 login 而不是 j spring security check 我需要做的是允许登录 目录并保护 admin report html 页面 首先 我使用教