Spring Security 入门 动态认证用户信息

动态获取用户的认证信息

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginPage("/login/page")  //自定义登录页面
                .loginProcessingUrl("/login")
                .and()
                .authorizeRequests()
                .antMatchers("/login/page").permitAll() // 放行跳转认证请求
                .anyRequest().authenticated();

        //关闭CSRF(Cross-site request forgery) 跨站请求伪造
        http.csrf().disable();
    }

}

重要的两个接口UserDetailsServiceUserDetails

package org.springframework.security.core.userdetails;

public interface UserDetailsService {

    UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;

}
package org.springframework.security.core.userdetails;

import java.io.Serializable;
import java.util.Collection;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

public interface UserDetails extends Serializable {
    Collection<? extends GrantedAuthority> getAuthorities();
    String getPassword();
    String getUsername();
    boolean isAccountNonExpired();
    boolean isAccountNonLocked();
    boolean isCredentialsNonExpired();
    boolean isEnabled();
}

实现接口UserDetailsService获取用户信息,具体实现由我们自己决定,就是根据username获取存储的用户信息,这样就动态获取了用户的信息。

@Slf4j
@Component
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    public PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //通过传入的用户名最终获取到UserDetails对象,这个获取过程省略了
        //这个过程其实就是根据用户名去数据库查询获取密码和权限列表,最终组成User对象
        //Spring Security会用这个User和登录输入和密码比较,判断是否登录成功

        //模拟用户可以在数据库查询到
        if ("devin".equals(username)) {
            return new User("devin", passwordEncoder.encode("1234"),
                    AuthorityUtils.commaSeparatedStringToAuthorityList("ADMIN"));
        }
        throw new UsernameNotFoundException("用户名输入错误");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值