• 用springsecurity去代替拦截器


    Spring Security 可以替代拦截器,同时还可以提供更加细粒度的权限控制和身份认证。

    可以通过使用 Spring Security 的 Filter 拦截所有请求,来实现对请求的拦截和处理。在 Filter 中可以获取到 HttpServletRequest 对象,从而获取访问者的 IP 地址、请求 URL 等信息。对于需要身份认证和权限控制的接口,可以使用 Spring Security 的相关注解来进行配置,例如 @PreAuthorize、@PostAuthorize 等。

    下面是一个简单的示例代码,展示如何使用 Spring Security 实现对请求的拦截和身份认证。

    1. @Configuration
    2. @EnableWebSecurity
    3. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    4.     @Override
    5.     protected void configure(HttpSecurity http) throws Exception {
    6.         http.authorizeRequests()
    7.             .antMatchers("/login").permitAll()
    8.             .anyRequest().authenticated()
    9.             .and()
    10.         .formLogin()
    11.             .loginPage("/login")
    12.             .defaultSuccessUrl("/")
    13.             .permitAll()
    14.             .and()
    15.         .logout()
    16.             .invalidateHttpSession(true)
    17.             .clearAuthentication(true)
    18.             .logoutSuccessUrl("/login?logout")
    19.             .permitAll();
    20.     }
    1.     @Override
    2.     protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    3.         auth.inMemoryAuthentication()
    4.             .withUser("user").password("password").roles("USER")
    5.             .and()
    6.             .withUser("admin").password("password").roles("USER", "ADMIN");
    7.     }

       

    1. @Bean
    2.     public PasswordEncoder passwordEncoder() {
    3.         return new BCryptPasswordEncoder();
    4.     }
    5. }


     

    在上面的代码中,我们使用 @EnableWebSecurity 开启了 Spring Security 的 Web 安全功能,然后通过 configure() 方法配置了登录页面、注销功能等。

    在 configure() 方法中,我们使用了 authorizeRequests() 方法对请求进行了授权。我们允许所有用户访问 "/login" 页面,但是对于其他所有请求都需要进行身份认证。

    在 configure(AuthenticationManagerBuilder auth) 方法中,我们配置了一个用户的认证信息,这些信息将用于验证用户的身份。

    最后,我们定义了一个名为 passwordEncoder() 的 Bean,用于对用户密码进行加密。

  • 相关阅读:
    民安智库(第三方市场调研公司)哪家残疾人服务满意度调研公司比较专业
    第二届邯郸钢铁展会,图扑软件荣获“2022钢铁行业智造之星奖”
    Python 通过adb传输文件到手机
    QGIS开发笔记(二):Windows安装版二次开发环境搭建(上):安装OSGeo4W运行依赖其Qt的基础环境Demo
    es nested object区别
    【XGBoost】第 5 章:XGBoost 揭幕
    设计模式之单例模式
    如何完成网课答案公众号搭建?小白教程!内附网课题库接口!
    01BFS最短距离的原理和C++实现
    Python初体验
  • 原文地址:https://blog.csdn.net/Flying_Fish_roe/article/details/134035303