spring boot security自定义认证

前言

前置阅读

spring boot security快速使用示例
spring boot security之前后端分离配置

说明

实际场景,我们一般是把用户信息保存在db中(也可能是调用三方接口),需要自定义用户信息加载或认证部分的逻辑,下面提供一个示例。

代码示例

定义用户bean

@AllArgsConstructor
@Data
public class User {

    private String username;

    private String password;
}

定义Mapper

示例,代码写死了,并不是实际从数据库或某个存储查询用户信息:

@Component
public class UserMapper {

   public User select(String username) {
        return new User(username, "pass");
    }
}

定义加载用户数据的类

UserDetailsService 是spring security内置的加载用户信息的接口,我们只需要实现这个接口:

@Slf4j
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    public static final UserDetails INVALID_USER =
            new org.springframework.security.core.userdetails.User("invalid_user", "invalid_password", Collections.emptyList());

    private final UserMapper userMapper;

    public UserDetailsServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名从数据库查询用户信息
        User user = userMapper.select(username);
        if (user == null) {
            /**
             * 如果没查询到这个用户,考虑两种选择:
             * 1. 返回一个标记无效用户的常量对象
             * 2. 返回一个不可能认证通过的用户
             */
            return INVALID_USER;
//            return new User(username, System.currentTimeMillis() + UUID.randomUUID().toString(), Collections.emptyList());
        }
        /**
         * 这里返回的用户密码是否为库里保存的密码,是明文/密文,取决于认证时密码比对部分的实现,每个人的场景不一样,
         * 因为使用的是不加密的PasswordEncoder,所以可以返回明文
         */
        return new org.springframework.security.core.userdetails.User(username, user.getPassword(), Collections.emptyList());
    }
}

自定义认证的bean配置

@Configuration
public class WebConfiguration {

    @Bean
    public PasswordEncoder passwordEncoder() {
        // 示例,不对密码进行加密处理
        return NoOpPasswordEncoder.getInstance();
    }


    @Bean
    public AuthenticationManager authenticationManager(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder) {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        // 设置加载用户信息的类
        provider.setUserDetailsService(userDetailsService);
        // 比较用户密码的时候,密码加密方式
        provider.setPasswordEncoder(passwordEncoder);
        return new ProviderManager(Arrays.asList(provider));
    }

}

注意,因为这个是示例,AuthenticationProvider使用的是spring security的DaoAuthenticationProvider ,在实际场景中,如果不满足可以自定义实现或者继承DaoAuthenticationProvider ,重写其中的:additionalAuthenticationChecks方法,主要就是认证检查的,默认实现如下:

	@Override
	@SuppressWarnings("deprecation")
	protected void additionalAuthenticationChecks(UserDetails userDetails,
			UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
		if (authentication.getCredentials() == null) {
			this.logger.debug("Failed to authenticate since no credentials provided");
			throw new BadCredentialsException(this.messages
					.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
		}
		String presentedPassword = authentication.getCredentials().toString();
		// 就是比对下请求传过来的密码和根据该用户查询的密码是否一致,passwordEncoder是根据不同的加密算法进行加密,示例我们用的是NoOpPasswordEncoder,也就是原始明文比对
		if (!this.passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
			this.logger.debug("Failed to authenticate since password does not match stored value");
			throw new BadCredentialsException(this.messages
					.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
		}
	}

定义登录接口

@RequestMapping("/login")
@RestController
public class LoginController {

    private final AuthenticationManager authenticationManager;

    public LoginController(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @PostMapping()
    public Object login(@RequestBody User user) {
        try {
            // 使用定义的AuthenticationManager进行认证处理
            Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
            // 认证通过,设置到当前上下文,如果当前认证过程后续还有处理的逻辑需要的话。这个示例是没有必要了
            SecurityContextHolder.getContext().setAuthentication(authenticate);
            return "login success";
        }catch (Exception e) {
            return "login failed";
        }
    }

    /**
     * 获取验证码,需要的话,可以提供一个验证码获取的接口,在上面的login里把验证码传进来进行比对
     */
    @GetMapping("/captcha")
    public Object captcha() {
        return "1234";
    }
}

自定义HttpSecurity

@Component
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 在这里自定义配置
        http.authorizeRequests()
                // 登录相关接口都允许访问
                .antMatchers("/login/**").permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .exceptionHandling()
                // 认证失败返回401状态码,前端页面可以根据401状态码跳转到登录页面
                .authenticationEntryPoint((request, response, authException) ->
                        response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase()))
                .and().cors()
                // csrf是否决定禁用,请自行考量
                .and().csrf().disable()
                // 采用http 的基本认证.
                .httpBasic();
    }
}

测试

示例中,用户密码写死是:pass,
用一个错误的密码试一下,响应登录失败:
在这里插入图片描述
使用正确的密码,响应登录成功:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要自定义Spring Boot Security认证过程,您需要实现`UserDetailsService`接口来加载用户信息并验证其凭据。您可以在您的Security配置类中覆盖`configure(AuthenticationManagerBuilder auth)`方法来设置`UserDetailsService`,如下所示: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private MyUserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasAnyRole("ADMIN", "USER") .antMatchers("/**").permitAll() .and() .formLogin() .and() .logout().logoutSuccessUrl("/login"); } } ``` 在这里,我们使用`MyUserDetailsService`类作为我们的`UserDetailsService`实现。您需要创建此类并实现`loadUserByUsername`方法,该方法将从数据库或其他存储中加载用户信息并返回一个`UserDetails`对象。在这个`UserDetails`对象中,您可以指定用户的密码,角色和权限等详细信息。 ```java @Service public class MyUserDetailsService implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username); if (user == null) { throw new UsernameNotFoundException("User not found with username: " + username); } return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), getAuthorities(user)); } private Collection<? extends GrantedAuthority> getAuthorities(User user) { List<GrantedAuthority> authorities = new ArrayList<>(); for (Role role : user.getRoles()) { authorities.add(new SimpleGrantedAuthority(role.getName())); for (Permission permission : role.getPermissions()) { authorities.add(new SimpleGrantedAuthority(permission.getName())); } } return authorities; } } ``` 在这里,我们使用`UserRepository`类从数据库中加载用户信息。在`loadUserByUsername`方法中,我们从数据库中获取用户信息并返回一个`UserDetails`对象。在`getAuthorities`方法中,我们为用户添加了角色和权限。 这是一个基本的示例,您可以根据您的需求进行更改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不识君的荒漠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值