Spring Security设置用户信息

Spring Security设置用户信息

spring security默认情况下存在一个名为user的账号,对应的密码会在控制台输出

2022-02-26 22:35:32.825  INFO 10816 --- [           main] .s.s.UserDetailsServiceAutoConfiguration : 

Using generated security password: 5a709d3a-0c45-4ff7-a294-8a5a1e8b1c54

可以通过以下三种方法修改登录账号

  1. 配置文件

    spring:
      security:
        user:
          name: test
          password: 123
    
  2. 通过配置类

    package com.example.securitydemo3.config;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    import org.springframework.security.crypto.password.PasswordEncoder;
    
    /**
     * @author Allen
     */
    @Configuration
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            String password = bCryptPasswordEncoder.encode("123");
            auth.inMemoryAuthentication()
                    .withUser("admin")
                    .password(password)
                    .roles("admin");
        }
    
        @Bean
        PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    }
    
  3. 自定义实现类

    1. 实现UserDetailsService接口

      package com.example.securitydemo3.service.impl;
      
      import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
      import com.example.securitydemo3.domain.User;
      import com.example.securitydemo3.mapper.UserMapper;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.security.core.GrantedAuthority;
      import org.springframework.security.core.authority.AuthorityUtils;
      import org.springframework.security.core.userdetails.UserDetails;
      import org.springframework.security.core.userdetails.UserDetailsService;
      import org.springframework.security.core.userdetails.UsernameNotFoundException;
      import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
      import org.springframework.stereotype.Service;
      
      import java.util.List;
      
      /**
       * @author Allen
       */
      @Service("userDetailsService")
      public class MyUserDetailsServiceImpl implements UserDetailsService {
      
          @Autowired
          private UserMapper userMapper;
      
          @Override
          public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
              QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
              userQueryWrapper.lambda().eq(User::getUsername, username);
              User user = userMapper.selectOne(userQueryWrapper);
              if (user == null) {
                  throw new UsernameNotFoundException("用户不存在!");
              }
      
              List<GrantedAuthority> roles = AuthorityUtils.commaSeparatedStringToAuthorityList("admin");
              String password = new BCryptPasswordEncoder().encode(user.getPassword());
              return new org.springframework.security.core.userdetails.User(user.getUsername(), password, roles);
          }
      }
      
    2. 配置启用自定实现类

      package com.example.securitydemo3.config;
      
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
      import org.springframework.security.config.annotation.web.builders.HttpSecurity;
      import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
      import org.springframework.security.core.userdetails.UserDetailsService;
      import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
      import org.springframework.security.crypto.password.PasswordEncoder;
      
      /**
       * @author Allen
       */
      @Configuration
      public class SecurityConfig extends WebSecurityConfigurerAdapter {
      
          @Autowired
          private UserDetailsService userDetailsService;
      
          @Override
          protected void configure(AuthenticationManagerBuilder auth) throws Exception {
              auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
          }
      
          @Override
          protected void configure(HttpSecurity http) throws Exception {
              http.formLogin() // 自定义登录页面
                      // 设置自定义登录页面地址
                      .loginPage("/login.html")
                      // 登录访问路径
                      .loginProcessingUrl("/user/login")
                      // 默认登录成功跳转路径
                      .defaultSuccessUrl("/index").permitAll()
                      .and()
                      .authorizeRequests()
                      // 设置拦截放行路径
                      .antMatchers("/", "/hello", "/user/login").permitAll()
                      .anyRequest().authenticated()
                      .and()
                      // 关闭csrf防护
                      .csrf().disable();
          }
      
          @Bean
          PasswordEncoder passwordEncoder() {
              return new BCryptPasswordEncoder();
          }
      }
      
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值