首页 > 其他分享 >security中登录失败后没有走登录失败拦截器

security中登录失败后没有走登录失败拦截器

时间:2023-05-03 09:22:15浏览次数:32  
标签:拦截器 登录 private token 失败 new security public

在进行security做用户登录时,会创建一系列的拦截器和过滤器,在进行用户校验时,我这边采用的是继承UsernamePasswordAuthenticationFilter,然后重写其中的attemptAuthentication和successfulAuthentication方法,但是在校验失败后,没有走校验失败拦截器。


public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
public static final String TOKEN_HEADER = "Authorization";
public static final String TOKEN_PREFIX = "Bearer ";
private  static final Integer expire = 60*60*24*8;
private AuthenticationManager authenticationManager;

public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
    this.authenticationManager = authenticationManager;
}
/**
 * 进行登录验证
 */
@SneakyThrows
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    TbUser user =new TbUser(request.getParameter("username"),request.getParameter("password"));
    return authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword()));
}
/**
* 登录验证成功后,回调此方法,生成token
*1、将生成的token存入到redis中
* 2、将生成的token返回给前端
*/
@Override
protected void successfulAuthentication(HttpServletRequest request,
                                        HttpServletResponse response,
                                        FilterChain chain,
                                        Authentication auth) throws IOException, ServletException {
    User user = (User) auth.getPrincipal();
    String token = JwtUtil.generateJsonWebToken(user);
    RedisTemplate redisTemplate = SpringUtils.getBean("redisTemplate");
    redisTemplate.opsForValue().set(SystemParams.API_MAPPING_REDIS_TOKEN_PRE+user.getUsername(),token,expire, TimeUnit.SECONDS);
    // 登录成功后,返回token到body里面
    Map<String, Object> resultMap = new HashMap<>();
    resultMap.put(TOKEN_HEADER, TOKEN_PREFIX + token);
    Result result = Result.success(resultMap);
    response.getWriter().write(JSONUtil.toJsonStr(result));
  }
}

@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
@EnableWebSecurity   //启用security安全框架的安全校验
public class MyWebSecurity extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationFailHandler authenticationFailHandler;
@Autowired(required = true)
@Qualifier("myUserDetailService")
private UserDetailsService userDetailsService;
@Autowired
private ImageValidateFilter imageValidateFilter;
//在方法中配置用户名和密码,作为用户登录的数据
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
private static final String[] URL_WHITELIST = {
        "/logout",
        "/login.html",
        "/getImage",
        "/hello1"
};

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable()
            // 登录请求url
            .formLogin()
            .loginPage("/login.html")
            .loginProcessingUrl("/login")
            .failureHandler(authenticationFailHandler)
            // 配置拦截规则
            .and()
            .authorizeRequests()
            //.antMatchers(URL_WHITELIST).permitAll()
            .anyRequest().authenticated()//除了上面的这些请求不需要认证授权,其余全部的都需要认证授权
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            // 配置自定义的过滤器
            .and()
            //自定义的认证登录过滤器,并且在认证通过后生成Token,返回到前端
            .addFilter(new JwtAuthenticationFilter(authenticationManager()))
            //token认证过滤器
            .addFilter(new TokenVerifyFiter(authenticationManager()))
            // 图形验证码过滤器
            .addFilterBefore(imageValidateFilter, UsernamePasswordAuthenticationFilter.class);
}


@Bean
public PasswordEncoder passwordEncoder(){
    //加密方式,推荐的方式new BCryptPasswordEncoder();
    return new BCryptPasswordEncoder();
}

/**
 * 1、解决放行资源被token验证过滤器拦截问题
 * 2、WebSecurity主要是配置跟web资源相关的,比如css、js、images等等,但是这个还不是本质的区别,关键的区别如下:
 * ignore是完全绕过了spring security的所有filter,相当于不走spring security,所以ignore只适合配置静态资
 * 源的过滤,不适合api的过滤,过滤api就调用不了api了
 * permitall没有绕过spring security,其中包含了登录的以及匿名的。
 */
@Override
public void configure(WebSecurity web) {
    web.ignoring().antMatchers(URL_WHITELIST);
  }
}

这是因为一个很简单的问题,那就是这里定义的过滤器是在拦截器之前执行的,因此当UsernamePasswordAuthenticationFilter在进行校验时,发现用户名或者密码输入错误时,直接结束了,所以就没有再走到拦截器哪里了。
代码改造:


@Component
public class JwtAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
public static final String TOKEN_HEADER = "Authorization";
public static final String TOKEN_PREFIX = "Bearer ";
private  static final Integer expire = 60*60*24*8;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
    User user = (User) authentication.getPrincipal();
    String token = JwtUtil.generateJsonWebToken(user);
    RedisTemplate redisTemplate = SpringUtils.getBean("redisTemplate");
    redisTemplate.opsForValue().set(SystemParams.API_MAPPING_REDIS_TOKEN_PRE+user.getUsername(),token,expire, TimeUnit.SECONDS);
    // 登录成功后,返回token到body里面
    Map<String, Object> resultMap = new HashMap<>();
    resultMap.put(TOKEN_HEADER, TOKEN_PREFIX + token);
    Result result = Result.success(resultMap);
    response.getWriter().write(JSONUtil.toJsonStr(result));
  }
}
-------------------------------------------
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
@EnableWebSecurity   //启用security安全框架的安全校验
public class MyWebSecurity extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationFailHandler authenticationFailHandler;
@Autowired
@Qualifier("myUserDetailService")
private UserDetailsService userDetailsService;
@Autowired
private JwtAuthenticationSuccessHandler jwtAuthenticationSuccessHandler;
@Autowired
private ImageValidateFilter imageValidateFilter;
//在方法中配置用户名和密码,作为用户登录的数据
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
private static final String[] URL_WHITELIST = {
        "/login.html",
        "/getCode",
        "/hello1"
};

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable();
            // 登录请求url
    http    // 配置拦截规则
            .authorizeRequests()
            //.antMatchers(URL_WHITELIST).permitAll()
            .anyRequest().authenticated()//除了上面的这些请求不需要认证授权,其余全部的都需要认证授权
            .and()
            //设置登陆
            .formLogin()
            .loginProcessingUrl("/login")
            .successHandler(jwtAuthenticationSuccessHandler)
            .failureHandler(authenticationFailHandler)
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            // 配置自定义的过滤器
            .and()
            ///token认证过滤器
            .addFilter(new TokenVerifyFiter(authenticationManager()))
             //图形验证码过滤器
            .addFilterBefore(imageValidateFilter, UsernamePasswordAuthenticationFilter.class);
}


@Bean
public PasswordEncoder passwordEncoder(){
    //加密方式,推荐的方式new BCryptPasswordEncoder();
    return new BCryptPasswordEncoder();
}

/**
 * 1、解决放行资源被token验证过滤器拦截问题
 * 2、WebSecurity主要是配置跟web资源相关的,比如css、js、images等等,但是这个还不是本质的区别,关键的区别如下:
 * ignore是完全绕过了spring security的所有filter,相当于不走spring security,所以ignore只适合配置静态资
 * 源的过滤,不适合api的过滤,过滤api就调用不了api了
 * permitall没有绕过spring security,其中包含了登录的以及匿名的。
 */
@Override
public void configure(WebSecurity web) {
    web.ignoring().antMatchers(URL_WHITELIST);
  }
}

标签:拦截器,登录,private,token,失败,new,security,public
From: https://www.cnblogs.com/syq520/p/17368679.html

相关文章

  • 【转】Ubuntu系统Gnome桌面设置允许root登录
    转自https://www.cnblogs.com/tonyc/p/10432871.html设置方法如下:vi/etc/pam.d/gdm-autologin找到下面这一行authrequiredpam_succeed_if.souser!=rootquiet_success在最前面加上#注释掉。对/etc/pam.d/gdm-password进行同样的操作,重启。......
  • Ubuntu中开启root用户ssh远程登录
    1.将用户和Shell环境一起切换成root身份su-root2.编辑sshd_config文件vi/etc/ssh/sshd_config3.修改配置默认的Authentication区块#Authentication:#LoginGraceTime2m#PermitRootLoginprohibit-password#StrictModesyes#MaxAuthTries6#MaxSessions10修......
  • 拦截器Interceptor
    1、前言SpringMVC中的Interceptor拦截器也是相当重要和相当有用的,它的主要作用是拦截用户的请求并进行相应的处理。比如通过它来进行权限验证,或者是来判断用户是否登陆,或者是像12306那样子判断当前时间是否是购票时间。 Java里的拦截器是动态拦截action调用的对象。它提......
  • 微信公众号网页登录,获取用户信息
    0、参考wechat登录前端代码.zip下载后端java代码下载1、接口信息配置请填写接口配置信息,此信息需要你有自己的服务器资源,填写的URL需要正确响应微信发送的Token验证URL=http://自己的域名/rest/WeChat/verifyToken=123456792、JS接口安全域名域名=自己的域名3、网页......
  • 关于Linux操作系统-OS等保要求配置-禁止root用户直接ssh登录
    在等保中,都会去要求查看sshd配置,看是否有禁止root用户直接ssh登录,此项一般也会作为一个强制要求安全配置项笔者这里的操作系统如下,对于Redhat7.x应该也是一样的,可以自行测试[qq-5201351@Localhost~]$cat/etc/redhat-releaseRedHatEnterpriseLinuxrelease8.1(Ootpa)......
  • B/S 结构系统的 缓存机制(Cookie) 以及基于 cookie 机制实现 oa 十天免登录的功能
    B/S结构系统的缓存机制(Cookie)以及基于cookie机制实现oa十天免登录的功能@目录B/S结构系统的缓存机制(Cookie)以及基于cookie机制实现oa十天免登录的功能每博一文案1.Cookie的概述2.session与Cookie之间的联系:3.Cookie的作用:4.Cookie的生成机理的原理:5......
  • 项目政治与项目失败的关系
       具有政治头脑是当今项目经理的基本功。你不可能再仅仅依靠技术和管理能力管理一个项目,一定要懂得你将必须应付的人和组织的政治性。政治和项目冲突是不可避免的,是项目管理的一种生活方式。未来的项目经理必须在政治上变得机敏。一、政治风险   对于大型或复杂的项目......
  • 关于Linux操作系统OS账号最后一次登录时间的审计
    本文以RedHatEnterpriseLinuxrelease8.1(Ootpa)为例,应该也能适用于7.x版本的如果对操作系统中的账号审计,其中有一个项目可能会比较重要(尤其是对于个人账号),那就是最后一次登录的记录如果需要查看每一个OS账号的最后一次登录记录,可以使用lastlog命令[qq-5201351@localho......
  • 项目发起和治理失败
       所有项目都有陷入困境的可能。一、项目压力为了生存需要,公司接受风险较大和高度复杂的项目。客户要求在某种程度上可定制的小容量、高质量的产品。项目生命周期和新产品开发的时间被压缩。事业环境因素对项目执行有了更大的影响,特别在长期的项目中。客户和项目干系人希望......
  • 项目商业论证失败
        如果说是最差的失败原因可能是,项目的商业论证从项目一开始就是错的,或者在没有人意识到或愿意承认之际,在项目执行期间不适宜地改变。通常治理人员比项目经理更能洞察商业论证的有效性。干系人变更和假设条件的重新确认,都会造成项目商业论证的失败。经验教训:项目持续时间......