• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Y-wee
博客园    首页    新随笔    联系   管理     

springsecurity整合springboot实现自定义用户名和密码

springsecurity整合springboot实现自定义用户名和密码

通过配置文件实现

在application.yml中设置用户名和密码

spring:
  security:
    user:
      name: admin
      password: admin

通过配置类实现

package com.yl.config;

import com.yl.service.impl.MyUserDetailService;
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * spring security配置类
 *
 * @author Y-wee
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 密码加密
        String passwordEncode = new BCryptPasswordEncoder().encode("123");
        // 在内存中设置账号用户名为user密码为123角色为admin
        auth.inMemoryAuthentication().withUser("user").password(passwordEncode).roles("admin");
    }

    /**
     * 在容器中创建加密对象
     * <p>
     * BCryptPasswordEncoder是PasswordEncoder加密接口的实现类,是Spring Security官方推荐的密码解析器
     * 该类是对bcrypt强散列方法的具体实现,其基于Hash算法实现单向加密,可以通过strength控制加密强度,默认10
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

通过读取数据库实现

编写UserDetailsService实现类,重写UserDetails loadUserByUsername(String username) throws UsernameNotFoundException方法

package com.yl.service.impl;

import com.yl.service.UserService;
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.User;
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 org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * UserDetailsService实现类
 *
 * @author Y-wee
 */
@Service
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private UserService userService;

    /**
     * 认证
     *
     * @param username 用户名,此值是客户端表单传递过来的数据,默认情况下必须叫username,否则无法接收
     * @return UserDetails是系统默认的用户主体, 通过该类可以获取用户信息(用户名 、 密码......)
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 通过表单传递过来的用户名从数据库获取用户
        com.yl.bean.User user = userService.queryByUsername(username);
        // 如果用户不存在则抛出异常(一定要对用户名进行判断,否则不管输入什么用户名都可以登录成功)
        if (ObjectUtils.isEmpty(user)){
            throw new UsernameNotFoundException("用户名不存在");
        }
        // 存储用户角色,可以从数据库获取用户角色存储到List,这里为了方便直接自定义
        List<GrantedAuthority> roles = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
        // 将数据库获取到的用户名、密码和角色构建成spring security用户对象返回,进行校验
        return new User(user.getUsername(), new BCryptPasswordEncoder().encode(user.getPassword()), roles);
    }
}

编写spring security配置类实现WebSecurityConfigurerAdapter接口,重写void configure(AuthenticationManagerBuilder auth)方法

package com.yl.config;

import com.yl.service.impl.MyUserDetailService;
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * spring security配置类
 *
 * @author Y-wee
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyUserDetailService myUserDetailService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 设置UserDetailsService实现类以及加密对象
        auth.userDetailsService(myUserDetailService).passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

三种方式自定义用户名和密码的优先级依次升高

记得快乐
posted @ 2022-02-28 21:50  Y-wee  阅读(922)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3