Spring-Security的自定义过滤器

一 参考文章

http://www.spring4all.com/article/422

二 代码位置

https://github.com/cakin24/spring-security-demos/tree/master/02%20-%20%E8%87%AA%E5%AE%9A%E4%B9%89%E7%99%BB%E5%BD%95

三 关键代码

1 过滤器定义

package com.spring4all.config;

import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
* 自定义表单登录
*/
public class CustomFromLoginFilter extends AbstractAuthenticationProcessingFilter {


    CustomFromLoginFilter(String defaultFilterProcessesUrl) {
        super(new AntPathRequestMatcher(defaultFilterProcessesUrl, HttpMethod.POST.name()));
    }


    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
        String username = httpServletRequest.getParameter("username");
        String password = httpServletRequest.getParameter("password");
        customCheck(username, password);
        List<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
        simpleGrantedAuthorities.add(new SimpleGrantedAuthority("USER"));
        return new UsernamePasswordAuthenticationToken(username, password, simpleGrantedAuthorities);
    }

    private void customCheck(String username, String password){
        if (!("anoyi".equals(username) && "anoyi".equals(password))){
            throw new RuntimeException("用户名或密码错误!");
        }
    }
}

2 过滤器配置

package com.spring4all.config;


import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{


    /**
     * 匹配 "/" 路径,不需要权限即可访问
     * 匹配 "/user" 及其以下所有路径,都需要 "USER" 权限
     * 退出登录的地址为 "/logout",退出成功后跳转到页面 "/login"
     * 默认启用 CSRF
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/user/**").hasAuthority("USER")
                .and()
                .logout().logoutUrl("/logout").logoutSuccessUrl("/login");


        http.addFilterAt(customFromLoginFilter(), UsernamePasswordAuthenticationFilter.class);
    }


    /**
     * 自定义认证过滤器
     */
    private CustomFromLoginFilter customFromLoginFilter() {
        return new CustomFromLoginFilter("/login");
    }


}

addFilterAt该函数的用法参考: https://blog.csdn.net/qq_36882793/article/details/102869583

四 调试

我们调试下看看有哪些过滤器,以及过滤器的执行顺序。

1 在下面两个过滤器中设置断点

2 浏览器输入: http://localhost:8080/login

从调试结果看,先执行优先级高的过滤器。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Security 6中自定义权限过滤器的步骤如下: 1.创建一个类并实现`org.springframework.web.filter.OncePerRequestFilter`接口。 2.覆盖`doFilterInternal`方法,该方法接收`HttpServletRequest`和`HttpServletResponse`对象作为参数,并在其中编写自定义过滤器的逻辑。 3.使用`@Component`注释将自定义过滤器类标记为Spring组件。 4.在Spring Security配置类中使用`http.addFilterBefore()`方法将自定义过滤器添加到过滤器链中。 下面是一个示例代码,演示如何在Spring Security 6中创建自定义权限过滤器: ```java import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; @Component public class CustomAuthorizationFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // 在这里编写自定义过滤器的逻辑 // 检查用户是否有足够的权限访问请求的资源 // 如果没有权限,可以返回HTTP 403 Forbidden响应 // 如果有权限,可以继续处理请求 filterChain.doFilter(request, response); } } ``` 在Spring Security配置类中添加以下代码: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CustomAuthorizationFilter customAuthorizationFilter; @Override protected void configure(HttpSecurity http) throws Exception { http.addFilterBefore(customAuthorizationFilter, UsernamePasswordAuthenticationFilter.class) .authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasRole("USER") .anyRequest().authenticated() .and() .formLogin() .and() .httpBasic(); } } ``` 在上面的示例中,我们创建了一个名为`CustomAuthorizationFilter`的自定义过滤器,并将其添加到Spring Security过滤器链中。在Spring Security配置类中,我们使用`http.addFilterBefore()`方法将自定义过滤器添加到过滤器链中,并使用`authorizeRequests()`方法配置了请求的授权规则。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值