springsecurity+vue实现登陆认证

通过查看UsernamePasswordAuthenticationFilter获取用户名和密码的实现方法可以看到,默认只能获取form表单提供的数据无法获得请求体中的数据。所以,要想获得请求体中的数据,需要自定义过滤器。

这里有两种方式获得用户名和密码

  • 直接重写obtainPasswordobtainUsername
  • 查看attemptAuthentication这个方法我们可以发现,用户名和密码是在这个方法里面获得并且使用的,因此我们可以直接重写这个方法。
1、编写UserAuthenticationFilter过滤器,继承UsernamePasswordAuthenticationFilter
@Slf4j
public class UserAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @Autowired
    private AuthenticationManager authenticationManager;
  
    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
            throws AuthenticationException {
        try {
            Employee employee = new ObjectMapper().readValue(req.getInputStream(), Employee.class);
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(employee.getUsername(), employee.getPassword()));
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }

    }
}
2、IEmployeeService 接口继承UserDetailsService
public interface IEmployeeService extends IService<Employee>,UserDetailsService {

}

EmployeeServiceImpl实现类
这里只需要实现loadUserByUsername方法,验证用户是否存在、是否被禁用

@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService{

    @Autowired
    EmployeeMapper employeeMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        System.out.println(employeeMapper);
        System.out.println(username);
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        Employee employee = employeeMapper.selectOne(wrapper);
        UserDetails userDetail = User.withUsername(username).password(employee.getPassword()).roles(username).build();
        return userDetail;
    }
}
3、编写UserLoginAuthenticationProvider,继承DaoAuthenticationProvider

通过继承DaoAuthenticationProvider,可以自定义用户密码验证并查看异常信息。

若不实现该类,抛出的异常信息会都变成Bad credentials

@Component
public class UserLoginAuthenticationProvider extends DaoAuthenticationProvider {

    @Autowired
    private UserDetailsServiceImpl detailsService;
    @Autowired
    private PasswordEncoder encoder;

    /**
     * 找到容器中的detailsService,并执行setUserDetailsService方法,完成赋值
     *
     * 必须要给UserDetailsService赋值,否则会出现UnsatisfiedDependencyException
     */
    @Autowired
    private void setDetailsService() {
        setUserDetailsService(detailsService);
    }

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        String presentedPassword = authentication.getCredentials().toString();
        if (!encoder.matches(presentedPassword, userDetails.getPassword())) {
            throw new BadCredentialsException(messages.getMessage("badCredentials", "用户密码错误"));
        }
    }
}

4、WebSecurityConfig 配置
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Autowired
    IEmployeeService employeeService;

    //注入AuthenticationManager,可能存在同名bean,
    //配置文件中设置allow-bean-definition-overriding: true
    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       //使用DetailsService进行数据校验
        auth.userDetailsService(employeeService).passwordEncoder(passwordEncoder());

        //使用自定义的Provider,进行数据校验
//        auth.authenticationProvider(loginAuthenticationProvider);
    }

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

    //重要,将UserAuthenticationFilter添加到容器
    @Bean
    public UserAuthenticationFilter userAuthenticationFilter() throws Exception {
        UserAuthenticationFilter filter = new UserAuthenticationFilter();
        //设置验证成功后的回调
        filter.setAuthenticationSuccessHandler((request,response,authentication)->{

            //响应成功状态码必须为200
            response.setStatus(200);
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding("utf-8");
            //将数据以json的形式返回给前台
            response.getWriter().print(JSON.toJSONString(Result.success(null)));
        });
        //设置验证失败后的回调
        filter.setAuthenticationFailureHandler((request,  response,  exception) ->{

            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding("utf-8");
            //将数据以json的形式返回给前台
            response.getWriter().print(JSON.toJSONString(Result.error("登录失败")));

        });
        //设置用户发起登陆请求时的url
        filter.setFilterProcessesUrl("/employee/login");
        filter.setAuthenticationManager(authenticationManager());
        return filter;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()   //屏蔽跨站请求

                .authorizeRequests()
                .anyRequest().permitAll()
                .and()
                .formLogin()
//                .loginPage("employee/login")
                .loginProcessingUrl("/employee/login")
                .successForwardUrl("/success");

        http.cors(); // 开启跨域
        //添加自定义的过滤器
        http.addFilterAt(userAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

}

5、axios.defaults.withCredentials=true//开启携带cookies

本文参考于:http://t.zoukankan.com/xlwq-p-13411575.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现用户登录和用户添加需要如下步骤: 1. 创建Spring Boot项目 2. 集成Spring Security 3. 创建用户实体类和DAO层 4. 创建用户Service层和Controller层 5. 创建Vue前端页面 6. 实现登录和用户添加功能 具体步骤如下: 1. 创建Spring Boot项目 可以使用Spring Initializr创建一个Maven项目,添加Web、Spring Security、MyBatis等依赖。 2. 集成Spring SecuritySpring Boot项目中,可以通过添加Spring Security依赖来实现安全认证和授权。在配置类中,可以定义登录页面和权限配置等。 3. 创建用户实体类和DAO层 创建用户实体类,包含用户名和密码等属性。然后创建UserMapper接口,继承MyBatis的Mapper接口,定义查询用户的方法。 4. 创建用户Service层和Controller层 创建UserService接口和UserServiceImpl实现类,定义用户登录和添加用户的方法。然后创建UserController类,处理用户登录和用户添加的请求。 5. 创建Vue前端页面 使用Vue框架创建前端页面,包括登录页面和用户添加页面。 6. 实现登录和用户添加功能 在登录页面中,输入用户名和密码,通过axios发送请求到后端UserController中的登录方法进行认证。在用户添加页面中,输入用户信息,通过axios发送请求到后端UserController中的添加用户方法进行添加。 以上就是实现用户登录和用户添加的步骤。具体实现过程可以参考相关文档和示例代码。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值