浅谈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重写默认配置内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

相关文章

  • Java中的接口回调实例

    Java中的接口回调实例

    今天小编就为大家分享一篇关于Java中的接口回调实例,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-01-01
  • SpringBoot过滤敏感词的两种实现方式

    SpringBoot过滤敏感词的两种实现方式

    Spring Boot本身并不直接提供过滤敏感词的功能,但你可以使用第三方库或者自定义过滤器来实现这个需求,所以本文给大家介绍了SpringBoot过滤敏感词的两种实现方式,感兴趣的朋友可以参考下
    2024-06-06
  • Java IO流之字节输入流的使用详解

    Java IO流之字节输入流的使用详解

    这篇文章主要为大家详细介绍了Java IO流中字节输入流的使用,文中的示例代码讲解详细,对我们学习Java有一定的帮助,需要的可以参考一下
    2022-08-08
  • java从控制台接收一个数字的实例详解

    java从控制台接收一个数字的实例详解

    这篇文章主要介绍了java从控制台接收一个数字的实例详解的相关资料,这里提供实例代码,注释说明清晰,需要的朋友可以参考下
    2017-07-07
  • java实现面板之间切换功能

    java实现面板之间切换功能

    这篇文章主要为大家详细介绍了java实现面板之间切换功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-06-06
  • Java的System.getProperty()方法获取大全

    Java的System.getProperty()方法获取大全

    这篇文章主要介绍了Java的System.getProperty()方法获取大全,罗列了System.getProperty()方法获取各类信息的用法,具有一定的参考借鉴价值,需要的朋友可以参考下
    2014-12-12
  • Spring的@Conditional详解

    Spring的@Conditional详解

    这篇文章主要介绍了Spring的@Conditional详解,给想要注入Bean增加限制条件,只有满足限制条件才会被构造并注入到Spring的IOC容器中,通常和@Bean注解一起使用,需要的朋友可以参考下
    2024-01-01
  • Java实现验证码具体代码

    Java实现验证码具体代码

    这篇文章主要介绍了Java实现验证码具体代码,有需要的朋友可以参考一下
    2013-12-12
  • AsyncHttpClient ClientStats源码流程解读

    AsyncHttpClient ClientStats源码流程解读

    这篇文章主要为大家介绍了AsyncHttpClient ClientStats源码流程解读,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-12-12
  • 基于SpringBoot框架管理Excel和PDF文件类型

    基于SpringBoot框架管理Excel和PDF文件类型

    这篇文章主要介绍了基于SpringBoot框架,管理Excel和PDF文件类型,本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-02-02

最新评论