SpringSecurity自定义用户认证逻辑(二)

本文详细介绍了Spring Security框架中用户认证的过程,包括用户信息获取、用户校验及密码加密解密的具体实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

根据上一节的配置,默认在服务开启的时候会被要求自动的进行表单登陆。用到的用户名只能是一个固定的用户名user,它的密码是每次启动的时候服务器自动生成的。最常见的场景是我们的用户是从数据库中获取的。
处理用户信息获取逻辑

/**
 * 自定义用户逻辑
 * Created by ZhuPengWei on 2017/11/27.
 */
@Component
public class MyUserDetailService implements UserDetailsService {

    /**
     * 日志处理类
     */
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 根据用户名加载用户信息
     *
     * @param username 用户名
     * @return UserDetails
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("表单登录用户名:" + username);
        return new User(username,"123456",true,
                true,
                true,
                true,
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin")));
    }

}

需要注意的是 在这里用了Spring默认的一个类User,在自己的实现过程中并不一定要用Spring的类
可以自己定义一个对象实现UserDetail接口。

public class User implements  UserDetails,CredentialsContrain{}

处理用户校验逻辑

UserDetails中有四个方法

    /**
     * Indicates whether the user's account has expired. An expired account cannot be
     * authenticated.
     *
     * @return <code>true</code> if the user's account is valid (ie non-expired),
     * <code>false</code> if no longer valid (ie expired)
     */
    boolean isAccountNonExpired();

    /**
     * Indicates whether the user is locked or unlocked. A locked user cannot be
     * authenticated.
     *
     * @return <code>true</code> if the user is not locked, <code>false</code> otherwise
     */
    boolean isAccountNonLocked();

    /**
     * Indicates whether the user's credentials (password) has expired. Expired
     * credentials prevent authentication.
     *
     * @return <code>true</code> if the user's credentials are valid (ie non-expired),
     * <code>false</code> if no longer valid (ie expired)
     */
    boolean isCredentialsNonExpired();

    /**
     * Indicates whether the user is enabled or disabled. A disabled user cannot be
     * authenticated.
     *
     * @return <code>true</code> if the user is enabled, <code>false</code> otherwise
     */
    boolean isEnabled();

第一个:账户没有过期
第二个:账户没被锁定 (是否冻结)
第三个:密码没有过期
第四个:账户是否可用(是否被删除)

处理密码加密解密逻辑
Interface PasswordEncoder

public interface PasswordEncoder {

    /**
     * Encode the raw password. Generally, a good encoding algorithm applies a SHA-1 or
     * greater hash combined with an 8-byte or greater randomly generated salt.
     */
    String encode(CharSequence rawPassword);

    /**
     * Verify the encoded password obtained from storage matches the submitted raw
     * password after it too is encoded. Returns true if the passwords match, false if
     * they do not. The stored password itself is never decoded.
     *
     * @param rawPassword the raw password to encode and match
     * @param encodedPassword the encoded password from storage to compare with
     * @return true if the raw password, after encoding, matches the encoded password from
     * storage
     */
    boolean matches(CharSequence rawPassword, String encodedPassword);

}
/**
 * security配置
 * Created by ZhuPengWei on 2017/11/27.
 */
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {

    // 处理密码加密解密逻辑
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.formLogin() //表单登陆
                .and()
                .authorizeRequests() // 请求授权
                .anyRequest()  // 任何请求
                .authenticated();  // 都需要认证
    }
}

/**
 * 自定义用户逻辑
 * Created by ZhuPengWei on 2017/11/27.
 */
@Component
public class MyUserDetailService implements UserDetailsService {

    /**
     * 日志处理类
     */
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private PasswordEncoder passwordEncoder;
    /**
     * 根据用户名加载用户信息
   *
     * @param username 用户名
   * @return UserDetails
     * @throws UsernameNotFoundException
     */
    @Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        grantedAuthorityList.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                return "admin";
            }
        });
        String pWord =passwordEncoder.encode("123456");
        logger.info(pWord);
        // SpringSecurity带有的用户类
        User user = new User(
                 username:"xm123",
                password:pWord,
                enabled:   true,  // 是否可用
         accountNonExpired: true,  // 账户没有过期
         credentialsNonExpired:true, // 密码没有过期
         accountNonLocked:  true,   // 帐号没有被锁定
          // 相当于 grantedAuthorityList  
          AuthorityUtils.commaSeparatedStringToAuthorityList("admin")
        );
        return user;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值