浅谈SpringSecurity重写默认配置

 更新时间:2025年01月20日 10:04:56   作者:@来杯咖啡  
这篇文章主要介绍了SpringSecurity重写默认配置,包括注入Bean、扩展WebSecurityConfigurerAdapter、重写端点授权配置及实现AuthenticationProvider,感兴趣的可以了解一下

重写UserDetailService组件

1.注入Bean的方式

/**
 * @author: coffee
 * @date: 2024/6/22 21:22
 * @description: 重写springsecurity默认组件:注入Bean的方式
 */
 @Configuration
public class ProjectConfig {

    /**
     * 重写userDetailsService组件
     */
     @Bean
    public UserDetailsService userDetailsService () {
        // InMemoryUserDetailsManager实现并不适用生成环境,此处进作为demo使用
        InMemoryUserDetailsManager userDetailsService = new InMemoryUserDetailsManager();

        // 使用指定用户名、密码和权限列表构建用户
        UserDetails user = User.withUsername("john").password("12345").authorities("read").build();

        // 添加该用户以便让UserDetailsService对其进行管理
        userDetailsService.createUser(user);

        return userDetailsService;
    }

    /**
     * 重写UserDetailsService组件也必须重写PasswordEncoder组件,否则会报:
     *    java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
     */
     @Bean
    public PasswordEncoder passwordEncoder () {
        // NoOpPasswordEncoder实例会将密码视为普通文本,他不会对密码进行加密或者hash处理
        return NoOpPasswordEncoder.getInstance();
    }
}

2.扩展WebSecurityConfigurerAdapter

/**
 * @author: coffee
 * @date: 2024/6/22 21:46
 * @description:
 */
@Configuration
public class ProjectConfig2 extends WebSecurityConfigurerAdapter {


    /**
     * 重写端点授权配置,就需要扩展WebSecurityConfigurerAdapter类,可以使用HttpSecurity对象的不同方法更改配置
     */
    @Override
    protected void configure (HttpSecurity httpSecurity) throws Exception {
        httpSecurity.httpBasic();

        // 所有请求都需要身份验证
        // httpSecurity.authorizeRequests().anyRequest().authenticated();

        // permitAll()方法修改授权配置,无需凭据(用户名密码)也可以直接调用接口。   curl http://localhost:8080/hello
        httpSecurity.authorizeRequests().anyRequest().permitAll();
    }

    /**
     * 重写springsecurity默认组件:继承WebSecurityConfigurerAdapter的方式
     */
    @Override
    protected void configure (AuthenticationManagerBuilder auth) throws Exception {
        // InMemoryUserDetailsManager实现并不适用生成环境,此处进作为demo使用
        InMemoryUserDetailsManager userDetailsService = new InMemoryUserDetailsManager();

        // 使用指定用户名、密码和权限列表构建用户
        UserDetails user = User.withUsername("john").password("12345").authorities("read").build();

        // 添加该用户以便让UserDetailsService对其进行管理
        userDetailsService.createUser(user);

        // AuthenticationManagerBuilder调用userDetailsService()方法来注册UserDetailsService实例
        // AuthenticationManagerBuilder调用passwordEncoder()方法来注册NoOpPasswordEncoder实例
        auth.userDetailsService(userDetailsService).passwordEncoder(NoOpPasswordEncoder.getInstance());

    }
}

重写端点授权配置

/**
 * @author: coffee
 * @date: 2024/6/22 21:46
 * @description:
 */
@Configuration
public class ProjectConfig2 extends WebSecurityConfigurerAdapter {


    /**
     * 重写端点授权配置,就需要扩展WebSecurityConfigurerAdapter类,可以使用HttpSecurity对象的不同方法更改配置
     */
    @Override
    protected void configure (HttpSecurity httpSecurity) throws Exception {
        httpSecurity.httpBasic();

        // 所有请求都需要身份验证
        // httpSecurity.authorizeRequests().anyRequest().authenticated();

        // permitAll()方法修改授权配置,无需凭据(用户名密码)也可以直接调用接口。   curl http://localhost:8080/hello
        httpSecurity.authorizeRequests().anyRequest().permitAll();
    }
}

重写AuthenticationProvider实现

/**
 * @author: coffee
 * @date: 2024/6/22 22:15
 * @description: ...
 */
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String userName = authentication.getName();
        String password = String.valueOf(authentication.getCredentials());

        // 重写身份验证提供者,用if else 替换 UserDetailsService和PasswordEncoder
        if ("john".equals(userName) && "12345".equals(password)) {
            return new UsernamePasswordAuthenticationToken(userName, password, Arrays.asList());
        } else {
            throw new AuthenticationCredentialsNotFoundException("ERROR");
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
/**
 * @author: coffee
 * @date: 2024/6/22 21:46
 * @description:
 */
@Configuration
public class ProjectConfig2 extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationProvider customAuthenticationProvider;

    /**
     * 重写端点授权配置,就需要扩展WebSecurityConfigurerAdapter类,可以使用HttpSecurity对象的不同方法更改配置
     */
    @Override
    protected void configure (HttpSecurity httpSecurity) throws Exception {
        httpSecurity.httpBasic();

        // 所有请求都需要身份验证
         httpSecurity.authorizeRequests().anyRequest().authenticated();

    }

    /**
     * 重写身份验证提供者
     */
    @Override
    protected void configure (AuthenticationManagerBuilder auth) throws Exception {
       
        auth.authenticationProvider(customAuthenticationProvider);

    }
}

到此这篇关于浅谈SpringSecurity重写默认配置的文章就介绍到这了,更多相关SpringSecurity重写默认配置内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

相关文章

  • springBoot整合rabbitmq测试常用模型小结

    springBoot整合rabbitmq测试常用模型小结

    这篇文章主要介绍了springBoot整合rabbitmq并测试五种常用模型,本文主要针对前五种常用模型,在spirngboot框架的基础上整合rabbitmq并进行测试使用,需要的朋友可以参考下
    2022-01-01
  • 详解spring security四种实现方式

    详解spring security四种实现方式

    这篇文章主要介绍了详解spring security四种实现方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-11-11
  • SpringBoot全局异常处理之多个处理器匹配顺序(最新推荐)

    SpringBoot全局异常处理之多个处理器匹配顺序(最新推荐)

    这篇文章主要介绍了SpringBoot全局异常处理之多个处理器匹配顺序(最新推荐),调试源码可见匹配顺序为:异常层级高者优先,再清楚点,子类异常处理器优先,本文给大家介绍的非常详细,感兴趣的朋友一起看看吧
    2024-03-03
  • 通过实例解析Spring argNames属性

    通过实例解析Spring argNames属性

    这篇文章主要介绍了通过实例解析Spring argNames属性,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-11-11
  • Java字符串的intern方法有何奥妙之处

    Java字符串的intern方法有何奥妙之处

    intern() 方法返回字符串对象的规范化表示形式。它遵循以下规则:对于任意两个字符串 s 和 t,当且仅当 s.equals(t) 为 true 时,s.intern() == t.intern() 才为 true
    2021-10-10
  • mybatis中的if test判断入参的值问题

    mybatis中的if test判断入参的值问题

    这篇文章主要介绍了mybatis中的if test判断入参的值问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-06-06
  • SpringSecurity rememberme功能实现过程解析

    SpringSecurity rememberme功能实现过程解析

    这篇文章主要介绍了SpringSecurity rememberme功能实现过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-03-03
  • java环境变量配置超详细图文教程

    java环境变量配置超详细图文教程

    在我们学习Java语言的时候,要在命令提示符里运用Java和Javac,用到这两个命令的时候就要配置Java环节变量才可以,这篇文章主要给大家介绍了关于java环境变量配置的相关资料,需要的朋友可以参考下
    2023-10-10
  • Java 关键字 速查表介绍

    Java 关键字 速查表介绍

    下面小编就为大家带来一篇Java 关键字 速查表介绍。小编觉得听不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-04-04
  • 在Java中使用Jwt的示例代码

    在Java中使用Jwt的示例代码

    这篇文章主要介绍了在Java中使用Jwt的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-04-04

最新评论