• 用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,用于对用户密码进行加密。

  • 相关阅读:
    win7系统修改磁盘提示参数错误的解决办法
    Domino服务器SSL证书安装指南
    美团MTCTF 2022 ret2libc_aarch64 pwn解
    壁挂式新风机市场现状及未来发展趋势分析
    Python:Django框架的Hello wrold示例
    自古以来,代理程序都是兵家折戟之地
    二叉树的最近公共祖先LCA
    SpringSecurity系列 - 18 SpringSecurity Oauth2 搭建授权服务器和资源服务器
    C++学习之路-智能指针
    ADO.NET实体数据模型-DatabaseFirst
  • 原文地址:https://blog.csdn.net/Flying_Fish_roe/article/details/134035303